agenttwin 0.3.36 → 0.3.38
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 +3830 -1774
- package/dist/dashboard/assets/next/static/chunks/{1937-2369d8ef2eae7700.js → 1937-6c86fddc443de922.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-2fd2e381a895d366.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/about/page-40c8beec9496b8b7.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/account/password/page-f73c2b9267b5d7e0.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/auth/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/{enterprise/page-11514cc52285b7f3.js → blog/layout-50a710e1993b90e4.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/compare/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/contact/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-209f837090dfdb78.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/{page-3d8c07ca2af8081c.js → page-9599e4d7dbe9d109.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/demo/{page-ac6e235c635cb130.js → page-31cfcdbb616ad4d4.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/developers/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-9d51ad46fff3ed1d.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dpa/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-eaf9847de1de035e.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/guides/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/{layout-8aa153f632f0aa20.js → layout-128b6774e096cd58.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/login/page-fd6021c3acb6bfba.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/not-found-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-f115c111de9d5332.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/{page-76277dc68b6a22bd.js → page-894aeddae568cc62.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/{blog/layout-6c159db381b82832.js → pricing/page-814d931ab23c41a1.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/privacy/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/security/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/signup/page-fd6021c3acb6bfba.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/status/{page-fd41c4e7838d9949.js → page-ff7cb74a07e7a9e2.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/terms/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-b0875609e09201bf.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-1dac0135be05c7c8.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/layout-7c6be3e291ee6a1d.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-893f3f867fbaab89.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-d0d081d4ea987ae2.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/page-cfa46e7717999ca0.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-893f3f867fbaab89.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-f4b72a7ad1e56298.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/{main-app-4051d8ba998bea15.js → main-app-916068fc13b0fb5b.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/{webpack-fb2ff67c26653fb6.js → webpack-2f5d1da47be2abc8.js} +1 -1
- package/dist/dashboard/assets/next/static/css/8b41516b04992d45.css +1 -0
- package/dist/dashboard/index.html +2 -2
- package/dist/engine.js +6979 -1804
- package/dist/gateway.js +3831 -1770
- package/dist/worker.js +446 -35
- package/dist/world-host.js +732 -130
- package/package.json +8 -1
- package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-b60a5aad66f3bf1d.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/about/page-a30c6925cc9ac983.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/account/password/page-0478a7f18cc5e31b.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/auth/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/compare/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/contact/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0050f308b9f77c24.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/developers/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-c86920ba0d1f3bc0.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dpa/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/guides/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/login/page-99ebb4d265222728.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/not-found-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-9e59af0296c9366b.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/pricing/page-c7015af858f4db8e.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/privacy/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/security/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/signup/page-99ebb4d265222728.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/terms/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-a79d128eb3b0b7d2.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-a9fa05c9ae5c24dc.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/layout-2e97381ae7a59ba0.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-57afbac97afd31fa.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-7c08d2c43f0be9d5.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/page-35998431fb40a9c9.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-57afbac97afd31fa.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-91ad6c5e4226778f.js +0 -1
- package/dist/dashboard/assets/next/static/css/96134c7d160c4fc3.css +0 -1
- /package/dist/dashboard/assets/next/static/{Hohse_HEIQKL22XK1m9DZ → Jcm2T3zQdpRyYqps7LFDD}/_buildManifest.js +0 -0
- /package/dist/dashboard/assets/next/static/{Hohse_HEIQKL22XK1m9DZ → Jcm2T3zQdpRyYqps7LFDD}/_ssgManifest.js +0 -0
package/dist/world-host.js
CHANGED
|
@@ -92,7 +92,8 @@ async function createRequestSourceHook(app, spec, credentials, runtime) {
|
|
|
92
92
|
const violationsPath = join(dir, "blocked.jsonl");
|
|
93
93
|
const config = { root: runtime?.root ?? await realpath(resolve(app)), files: spec.files, origins: Object.values(credentials).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials[r.service]])), routing: !!spec.fetchRoutes, violationsFd: runtime?.violationsFd, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
|
|
94
94
|
const guard = "const hookKey=Symbol.for('agenttwin.requestHook.v1');if(globalThis[hookKey])return;Object.defineProperty(globalThis,hookKey,{value:true});\n";
|
|
95
|
-
const
|
|
95
|
+
const orphanGuard = "if(process.platform!=='win32'){const launcher=process.ppid;setInterval(()=>{if(process.ppid!==launcher)process.exit(1);},1000).unref();}\n";
|
|
96
|
+
const hook = guard + orphanGuard + applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
|
|
96
97
|
` + String.raw`
|
|
97
98
|
const http=require('node:http'),https=require('node:https'),path=require('node:path'),{fileURLToPath}=require('node:url');
|
|
98
99
|
const origins=new Set(config.origins),files=new Set(config.files);
|
|
@@ -121,7 +122,7 @@ function esbuildBinary(real){const match=real.match(/^(.*[\/\\]node_modules[\/\\
|
|
|
121
122
|
// Operating-system tools that only print facts about this machine and cannot open a connection. SDKs and frameworks
|
|
122
123
|
// run them for a user-agent string (Stripe: uname; Next.js: sw_vers). Matched by their fixed system path, so a file of
|
|
123
124
|
// the same name inside a project or earlier on PATH is still reported.
|
|
124
|
-
const SYSTEM_INFO_BINARIES=new Set(['/usr/bin/uname','/bin/uname','/usr/bin/sw_vers','/usr/bin/arch','/usr/bin/nproc','/usr/bin/getconf']);
|
|
125
|
+
const SYSTEM_INFO_BINARIES=new Set(['/usr/bin/uname','/bin/uname','/usr/bin/sw_vers','/usr/bin/arch','/usr/bin/nproc','/usr/bin/getconf','/usr/sbin/sysctl']);
|
|
125
126
|
function systemInfoBinary(real){return process.platform!=='win32'&&SYSTEM_INFO_BINARIES.has(real);}
|
|
126
127
|
// pnpm's node_modules/.bin entries are sh scripts that exec node on the package's JS: the child is Node and loads the hook.
|
|
127
128
|
function pnpmNodeShim(real,text){if(!/[\\/]node_modules[\\/]\.bin[\\/]/.test(real)||!/^#!\/bin\/sh/.test(text))return false;const execs=[...text.matchAll(/\bexec\s+(\S+)/g)].map(m=>m[1]);return execs.length>0&&execs.every(e=>/^(?:node|"\$basedir\/node)(?:\.exe)?"?$/.test(e));}
|
|
@@ -133,7 +134,21 @@ function hookedEnv(options){const env={...((options&&options.env)||process.env)}
|
|
|
133
134
|
// git asked about the local checkout only (the commit a build stamps, the branch): no network, nothing written.
|
|
134
135
|
const LOCAL_GIT=/^(rev-parse|describe|log|show|status|branch|symbolic-ref|ls-files|rev-list|config)$/;
|
|
135
136
|
function localGit(name,words){if(name!=='git')return false;const sub=words.find(w=>!String(w).startsWith('-'));return !!sub&&LOCAL_GIT.test(String(sub))&&(sub!=='config'||words.some(w=>/^--get/.test(String(w))));}
|
|
136
|
-
|
|
137
|
+
// A package manager or task runner running a project script (pnpm run test, turbo run test) only launches it: the
|
|
138
|
+
// Node processes it starts inherit this hook through NODE_OPTIONS and are checked themselves. Installing or downloading
|
|
139
|
+
// (install, add, dlx) reaches the network, so it is not trusted.
|
|
140
|
+
const LAUNCHERS=/^(pnpm|pnpm-native|yarn|npm|npx|corepack|turbo)$/;
|
|
141
|
+
function scriptLauncher(name,words){if(!LAUNCHERS.test(name))return false;const plain=words.map(String).filter(w=>!w.startsWith('-'));if(plain.some(w=>/^(install|i|add|ci|dlx|create|init|publish|update|up|upgrade)$/.test(w)))return false;return plain.some(w=>/^(run|run-script|exec|test|t)$/.test(w));}
|
|
142
|
+
// npm runs a script as sh -c "<script>": judge the command the script runs (vitest, a Node CLI), not the shell itself.
|
|
143
|
+
const SHELLS=/^(sh|bash|dash|zsh)$/;
|
|
144
|
+
// A shell script is judged one command at a time (cd x && vitest run): builtins run nothing, exec X runs X.
|
|
145
|
+
const BUILTINS=/^(cd|export|set|unset|true|false|echo|printf|exit|test|\[|:|source|\.|shift|umask|wait|trap|type|command|pwd|read)$/;
|
|
146
|
+
function shellSegments(text){return String(text).split(/&&|\|\||;|\||\n/).map(t=>t.trim().replace(/^exec\s+/,'').replace(/^\(+|\)+$/g,'').trim()).filter(Boolean);}
|
|
147
|
+
// Tools that only read local state: Jest asks watchman which files changed.
|
|
148
|
+
// Local tools are trusted only from the system's own folders, never a same-named file inside the project.
|
|
149
|
+
const SYSTEM_DIRS=/^\/(usr\/(local\/)?)?s?bin$|^\/opt\/homebrew\/bin$/;
|
|
150
|
+
const LOCAL_TOOLS=/^(watchman|sleep|cat|ls|cp|mv|rm|mkdir|rmdir|touch|ln|chmod|readlink|realpath|mktemp|basename|dirname|head|tail|wc|sort|uniq|cut|tr|tee|grep|egrep|date|which|uname|printenv|diff|cmp|gzip|gunzip|zcat|seq|yes|nproc|id|whoami|hostname|stat|du|df|kill|ps|true|false)$/;
|
|
151
|
+
function checkExecutable(command,shell,options,args){if(!shell&&SHELLS.test(path.basename(String(command)))&&Array.isArray(args)&&args[0]==='-c'&&typeof args[1]==='string'){for(const part of shellSegments(args[1])){const word=(part.split(/\s+/).find(t=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))||'');if(word&&!BUILTINS.test(word))checkExecutable(part,true,options,[]);}return;}if(shell&&/&&|\|\||;|\|/.test(String(command))){for(const part of shellSegments(command)){const word=(part.split(/\s+/).find(t=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))||'');if(word&&!BUILTINS.test(word)&&part!==String(command).trim())checkExecutable(part,true,options,[]);}return;}{const tool=String(command).trim().split(/\s+/).find(t=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(t))||'';if(LOCAL_TOOLS.test(path.basename(tool))){let where='';try{where=resolveCommand(tool,options)||'';}catch{}if(tool==='watchman'||SYSTEM_DIRS.test(path.dirname(where)))return;}}let name='unknown',trusted=false;try{const text=String(command).trim();const first=(shell?(text.split(/\s+/).find(token=>!/^[A-Za-z_][A-Za-z0-9_]*=/.test(token))||''):text).replace(/^["']|["']$/g,'');name=path.basename(first).replace(/\.(exe|cmd)$/i,'')||'unknown';if(reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;const file=first&&resolveCommand(first,options);trusted=!!file&&trustedExecutable(file,options);if(!trusted){const words=shell?text.split(/\s+/).slice(1):(Array.isArray(args)?args:[]);trusted=localGit(name,words)||scriptLauncher(name,words);}}catch{trusted=false;}if(trusted||reportedSubprocesses.has(name)||reportedSubprocesses.size>=100)return;reportedSubprocesses.add(name);try{writeViolation({origin:('subprocess:'+name).slice(0,2048),reason:'unhooked-subprocess'});}catch{}}
|
|
137
152
|
// Puts the hooked env into the options argument at index i, inserting an options object when there is none.
|
|
138
153
|
function withOptions(args,i){const out=[...args];const o=out[i];if(o&&typeof o==='object'&&!Array.isArray(o))out[i]=hookedEnv(o);else out.splice(Math.min(i,out.length),o==null&&i<out.length?1:0,hookedEnv({}));return out;}
|
|
139
154
|
for(const name of ['spawn','spawnSync','execFile','execFileSync','fork']){const original=childProcess[name];if(typeof original!=='function')continue;childProcess[name]=function(file,...rest){const optionsAt=Array.isArray(rest[0])||(rest[0]==null&&rest.length>1)?2:1;const patched=withOptions([file,...rest],optionsAt);if(name!=='fork')checkExecutable(file,!!patched[optionsAt].shell,patched[optionsAt],Array.isArray(rest[0])?rest[0]:[]);return original.apply(this,patched);};}
|
|
@@ -300,11 +315,50 @@ function subscriptionItemOperation(method, id, params, data) {
|
|
|
300
315
|
item.quantity = quantity;
|
|
301
316
|
return { status: 200, body: item, collection, record: structuredClone(item), operation: "write" };
|
|
302
317
|
}
|
|
318
|
+
function chargeCreate(params, data, sequence) {
|
|
319
|
+
const collection = "/v1/charges", charges = data[collection];
|
|
320
|
+
if (!charges) return void 0;
|
|
321
|
+
const allowed = ["amount", "currency", "source", "customer", "description", "receipt_email", "capture", "statement_descriptor"];
|
|
322
|
+
if (Object.keys(params).some((k) => !allowed.includes(k) && !/^metadata\[[^\]]+\]$/.test(k) && k !== "metadata")) return void 0;
|
|
323
|
+
const amount = Number(params.amount);
|
|
324
|
+
if (params.amount === void 0) return { ...stripeError(400, "parameter_missing", "Missing required param: amount.", "amount"), collection };
|
|
325
|
+
if (!Number.isInteger(amount) || amount < 50) return { ...stripeError(400, "amount_too_small", "Amount must be at least 50 cents", "amount"), collection };
|
|
326
|
+
if (typeof params.currency !== "string" || !params.currency) return { ...stripeError(400, "parameter_missing", "Missing required param: currency.", "currency"), collection };
|
|
327
|
+
if (params.source === void 0 && params.customer === void 0) return { ...stripeError(400, "parameter_missing", "Must provide source or customer.", "source"), collection };
|
|
328
|
+
if (params.source === "tok_chargeDeclined") {
|
|
329
|
+
const declined = stripeError(402, "card_declined", "Your card was declined.", "source");
|
|
330
|
+
declined.body.error.type = "card_error";
|
|
331
|
+
return { ...declined, collection };
|
|
332
|
+
}
|
|
333
|
+
const charge = {
|
|
334
|
+
id: nextId(charges, "ch", sequence),
|
|
335
|
+
object: "charge",
|
|
336
|
+
amount,
|
|
337
|
+
amount_refunded: 0,
|
|
338
|
+
amount_captured: params.capture === "false" || params.capture === false ? 0 : amount,
|
|
339
|
+
currency: params.currency.toLowerCase(),
|
|
340
|
+
customer: params.customer ?? null,
|
|
341
|
+
description: params.description ?? null,
|
|
342
|
+
receipt_email: params.receipt_email ?? null,
|
|
343
|
+
metadata: metadataOf(params),
|
|
344
|
+
payment_intent: null,
|
|
345
|
+
captured: !(params.capture === "false" || params.capture === false),
|
|
346
|
+
paid: true,
|
|
347
|
+
refunded: false,
|
|
348
|
+
status: "succeeded",
|
|
349
|
+
created: twinNowSeconds(17e8),
|
|
350
|
+
livemode: false,
|
|
351
|
+
payment_method_details: { type: "card", card: { brand: "visa", last4: "4242" } }
|
|
352
|
+
};
|
|
353
|
+
charges.push(charge);
|
|
354
|
+
return { status: 200, body: charge, collection, operation: "write" };
|
|
355
|
+
}
|
|
303
356
|
function stripeOperation(method, path, params, data, sequence) {
|
|
304
357
|
const item = /^\/v1\/subscription_items\/([^/]+)$/.exec(path);
|
|
305
358
|
if (item) return subscriptionItemOperation(method, item[1], params, data);
|
|
306
359
|
const error = stripeError;
|
|
307
360
|
const other = /^\/v1\/(refunds|charges|events)(?:\/([^/]+))?$/.exec(path);
|
|
361
|
+
if (other?.[1] === "charges" && method === "POST" && !other[2]) return chargeCreate(params, data, sequence);
|
|
308
362
|
if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
|
|
309
363
|
const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
|
|
310
364
|
if (!match || !["GET", "POST"].includes(method)) return void 0;
|
|
@@ -764,12 +818,12 @@ var init_resp = __esm({
|
|
|
764
818
|
socket.on("data", (chunk) => {
|
|
765
819
|
this.buffer = Buffer.concat([this.buffer, chunk]);
|
|
766
820
|
for (; ; ) {
|
|
767
|
-
const
|
|
768
|
-
if (!
|
|
769
|
-
this.buffer = this.buffer.subarray(
|
|
821
|
+
const frame3 = parseResp(this.buffer);
|
|
822
|
+
if (!frame3) break;
|
|
823
|
+
this.buffer = this.buffer.subarray(frame3.end);
|
|
770
824
|
const w = this.waiting.shift();
|
|
771
825
|
if (!w) continue;
|
|
772
|
-
const v =
|
|
826
|
+
const v = frame3.value;
|
|
773
827
|
if (v && typeof v === "object" && "error" in v) w.reject(new Error(v.error));
|
|
774
828
|
else w.resolve(v);
|
|
775
829
|
}
|
|
@@ -980,7 +1034,7 @@ var POSTGRES_EXTENSIONS, EngineUnavailable, FaultGate, sleep;
|
|
|
980
1034
|
var init_types = __esm({
|
|
981
1035
|
"src/runtime/engines/types.ts"() {
|
|
982
1036
|
"use strict";
|
|
983
|
-
POSTGRES_EXTENSIONS = ["uuid-ossp", "btree_gist", "btree_gin", "citext", "pg_trgm", "hstore", "ltree", "cube", "earthdistance", "fuzzystrmatch", "tablefunc", "isn", "lo", "seg", "tcn", "unaccent", "bloom", "intarray", "pgcrypto"];
|
|
1037
|
+
POSTGRES_EXTENSIONS = ["uuid-ossp", "btree_gist", "btree_gin", "citext", "pg_trgm", "hstore", "ltree", "cube", "earthdistance", "fuzzystrmatch", "tablefunc", "isn", "lo", "seg", "tcn", "unaccent", "bloom", "intarray", "pgcrypto", "vector"];
|
|
984
1038
|
EngineUnavailable = class extends Error {
|
|
985
1039
|
constructor(kind, message) {
|
|
986
1040
|
super(message);
|
|
@@ -1171,17 +1225,17 @@ function respFrontEnd(upstreamPort, gate, events, commit) {
|
|
|
1171
1225
|
inbound = Buffer.concat([inbound, chunk]);
|
|
1172
1226
|
const forward = [];
|
|
1173
1227
|
for (; ; ) {
|
|
1174
|
-
let
|
|
1228
|
+
let frame3;
|
|
1175
1229
|
try {
|
|
1176
|
-
|
|
1230
|
+
frame3 = parseResp(inbound, 0, true);
|
|
1177
1231
|
} catch {
|
|
1178
1232
|
close();
|
|
1179
1233
|
return;
|
|
1180
1234
|
}
|
|
1181
|
-
if (!
|
|
1182
|
-
const bytes = inbound.subarray(0,
|
|
1183
|
-
inbound = inbound.subarray(
|
|
1184
|
-
const args =
|
|
1235
|
+
if (!frame3) break;
|
|
1236
|
+
const bytes = inbound.subarray(0, frame3.end);
|
|
1237
|
+
inbound = inbound.subarray(frame3.end);
|
|
1238
|
+
const args = frame3.value.map((b) => b.toString("utf8"));
|
|
1185
1239
|
if (!args.length) continue;
|
|
1186
1240
|
const name = args[0].toLowerCase(), rest = args.slice(1);
|
|
1187
1241
|
if (["subscribe", "psubscribe", "ssubscribe", "monitor"].includes(name)) {
|
|
@@ -1230,23 +1284,23 @@ function respFrontEnd(upstreamPort, gate, events, commit) {
|
|
|
1230
1284
|
}
|
|
1231
1285
|
outbound = Buffer.concat([outbound, chunk]);
|
|
1232
1286
|
for (; ; ) {
|
|
1233
|
-
let
|
|
1287
|
+
let frame3;
|
|
1234
1288
|
try {
|
|
1235
|
-
|
|
1289
|
+
frame3 = parseResp(outbound);
|
|
1236
1290
|
} catch {
|
|
1237
1291
|
close();
|
|
1238
1292
|
return;
|
|
1239
1293
|
}
|
|
1240
|
-
if (!
|
|
1241
|
-
const bytes = Buffer.from(outbound.subarray(0,
|
|
1242
|
-
outbound = outbound.subarray(
|
|
1294
|
+
if (!frame3) break;
|
|
1295
|
+
const bytes = Buffer.from(outbound.subarray(0, frame3.end));
|
|
1296
|
+
outbound = outbound.subarray(frame3.end);
|
|
1243
1297
|
const p = pending.find((x) => !x.local && !x.reply);
|
|
1244
1298
|
if (!p) {
|
|
1245
1299
|
client.write(bytes);
|
|
1246
1300
|
continue;
|
|
1247
1301
|
}
|
|
1248
1302
|
p.reply = bytes;
|
|
1249
|
-
const v =
|
|
1303
|
+
const v = frame3.value;
|
|
1250
1304
|
if (v && typeof v === "object" && "error" in v) p.error = true;
|
|
1251
1305
|
}
|
|
1252
1306
|
void drain();
|
|
@@ -1476,10 +1530,10 @@ var init_redis = __esm({
|
|
|
1476
1530
|
const out = [];
|
|
1477
1531
|
try {
|
|
1478
1532
|
for (; ; ) {
|
|
1479
|
-
const
|
|
1480
|
-
if (!
|
|
1481
|
-
buffer = buffer.subarray(
|
|
1482
|
-
const args =
|
|
1533
|
+
const frame3 = parseResp(buffer, 0, true);
|
|
1534
|
+
if (!frame3) break;
|
|
1535
|
+
buffer = buffer.subarray(frame3.end);
|
|
1536
|
+
const args = frame3.value.map((b) => b.toString("latin1"));
|
|
1483
1537
|
if (!args.length) continue;
|
|
1484
1538
|
if (args[0].toLowerCase() === "quit") {
|
|
1485
1539
|
out.push(encode.simple("OK"));
|
|
@@ -2031,7 +2085,7 @@ function engineFor(rows2) {
|
|
|
2031
2085
|
return cache2;
|
|
2032
2086
|
}
|
|
2033
2087
|
function upstashReply(reply, base64) {
|
|
2034
|
-
const
|
|
2088
|
+
const frame3 = parseResp(reply);
|
|
2035
2089
|
const json = (value) => {
|
|
2036
2090
|
if (value === null || typeof value === "number" || typeof value === "boolean") return value;
|
|
2037
2091
|
if (Buffer.isBuffer(value)) return base64 ? value.toString("base64") : value.toString("utf8");
|
|
@@ -2039,9 +2093,9 @@ function upstashReply(reply, base64) {
|
|
|
2039
2093
|
if ("simple" in value) return base64 && value.simple !== "OK" ? Buffer.from(value.simple).toString("base64") : value.simple;
|
|
2040
2094
|
throw new Error(value.error);
|
|
2041
2095
|
};
|
|
2042
|
-
if (!
|
|
2043
|
-
if (
|
|
2044
|
-
return { result: json(
|
|
2096
|
+
if (!frame3) return { error: "ERR empty reply" };
|
|
2097
|
+
if (frame3.value && typeof frame3.value === "object" && !Array.isArray(frame3.value) && !Buffer.isBuffer(frame3.value) && "error" in frame3.value) return { error: frame3.value.error };
|
|
2098
|
+
return { result: json(frame3.value) };
|
|
2045
2099
|
}
|
|
2046
2100
|
function upstashRedisOperation(method, path, params, headers, data, _sequence, raw) {
|
|
2047
2101
|
if (method !== "POST" || !["/", "/pipeline", "/multi-exec"].includes(path) || raw === void 0 || Object.keys(params).length) return void 0;
|
|
@@ -3576,7 +3630,7 @@ function normalizeSeed(seed) {
|
|
|
3576
3630
|
return createHash4("sha256").update(text2).digest("hex").slice(0, 32);
|
|
3577
3631
|
}
|
|
3578
3632
|
function faultOrdinals(selection, seed) {
|
|
3579
|
-
const count = selection.type === "timeout-after-write" ? 1 : selection.count ?? 1;
|
|
3633
|
+
const count = selection.type === "timeout-after-write" || selection.type === "lost-reply" ? 1 : selection.count ?? 1;
|
|
3580
3634
|
if (selection.schedule === "first") return Array.from({ length: Math.min(count, FAULT_SCHEDULE_WINDOW) }, (_, i) => i);
|
|
3581
3635
|
const stream = new SeedStream(seed, `fault:${selection.type}:${selection.service}:${selection.path}`);
|
|
3582
3636
|
const all = Array.from({ length: FAULT_SCHEDULE_WINDOW }, (_, i) => i);
|
|
@@ -5268,7 +5322,7 @@ function parseWorld(value) {
|
|
|
5268
5322
|
if (!Array.isArray(v.files) || !v.files.length || v.files.length > 100 || !v.files.every((f) => typeof f === "string" && f.length > 0)) invalid("files must explicitly list 1\u2013100 application files");
|
|
5269
5323
|
if (new Set(v.files).size !== v.files.length) invalid("files must be unique");
|
|
5270
5324
|
if (!Array.isArray(v.command) || !v.command.length || !v.command.every((c) => typeof c === "string" && c.length > 0) || !RUNTIMES.test(v.command[0])) invalid("command must be an argv array starting with node, python, python3, uv, poetry, go, ruby, bundle, deno, bun or curl");
|
|
5271
|
-
if (!Number.isInteger(v.timeoutSeconds) || Number(v.timeoutSeconds) < 1 || Number(v.timeoutSeconds) >
|
|
5325
|
+
if (!Number.isInteger(v.timeoutSeconds) || Number(v.timeoutSeconds) < 1 || Number(v.timeoutSeconds) > 3600) invalid("timeoutSeconds must be 1\u20133600");
|
|
5272
5326
|
if (v.workflowId !== void 0 && (typeof v.workflowId !== "string" || !v.workflowId)) invalid("workflowId must be a nonempty string");
|
|
5273
5327
|
if (v.sourceBuild !== void 0 && (typeof v.sourceBuild !== "string" || !/^[a-f0-9]{64}$/.test(v.sourceBuild))) invalid("sourceBuild must be a SHA-256 build-record digest");
|
|
5274
5328
|
if (v.twinClock !== void 0 && !validTwinClock(v.twinClock)) invalid("twinClock requires only now as a canonical UTC timestamp with milliseconds");
|
|
@@ -5340,7 +5394,7 @@ function parseWorld(value) {
|
|
|
5340
5394
|
}
|
|
5341
5395
|
}
|
|
5342
5396
|
if (v.fault !== void 0) {
|
|
5343
|
-
if (!object2(v.fault) || !(known2(v.fault) || requestPathFaults.has(String(v.fault.service)) && typeof v.fault.path === "string" && /^\/[a-zA-Z0-9_.:/-]+$/.test(v.fault.path) && !v.fault.path.includes("//")) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, blackhole, server-error, duplicate-write or slow-response");
|
|
5397
|
+
if (!object2(v.fault) || !(known2(v.fault) || requestPathFaults.has(String(v.fault.service)) && typeof v.fault.path === "string" && /^\/[a-zA-Z0-9_.:/-]+$/.test(v.fault.path) && !v.fault.path.includes("//")) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, lost-reply, blackhole, server-error, duplicate-write or slow-response");
|
|
5344
5398
|
const f = v.fault;
|
|
5345
5399
|
const allowed = ["service", "path", "type"];
|
|
5346
5400
|
const count = f.count, windowMs = f.windowMs;
|
|
@@ -5358,7 +5412,7 @@ function parseWorld(value) {
|
|
|
5358
5412
|
if (["blackhole", "duplicate-write", "slow-response"].includes(f.type)) allowed.push("count");
|
|
5359
5413
|
}
|
|
5360
5414
|
if (f.schedule !== void 0) {
|
|
5361
|
-
if (f.type === "timeout-after-write" || !["seeded", "first"].includes(f.schedule)) invalid(`${f.type} fault does not take schedule ${String(f.schedule)}; use seeded or first`);
|
|
5415
|
+
if (f.type === "timeout-after-write" || f.type === "lost-reply" || !["seeded", "first"].includes(f.schedule)) invalid(`${f.type} fault does not take schedule ${String(f.schedule)}; use seeded or first`);
|
|
5362
5416
|
allowed.push("schedule");
|
|
5363
5417
|
}
|
|
5364
5418
|
if (Object.keys(f).some((k) => !allowed.includes(k))) invalid(`unknown fault field for ${f.type}`);
|
|
@@ -5415,6 +5469,11 @@ function parseWorld(value) {
|
|
|
5415
5469
|
}
|
|
5416
5470
|
if (v.background !== void 0 && (!object2(v.background) || !known2(v.background) || !Number.isSafeInteger(v.background.count) || Number(v.background.count) < 0 || !Number.isInteger(v.background.timeoutMs) || Number(v.background.timeoutMs) < 1 || Number(v.background.timeoutMs) > Number(v.timeoutSeconds) * 1e3 || v.background.where !== void 0 && !object2(v.background.where) || Object.keys(v.background).some((k) => !["service", "path", "count", "where", "timeoutMs"].includes(k)))) invalid("background requires a known collection, expected count, optional where, and bounded timeoutMs");
|
|
5417
5471
|
if (v.directory !== void 0 && (typeof v.directory !== "string" || !v.directory || v.directory.length > 1024 || /\0/.test(v.directory) || isAbsolute(v.directory))) invalid("directory must be a relative path to the application folder");
|
|
5472
|
+
if (v.settingAliases !== void 0) {
|
|
5473
|
+
if (!object2(v.settingAliases) || Object.keys(v.settingAliases).length > 100) invalid("settingAliases must be an object of at most 100 settings");
|
|
5474
|
+
for (const [name, key2] of Object.entries(v.settingAliases))
|
|
5475
|
+
if (!/^[A-Z][A-Z0-9_]{0,127}$/.test(name) || typeof key2 !== "string" || !/^[A-Z][A-Z0-9_]{0,127}$/.test(key2) || RESERVED_ENV.test(name)) invalid("settingAliases maps setting names to twin key names");
|
|
5476
|
+
}
|
|
5418
5477
|
if (v.env !== void 0) {
|
|
5419
5478
|
if (!object2(v.env) || Object.keys(v.env).length > 200) invalid("env must be an object of at most 200 string variables");
|
|
5420
5479
|
for (const [key2, value2] of Object.entries(v.env)) {
|
|
@@ -5463,10 +5522,13 @@ function parseWorld(value) {
|
|
|
5463
5522
|
origins.add(mapping.origin);
|
|
5464
5523
|
}
|
|
5465
5524
|
}
|
|
5466
|
-
const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "twinClock", "files", "command", "timeoutSeconds", "browser", "background", "directory", "env", "server", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
|
|
5525
|
+
const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "twinClock", "files", "command", "timeoutSeconds", "browser", "background", "directory", "env", "settingAliases", "server", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
|
|
5467
5526
|
if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
|
|
5468
5527
|
return v;
|
|
5469
5528
|
}
|
|
5529
|
+
function applySettingAliases(env, aliases) {
|
|
5530
|
+
for (const [name, key2] of Object.entries(aliases ?? {})) if (!env[name] && env[key2]) env[name] = env[key2];
|
|
5531
|
+
}
|
|
5470
5532
|
var RUNTIMES, ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, RESERVED_ENV, isServerPath, object2, namePattern, inRangeInt;
|
|
5471
5533
|
var init_spec = __esm({
|
|
5472
5534
|
"src/runtime/spec.ts"() {
|
|
@@ -5509,7 +5571,7 @@ var init_spec = __esm({
|
|
|
5509
5571
|
// Enterprise twins: any subset of their optional collections; Snowflake tables are free-form.
|
|
5510
5572
|
...Object.fromEntries(ENTERPRISE_ADAPTERS.filter((a) => !FREEFORM_COLLECTION_ADAPTERS.includes(a)).map((a) => [a, []]))
|
|
5511
5573
|
};
|
|
5512
|
-
FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write", "slow-response"];
|
|
5574
|
+
FAULT_TYPES = ["timeout-after-write", "lost-reply", "blackhole", "server-error", "duplicate-write", "slow-response"];
|
|
5513
5575
|
PROPERTY_KINDS = ["unique-per-act", "no-loss", "effect-count"];
|
|
5514
5576
|
RESERVED_ENV = /^(PATH|NODE_OPTIONS|AGENTTWIN_.*|DATABASE_URL|POSTGRES_URL|PG_URL|PG(HOST|PORT|USER|PASSWORD|DATABASE|SSLMODE)|REDIS_(URL|HOST|PORT|TLS_URL)|REDISHOST|REDISPORT|KV_URL|HTTPS?_PROXY|ALL_PROXY|NO_PROXY|SSL_CERT_FILE|REQUESTS_CA_BUNDLE|CURL_CA_BUNDLE|NODE_EXTRA_CA_CERTS|GRPC_DEFAULT_SSL_ROOTS_FILE_PATH)$/i;
|
|
5515
5577
|
isServerPath = (path) => typeof path === "string" && path.length <= 4096 && path.startsWith("/") && !path.startsWith("//") && !path.includes("\\") && !/[\u0000-\u001f\u007f]/.test(path);
|
|
@@ -5539,6 +5601,20 @@ var init_postgrest = __esm({
|
|
|
5539
5601
|
return this.pool.end().catch(() => {
|
|
5540
5602
|
});
|
|
5541
5603
|
}
|
|
5604
|
+
/**
|
|
5605
|
+
* A Supabase Auth user as a row of auth.users, as GoTrue writes it: the project's own triggers on that table (a
|
|
5606
|
+
* profile, a workspace) run. Returns the database's error when one refuses it; a project without the table is fine.
|
|
5607
|
+
*/
|
|
5608
|
+
async addAuthUser(u) {
|
|
5609
|
+
try {
|
|
5610
|
+
await this.pool.query(`INSERT INTO auth.users (id, aud, role, email, email_confirmed_at, raw_app_meta_data, raw_user_meta_data, created_at, updated_at, last_sign_in_at)
|
|
5611
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $5, $5, $5) ON CONFLICT (id) DO NOTHING`, [u.id, u.aud, u.role, u.email, u.created_at, JSON.stringify(u.app_metadata), JSON.stringify(u.user_metadata)]);
|
|
5612
|
+
return void 0;
|
|
5613
|
+
} catch (error) {
|
|
5614
|
+
const e = error;
|
|
5615
|
+
return e.code === "42P01" || e.code === "3F000" ? void 0 : e.message ?? String(error);
|
|
5616
|
+
}
|
|
5617
|
+
}
|
|
5542
5618
|
foreignKeys() {
|
|
5543
5619
|
return this.fks ??= this.pool.query(`SELECT c.conrelid::regclass::text AS table, a.attname AS column, c.confrelid::regclass::text AS "refTable", r.attname AS "refColumn"
|
|
5544
5620
|
FROM pg_constraint c JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=c.conkey[1] JOIN pg_attribute r ON r.attrelid=c.confrelid AND r.attnum=c.confkey[1]
|
|
@@ -5634,7 +5710,7 @@ var init_postgrest = __esm({
|
|
|
5634
5710
|
const cols = await this.columns(table2, "r", params.get("select") ?? "*");
|
|
5635
5711
|
return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
|
|
5636
5712
|
};
|
|
5637
|
-
let sql, status = 200;
|
|
5713
|
+
let sql, status = 200, perRow = false;
|
|
5638
5714
|
const method = request.method.toUpperCase();
|
|
5639
5715
|
if (method === "GET" || method === "HEAD") {
|
|
5640
5716
|
const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
|
|
@@ -5643,7 +5719,8 @@ var init_postgrest = __esm({
|
|
|
5643
5719
|
});
|
|
5644
5720
|
const limit = Number(params.get("limit")), offset = Number(params.get("offset"));
|
|
5645
5721
|
const cols = await this.columns(table2, "t", params.get("select") ?? "*");
|
|
5646
|
-
|
|
5722
|
+
perRow = true;
|
|
5723
|
+
sql = `SELECT row_to_json(x) AS row FROM (SELECT ${cols} FROM ${t} t${_PostgrestLayer.where(params, values)}${order.length ? ` ORDER BY ${order.join(", ")}` : ""}${limit >= 0 && params.has("limit") ? ` LIMIT ${Math.trunc(limit)}` : ""}${offset > 0 ? ` OFFSET ${Math.trunc(offset)}` : ""}) x`;
|
|
5647
5724
|
} else if (method === "POST") {
|
|
5648
5725
|
const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
|
|
5649
5726
|
const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
|
|
@@ -5664,7 +5741,8 @@ var init_postgrest = __esm({
|
|
|
5664
5741
|
} else if (method === "DELETE") {
|
|
5665
5742
|
sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
|
|
5666
5743
|
} else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
|
|
5667
|
-
const
|
|
5744
|
+
const result = await this.pool.query(sql, values);
|
|
5745
|
+
const rows2 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
|
|
5668
5746
|
const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
|
|
5669
5747
|
if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
|
|
5670
5748
|
if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
|
|
@@ -5680,6 +5758,296 @@ var init_postgrest = __esm({
|
|
|
5680
5758
|
}
|
|
5681
5759
|
});
|
|
5682
5760
|
|
|
5761
|
+
// src/runtime/gotrue.ts
|
|
5762
|
+
import { createHash as createHash6, createHmac, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
|
|
5763
|
+
var b64url, userIdFor, GoTrueLayer;
|
|
5764
|
+
var init_gotrue = __esm({
|
|
5765
|
+
"src/runtime/gotrue.ts"() {
|
|
5766
|
+
"use strict";
|
|
5767
|
+
b64url = (v) => Buffer.from(v).toString("base64url");
|
|
5768
|
+
userIdFor = (email) => {
|
|
5769
|
+
const h = createHash6("sha256").update(`agenttwin-user:${email.toLowerCase()}`).digest("hex");
|
|
5770
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
5771
|
+
};
|
|
5772
|
+
GoTrueLayer = class {
|
|
5773
|
+
constructor(secret = randomBytes2(32).toString("hex"), now = () => /* @__PURE__ */ new Date()) {
|
|
5774
|
+
this.secret = secret;
|
|
5775
|
+
this.now = now;
|
|
5776
|
+
}
|
|
5777
|
+
secret;
|
|
5778
|
+
now;
|
|
5779
|
+
users = /* @__PURE__ */ new Map();
|
|
5780
|
+
refresh = /* @__PURE__ */ new Map();
|
|
5781
|
+
/** Called when a user is created (sign-up, admin create); a returned message fails the call as GoTrue does. */
|
|
5782
|
+
onCreate;
|
|
5783
|
+
/** Users written so far, for the run's evidence. */
|
|
5784
|
+
list() {
|
|
5785
|
+
return [...this.users.values()].map(({ password: _p, ...u }) => u);
|
|
5786
|
+
}
|
|
5787
|
+
sign(claims) {
|
|
5788
|
+
const head = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" })), body = b64url(JSON.stringify(claims));
|
|
5789
|
+
return `${head}.${body}.${b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest())}`;
|
|
5790
|
+
}
|
|
5791
|
+
verify(token) {
|
|
5792
|
+
const [head, body, sig] = token.split(".");
|
|
5793
|
+
if (!head || !body || !sig) return void 0;
|
|
5794
|
+
if (b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
|
|
5795
|
+
try {
|
|
5796
|
+
const c = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
5797
|
+
return typeof c.exp === "number" && c.exp * 1e3 < this.now().getTime() ? void 0 : c;
|
|
5798
|
+
} catch {
|
|
5799
|
+
return void 0;
|
|
5800
|
+
}
|
|
5801
|
+
}
|
|
5802
|
+
create(email, password, meta = {}) {
|
|
5803
|
+
const at = this.now().toISOString(), id = userIdFor(email);
|
|
5804
|
+
const user = {
|
|
5805
|
+
id,
|
|
5806
|
+
aud: "authenticated",
|
|
5807
|
+
role: "authenticated",
|
|
5808
|
+
email,
|
|
5809
|
+
phone: "",
|
|
5810
|
+
email_confirmed_at: at,
|
|
5811
|
+
confirmed_at: at,
|
|
5812
|
+
last_sign_in_at: at,
|
|
5813
|
+
app_metadata: { provider: "email", providers: ["email"] },
|
|
5814
|
+
user_metadata: meta,
|
|
5815
|
+
identities: [],
|
|
5816
|
+
created_at: at,
|
|
5817
|
+
updated_at: at,
|
|
5818
|
+
is_anonymous: false,
|
|
5819
|
+
password
|
|
5820
|
+
};
|
|
5821
|
+
this.users.set(id, user);
|
|
5822
|
+
return user;
|
|
5823
|
+
}
|
|
5824
|
+
session(user) {
|
|
5825
|
+
const iat = Math.floor(this.now().getTime() / 1e3), expires_in = 3600;
|
|
5826
|
+
const refresh_token = randomUUID2().replace(/-/g, "");
|
|
5827
|
+
this.refresh.set(refresh_token, user.id);
|
|
5828
|
+
const { password: _p, ...publicUser } = user;
|
|
5829
|
+
const access_token = this.sign({
|
|
5830
|
+
aud: "authenticated",
|
|
5831
|
+
exp: iat + expires_in,
|
|
5832
|
+
iat,
|
|
5833
|
+
iss: "supabase",
|
|
5834
|
+
sub: user.id,
|
|
5835
|
+
email: user.email,
|
|
5836
|
+
phone: "",
|
|
5837
|
+
role: "authenticated",
|
|
5838
|
+
app_metadata: user.app_metadata,
|
|
5839
|
+
user_metadata: user.user_metadata,
|
|
5840
|
+
aal: "aal1",
|
|
5841
|
+
amr: [{ method: "password", timestamp: iat }],
|
|
5842
|
+
session_id: randomUUID2(),
|
|
5843
|
+
is_anonymous: false
|
|
5844
|
+
});
|
|
5845
|
+
return { access_token, token_type: "bearer", expires_in, expires_at: iat + expires_in, refresh_token, user: publicUser };
|
|
5846
|
+
}
|
|
5847
|
+
bearer(headers) {
|
|
5848
|
+
const raw = headers["x-agenttwin-app-authorization"] ?? headers.authorization;
|
|
5849
|
+
const v = Array.isArray(raw) ? raw[0] : raw;
|
|
5850
|
+
return v?.startsWith("Bearer ") ? v.slice(7) : void 0;
|
|
5851
|
+
}
|
|
5852
|
+
current(headers) {
|
|
5853
|
+
const token = this.bearer(headers);
|
|
5854
|
+
const claims = token ? this.verify(token) : void 0;
|
|
5855
|
+
return typeof claims?.sub === "string" ? this.users.get(claims.sub) : void 0;
|
|
5856
|
+
}
|
|
5857
|
+
/** Answer one /auth/v1 request; `write` says whether it changed users (for the run's events). */
|
|
5858
|
+
async handle(request) {
|
|
5859
|
+
const path = request.url.pathname.replace(/^\/auth\/v1/, "").replace(/\/$/, "") || "/";
|
|
5860
|
+
const method = request.method.toUpperCase();
|
|
5861
|
+
const reply = (status, value, write3) => ({ status, headers: { "content-type": "application/json" }, body: JSON.stringify(value), write: write3 });
|
|
5862
|
+
const fail = (status, error_code, msg2) => reply(status, { code: status, error_code, msg: msg2 });
|
|
5863
|
+
let body = {};
|
|
5864
|
+
try {
|
|
5865
|
+
if (request.body?.length) body = JSON.parse(request.body.toString("utf8"));
|
|
5866
|
+
} catch {
|
|
5867
|
+
return fail(400, "bad_json", "Could not parse request body as JSON");
|
|
5868
|
+
}
|
|
5869
|
+
const strip = (u) => {
|
|
5870
|
+
const { password: _p, ...rest } = u;
|
|
5871
|
+
return rest;
|
|
5872
|
+
};
|
|
5873
|
+
if (method === "GET" && path === "/health") return reply(200, { version: "agenttwin", name: "GoTrue", description: "GoTrue twin" });
|
|
5874
|
+
if (method === "GET" && path === "/settings") return reply(200, { external: { email: true, phone: false }, disable_signup: false, mailer_autoconfirm: true, phone_autoconfirm: false, sms_provider: "" });
|
|
5875
|
+
if (method === "GET" && path === "/.well-known/jwks.json") return reply(200, { keys: [] });
|
|
5876
|
+
if (method === "POST" && path === "/signup") {
|
|
5877
|
+
const email = String(body.email ?? "").trim().toLowerCase();
|
|
5878
|
+
if (!email) return fail(422, "validation_failed", "Signup requires a valid email");
|
|
5879
|
+
if (String(body.password ?? "").length < 6) return fail(422, "weak_password", "Password should be at least 6 characters.");
|
|
5880
|
+
if (this.users.has(userIdFor(email))) return fail(422, "user_already_exists", "User already registered");
|
|
5881
|
+
const user = this.create(email, String(body.password), body.data ?? body.options?.data ?? {});
|
|
5882
|
+
const refused = await this.onCreate?.(strip(user));
|
|
5883
|
+
if (refused) {
|
|
5884
|
+
this.users.delete(user.id);
|
|
5885
|
+
return fail(500, "unexpected_failure", `Database error saving new user: ${refused}`);
|
|
5886
|
+
}
|
|
5887
|
+
return reply(200, this.session(user), `signed up ${email}`);
|
|
5888
|
+
}
|
|
5889
|
+
if (method === "POST" && path === "/token") {
|
|
5890
|
+
const grant = request.url.searchParams.get("grant_type");
|
|
5891
|
+
if (grant === "password") {
|
|
5892
|
+
const user = this.users.get(userIdFor(String(body.email ?? "")));
|
|
5893
|
+
if (!user || user.password !== String(body.password ?? "")) return fail(400, "invalid_credentials", "Invalid login credentials");
|
|
5894
|
+
user.last_sign_in_at = this.now().toISOString();
|
|
5895
|
+
return reply(200, this.session(user), `signed in ${user.email}`);
|
|
5896
|
+
}
|
|
5897
|
+
if (grant === "refresh_token") {
|
|
5898
|
+
const id = this.refresh.get(String(body.refresh_token ?? ""));
|
|
5899
|
+
const user = id ? this.users.get(id) : void 0;
|
|
5900
|
+
if (!user) return fail(400, "refresh_token_not_found", "Invalid Refresh Token: Refresh Token Not Found");
|
|
5901
|
+
this.refresh.delete(String(body.refresh_token));
|
|
5902
|
+
return reply(200, this.session(user));
|
|
5903
|
+
}
|
|
5904
|
+
return fail(400, "unsupported_grant_type", `grant_type ${grant} is not supported by the AgentTwin Auth twin`);
|
|
5905
|
+
}
|
|
5906
|
+
if (path === "/user") {
|
|
5907
|
+
const user = this.current(request.headers);
|
|
5908
|
+
if (!user) return fail(403, "bad_jwt", "invalid JWT: unable to parse or verify signature, token is unverifiable");
|
|
5909
|
+
if (method === "GET") return reply(200, strip(user));
|
|
5910
|
+
if (method === "PUT") {
|
|
5911
|
+
if (body.email) user.email = String(body.email);
|
|
5912
|
+
if (body.password) user.password = String(body.password);
|
|
5913
|
+
if (body.data) user.user_metadata = { ...user.user_metadata, ...body.data };
|
|
5914
|
+
user.updated_at = this.now().toISOString();
|
|
5915
|
+
return reply(200, strip(user), `updated user ${user.id}`);
|
|
5916
|
+
}
|
|
5917
|
+
}
|
|
5918
|
+
if (method === "POST" && path === "/logout") return { status: 204, headers: {}, body: "" };
|
|
5919
|
+
if (path === "/admin/users" && method === "POST") {
|
|
5920
|
+
const email = String(body.email ?? "").trim().toLowerCase();
|
|
5921
|
+
if (!email) return fail(422, "validation_failed", "email is required");
|
|
5922
|
+
if (this.users.has(userIdFor(email))) return fail(422, "email_exists", "A user with this email address has already been registered");
|
|
5923
|
+
const user = this.create(email, body.password, body.user_metadata ?? {});
|
|
5924
|
+
const refused = await this.onCreate?.(strip(user));
|
|
5925
|
+
if (refused) {
|
|
5926
|
+
this.users.delete(user.id);
|
|
5927
|
+
return fail(500, "unexpected_failure", `Database error creating new user: ${refused}`);
|
|
5928
|
+
}
|
|
5929
|
+
return reply(200, strip(user), `created user ${email}`);
|
|
5930
|
+
}
|
|
5931
|
+
if (path === "/admin/users" && method === "GET") return reply(200, { users: this.list(), aud: "authenticated" });
|
|
5932
|
+
const one = /^\/admin\/users\/([^/]+)$/.exec(path);
|
|
5933
|
+
if (one) {
|
|
5934
|
+
const user = this.users.get(decodeURIComponent(one[1]));
|
|
5935
|
+
if (!user) return fail(404, "user_not_found", "User not found");
|
|
5936
|
+
if (method === "GET") return reply(200, strip(user));
|
|
5937
|
+
if (method === "DELETE") {
|
|
5938
|
+
this.users.delete(user.id);
|
|
5939
|
+
return reply(200, {}, `deleted user ${user.id}`);
|
|
5940
|
+
}
|
|
5941
|
+
if (method === "PUT") {
|
|
5942
|
+
if (body.user_metadata) user.user_metadata = { ...user.user_metadata, ...body.user_metadata };
|
|
5943
|
+
if (body.email) user.email = body.email;
|
|
5944
|
+
return reply(200, strip(user), `updated user ${user.id}`);
|
|
5945
|
+
}
|
|
5946
|
+
}
|
|
5947
|
+
return fail(501, "not_implemented", `AgentTwin Auth twin does not model ${method} /auth/v1${path}`);
|
|
5948
|
+
}
|
|
5949
|
+
};
|
|
5950
|
+
}
|
|
5951
|
+
});
|
|
5952
|
+
|
|
5953
|
+
// src/runtime/supabase-storage.ts
|
|
5954
|
+
var StorageLayer;
|
|
5955
|
+
var init_supabase_storage = __esm({
|
|
5956
|
+
"src/runtime/supabase-storage.ts"() {
|
|
5957
|
+
"use strict";
|
|
5958
|
+
StorageLayer = class {
|
|
5959
|
+
constructor(now = () => /* @__PURE__ */ new Date()) {
|
|
5960
|
+
this.now = now;
|
|
5961
|
+
}
|
|
5962
|
+
now;
|
|
5963
|
+
buckets = /* @__PURE__ */ new Map();
|
|
5964
|
+
objects = /* @__PURE__ */ new Map();
|
|
5965
|
+
key(bucket, name) {
|
|
5966
|
+
return `${bucket}/${name}`;
|
|
5967
|
+
}
|
|
5968
|
+
bucket(name, isPublic = false) {
|
|
5969
|
+
let b = this.buckets.get(name);
|
|
5970
|
+
if (!b) {
|
|
5971
|
+
b = { id: name, name, public: isPublic, created_at: this.now().toISOString() };
|
|
5972
|
+
this.buckets.set(name, b);
|
|
5973
|
+
}
|
|
5974
|
+
return b;
|
|
5975
|
+
}
|
|
5976
|
+
handle(request) {
|
|
5977
|
+
const path = decodeURIComponent(request.url.pathname.replace(/^\/storage\/v1/, ""));
|
|
5978
|
+
const method = request.method.toUpperCase();
|
|
5979
|
+
const reply = (status, value, write3, note) => ({ status, headers: { "content-type": "application/json" }, body: JSON.stringify(value), write: write3, note });
|
|
5980
|
+
const fail = (status, error, message) => reply(status, { statusCode: String(status), error, message });
|
|
5981
|
+
const json = () => {
|
|
5982
|
+
try {
|
|
5983
|
+
return request.body?.length ? JSON.parse(request.body.toString("utf8")) : {};
|
|
5984
|
+
} catch {
|
|
5985
|
+
return {};
|
|
5986
|
+
}
|
|
5987
|
+
};
|
|
5988
|
+
const header3 = (name) => {
|
|
5989
|
+
const v = request.headers[name];
|
|
5990
|
+
return Array.isArray(v) ? v[0] : v;
|
|
5991
|
+
};
|
|
5992
|
+
if (path === "/bucket" && method === "GET") return reply(200, [...this.buckets.values()]);
|
|
5993
|
+
if (path === "/bucket" && method === "POST") {
|
|
5994
|
+
const body = json();
|
|
5995
|
+
const name = String(body.name ?? body.id ?? "");
|
|
5996
|
+
if (!name) return fail(400, "invalid_request", "bucket name is required");
|
|
5997
|
+
if (this.buckets.has(name)) return fail(409, "Duplicate", "The resource already exists");
|
|
5998
|
+
this.bucket(name, !!body.public);
|
|
5999
|
+
return reply(200, { name }, `created bucket ${name}`);
|
|
6000
|
+
}
|
|
6001
|
+
const bucketOne = /^\/bucket\/([^/]+)$/.exec(path);
|
|
6002
|
+
if (bucketOne) {
|
|
6003
|
+
const b = this.buckets.get(bucketOne[1]);
|
|
6004
|
+
if (method === "GET") return b ? reply(200, b) : fail(404, "not_found", "Bucket not found");
|
|
6005
|
+
if (method === "DELETE") {
|
|
6006
|
+
this.buckets.delete(bucketOne[1]);
|
|
6007
|
+
return reply(200, { message: "Successfully deleted" }, `deleted bucket ${bucketOne[1]}`);
|
|
6008
|
+
}
|
|
6009
|
+
}
|
|
6010
|
+
const list2 = /^\/object\/list\/([^/]+)$/.exec(path);
|
|
6011
|
+
if (list2 && method === "POST") {
|
|
6012
|
+
const prefix = String(json().prefix ?? "");
|
|
6013
|
+
const items = [...this.objects.values()].filter((o) => o.bucket === list2[1] && o.name.startsWith(prefix ? `${prefix.replace(/\/$/, "")}/` : "")).map((o) => ({ name: o.name.slice(prefix ? prefix.replace(/\/$/, "").length + 1 : 0), id: this.key(o.bucket, o.name), created_at: o.created, metadata: { size: o.body.length, mimetype: o.type } }));
|
|
6014
|
+
return reply(200, items);
|
|
6015
|
+
}
|
|
6016
|
+
const sign = /^\/object\/sign\/([^/]+)\/(.+)$/.exec(path);
|
|
6017
|
+
if (sign && method === "POST") return reply(200, { signedURL: `/object/sign/${sign[1]}/${sign[2]}?token=agenttwin-signed` });
|
|
6018
|
+
if (method === "DELETE" && /^\/object\/([^/]+)$/.test(path)) {
|
|
6019
|
+
const bucket = path.split("/")[2];
|
|
6020
|
+
const names = json().prefixes ?? [];
|
|
6021
|
+
const gone = names.filter((n) => this.objects.delete(this.key(bucket, n)));
|
|
6022
|
+
return reply(200, gone.map((name) => ({ name, bucket_id: bucket })), gone.length ? `deleted ${gone.length} object(s) from ${bucket}` : void 0);
|
|
6023
|
+
}
|
|
6024
|
+
const obj = /^\/object\/(?:(?:authenticated|public|sign)\/)?([^/]+)\/(.+)$/.exec(path);
|
|
6025
|
+
if (obj) {
|
|
6026
|
+
const [, bucket, name] = obj;
|
|
6027
|
+
const k = this.key(bucket, name);
|
|
6028
|
+
if (method === "POST" || method === "PUT") {
|
|
6029
|
+
if (method === "POST" && this.objects.has(k) && header3("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
|
|
6030
|
+
this.bucket(bucket);
|
|
6031
|
+
this.objects.set(k, { bucket, name, type: header3("content-type")?.split(";")[0] ?? "application/octet-stream", body: request.body ?? Buffer.alloc(0), created: this.now().toISOString() });
|
|
6032
|
+
return reply(200, { Key: k, Id: k }, `uploaded ${k} (${request.body?.length ?? 0} bytes)`);
|
|
6033
|
+
}
|
|
6034
|
+
if (method === "GET" || method === "HEAD") {
|
|
6035
|
+
let o = this.objects.get(k), note;
|
|
6036
|
+
if (!o) {
|
|
6037
|
+
o = { bucket, name, type: /\.(json)$/i.test(name) ? "application/json" : "text/plain", body: Buffer.from(/\.json$/i.test(name) ? "{}" : "AgentTwin stand-in file\n"), created: this.now().toISOString(), standIn: true };
|
|
6038
|
+
this.bucket(bucket);
|
|
6039
|
+
this.objects.set(k, o);
|
|
6040
|
+
note = `stand-in object ${k}: no file was uploaded there in this run, so a small text file was served`;
|
|
6041
|
+
}
|
|
6042
|
+
return { status: 200, headers: { "content-type": o.type, "content-length": String(o.body.length) }, body: "", bytes: method === "HEAD" ? Buffer.alloc(0) : o.body, note };
|
|
6043
|
+
}
|
|
6044
|
+
}
|
|
6045
|
+
return fail(501, "not_implemented", `AgentTwin Storage twin does not model ${method} /storage/v1${path}`);
|
|
6046
|
+
}
|
|
6047
|
+
};
|
|
6048
|
+
}
|
|
6049
|
+
});
|
|
6050
|
+
|
|
5683
6051
|
// src/runtime/pack-log.ts
|
|
5684
6052
|
import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
|
|
5685
6053
|
import { join as join5 } from "path";
|
|
@@ -5702,8 +6070,9 @@ function seedActions(service, collections, at, tenant = {}) {
|
|
|
5702
6070
|
for (const c of collections) {
|
|
5703
6071
|
const last = c.path.split("/").filter(Boolean).pop() ?? "record", type = singular2(last.replace(/-/g, "_"));
|
|
5704
6072
|
c.seed.forEach((row, i) => {
|
|
5705
|
-
const
|
|
5706
|
-
const
|
|
6073
|
+
const numeric = typeof row.id === "number" && Number.isSafeInteger(row.id);
|
|
6074
|
+
const id = numeric ? String(row.id) : typeof row.id === "string" && row.id ? row.id : `${type}_seed_${i + 1}`;
|
|
6075
|
+
const fields = { ...tenant, ...numeric ? { id: row.id } : {}, ...Object.fromEntries(Object.entries(row).filter(([k]) => k !== "id")) };
|
|
5707
6076
|
lines.push(JSON.stringify({ id: `twin:${service}:${type}.create:${id}:${at}:seed${i + 1}`, service, op: "set", operation: `${type}.create`, subject: { type, id }, occurredAt: at, actor: { kind: "system" }, fields }));
|
|
5708
6077
|
});
|
|
5709
6078
|
}
|
|
@@ -5778,7 +6147,7 @@ var init_pack_aliases = __esm({
|
|
|
5778
6147
|
import { createServer as createServer3 } from "http";
|
|
5779
6148
|
import { createServer as createNetServer } from "net";
|
|
5780
6149
|
import { isDeepStrictEqual } from "util";
|
|
5781
|
-
import { createHash as
|
|
6150
|
+
import { createHash as createHash7 } from "crypto";
|
|
5782
6151
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
5783
6152
|
import { mkdir, mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile2 } from "fs/promises";
|
|
5784
6153
|
import { tmpdir as tmpdir3 } from "os";
|
|
@@ -5796,13 +6165,15 @@ var init_http_world = __esm({
|
|
|
5796
6165
|
init_enterprise_twins();
|
|
5797
6166
|
init_adapters();
|
|
5798
6167
|
init_postgrest();
|
|
6168
|
+
init_gotrue();
|
|
6169
|
+
init_supabase_storage();
|
|
5799
6170
|
init_packs();
|
|
5800
6171
|
init_pack_log();
|
|
5801
6172
|
init_pack_aliases();
|
|
5802
6173
|
init_compatible_packs();
|
|
5803
6174
|
KEYED_PACKS = /* @__PURE__ */ new Set(["resend"]);
|
|
5804
|
-
slackDirectMessageId = (user) => `D${
|
|
5805
|
-
idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${
|
|
6175
|
+
slackDirectMessageId = (user) => `D${createHash7("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
|
|
6176
|
+
idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash7("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
|
|
5806
6177
|
HttpWorld = class {
|
|
5807
6178
|
/** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
|
|
5808
6179
|
constructor(spec, seed, options = {}) {
|
|
@@ -5829,6 +6200,10 @@ var init_http_world = __esm({
|
|
|
5829
6200
|
replayKeys = /* @__PURE__ */ new Map();
|
|
5830
6201
|
sourceContext = new AsyncLocalStorage2();
|
|
5831
6202
|
postgrest;
|
|
6203
|
+
/** Supabase Auth (/auth/v1) for the run: the pack's auth lane is not modelled, so users and sessions live here. */
|
|
6204
|
+
gotrue;
|
|
6205
|
+
/** Supabase Storage (/storage/v1): objects uploaded and downloaded in this run. */
|
|
6206
|
+
storage;
|
|
5832
6207
|
/** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
|
|
5833
6208
|
attachDatabase(url) {
|
|
5834
6209
|
void this.postgrest?.close();
|
|
@@ -6209,6 +6584,12 @@ var init_http_world = __esm({
|
|
|
6209
6584
|
respond(result.status, result.body, headers(result));
|
|
6210
6585
|
}, fault.delayMs);
|
|
6211
6586
|
this.timers.add(timer);
|
|
6587
|
+
} else if (!this.fired && result.operation === "write" && fault?.type === "lost-reply" && fault.service === service.name && (fault.path === result.collection || matchesFault(normalPath(req.url ?? "/", req.method)))) {
|
|
6588
|
+
this.fired = true;
|
|
6589
|
+
this.faultActions++;
|
|
6590
|
+
this.record(service.name, "fault", result.collection, "write committed; reply lost (connection closed before the response)");
|
|
6591
|
+
this.keyed(keyHeader2);
|
|
6592
|
+
res.socket?.destroy();
|
|
6212
6593
|
} else respondSlowly(result.collection, result.operation ?? "request", result.status, result.body, headers(result));
|
|
6213
6594
|
if (deliveries.length) this.push(service.name, deliveries, epoch);
|
|
6214
6595
|
return;
|
|
@@ -6335,6 +6716,12 @@ var init_http_world = __esm({
|
|
|
6335
6716
|
respond(faultResponse, reply);
|
|
6336
6717
|
}, fault.delayMs);
|
|
6337
6718
|
this.timers.add(timer);
|
|
6719
|
+
} else if (!this.fired && fault?.type === "lost-reply" && fault.service === service.name && fault.path === path) {
|
|
6720
|
+
this.fired = true;
|
|
6721
|
+
this.faultActions++;
|
|
6722
|
+
this.record(service.name, "fault", path, "write committed; reply lost (connection closed before the response)");
|
|
6723
|
+
this.keyed(keyHeader);
|
|
6724
|
+
res.socket?.destroy();
|
|
6338
6725
|
} else respondSlowly(path, "write", faultResponse, reply);
|
|
6339
6726
|
} catch {
|
|
6340
6727
|
respond(500, { error: "world_request_error" });
|
|
@@ -6543,7 +6930,7 @@ var init_http_world = __esm({
|
|
|
6543
6930
|
return;
|
|
6544
6931
|
}
|
|
6545
6932
|
const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
|
|
6546
|
-
const again = { ...last.envelope, envelope_id:
|
|
6933
|
+
const again = { ...last.envelope, envelope_id: createHash7("sha256").update(`${String(last.envelope.envelope_id)}:${attempt}`).digest("hex").replace(/^(.{8})(.{4})(.{4})(.{4})(.{12}).*/, "$1-$2-$3-$4-$5"), retry_attempt: attempt, retry_reason: "timeout" };
|
|
6547
6934
|
last.send(JSON.stringify(again));
|
|
6548
6935
|
this.record(service.name, "twin", path, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
|
|
6549
6936
|
json(200, { ok: true, retry_attempt: attempt });
|
|
@@ -6589,6 +6976,26 @@ var init_http_world = __esm({
|
|
|
6589
6976
|
res.end(r.body);
|
|
6590
6977
|
return;
|
|
6591
6978
|
}
|
|
6979
|
+
if (name === "supabase" && path.startsWith("/auth/v1/")) {
|
|
6980
|
+
if (!this.gotrue) {
|
|
6981
|
+
this.gotrue = new GoTrueLayer();
|
|
6982
|
+
this.gotrue.onCreate = async (user) => this.postgrest?.addAuthUser(user);
|
|
6983
|
+
}
|
|
6984
|
+
const r = await this.gotrue.handle({ method, url, headers: req.headers, body });
|
|
6985
|
+
if (r.status === 501) this.rejectUnsupported(service.name, method, path, `supabase auth twin does not model ${method} ${path}`);
|
|
6986
|
+
else this.record(service.name, r.write ? "write" : r.status < 400 ? "read" : "rejected", path, r.write ?? `${method} ${path} \u2192 ${r.status}`);
|
|
6987
|
+
res.writeHead(r.status, r.headers);
|
|
6988
|
+
res.end(r.body);
|
|
6989
|
+
return;
|
|
6990
|
+
}
|
|
6991
|
+
if (name === "supabase" && path.startsWith("/storage/v1/")) {
|
|
6992
|
+
const r = (this.storage ??= new StorageLayer()).handle({ method, url, headers: req.headers, body });
|
|
6993
|
+
if (r.status === 501) this.rejectUnsupported(service.name, method, path, `supabase storage twin does not model ${method} ${path}`);
|
|
6994
|
+
else this.record(service.name, r.write ? "write" : r.status < 400 ? "read" : "rejected", path, r.write ?? r.note ?? `${method} ${path} \u2192 ${r.status}`);
|
|
6995
|
+
res.writeHead(r.status, r.headers);
|
|
6996
|
+
res.end(r.bytes ?? r.body);
|
|
6997
|
+
return;
|
|
6998
|
+
}
|
|
6592
6999
|
let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
|
|
6593
7000
|
if (name === "pinecone") {
|
|
6594
7001
|
const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
|
|
@@ -6676,6 +7083,12 @@ var init_http_world = __esm({
|
|
|
6676
7083
|
this.record(service.name, "fault", target, `write committed; response delayed ${fault.delayMs}ms`);
|
|
6677
7084
|
this.keyed(requestKey);
|
|
6678
7085
|
later(fault.delayMs, () => send(first.status, out, first.bytes));
|
|
7086
|
+
} else if (target && !this.fired && fault?.type === "lost-reply" && fault.service === service.name && (matchesFault(target) || matchesFault(path))) {
|
|
7087
|
+
this.fired = true;
|
|
7088
|
+
this.faultActions++;
|
|
7089
|
+
this.record(service.name, "fault", target, "write committed; reply lost (connection closed before the response)");
|
|
7090
|
+
this.keyed(requestKey);
|
|
7091
|
+
res.socket?.destroy();
|
|
6679
7092
|
} else if (fault?.type === "slow-response" && faultOrdinalsFor && (matchesFault(target ?? path) || matchesFault(path)) && faultOrdinalsFor.includes(this.candidateIndex(faultKey))) {
|
|
6680
7093
|
this.faultActions++;
|
|
6681
7094
|
this.record(service.name, "fault", target ?? path, `slow-response: ${target ? "write" : "request"} applied; response delayed ${fault.delayMs}ms`);
|
|
@@ -6792,6 +7205,8 @@ var init_http_world = __esm({
|
|
|
6792
7205
|
async close() {
|
|
6793
7206
|
await this.postgrest?.close();
|
|
6794
7207
|
this.postgrest = void 0;
|
|
7208
|
+
this.gotrue = void 0;
|
|
7209
|
+
this.storage = void 0;
|
|
6795
7210
|
this.epoch++;
|
|
6796
7211
|
for (const timer of this.timers) clearTimeout(timer);
|
|
6797
7212
|
this.timers.clear();
|
|
@@ -6837,6 +7252,31 @@ var init_node_options = __esm({
|
|
|
6837
7252
|
}
|
|
6838
7253
|
});
|
|
6839
7254
|
|
|
7255
|
+
// src/flow/setup.ts
|
|
7256
|
+
import { spawn as spawn2, spawnSync } from "child_process";
|
|
7257
|
+
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, readdirSync as readdirSync3 } from "fs";
|
|
7258
|
+
import { delimiter as delimiter2, join as join7, posix } from "path";
|
|
7259
|
+
var init_setup = __esm({
|
|
7260
|
+
"src/flow/setup.ts"() {
|
|
7261
|
+
"use strict";
|
|
7262
|
+
}
|
|
7263
|
+
});
|
|
7264
|
+
|
|
7265
|
+
// src/flow/node-runtime.ts
|
|
7266
|
+
import { spawnSync as spawnSync2 } from "child_process";
|
|
7267
|
+
import { createHash as createHash8 } from "crypto";
|
|
7268
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync3, renameSync, rmSync, writeFileSync } from "fs";
|
|
7269
|
+
import { homedir } from "os";
|
|
7270
|
+
import { delimiter as delimiter3, join as join8 } from "path";
|
|
7271
|
+
var chosen, appNode;
|
|
7272
|
+
var init_node_runtime = __esm({
|
|
7273
|
+
"src/flow/node-runtime.ts"() {
|
|
7274
|
+
"use strict";
|
|
7275
|
+
init_setup();
|
|
7276
|
+
appNode = () => chosen ?? process.execPath;
|
|
7277
|
+
}
|
|
7278
|
+
});
|
|
7279
|
+
|
|
6840
7280
|
// src/runtime/application-process.ts
|
|
6841
7281
|
import { execFile as execFile2 } from "child_process";
|
|
6842
7282
|
import { promisify as promisify2 } from "util";
|
|
@@ -6975,12 +7415,12 @@ var init_application_process = __esm({
|
|
|
6975
7415
|
});
|
|
6976
7416
|
|
|
6977
7417
|
// src/runtime/browser-process-windows.ts
|
|
6978
|
-
import { randomUUID as
|
|
7418
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
6979
7419
|
import { execFile as execFile3 } from "child_process";
|
|
6980
7420
|
import { promisify as promisify3 } from "util";
|
|
6981
7421
|
import { win32 as win322 } from "path";
|
|
6982
7422
|
function windowsBrowserProcess(executable, commands = run) {
|
|
6983
|
-
const marker = "--agenttwin-browser-owner=" +
|
|
7423
|
+
const marker = "--agenttwin-browser-owner=" + randomUUID3();
|
|
6984
7424
|
const system = process.env.SystemRoot || process.env.SYSTEMROOT || "C:\\Windows";
|
|
6985
7425
|
const powershell = win322.join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
6986
7426
|
const taskkill = win322.join(system, "System32", "taskkill.exe");
|
|
@@ -7042,14 +7482,14 @@ var init_browser_process_windows = __esm({
|
|
|
7042
7482
|
// src/runtime/browser-process.ts
|
|
7043
7483
|
import { mkdtemp as mkdtemp4, writeFile as writeFile4, readFile, rm as rm4 } from "fs/promises";
|
|
7044
7484
|
import { tmpdir as tmpdir4 } from "os";
|
|
7045
|
-
import { join as
|
|
7485
|
+
import { join as join9 } from "path";
|
|
7046
7486
|
import { execFile as execFile4 } from "child_process";
|
|
7047
7487
|
import { promisify as promisify4 } from "util";
|
|
7048
7488
|
async function ownBrowserProcess(executable) {
|
|
7049
7489
|
if (process.platform === "win32") return withCleanup(windowsBrowserProcess(executable), async () => {
|
|
7050
7490
|
});
|
|
7051
|
-
const root = await mkdtemp4(
|
|
7052
|
-
const pidFile =
|
|
7491
|
+
const root = await mkdtemp4(join9(tmpdir4(), "agenttwin-browser-owner-"));
|
|
7492
|
+
const pidFile = join9(root, "pid"), launcher = join9(root, "launch");
|
|
7053
7493
|
await writeFile4(launcher, `#!/bin/sh
|
|
7054
7494
|
echo $$ > ${quote(pidFile)}
|
|
7055
7495
|
exec ${quote(executable)} "$@"
|
|
@@ -7151,11 +7591,11 @@ var init_browser_process = __esm({
|
|
|
7151
7591
|
// src/runtime/browser-directories.ts
|
|
7152
7592
|
import { mkdtemp as mkdtemp5, mkdir as mkdir2, chown, chmod, rm as rm5 } from "fs/promises";
|
|
7153
7593
|
import { tmpdir as tmpdir5 } from "os";
|
|
7154
|
-
import { join as
|
|
7594
|
+
import { join as join10 } from "path";
|
|
7155
7595
|
async function createBrowserDirectories(identity) {
|
|
7156
7596
|
if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
|
|
7157
|
-
const root = await mkdtemp5(
|
|
7158
|
-
const profile =
|
|
7597
|
+
const root = await mkdtemp5(join10(tmpdir5(), "agenttwin-browser-"));
|
|
7598
|
+
const profile = join10(root, "profile"), artifacts = join10(root, "artifacts");
|
|
7159
7599
|
const close = () => rm5(root, { recursive: true, force: true });
|
|
7160
7600
|
try {
|
|
7161
7601
|
await mkdir2(profile, { mode: 448 });
|
|
@@ -7782,7 +8222,7 @@ var init_contracts = __esm({
|
|
|
7782
8222
|
|
|
7783
8223
|
// src/runtime/cost-model.ts
|
|
7784
8224
|
import { readFile as readFile2, writeFile as writeFile5 } from "fs/promises";
|
|
7785
|
-
import { join as
|
|
8225
|
+
import { join as join11 } from "path";
|
|
7786
8226
|
var init_cost_model = __esm({
|
|
7787
8227
|
"src/runtime/cost-model.ts"() {
|
|
7788
8228
|
"use strict";
|
|
@@ -7800,7 +8240,7 @@ var init_run_summary = __esm({
|
|
|
7800
8240
|
});
|
|
7801
8241
|
|
|
7802
8242
|
// src/runtime/generic-calls.ts
|
|
7803
|
-
import { createHash as
|
|
8243
|
+
import { createHash as createHash9 } from "crypto";
|
|
7804
8244
|
function canonical2(value) {
|
|
7805
8245
|
return Array.isArray(value) ? `[${value.map(canonical2).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical2(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
|
|
7806
8246
|
}
|
|
@@ -7876,7 +8316,10 @@ function callsFromWorldEvents(events, tierOf = () => void 0) {
|
|
|
7876
8316
|
else if (e.operation === "auth-denied") calls.push(base("POST", e.path.split("?")[0], { outcome: "unauthorized", committed: false }));
|
|
7877
8317
|
else if (e.operation === "fault") {
|
|
7878
8318
|
const prior = last(e.service), method = /\((POST|PUT|PATCH|DELETE|GET)\)\s*$/.exec(e.detail)?.[1];
|
|
7879
|
-
if (/^write committed
|
|
8319
|
+
if (/^write committed; reply lost/.test(e.detail) && prior) {
|
|
8320
|
+
prior.outcome = "lost-response";
|
|
8321
|
+
prior.committed = true;
|
|
8322
|
+
} else if (/^write committed|^slow-response: write/.test(e.detail) && prior) {
|
|
7880
8323
|
prior.outcome = "timeout";
|
|
7881
8324
|
prior.committed = true;
|
|
7882
8325
|
} else if (/^duplicate-write: (one write committed as two|a single write was delivered twice)/.test(e.detail) && prior) prior.duplicated = true;
|
|
@@ -7932,7 +8375,7 @@ function faultWords(c) {
|
|
|
7932
8375
|
}
|
|
7933
8376
|
function genericChecks(calls, opts = {}) {
|
|
7934
8377
|
const out = [], covered = opts.covered ?? (() => false);
|
|
7935
|
-
const ordered = [...calls].sort((a, b) => a.sequence - b.sequence), writes = ordered.filter((c) => c.isWrite && c.outcome !== "blocked");
|
|
8378
|
+
const ordered = [...calls].sort((a, b) => a.sequence - b.sequence), writes = ordered.filter((c) => c.isWrite && c.outcome !== "blocked" && !TWIN_CONTROL.test(c.path));
|
|
7936
8379
|
const claims = opts.claims ?? claimsOf(ordered, opts.output);
|
|
7937
8380
|
const announcementSeqs = new Set(claims.map((c) => c.via).filter((v) => v !== void 0));
|
|
7938
8381
|
for (const group of groupsOf(writes)) {
|
|
@@ -8076,7 +8519,7 @@ function genericWorldChecks(covers) {
|
|
|
8076
8519
|
}
|
|
8077
8520
|
}));
|
|
8078
8521
|
}
|
|
8079
|
-
var WRITE_METHODS, READ_LIKE, MODEL_HOST, VOLATILE, KEY_HEADERS, KEY_FIELDS, digest, stable, idLike, outcomeOf, parseSource, SUCCESS, FAILURE, TEXT_FIELDS, MESSAGING, polarityOf, RECIPIENT, isAnnouncement, AMOUNT, times, FAILED, AMBIGUOUS, label, sameRequest, succeeded, effects, sites, groupsOf, GENERIC_TITLES;
|
|
8522
|
+
var WRITE_METHODS, READ_LIKE, MODEL_HOST, VOLATILE, KEY_HEADERS, KEY_FIELDS, digest, stable, idLike, outcomeOf, parseSource, SUCCESS, FAILURE, TEXT_FIELDS, MESSAGING, polarityOf, RECIPIENT, isAnnouncement, AMOUNT, times, FAILED, AMBIGUOUS, label, sameRequest, succeeded, effects, sites, TWIN_CONTROL, groupsOf, GENERIC_TITLES;
|
|
8080
8523
|
var init_generic_calls = __esm({
|
|
8081
8524
|
"src/runtime/generic-calls.ts"() {
|
|
8082
8525
|
"use strict";
|
|
@@ -8087,7 +8530,7 @@ var init_generic_calls = __esm({
|
|
|
8087
8530
|
VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
|
|
8088
8531
|
KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
|
|
8089
8532
|
KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
|
|
8090
|
-
digest = (value) => `sha256:${
|
|
8533
|
+
digest = (value) => `sha256:${createHash9("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
|
|
8091
8534
|
stable = (value) => Array.isArray(value) ? value.map(stable) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter(([k]) => !VOLATILE.test(k) && !KEY_FIELDS.test(k)).map(([k, v]) => [k, stable(v)])) : value;
|
|
8092
8535
|
idLike = (segment) => /^\d+$/.test(segment) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || segment.length >= 3 && /\d/.test(segment) && /^[A-Za-z0-9_\-:.]+$/.test(segment) && !/^v\d+(\.\d+)*$/i.test(segment) && !/^\d{4}-\d{2}-\d{2}$/.test(segment) && !/^[A-Za-z]+\.(json|xml)$/.test(segment);
|
|
8093
8536
|
outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
|
|
@@ -8117,6 +8560,7 @@ var init_generic_calls = __esm({
|
|
|
8117
8560
|
succeeded = (c) => c.outcome === "ok" || c.outcome === "replayed";
|
|
8118
8561
|
effects = (c) => c.committed === false || c.outcome === "replayed" || c.outcome === "blocked" ? 0 : (c.committed || c.outcome === "ok" ? 1 : 0) * (c.duplicated ? 2 : 1);
|
|
8119
8562
|
sites = (calls) => [...new Map(calls.filter((c) => c.source).map((c) => [`${c.source.file}:${c.source.line}`, c.source])).values()];
|
|
8563
|
+
TWIN_CONTROL = /(^|\/)_twin\//;
|
|
8120
8564
|
groupsOf = (writes) => {
|
|
8121
8565
|
const groups2 = [];
|
|
8122
8566
|
for (const c of writes) {
|
|
@@ -8162,12 +8606,17 @@ function groups(items, key2) {
|
|
|
8162
8606
|
}
|
|
8163
8607
|
return [...out.values()].filter((g) => g.length > 1);
|
|
8164
8608
|
}
|
|
8165
|
-
function faultPhrase(ctx) {
|
|
8609
|
+
function faultPhrase(ctx, evidence) {
|
|
8166
8610
|
if (ctx.duplicateDelivery) return " when the triggering webhook was delivered twice";
|
|
8167
8611
|
const f = ctx.fault;
|
|
8168
|
-
|
|
8612
|
+
const faults = ctx.events.filter((e) => e.operation === "fault" && (!f?.service || e.service === f.service)).map((e) => e.sequence);
|
|
8613
|
+
if (!f || f.triggered === false || !faults.length) return "";
|
|
8614
|
+
if (evidence?.length) {
|
|
8615
|
+
const caused = f.type === "duplicate-write" ? faults.some((at) => evidence.some((w) => w < at)) : faults.some((at) => evidence.some((w) => w > at) && (!(f.type === "timeout-after-write" || f.type === "lost-reply" || f.type === "slow-response") || evidence.some((w) => w < at)));
|
|
8616
|
+
if (!caused) return "";
|
|
8617
|
+
}
|
|
8169
8618
|
const who = displayName(ctx.services, f.service);
|
|
8170
|
-
return f.type === "timeout-after-write" ? ` when ${who} timed out after saving the write` : f.type === "server-error" ? ` when ${who} returned a 500` : f.type === "slow-response" ? ` when ${who} answered slower than your client timeout` : f.type === "blackhole" ? ` when ${who} dropped a request` : f.type === "duplicate-write" ? ` when ${who} received the same request twice` : ` when ${who} failed`;
|
|
8619
|
+
return f.type === "timeout-after-write" ? ` when ${who} timed out after saving the write` : f.type === "lost-reply" ? ` when ${who} saved the write and the connection closed before the reply` : f.type === "server-error" ? ` when ${who} returned a 500` : f.type === "slow-response" ? ` when ${who} answered slower than your client timeout` : f.type === "blackhole" ? ` when ${who} dropped a request` : f.type === "duplicate-write" ? ` when ${who} received the same request twice` : ` when ${who} failed`;
|
|
8171
8620
|
}
|
|
8172
8621
|
function messageChecks(adapter, path) {
|
|
8173
8622
|
const noun = adapter === "slack" ? "Slack message" : "email", name = PROVIDER[adapter];
|
|
@@ -8187,7 +8636,7 @@ function messageChecks(adapter, path) {
|
|
|
8187
8636
|
return groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), signature).map((group) => ({
|
|
8188
8637
|
path,
|
|
8189
8638
|
actual: { messages: group.map((r) => r.id), to: target(group[0]), text: text2(group[0]).slice(0, 200) },
|
|
8190
|
-
finding: `Your agent sent the same ${noun} to ${target(group[0])} ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
8639
|
+
finding: `Your agent sent the same ${noun} to ${target(group[0])} ${times2(group.length)}${faultPhrase(ctx, writeSequences(ctx, s, group.map((r) => r.id)))}`,
|
|
8191
8640
|
impact: { count: group.length - 1 },
|
|
8192
8641
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
8193
8642
|
}));
|
|
@@ -8262,7 +8711,7 @@ var init_default_checks = __esm({
|
|
|
8262
8711
|
};
|
|
8263
8712
|
rowsOf = (state, service, path) => (state?.[service]?.[path] ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
|
|
8264
8713
|
VOLATILE2 = /* @__PURE__ */ new Set(["id", "ts", "created", "created_at", "updated_at", "inserted_at", "createdAt", "updatedAt", "internalDate", "historyId", "threadId", "number", "iid", "latest_charge", "object", "sequence", "uuid"]);
|
|
8265
|
-
volatileKey = (key2) => VOLATILE2.has(key2) || /_at$|At$/.test(key2) || /^(?:sid|guid|etag|uri|self|href)$/i.test(key2) || /^date_|_date$|^(?:created|updated|modified|sent)(?:_on|_time|_date)?$/i.test(key2) || /^(?:ending|starting|running|resulting)_?balance$|^balance_?after$/i.test(key2);
|
|
8714
|
+
volatileKey = (key2) => VOLATILE2.has(key2) || /_at$|At$/.test(key2) || /^(?:sid|guid|etag|uri|self|href)$/i.test(key2) || /^date$|^date_|_date$|^(?:created|updated|modified|sent)(?:_on|_time|_date)?$/i.test(key2) || /^(?:ending|starting|running|resulting)_?balance$|^balance_?after$/i.test(key2);
|
|
8266
8715
|
canonical3 = (value) => Array.isArray(value) ? `[${value.map(canonical3).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical3(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
|
|
8267
8716
|
contentSignature = (row, collection) => {
|
|
8268
8717
|
const type = (collection?.split("/").filter(Boolean).pop() ?? "").toLowerCase().replace(/[^a-z]/g, "").replace(/ies$/, "y").replace(/s$/, "");
|
|
@@ -8290,7 +8739,7 @@ var init_default_checks = __esm({
|
|
|
8290
8739
|
out.push({
|
|
8291
8740
|
path: "/v1/refunds",
|
|
8292
8741
|
actual: { charge: group[0].charge, refunds: group.map((r) => r.id), amount, currency },
|
|
8293
|
-
finding: `Your agent refunded ${String(group[0].charge)} ${times2(group.length)} (${money(amount, currency)} each)${faultPhrase(ctx)}`,
|
|
8742
|
+
finding: `Your agent refunded ${String(group[0].charge)} ${times2(group.length)} (${money(amount, currency)} each)${faultPhrase(ctx, writeSequences(ctx, s, group.map((r) => r.id)))}`,
|
|
8294
8743
|
impact: { amount: extra, currency, count: group.length - 1 },
|
|
8295
8744
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
8296
8745
|
});
|
|
@@ -8325,7 +8774,7 @@ var init_default_checks = __esm({
|
|
|
8325
8774
|
out.push({
|
|
8326
8775
|
path: "/v1/payment_intents",
|
|
8327
8776
|
actual: { paymentIntents: group.map((r) => r.id), amount, currency, succeeded: succeeded2.length },
|
|
8328
|
-
finding: `Your agent created ${times2(group.length)} the same ${money(amount, currency)} payment${group[0].customer ? ` for ${String(group[0].customer)}` : ""}${faultPhrase(ctx)}`,
|
|
8777
|
+
finding: `Your agent created ${times2(group.length)} the same ${money(amount, currency)} payment${group[0].customer ? ` for ${String(group[0].customer)}` : ""}${faultPhrase(ctx, writeSequences(ctx, s, group.map((r) => r.id)))}`,
|
|
8329
8778
|
impact: { amount: amount * Math.max(0, succeeded2.length - 1), currency, count: group.length - 1 },
|
|
8330
8779
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
8331
8780
|
});
|
|
@@ -8338,7 +8787,7 @@ var init_default_checks = __esm({
|
|
|
8338
8787
|
out.push({
|
|
8339
8788
|
path: "/v1/subscriptions",
|
|
8340
8789
|
actual: { subscriptions: group.map((r) => r.id), customer: group[0].customer },
|
|
8341
|
-
finding: `Your agent subscribed ${String(group[0].customer)} ${times2(group.length)} to the same plan${faultPhrase(ctx)}`,
|
|
8790
|
+
finding: `Your agent subscribed ${String(group[0].customer)} ${times2(group.length)} to the same plan${faultPhrase(ctx, writeSequences(ctx, s, group.map((r) => r.id)))}`,
|
|
8342
8791
|
impact: perPeriod > 0 ? { amount: perPeriod * (group.length - 1), currency, count: group.length - 1, summary: `billed ${money(perPeriod, currency)} extra every billing period` } : { kind: "data-integrity", count: group.length - 1 },
|
|
8343
8792
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
8344
8793
|
});
|
|
@@ -8348,7 +8797,7 @@ var init_default_checks = __esm({
|
|
|
8348
8797
|
out.push({
|
|
8349
8798
|
path: "/v1/customers",
|
|
8350
8799
|
actual: { customers: group.map((r) => r.id), email: group[0].email },
|
|
8351
|
-
finding: `Your agent created ${times2(group.length)} the Stripe customer ${String(group[0].email)}${faultPhrase(ctx)}`,
|
|
8800
|
+
finding: `Your agent created ${times2(group.length)} the Stripe customer ${String(group[0].email)}${faultPhrase(ctx, writeSequences(ctx, s, group.map((r) => r.id)))}`,
|
|
8352
8801
|
impact: { kind: "data-integrity", count: group.length - 1 },
|
|
8353
8802
|
evidence: writeSequences(ctx, s, group.map((r) => r.id))
|
|
8354
8803
|
});
|
|
@@ -8506,7 +8955,7 @@ var init_default_checks = __esm({
|
|
|
8506
8955
|
out.push({
|
|
8507
8956
|
path,
|
|
8508
8957
|
actual: { records: group.map((r) => r.id ?? null), count: group.length },
|
|
8509
|
-
finding: `Your agent created the same ${s} ${label2.replace(/s$/, "")} ${times2(group.length)}${faultPhrase(ctx)}`,
|
|
8958
|
+
finding: `Your agent created the same ${s} ${label2.replace(/s$/, "")} ${times2(group.length)}${faultPhrase(ctx, seq)}`,
|
|
8510
8959
|
impact: { count: group.length - 1 },
|
|
8511
8960
|
evidence: seq
|
|
8512
8961
|
});
|
|
@@ -8534,7 +8983,7 @@ import { execFile as execFile5 } from "child_process";
|
|
|
8534
8983
|
import { mkdtemp as mkdtemp6, readFile as readFile3, rm as rm6, writeFile as writeFile6 } from "fs/promises";
|
|
8535
8984
|
import { createServer as createServer4, request as httpRequest } from "http";
|
|
8536
8985
|
import { tmpdir as tmpdir6 } from "os";
|
|
8537
|
-
import { join as
|
|
8986
|
+
import { join as join12 } from "path";
|
|
8538
8987
|
import { createSecureContext, TLSSocket } from "tls";
|
|
8539
8988
|
import { promisify as promisify5 } from "util";
|
|
8540
8989
|
function matchRoute(routes2, host, pathname) {
|
|
@@ -8559,7 +9008,7 @@ function rewrite(r, p) {
|
|
|
8559
9008
|
return p;
|
|
8560
9009
|
}
|
|
8561
9010
|
async function runAuthority(dir) {
|
|
8562
|
-
const ca = { key:
|
|
9011
|
+
const ca = { key: join12(dir, "ca.key"), cert: join12(dir, "ca.pem") };
|
|
8563
9012
|
await run2("openssl", [
|
|
8564
9013
|
"req",
|
|
8565
9014
|
"-x509",
|
|
@@ -8590,7 +9039,7 @@ async function runAuthority(dir) {
|
|
|
8590
9039
|
let ctx = contexts.get(host);
|
|
8591
9040
|
if (!ctx) {
|
|
8592
9041
|
ctx = (async () => {
|
|
8593
|
-
const base =
|
|
9042
|
+
const base = join12(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
|
|
8594
9043
|
await writeFile6(base + ".ext", `basicConstraints=critical,CA:FALSE
|
|
8595
9044
|
keyUsage=critical,digitalSignature
|
|
8596
9045
|
extendedKeyUsage=serverAuth
|
|
@@ -8609,7 +9058,7 @@ authorityKeyIdentifier=keyid,issuer
|
|
|
8609
9058
|
};
|
|
8610
9059
|
}
|
|
8611
9060
|
async function startTwinProxy(routes2) {
|
|
8612
|
-
const dir = await mkdtemp6(
|
|
9061
|
+
const dir = await mkdtemp6(join12(tmpdir6(), "agenttwin-proxy-"));
|
|
8613
9062
|
const authority = await runAuthority(dir).catch((error) => {
|
|
8614
9063
|
throw new Error(`The twin proxy needs the openssl command to make this run's certificate authority: ${error instanceof Error ? error.message : error}`);
|
|
8615
9064
|
});
|
|
@@ -8630,7 +9079,7 @@ async function startTwinProxy(routes2) {
|
|
|
8630
9079
|
const headers = {};
|
|
8631
9080
|
const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
|
|
8632
9081
|
for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
|
|
8633
|
-
if (
|
|
9082
|
+
if (typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
|
|
8634
9083
|
if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
|
|
8635
9084
|
else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
|
|
8636
9085
|
else headers.authorization = `Bearer ${route.token}`;
|
|
@@ -8728,7 +9177,7 @@ var init_twin_proxy = __esm({
|
|
|
8728
9177
|
// src/runtime/twin-routing.ts
|
|
8729
9178
|
import { mkdtemp as mkdtemp7, readFile as readFile4, rm as rm7, writeFile as writeFile7 } from "fs/promises";
|
|
8730
9179
|
import { tmpdir as tmpdir7 } from "os";
|
|
8731
|
-
import { join as
|
|
9180
|
+
import { join as join13 } from "path";
|
|
8732
9181
|
function twinRoutes(services, world, models) {
|
|
8733
9182
|
const routes2 = [];
|
|
8734
9183
|
for (const service of services) {
|
|
@@ -8810,16 +9259,25 @@ const removed=r=>r.auth==='passthrough'?['host']:SECRET;
|
|
|
8810
9259
|
// AbortSignal.timeout is what makes a lost reply turn into a retry, so it must never be lost on the way to a twin.
|
|
8811
9260
|
function abortable(signal,promise){if(!signal)return promise;if(signal.aborted)return Promise.reject(signal.reason);return new Promise((resolve,reject)=>{const stop=()=>reject(signal.reason);signal.addEventListener('abort',stop,{once:true});promise.then(v=>{signal.removeEventListener('abort',stop);resolve(v);},e=>{signal.removeEventListener('abort',stop);reject(e);});});}
|
|
8812
9261
|
const originalFetch=globalThis.fetch;
|
|
9262
|
+
// A Google Fonts stylesheet for the families a request names, each marked latin (next/font keeps the subsets it asked for).
|
|
9263
|
+
const fontBody=(host,pathAndQuery)=>{
|
|
9264
|
+
if(!/googleapis/.test(host))return '';
|
|
9265
|
+
const query=new URLSearchParams(String(pathAndQuery).split('?')[1]||'');
|
|
9266
|
+
const families=query.getAll('family').map(f=>f.split(':')[0].replace(/\+/g,' ')).filter(Boolean);
|
|
9267
|
+
return (families.length?families:['Inter']).map(f=>'/* latin */\n@font-face {\n font-family: \''+f+'\';\n font-style: normal;\n font-weight: 400;\n font-display: swap;\n src: url(https://fonts.gstatic.com/s/agenttwin/v1/'+encodeURIComponent(f)+'.woff2) format(\'woff2\');\n unicode-range: U+0000-00FF;\n}\n').join('');
|
|
9268
|
+
};
|
|
8813
9269
|
if(originalFetch)globalThis.fetch=async function(input,init){
|
|
8814
9270
|
let url;try{url=new URL(typeof input==='string'||input instanceof URL?String(input):input.url);}catch{return originalFetch(input,init);}
|
|
8815
9271
|
if((url.protocol!=='http:'&&url.protocol!=='https:')||loopback(url.hostname))return originalFetch(input,init);
|
|
8816
9272
|
const method=String(init?.method||input?.method||'GET').toUpperCase(),r=match(url.hostname,url.pathname);
|
|
8817
|
-
// Web fonts a framework downloads while it renders (next/font):
|
|
8818
|
-
|
|
9273
|
+
// Web fonts a framework downloads while it renders (next/font): a stylesheet naming the fonts asked for and an empty
|
|
9274
|
+
// font file, so rendering goes on offline (an empty stylesheet is an error to next/font).
|
|
9275
|
+
if(!r&&/^fonts\.(googleapis|gstatic)\.com$/.test(bare(url.hostname)))return new Response(fontBody(url.hostname,url.pathname+url.search),{status:200,headers:{'content-type':/googleapis/.test(url.hostname)?'text/css':'font/woff2'}});
|
|
8819
9276
|
if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
|
|
8820
9277
|
if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
|
|
8821
9278
|
const request=new Request(input,init),headers=new Headers(request.headers);
|
|
8822
|
-
|
|
9279
|
+
// The app's own bearer token (a twin-issued key, a signed-in user's session) travels beside the twin credential.
|
|
9280
|
+
{const own=headers.get('authorization');if(own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
|
|
8823
9281
|
for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
|
|
8824
9282
|
headers.set('x-agenttwin-original-host',url.hostname);const location=source();if(location)headers.set('x-agenttwin-source',location);
|
|
8825
9283
|
// Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
|
|
@@ -8837,15 +9295,25 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
|
|
|
8837
9295
|
const callback=args.find(a=>typeof a==='function');
|
|
8838
9296
|
if(options.socketPath)return original.apply(this,args);
|
|
8839
9297
|
const host=url?url.hostname:(options.hostname||String(options.host||'localhost').replace(/:\d+$/,''));
|
|
9298
|
+
// Postgres over a secure WebSocket to this machine (Neon's serverless driver opens wss://<db host>/v2): the run's
|
|
9299
|
+
// database engine answers the upgrade on its own port, unencrypted, so the driver's frames reach it.
|
|
9300
|
+
if(scheme==='https'&&loopback(host)&&process.env.PGPORT){
|
|
9301
|
+
const h=Array.isArray(options.headers)?{}:(options.headers||{}),wsPath=String(options.path||(url?url.pathname+url.search:'/')),port=Number(options.port||url?.port||443);
|
|
9302
|
+
if(Object.entries(h).some(([k,v])=>k.toLowerCase()==='upgrade'&&/websocket/i.test(String(v)))&&/^\/v\d+(\/|\?|$)/.test(wsPath)&&(port===443||port===Number(process.env.PGPORT))){
|
|
9303
|
+
const {agent:_a,protocol:_p,createConnection:_c,_defaultAgent:_d,...plain}=options;
|
|
9304
|
+
return originalHttpRequest({...plain,protocol:'http:',host:'127.0.0.1',hostname:'127.0.0.1',port:Number(process.env.PGPORT),path:wsPath},callback);
|
|
9305
|
+
}
|
|
9306
|
+
}
|
|
8840
9307
|
if(loopback(host))return original.apply(this,args);
|
|
8841
9308
|
const method=String(options.method||'GET').toUpperCase(),requestPath=options.path||(url?url.pathname+url.search:'/');
|
|
8842
9309
|
const r=match(host,String(requestPath).split('?')[0]);
|
|
8843
9310
|
// Web fonts (next/font) over http(s): an empty answer from an in-memory socket, so rendering goes on offline.
|
|
8844
9311
|
if(!r&&/^fonts\.(googleapis|gstatic)\.com$/.test(bare(host))){
|
|
8845
|
-
const {Duplex}=require('node:stream'),type=/googleapis/.test(host)?'text/css':'font/woff2';let sent=false;
|
|
8846
|
-
const socket=new Duplex({read(){},write(chunk,enc,done){if(!sent&&/\r\n\r\n/.test(String(chunk))){sent=true;this.push('HTTP/1.1 200 OK\r\nContent-Type: '+type+'\r\nContent-Length:
|
|
9312
|
+
const {Duplex}=require('node:stream'),type=/googleapis/.test(host)?'text/css':'font/woff2',body=Buffer.from(fontBody(host,requestPath));let sent=false;
|
|
9313
|
+
const socket=new Duplex({read(){},write(chunk,enc,done){if(!sent&&/\r\n\r\n/.test(String(chunk))){sent=true;this.push('HTTP/1.1 200 OK\r\nContent-Type: '+type+'\r\nContent-Length: '+body.length+'\r\nConnection: close\r\n\r\n');if(body.length)this.push(body);this.push(null);}done();}});
|
|
8847
9314
|
socket.setTimeout=()=>socket;socket.setNoDelay=()=>socket;socket.setKeepAlive=()=>socket;socket.ref=()=>socket;socket.unref=()=>socket;
|
|
8848
|
-
|
|
9315
|
+
// The answer comes from memory over plain HTTP: drop the https agent and protocol the client asked for.
|
|
9316
|
+
const {agent:_a,protocol:_p,...plain}=options;
|
|
8849
9317
|
const req=originalHttpRequest({...plain,method,path:requestPath,host:'127.0.0.1',port:9,createConnection:()=>socket},callback);
|
|
8850
9318
|
return req;
|
|
8851
9319
|
}
|
|
@@ -8854,7 +9322,7 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
|
|
|
8854
9322
|
const given=options.headers||{};
|
|
8855
9323
|
for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
|
|
8856
9324
|
// The app's own credential travels beside the run token: a pack host keeps it when the twin issued it (an app-level token).
|
|
8857
|
-
|
|
9325
|
+
{const own=Array.isArray(given)?undefined:Object.entries(given).find(([k])=>k.toLowerCase()==='authorization')?.[1];if(typeof own==='string'&&/^Bearer \S{12,}$/.test(own))headers['x-agenttwin-app-authorization']=own;}
|
|
8858
9326
|
const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
|
|
8859
9327
|
const location=source();if(location)headers['x-agenttwin-source']=location;
|
|
8860
9328
|
const {agent,agents,host:_h,hostname:_hn,port:_p,protocol:_pr,servername:_s,ca,cert,key,pfx,passphrase,ciphers,rejectUnauthorized,checkServerIdentity,lookup,family,localAddress,createConnection,auth,...rest}=options;
|
|
@@ -8925,6 +9393,124 @@ require('node:module').syncBuiltinESMExports();
|
|
|
8925
9393
|
}
|
|
8926
9394
|
});
|
|
8927
9395
|
|
|
9396
|
+
// src/runtime/engines/ws-bridge.ts
|
|
9397
|
+
import { createHash as createHash10 } from "crypto";
|
|
9398
|
+
import { Duplex } from "stream";
|
|
9399
|
+
function bridgeWebSocket(socket, first, accept) {
|
|
9400
|
+
let buffer = first, upgraded = false;
|
|
9401
|
+
const shim = new Duplex({
|
|
9402
|
+
read() {
|
|
9403
|
+
},
|
|
9404
|
+
write(chunk, _enc, done) {
|
|
9405
|
+
if (!socket.destroyed) socket.write(frame2(2, Buffer.from(chunk)));
|
|
9406
|
+
done();
|
|
9407
|
+
},
|
|
9408
|
+
final(done) {
|
|
9409
|
+
if (!socket.destroyed) {
|
|
9410
|
+
socket.write(frame2(8, Buffer.alloc(0)));
|
|
9411
|
+
socket.end();
|
|
9412
|
+
}
|
|
9413
|
+
done();
|
|
9414
|
+
},
|
|
9415
|
+
destroy(error, done) {
|
|
9416
|
+
socket.destroy();
|
|
9417
|
+
done(error);
|
|
9418
|
+
}
|
|
9419
|
+
});
|
|
9420
|
+
shim.setNoDelay = () => shim;
|
|
9421
|
+
shim.setKeepAlive = () => shim;
|
|
9422
|
+
shim.setTimeout = () => shim;
|
|
9423
|
+
socket.on("error", () => shim.destroy());
|
|
9424
|
+
socket.on("close", () => shim.destroy());
|
|
9425
|
+
const pump = () => {
|
|
9426
|
+
if (!upgraded) {
|
|
9427
|
+
const end = buffer.indexOf("\r\n\r\n");
|
|
9428
|
+
if (end < 0) {
|
|
9429
|
+
if (buffer.length > 16384) socket.destroy();
|
|
9430
|
+
return;
|
|
9431
|
+
}
|
|
9432
|
+
const lines = buffer.subarray(0, end).toString("latin1").split("\r\n");
|
|
9433
|
+
buffer = buffer.subarray(end + 4);
|
|
9434
|
+
const headers = new Map(lines.slice(1).map((l) => {
|
|
9435
|
+
const i = l.indexOf(":");
|
|
9436
|
+
return [l.slice(0, i).trim().toLowerCase(), l.slice(i + 1).trim()];
|
|
9437
|
+
}));
|
|
9438
|
+
const key2 = headers.get("sec-websocket-key");
|
|
9439
|
+
if (!key2 || !/websocket/i.test(headers.get("upgrade") ?? "")) {
|
|
9440
|
+
socket.end("HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nThis port speaks Postgres, over TCP or a WebSocket upgrade.\n");
|
|
9441
|
+
return;
|
|
9442
|
+
}
|
|
9443
|
+
const acceptKey = createHash10("sha1").update(key2 + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
|
|
9444
|
+
const protocol = headers.get("sec-websocket-protocol")?.split(",")[0]?.trim();
|
|
9445
|
+
socket.write(`HTTP/1.1 101 Switching Protocols\r
|
|
9446
|
+
Upgrade: websocket\r
|
|
9447
|
+
Connection: Upgrade\r
|
|
9448
|
+
Sec-WebSocket-Accept: ${acceptKey}\r
|
|
9449
|
+
${protocol ? `Sec-WebSocket-Protocol: ${protocol}\r
|
|
9450
|
+
` : ""}\r
|
|
9451
|
+
`);
|
|
9452
|
+
upgraded = true;
|
|
9453
|
+
accept(shim);
|
|
9454
|
+
}
|
|
9455
|
+
for (; ; ) {
|
|
9456
|
+
if (buffer.length < 2) return;
|
|
9457
|
+
const opcode = buffer[0] & 15, masked = (buffer[1] & 128) !== 0;
|
|
9458
|
+
let length = buffer[1] & 127, offset = 2;
|
|
9459
|
+
if (length === 126) {
|
|
9460
|
+
if (buffer.length < 4) return;
|
|
9461
|
+
length = buffer.readUInt16BE(2);
|
|
9462
|
+
offset = 4;
|
|
9463
|
+
} else if (length === 127) {
|
|
9464
|
+
if (buffer.length < 10) return;
|
|
9465
|
+
length = Number(buffer.readBigUInt64BE(2));
|
|
9466
|
+
offset = 10;
|
|
9467
|
+
}
|
|
9468
|
+
const mask = masked ? buffer.subarray(offset, offset + 4) : void 0;
|
|
9469
|
+
if (masked) offset += 4;
|
|
9470
|
+
if (buffer.length < offset + length) return;
|
|
9471
|
+
const payload = Buffer.from(buffer.subarray(offset, offset + length));
|
|
9472
|
+
buffer = buffer.subarray(offset + length);
|
|
9473
|
+
if (mask) for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
|
|
9474
|
+
if (opcode === 0 || opcode === 1 || opcode === 2) {
|
|
9475
|
+
if (payload.length) shim.push(payload);
|
|
9476
|
+
} else if (opcode === 8) {
|
|
9477
|
+
if (!socket.destroyed) {
|
|
9478
|
+
socket.write(frame2(8, payload.subarray(0, 2)));
|
|
9479
|
+
socket.end();
|
|
9480
|
+
}
|
|
9481
|
+
shim.push(null);
|
|
9482
|
+
return;
|
|
9483
|
+
} else if (opcode === 9) socket.write(frame2(10, payload));
|
|
9484
|
+
}
|
|
9485
|
+
};
|
|
9486
|
+
socket.on("data", (chunk) => {
|
|
9487
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
9488
|
+
pump();
|
|
9489
|
+
});
|
|
9490
|
+
pump();
|
|
9491
|
+
}
|
|
9492
|
+
var looksLikeHttp, frame2;
|
|
9493
|
+
var init_ws_bridge = __esm({
|
|
9494
|
+
"src/runtime/engines/ws-bridge.ts"() {
|
|
9495
|
+
"use strict";
|
|
9496
|
+
looksLikeHttp = (chunk) => /^(GET|HEAD|POST) \//.test(chunk.subarray(0, 8).toString("latin1"));
|
|
9497
|
+
frame2 = (opcode, payload) => {
|
|
9498
|
+
const n = payload.length;
|
|
9499
|
+
const head = n < 126 ? Buffer.from([128 | opcode, n]) : n < 65536 ? Buffer.alloc(4) : Buffer.alloc(10);
|
|
9500
|
+
if (n >= 126 && n < 65536) {
|
|
9501
|
+
head[0] = 128 | opcode;
|
|
9502
|
+
head[1] = 126;
|
|
9503
|
+
head.writeUInt16BE(n, 2);
|
|
9504
|
+
} else if (n >= 65536) {
|
|
9505
|
+
head[0] = 128 | opcode;
|
|
9506
|
+
head[1] = 127;
|
|
9507
|
+
head.writeBigUInt64BE(BigInt(n), 2);
|
|
9508
|
+
}
|
|
9509
|
+
return Buffer.concat([head, payload]);
|
|
9510
|
+
};
|
|
9511
|
+
}
|
|
9512
|
+
});
|
|
9513
|
+
|
|
8928
9514
|
// src/runtime/engines/postgres.ts
|
|
8929
9515
|
import { createServer as createServer5 } from "net";
|
|
8930
9516
|
function sqlTables(sql) {
|
|
@@ -8978,7 +9564,7 @@ async function startPostgresEngine(options = {}) {
|
|
|
8978
9564
|
if (!POSTGRES_EXTENSIONS.includes(name)) throw new Error(`PostgreSQL extension ${name} is not available in the embedded engine`);
|
|
8979
9565
|
const module = name.replace(/-/g, "_");
|
|
8980
9566
|
try {
|
|
8981
|
-
extensions[module] = (await import(`@electric-sql/pglite/contrib/${module}`))[module];
|
|
9567
|
+
extensions[module] = name === "vector" ? (await import("@electric-sql/pglite-pgvector")).vector : (await import(`@electric-sql/pglite/contrib/${module}`))[module];
|
|
8982
9568
|
} catch (error) {
|
|
8983
9569
|
throw new EngineUnavailable("postgres", `PGlite extension ${name} could not be loaded (${error instanceof Error ? error.message : String(error)})`);
|
|
8984
9570
|
}
|
|
@@ -9227,6 +9813,7 @@ async function startPostgresEngine(options = {}) {
|
|
|
9227
9813
|
socket.end();
|
|
9228
9814
|
return;
|
|
9229
9815
|
}
|
|
9816
|
+
if (type === "p") continue;
|
|
9230
9817
|
batch.push({ type, body });
|
|
9231
9818
|
if ("SQHcf".includes(type)) {
|
|
9232
9819
|
const b = batch;
|
|
@@ -9236,7 +9823,17 @@ async function startPostgresEngine(options = {}) {
|
|
|
9236
9823
|
}
|
|
9237
9824
|
});
|
|
9238
9825
|
};
|
|
9239
|
-
const server = createServer5(
|
|
9826
|
+
const server = createServer5((socket) => {
|
|
9827
|
+
socket.once("data", (first) => {
|
|
9828
|
+
if (looksLikeHttp(first)) bridgeWebSocket(socket, first, accept);
|
|
9829
|
+
else {
|
|
9830
|
+
accept(socket);
|
|
9831
|
+
socket.emit("data", first);
|
|
9832
|
+
}
|
|
9833
|
+
});
|
|
9834
|
+
socket.on("error", () => {
|
|
9835
|
+
});
|
|
9836
|
+
});
|
|
9240
9837
|
await new Promise((resolve8, reject) => {
|
|
9241
9838
|
server.once("error", reject);
|
|
9242
9839
|
server.listen(0, "127.0.0.1", resolve8);
|
|
@@ -9308,10 +9905,10 @@ async function startPostgresEngine(options = {}) {
|
|
|
9308
9905
|
for (const row of rows2) {
|
|
9309
9906
|
const fields = Object.keys(row);
|
|
9310
9907
|
if (!fields.length) {
|
|
9311
|
-
await db.exec(`insert into ${
|
|
9908
|
+
await db.exec(`insert into ${quoteTable(table2)} default values`);
|
|
9312
9909
|
continue;
|
|
9313
9910
|
}
|
|
9314
|
-
await db.query(`insert into ${
|
|
9911
|
+
await db.query(`insert into ${quoteTable(table2)} (${fields.map(quote2).join(",")}) values (${fields.map((_, i) => `$${i + 1}`).join(",")})`, fields.map((c) => {
|
|
9315
9912
|
const v = row[c];
|
|
9316
9913
|
return v !== null && typeof v === "object" ? JSON.stringify(v) : v ?? null;
|
|
9317
9914
|
}));
|
|
@@ -9389,10 +9986,11 @@ function queryReadOnly(handle, sql) {
|
|
|
9389
9986
|
function snapshotPublicTables(handle) {
|
|
9390
9987
|
return hidden(handle, "snapshotPublic")();
|
|
9391
9988
|
}
|
|
9392
|
-
var LockWait, WRITE, TABLE, normalizeTable, isWriteSql, cstr, msg, int32, errorMessage, ready, quote2, plain, PUBLIC_SNAPSHOT_LIMITS, hidden;
|
|
9989
|
+
var LockWait, WRITE, TABLE, normalizeTable, isWriteSql, cstr, msg, int32, errorMessage, ready, quote2, quoteTable, plain, PUBLIC_SNAPSHOT_LIMITS, hidden;
|
|
9393
9990
|
var init_postgres = __esm({
|
|
9394
9991
|
"src/runtime/engines/postgres.ts"() {
|
|
9395
9992
|
"use strict";
|
|
9993
|
+
init_ws_bridge();
|
|
9396
9994
|
init_types();
|
|
9397
9995
|
LockWait = class extends Error {
|
|
9398
9996
|
};
|
|
@@ -9419,6 +10017,7 @@ var init_postgres = __esm({
|
|
|
9419
10017
|
errorMessage = (code, message) => msg("E", Buffer.concat([cstr("SERROR"), cstr("VERROR"), cstr("C" + code), cstr("M" + message), Buffer.from([0])]));
|
|
9420
10018
|
ready = (status) => msg("Z", Buffer.from(status));
|
|
9421
10019
|
quote2 = (name) => '"' + name.replaceAll('"', '""') + '"';
|
|
10020
|
+
quoteTable = (name) => /^\w+\.\w+$/.test(name) ? name.split(".").map(quote2).join(".") : quote2(name);
|
|
9422
10021
|
plain = (v) => v instanceof Date ? v.toISOString() : typeof v === "bigint" ? Number.isSafeInteger(Number(v)) ? Number(v) : v.toString() : v instanceof Uint8Array ? Buffer.from(v).toString("base64") : v;
|
|
9423
10022
|
PUBLIC_SNAPSHOT_LIMITS = { tables: 200, columns: 100, rows: 1e3, bytes: 512 * 1024 };
|
|
9424
10023
|
hidden = (handle, name) => {
|
|
@@ -9431,7 +10030,7 @@ var init_postgres = __esm({
|
|
|
9431
10030
|
|
|
9432
10031
|
// src/runtime/local-engines.ts
|
|
9433
10032
|
import { readFile as readFile5 } from "fs/promises";
|
|
9434
|
-
import { join as
|
|
10033
|
+
import { join as join14 } from "path";
|
|
9435
10034
|
async function evaluatePostgresAssertions(postgres2, assertions) {
|
|
9436
10035
|
const results = [];
|
|
9437
10036
|
for (const assertion of assertions) {
|
|
@@ -9457,7 +10056,7 @@ async function startLocalEngines(app, spec) {
|
|
|
9457
10056
|
postgres2 = await startPostgresEngine({ extensions: spec.postgres.extensions });
|
|
9458
10057
|
started.push(postgres2);
|
|
9459
10058
|
if (spec.postgres.seedFile) {
|
|
9460
|
-
const sql = await readFile5(
|
|
10059
|
+
const sql = await readFile5(join14(app, spec.postgres.seedFile), "utf8");
|
|
9461
10060
|
try {
|
|
9462
10061
|
await postgres2.seed({ sql });
|
|
9463
10062
|
} catch (error) {
|
|
@@ -9596,7 +10195,7 @@ var init_server_steps = __esm({
|
|
|
9596
10195
|
});
|
|
9597
10196
|
|
|
9598
10197
|
// src/runtime/local.ts
|
|
9599
|
-
import { spawn as
|
|
10198
|
+
import { spawn as spawn3 } from "child_process";
|
|
9600
10199
|
import { realpath as realpath3 } from "fs/promises";
|
|
9601
10200
|
import { dirname as dirname2, resolve as resolve3 } from "path";
|
|
9602
10201
|
async function sourceRoot(app, spec) {
|
|
@@ -9622,6 +10221,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
|
|
|
9622
10221
|
}
|
|
9623
10222
|
engines = await startLocalEngines(filesDir, spec);
|
|
9624
10223
|
Object.assign(env, engines.env);
|
|
10224
|
+
applySettingAliases(env, spec.settingAliases);
|
|
9625
10225
|
if (engines.env.DATABASE_URL) world.attachDatabase(engines.env.DATABASE_URL);
|
|
9626
10226
|
let stdout = "", stderr = "", timedOut = false;
|
|
9627
10227
|
const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
|
|
@@ -9634,7 +10234,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
|
|
|
9634
10234
|
Object.assign(env, proxy.env, { HOME: process.env.HOME ?? "", LANG: process.env.LANG ?? "C.UTF-8", PYTHONUNBUFFERED: "1", PYTHONDONTWRITEBYTECODE: "1" });
|
|
9635
10235
|
if (process.env.VIRTUAL_ENV) env.VIRTUAL_ENV = process.env.VIRTUAL_ENV;
|
|
9636
10236
|
}
|
|
9637
|
-
const child = node ?
|
|
10237
|
+
const child = node ? spawn3(appNode(), ["--require", hook.path, ...spec.command.slice(1)], { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" }) : spawn3(spec.command[0], spec.command.slice(1), { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
|
|
9638
10238
|
child.stdout.on("data", (b) => {
|
|
9639
10239
|
stdout = (stdout + b.toString()).slice(-65536);
|
|
9640
10240
|
});
|
|
@@ -9751,6 +10351,7 @@ var init_local = __esm({
|
|
|
9751
10351
|
"src/runtime/local.ts"() {
|
|
9752
10352
|
"use strict";
|
|
9753
10353
|
init_node_options();
|
|
10354
|
+
init_node_runtime();
|
|
9754
10355
|
init_application_process();
|
|
9755
10356
|
init_browser_process();
|
|
9756
10357
|
init_twin_clock();
|
|
@@ -9758,6 +10359,7 @@ var init_local = __esm({
|
|
|
9758
10359
|
init_browser_execution();
|
|
9759
10360
|
init_request_source();
|
|
9760
10361
|
init_http_world();
|
|
10362
|
+
init_spec();
|
|
9761
10363
|
init_evaluation();
|
|
9762
10364
|
init_contracts();
|
|
9763
10365
|
init_default_checks();
|
|
@@ -9769,9 +10371,9 @@ var init_local = __esm({
|
|
|
9769
10371
|
});
|
|
9770
10372
|
|
|
9771
10373
|
// src/runtime/scenarios.ts
|
|
9772
|
-
import { createHash as
|
|
10374
|
+
import { createHash as createHash11 } from "crypto";
|
|
9773
10375
|
import { mkdir as mkdir3, readFile as readFile6, readdir, writeFile as writeFile8 } from "fs/promises";
|
|
9774
|
-
import { join as
|
|
10376
|
+
import { join as join15 } from "path";
|
|
9775
10377
|
import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
|
|
9776
10378
|
function parseScenario(value) {
|
|
9777
10379
|
const fail = (detail) => {
|
|
@@ -9810,7 +10412,7 @@ function reference(ref) {
|
|
|
9810
10412
|
}
|
|
9811
10413
|
async function loadScenario(cwd, ref) {
|
|
9812
10414
|
const { id, version } = reference(ref);
|
|
9813
|
-
const path =
|
|
10415
|
+
const path = join15(cwd, ".agenttwin/scenarios", id, `${version}.json`);
|
|
9814
10416
|
const bytes = await readFile6(path);
|
|
9815
10417
|
if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
|
|
9816
10418
|
const scenario = parseScenario(JSON.parse(bytes.toString()));
|
|
@@ -9830,7 +10432,7 @@ var init_scenarios = __esm({
|
|
|
9830
10432
|
identifier = /^[a-z][a-z0-9_]{0,39}$/;
|
|
9831
10433
|
object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
9832
10434
|
sort = (v) => Array.isArray(v) ? v.map(sort) : object3(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
|
|
9833
|
-
scenarioDigest = (scenario) =>
|
|
10435
|
+
scenarioDigest = (scenario) => createHash11("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
|
|
9834
10436
|
}
|
|
9835
10437
|
});
|
|
9836
10438
|
|
|
@@ -9862,7 +10464,7 @@ var init_exit = __esm({
|
|
|
9862
10464
|
|
|
9863
10465
|
// src/runtime/stage-worker.ts
|
|
9864
10466
|
import { copyFile, rm as rm8 } from "fs/promises";
|
|
9865
|
-
import { basename, dirname as dirname3, join as
|
|
10467
|
+
import { basename, dirname as dirname3, join as join16 } from "path";
|
|
9866
10468
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
9867
10469
|
var init_stage_worker = __esm({
|
|
9868
10470
|
"src/runtime/stage-worker.ts"() {
|
|
@@ -9879,8 +10481,8 @@ var init_offline = __esm({
|
|
|
9879
10481
|
});
|
|
9880
10482
|
|
|
9881
10483
|
// src/runtime/credentials.ts
|
|
9882
|
-
import { homedir } from "os";
|
|
9883
|
-
import { join as
|
|
10484
|
+
import { homedir as homedir2 } from "os";
|
|
10485
|
+
import { join as join17 } from "path";
|
|
9884
10486
|
import { readFile as readFile7, mkdir as mkdir4, writeFile as writeFile9, chmod as chmod2, rm as rm9 } from "fs/promises";
|
|
9885
10487
|
var init_credentials = __esm({
|
|
9886
10488
|
"src/runtime/credentials.ts"() {
|
|
@@ -9890,7 +10492,7 @@ var init_credentials = __esm({
|
|
|
9890
10492
|
|
|
9891
10493
|
// src/runtime/remote.ts
|
|
9892
10494
|
import { readFile as readFile8 } from "fs/promises";
|
|
9893
|
-
import { join as
|
|
10495
|
+
import { join as join18 } from "path";
|
|
9894
10496
|
var init_remote = __esm({
|
|
9895
10497
|
"src/runtime/remote.ts"() {
|
|
9896
10498
|
"use strict";
|
|
@@ -9913,10 +10515,10 @@ var init_docker_engine = __esm({
|
|
|
9913
10515
|
|
|
9914
10516
|
// src/runtime/docker-postgres.ts
|
|
9915
10517
|
import postgres from "postgres";
|
|
9916
|
-
import { execFile as execFile7, spawn as
|
|
10518
|
+
import { execFile as execFile7, spawn as spawn4 } from "child_process";
|
|
9917
10519
|
import { promisify as promisify7, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
|
|
9918
|
-
import { randomBytes as
|
|
9919
|
-
import { Duplex } from "stream";
|
|
10520
|
+
import { randomBytes as randomBytes3, randomUUID as randomUUID4 } from "crypto";
|
|
10521
|
+
import { Duplex as Duplex2 } from "stream";
|
|
9920
10522
|
var exec6;
|
|
9921
10523
|
var init_docker_postgres = __esm({
|
|
9922
10524
|
"src/runtime/docker-postgres.ts"() {
|
|
@@ -9937,12 +10539,12 @@ var init_stdio_fetch = __esm({
|
|
|
9937
10539
|
});
|
|
9938
10540
|
|
|
9939
10541
|
// src/runtime/docker.ts
|
|
9940
|
-
import { execFile as execFile8, spawn as
|
|
10542
|
+
import { execFile as execFile8, spawn as spawn5 } from "child_process";
|
|
9941
10543
|
import { promisify as promisify8 } from "util";
|
|
9942
10544
|
import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir5, mkdtemp as mkdtemp8, readFile as readFile9, rm as rm10, writeFile as writeFile10 } from "fs/promises";
|
|
9943
10545
|
import { tmpdir as tmpdir8 } from "os";
|
|
9944
|
-
import { join as
|
|
9945
|
-
import { randomUUID as
|
|
10546
|
+
import { join as join19 } from "path";
|
|
10547
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
9946
10548
|
var exec7;
|
|
9947
10549
|
var init_docker = __esm({
|
|
9948
10550
|
"src/runtime/docker.ts"() {
|
|
@@ -9995,7 +10597,7 @@ var init_git = __esm({
|
|
|
9995
10597
|
|
|
9996
10598
|
// src/runtime/hosted-packs.ts
|
|
9997
10599
|
import { readFile as readFile10, readdir as readdir2 } from "fs/promises";
|
|
9998
|
-
import { join as
|
|
10600
|
+
import { join as join20 } from "path";
|
|
9999
10601
|
var init_hosted_packs = __esm({
|
|
10000
10602
|
"src/runtime/hosted-packs.ts"() {
|
|
10001
10603
|
"use strict";
|
|
@@ -10006,9 +10608,9 @@ var init_hosted_packs = __esm({
|
|
|
10006
10608
|
// src/runtime/e2b.ts
|
|
10007
10609
|
import { createRequire as createRequire3 } from "module";
|
|
10008
10610
|
import { readFile as readFile11 } from "fs/promises";
|
|
10009
|
-
import { randomBytes as
|
|
10010
|
-
import { homedir as
|
|
10011
|
-
import { join as
|
|
10611
|
+
import { randomBytes as randomBytes4 } from "crypto";
|
|
10612
|
+
import { homedir as homedir3 } from "os";
|
|
10613
|
+
import { join as join21 } from "path";
|
|
10012
10614
|
var init_e2b = __esm({
|
|
10013
10615
|
"src/runtime/e2b.ts"() {
|
|
10014
10616
|
"use strict";
|
|
@@ -10020,9 +10622,9 @@ var init_e2b = __esm({
|
|
|
10020
10622
|
});
|
|
10021
10623
|
|
|
10022
10624
|
// src/runtime/matrix.ts
|
|
10023
|
-
import { createHash as
|
|
10625
|
+
import { createHash as createHash12 } from "crypto";
|
|
10024
10626
|
import { mkdir as mkdir6, readFile as readFile12, writeFile as writeFile11 } from "fs/promises";
|
|
10025
|
-
import { join as
|
|
10627
|
+
import { join as join22, relative, resolve as resolve4 } from "path";
|
|
10026
10628
|
var init_matrix = __esm({
|
|
10027
10629
|
"src/runtime/matrix.ts"() {
|
|
10028
10630
|
"use strict";
|
|
@@ -10033,9 +10635,9 @@ var init_matrix = __esm({
|
|
|
10033
10635
|
});
|
|
10034
10636
|
|
|
10035
10637
|
// src/runtime/source-build.ts
|
|
10036
|
-
import { createHash as
|
|
10638
|
+
import { createHash as createHash13 } from "crypto";
|
|
10037
10639
|
import { lstat, readFile as readFile13, realpath as realpath4 } from "fs/promises";
|
|
10038
|
-
import { isAbsolute as isAbsolute2, join as
|
|
10640
|
+
import { isAbsolute as isAbsolute2, join as join23, relative as relative2, resolve as resolve5, sep } from "path";
|
|
10039
10641
|
import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
|
|
10040
10642
|
var init_source_build = __esm({
|
|
10041
10643
|
"src/runtime/source-build.ts"() {
|
|
@@ -10047,8 +10649,8 @@ var init_source_build = __esm({
|
|
|
10047
10649
|
// src/commands/run.ts
|
|
10048
10650
|
import { mkdtemp as mkdtemp9, mkdir as mkdir7, readFile as readFile14, writeFile as writeFile12, realpath as realpath5, lstat as lstat2, rm as rm11 } from "fs/promises";
|
|
10049
10651
|
import { tmpdir as tmpdir9 } from "os";
|
|
10050
|
-
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as
|
|
10051
|
-
import { createHash as
|
|
10652
|
+
import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join24, relative as relative3, resolve as resolve6, sep as sep2 } from "path";
|
|
10653
|
+
import { createHash as createHash14, randomUUID as randomUUID6 } from "crypto";
|
|
10052
10654
|
async function stageApplication(root, files, destination) {
|
|
10053
10655
|
const canonicalRoot = await realpath5(root);
|
|
10054
10656
|
const digests = {};
|
|
@@ -10061,10 +10663,10 @@ async function stageApplication(root, files, destination) {
|
|
|
10061
10663
|
const contents = await readFile14(source);
|
|
10062
10664
|
bytes += contents.length;
|
|
10063
10665
|
if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
|
|
10064
|
-
const target =
|
|
10666
|
+
const target = join24(destination, file);
|
|
10065
10667
|
await mkdir7(dirname4(target), { recursive: true });
|
|
10066
10668
|
await writeFile12(target, contents, { mode: 420 });
|
|
10067
|
-
digests[file] =
|
|
10669
|
+
digests[file] = createHash14("sha256").update(contents).digest("hex");
|
|
10068
10670
|
}
|
|
10069
10671
|
return digests;
|
|
10070
10672
|
}
|
|
@@ -10097,28 +10699,28 @@ init_contracts();
|
|
|
10097
10699
|
init_run();
|
|
10098
10700
|
init_git();
|
|
10099
10701
|
import { createServer as createServer6 } from "http";
|
|
10100
|
-
import { randomBytes as
|
|
10702
|
+
import { randomBytes as randomBytes5, randomUUID as randomUUID7, createHash as createHash15 } from "crypto";
|
|
10101
10703
|
import { mkdir as mkdir8, mkdtemp as mkdtemp10, readFile as readFile15, readdir as readdir3, rename, rm as rm12, writeFile as writeFile13 } from "fs/promises";
|
|
10102
|
-
import { dirname as dirname5, join as
|
|
10704
|
+
import { dirname as dirname5, join as join25, resolve as resolve7, relative as relative4, sep as sep3 } from "path";
|
|
10103
10705
|
import { tmpdir as tmpdir10 } from "os";
|
|
10104
10706
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
10105
|
-
import { spawn as
|
|
10707
|
+
import { spawn as spawn6 } from "child_process";
|
|
10106
10708
|
var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
10107
|
-
var hash2 = (spec) =>
|
|
10709
|
+
var hash2 = (spec) => createHash15("sha256").update(JSON.stringify(spec)).digest("hex");
|
|
10108
10710
|
function duration(value) {
|
|
10109
10711
|
if (!Number.isInteger(value) || value < 1 || value > 86400) throw new Error("ttlSeconds must be 1\u201386400");
|
|
10110
10712
|
return value;
|
|
10111
10713
|
}
|
|
10112
10714
|
async function persist(directory2, session) {
|
|
10113
|
-
const temporary =
|
|
10715
|
+
const temporary = join25(directory2, `${randomUUID7()}.tmp`);
|
|
10114
10716
|
await writeFile13(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
|
|
10115
|
-
await rename(temporary,
|
|
10717
|
+
await rename(temporary, join25(directory2, "session.json"));
|
|
10116
10718
|
}
|
|
10117
10719
|
var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
|
|
10118
10720
|
async function serveWorldSession(directory2) {
|
|
10119
|
-
const session = JSON.parse(await readFile15(
|
|
10721
|
+
const session = JSON.parse(await readFile15(join25(directory2, "session.json"), "utf8"));
|
|
10120
10722
|
if (session.status !== "provisioning" || !uuid.test(session.id)) throw new Error("Session is not awaiting provisioning");
|
|
10121
|
-
const spec = parseWorld(JSON.parse(await readFile15(
|
|
10723
|
+
const spec = parseWorld(JSON.parse(await readFile15(join25(directory2, "world.json"), "utf8")));
|
|
10122
10724
|
const world = new HttpWorld(spec);
|
|
10123
10725
|
let control;
|
|
10124
10726
|
let timer;
|
|
@@ -10221,7 +10823,7 @@ async function serveWorldSession(directory2) {
|
|
|
10221
10823
|
let current = parseWorld(JSON.parse(await readFile15(session.file, "utf8")));
|
|
10222
10824
|
if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
|
|
10223
10825
|
if (hash2(current) !== hash2(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
|
|
10224
|
-
const stage = await mkdtemp10(
|
|
10826
|
+
const stage = await mkdtemp10(join25(tmpdir10(), "agenttwin-session-run-"));
|
|
10225
10827
|
active = new AbortController();
|
|
10226
10828
|
let result;
|
|
10227
10829
|
try {
|
|
@@ -10234,18 +10836,18 @@ async function serveWorldSession(directory2) {
|
|
|
10234
10836
|
world.reset();
|
|
10235
10837
|
const report = await executeLocal(stage, spec, active.signal, world);
|
|
10236
10838
|
if (stopping) throw new Error("World expired during execution");
|
|
10237
|
-
const runId =
|
|
10839
|
+
const runId = randomUUID7();
|
|
10238
10840
|
let project = "local-workspace";
|
|
10239
10841
|
try {
|
|
10240
|
-
project = JSON.parse(await readFile15(
|
|
10842
|
+
project = JSON.parse(await readFile15(join25(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
|
|
10241
10843
|
} catch {
|
|
10242
10844
|
}
|
|
10243
10845
|
const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname5(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
|
|
10244
|
-
const out =
|
|
10846
|
+
const out = join25(session.cwd, ".agenttwin/runs", runId);
|
|
10245
10847
|
await mkdir8(out, { recursive: true, mode: 448 });
|
|
10246
|
-
const evidencePath =
|
|
10848
|
+
const evidencePath = join25(out, "run.json");
|
|
10247
10849
|
await writeFile13(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
|
|
10248
|
-
await writeFile13(
|
|
10850
|
+
await writeFile13(join25(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
|
|
10249
10851
|
session.lastRunId = runId;
|
|
10250
10852
|
result = { ...receipt, evidencePath };
|
|
10251
10853
|
} finally {
|
|
@@ -10268,7 +10870,7 @@ async function serveWorldSession(directory2) {
|
|
|
10268
10870
|
control.once("error", reject);
|
|
10269
10871
|
control.listen(0, "127.0.0.1", resolve8);
|
|
10270
10872
|
});
|
|
10271
|
-
const latest = JSON.parse(await readFile15(
|
|
10873
|
+
const latest = JSON.parse(await readFile15(join25(directory2, "session.json"), "utf8"));
|
|
10272
10874
|
if (latest.status !== "provisioning") throw new Error("Provisioning was abandoned");
|
|
10273
10875
|
session.controlUrl = `http://127.0.0.1:${control.address().port}`;
|
|
10274
10876
|
if (stopping) throw new Error("World expired during provisioning");
|