agenttwin 0.3.36 → 0.3.37

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.
@@ -764,12 +764,12 @@ var init_resp = __esm({
764
764
  socket.on("data", (chunk) => {
765
765
  this.buffer = Buffer.concat([this.buffer, chunk]);
766
766
  for (; ; ) {
767
- const frame2 = parseResp(this.buffer);
768
- if (!frame2) break;
769
- this.buffer = this.buffer.subarray(frame2.end);
767
+ const frame3 = parseResp(this.buffer);
768
+ if (!frame3) break;
769
+ this.buffer = this.buffer.subarray(frame3.end);
770
770
  const w = this.waiting.shift();
771
771
  if (!w) continue;
772
- const v = frame2.value;
772
+ const v = frame3.value;
773
773
  if (v && typeof v === "object" && "error" in v) w.reject(new Error(v.error));
774
774
  else w.resolve(v);
775
775
  }
@@ -980,7 +980,7 @@ var POSTGRES_EXTENSIONS, EngineUnavailable, FaultGate, sleep;
980
980
  var init_types = __esm({
981
981
  "src/runtime/engines/types.ts"() {
982
982
  "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"];
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", "vector"];
984
984
  EngineUnavailable = class extends Error {
985
985
  constructor(kind, message) {
986
986
  super(message);
@@ -1171,17 +1171,17 @@ function respFrontEnd(upstreamPort, gate, events, commit) {
1171
1171
  inbound = Buffer.concat([inbound, chunk]);
1172
1172
  const forward = [];
1173
1173
  for (; ; ) {
1174
- let frame2;
1174
+ let frame3;
1175
1175
  try {
1176
- frame2 = parseResp(inbound, 0, true);
1176
+ frame3 = parseResp(inbound, 0, true);
1177
1177
  } catch {
1178
1178
  close();
1179
1179
  return;
1180
1180
  }
1181
- if (!frame2) break;
1182
- const bytes = inbound.subarray(0, frame2.end);
1183
- inbound = inbound.subarray(frame2.end);
1184
- const args = frame2.value.map((b) => b.toString("utf8"));
1181
+ if (!frame3) break;
1182
+ const bytes = inbound.subarray(0, frame3.end);
1183
+ inbound = inbound.subarray(frame3.end);
1184
+ const args = frame3.value.map((b) => b.toString("utf8"));
1185
1185
  if (!args.length) continue;
1186
1186
  const name = args[0].toLowerCase(), rest = args.slice(1);
1187
1187
  if (["subscribe", "psubscribe", "ssubscribe", "monitor"].includes(name)) {
@@ -1230,23 +1230,23 @@ function respFrontEnd(upstreamPort, gate, events, commit) {
1230
1230
  }
1231
1231
  outbound = Buffer.concat([outbound, chunk]);
1232
1232
  for (; ; ) {
1233
- let frame2;
1233
+ let frame3;
1234
1234
  try {
1235
- frame2 = parseResp(outbound);
1235
+ frame3 = parseResp(outbound);
1236
1236
  } catch {
1237
1237
  close();
1238
1238
  return;
1239
1239
  }
1240
- if (!frame2) break;
1241
- const bytes = Buffer.from(outbound.subarray(0, frame2.end));
1242
- outbound = outbound.subarray(frame2.end);
1240
+ if (!frame3) break;
1241
+ const bytes = Buffer.from(outbound.subarray(0, frame3.end));
1242
+ outbound = outbound.subarray(frame3.end);
1243
1243
  const p = pending.find((x) => !x.local && !x.reply);
1244
1244
  if (!p) {
1245
1245
  client.write(bytes);
1246
1246
  continue;
1247
1247
  }
1248
1248
  p.reply = bytes;
1249
- const v = frame2.value;
1249
+ const v = frame3.value;
1250
1250
  if (v && typeof v === "object" && "error" in v) p.error = true;
1251
1251
  }
1252
1252
  void drain();
@@ -1476,10 +1476,10 @@ var init_redis = __esm({
1476
1476
  const out = [];
1477
1477
  try {
1478
1478
  for (; ; ) {
1479
- const frame2 = parseResp(buffer, 0, true);
1480
- if (!frame2) break;
1481
- buffer = buffer.subarray(frame2.end);
1482
- const args = frame2.value.map((b) => b.toString("latin1"));
1479
+ const frame3 = parseResp(buffer, 0, true);
1480
+ if (!frame3) break;
1481
+ buffer = buffer.subarray(frame3.end);
1482
+ const args = frame3.value.map((b) => b.toString("latin1"));
1483
1483
  if (!args.length) continue;
1484
1484
  if (args[0].toLowerCase() === "quit") {
1485
1485
  out.push(encode.simple("OK"));
@@ -2031,7 +2031,7 @@ function engineFor(rows2) {
2031
2031
  return cache2;
2032
2032
  }
2033
2033
  function upstashReply(reply, base64) {
2034
- const frame2 = parseResp(reply);
2034
+ const frame3 = parseResp(reply);
2035
2035
  const json = (value) => {
2036
2036
  if (value === null || typeof value === "number" || typeof value === "boolean") return value;
2037
2037
  if (Buffer.isBuffer(value)) return base64 ? value.toString("base64") : value.toString("utf8");
@@ -2039,9 +2039,9 @@ function upstashReply(reply, base64) {
2039
2039
  if ("simple" in value) return base64 && value.simple !== "OK" ? Buffer.from(value.simple).toString("base64") : value.simple;
2040
2040
  throw new Error(value.error);
2041
2041
  };
2042
- if (!frame2) return { error: "ERR empty reply" };
2043
- if (frame2.value && typeof frame2.value === "object" && !Array.isArray(frame2.value) && !Buffer.isBuffer(frame2.value) && "error" in frame2.value) return { error: frame2.value.error };
2044
- return { result: json(frame2.value) };
2042
+ if (!frame3) return { error: "ERR empty reply" };
2043
+ if (frame3.value && typeof frame3.value === "object" && !Array.isArray(frame3.value) && !Buffer.isBuffer(frame3.value) && "error" in frame3.value) return { error: frame3.value.error };
2044
+ return { result: json(frame3.value) };
2045
2045
  }
2046
2046
  function upstashRedisOperation(method, path, params, headers, data, _sequence, raw) {
2047
2047
  if (method !== "POST" || !["/", "/pipeline", "/multi-exec"].includes(path) || raw === void 0 || Object.keys(params).length) return void 0;
@@ -5415,6 +5415,11 @@ function parseWorld(value) {
5415
5415
  }
5416
5416
  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
5417
  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");
5418
+ if (v.settingAliases !== void 0) {
5419
+ if (!object2(v.settingAliases) || Object.keys(v.settingAliases).length > 100) invalid("settingAliases must be an object of at most 100 settings");
5420
+ for (const [name, key2] of Object.entries(v.settingAliases))
5421
+ 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");
5422
+ }
5418
5423
  if (v.env !== void 0) {
5419
5424
  if (!object2(v.env) || Object.keys(v.env).length > 200) invalid("env must be an object of at most 200 string variables");
5420
5425
  for (const [key2, value2] of Object.entries(v.env)) {
@@ -5463,10 +5468,13 @@ function parseWorld(value) {
5463
5468
  origins.add(mapping.origin);
5464
5469
  }
5465
5470
  }
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"];
5471
+ 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
5472
  if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
5468
5473
  return v;
5469
5474
  }
5475
+ function applySettingAliases(env, aliases) {
5476
+ for (const [name, key2] of Object.entries(aliases ?? {})) if (!env[name] && env[key2]) env[name] = env[key2];
5477
+ }
5470
5478
  var RUNTIMES, ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, RESERVED_ENV, isServerPath, object2, namePattern, inRangeInt;
5471
5479
  var init_spec = __esm({
5472
5480
  "src/runtime/spec.ts"() {
@@ -5539,6 +5547,20 @@ var init_postgrest = __esm({
5539
5547
  return this.pool.end().catch(() => {
5540
5548
  });
5541
5549
  }
5550
+ /**
5551
+ * A Supabase Auth user as a row of auth.users, as GoTrue writes it: the project's own triggers on that table (a
5552
+ * profile, a workspace) run. Returns the database's error when one refuses it; a project without the table is fine.
5553
+ */
5554
+ async addAuthUser(u) {
5555
+ try {
5556
+ 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)
5557
+ 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)]);
5558
+ return void 0;
5559
+ } catch (error) {
5560
+ const e = error;
5561
+ return e.code === "42P01" || e.code === "3F000" ? void 0 : e.message ?? String(error);
5562
+ }
5563
+ }
5542
5564
  foreignKeys() {
5543
5565
  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
5566
  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 +5656,7 @@ var init_postgrest = __esm({
5634
5656
  const cols = await this.columns(table2, "r", params.get("select") ?? "*");
5635
5657
  return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
5636
5658
  };
5637
- let sql, status = 200;
5659
+ let sql, status = 200, perRow = false;
5638
5660
  const method = request.method.toUpperCase();
5639
5661
  if (method === "GET" || method === "HEAD") {
5640
5662
  const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
@@ -5643,7 +5665,8 @@ var init_postgrest = __esm({
5643
5665
  });
5644
5666
  const limit = Number(params.get("limit")), offset = Number(params.get("offset"));
5645
5667
  const cols = await this.columns(table2, "t", params.get("select") ?? "*");
5646
- sql = `SELECT coalesce(json_agg(x), '[]'::json) AS rows 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`;
5668
+ perRow = true;
5669
+ 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
5670
  } else if (method === "POST") {
5648
5671
  const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
5649
5672
  const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
@@ -5664,7 +5687,8 @@ var init_postgrest = __esm({
5664
5687
  } else if (method === "DELETE") {
5665
5688
  sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
5666
5689
  } else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
5667
- const rows2 = (await this.pool.query(sql, values)).rows[0]?.rows ?? [];
5690
+ const result = await this.pool.query(sql, values);
5691
+ const rows2 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
5668
5692
  const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
5669
5693
  if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
5670
5694
  if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
@@ -5680,6 +5704,296 @@ var init_postgrest = __esm({
5680
5704
  }
5681
5705
  });
5682
5706
 
5707
+ // src/runtime/gotrue.ts
5708
+ import { createHash as createHash6, createHmac, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
5709
+ var b64url, userIdFor, GoTrueLayer;
5710
+ var init_gotrue = __esm({
5711
+ "src/runtime/gotrue.ts"() {
5712
+ "use strict";
5713
+ b64url = (v) => Buffer.from(v).toString("base64url");
5714
+ userIdFor = (email) => {
5715
+ const h = createHash6("sha256").update(`agenttwin-user:${email.toLowerCase()}`).digest("hex");
5716
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
5717
+ };
5718
+ GoTrueLayer = class {
5719
+ constructor(secret = randomBytes2(32).toString("hex"), now = () => /* @__PURE__ */ new Date()) {
5720
+ this.secret = secret;
5721
+ this.now = now;
5722
+ }
5723
+ secret;
5724
+ now;
5725
+ users = /* @__PURE__ */ new Map();
5726
+ refresh = /* @__PURE__ */ new Map();
5727
+ /** Called when a user is created (sign-up, admin create); a returned message fails the call as GoTrue does. */
5728
+ onCreate;
5729
+ /** Users written so far, for the run's evidence. */
5730
+ list() {
5731
+ return [...this.users.values()].map(({ password: _p, ...u }) => u);
5732
+ }
5733
+ sign(claims) {
5734
+ const head = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" })), body = b64url(JSON.stringify(claims));
5735
+ return `${head}.${body}.${b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest())}`;
5736
+ }
5737
+ verify(token) {
5738
+ const [head, body, sig] = token.split(".");
5739
+ if (!head || !body || !sig) return void 0;
5740
+ if (b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
5741
+ try {
5742
+ const c = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
5743
+ return typeof c.exp === "number" && c.exp * 1e3 < this.now().getTime() ? void 0 : c;
5744
+ } catch {
5745
+ return void 0;
5746
+ }
5747
+ }
5748
+ create(email, password, meta = {}) {
5749
+ const at = this.now().toISOString(), id = userIdFor(email);
5750
+ const user = {
5751
+ id,
5752
+ aud: "authenticated",
5753
+ role: "authenticated",
5754
+ email,
5755
+ phone: "",
5756
+ email_confirmed_at: at,
5757
+ confirmed_at: at,
5758
+ last_sign_in_at: at,
5759
+ app_metadata: { provider: "email", providers: ["email"] },
5760
+ user_metadata: meta,
5761
+ identities: [],
5762
+ created_at: at,
5763
+ updated_at: at,
5764
+ is_anonymous: false,
5765
+ password
5766
+ };
5767
+ this.users.set(id, user);
5768
+ return user;
5769
+ }
5770
+ session(user) {
5771
+ const iat = Math.floor(this.now().getTime() / 1e3), expires_in = 3600;
5772
+ const refresh_token = randomUUID2().replace(/-/g, "");
5773
+ this.refresh.set(refresh_token, user.id);
5774
+ const { password: _p, ...publicUser } = user;
5775
+ const access_token = this.sign({
5776
+ aud: "authenticated",
5777
+ exp: iat + expires_in,
5778
+ iat,
5779
+ iss: "supabase",
5780
+ sub: user.id,
5781
+ email: user.email,
5782
+ phone: "",
5783
+ role: "authenticated",
5784
+ app_metadata: user.app_metadata,
5785
+ user_metadata: user.user_metadata,
5786
+ aal: "aal1",
5787
+ amr: [{ method: "password", timestamp: iat }],
5788
+ session_id: randomUUID2(),
5789
+ is_anonymous: false
5790
+ });
5791
+ return { access_token, token_type: "bearer", expires_in, expires_at: iat + expires_in, refresh_token, user: publicUser };
5792
+ }
5793
+ bearer(headers) {
5794
+ const raw = headers["x-agenttwin-app-authorization"] ?? headers.authorization;
5795
+ const v = Array.isArray(raw) ? raw[0] : raw;
5796
+ return v?.startsWith("Bearer ") ? v.slice(7) : void 0;
5797
+ }
5798
+ current(headers) {
5799
+ const token = this.bearer(headers);
5800
+ const claims = token ? this.verify(token) : void 0;
5801
+ return typeof claims?.sub === "string" ? this.users.get(claims.sub) : void 0;
5802
+ }
5803
+ /** Answer one /auth/v1 request; `write` says whether it changed users (for the run's events). */
5804
+ async handle(request) {
5805
+ const path = request.url.pathname.replace(/^\/auth\/v1/, "").replace(/\/$/, "") || "/";
5806
+ const method = request.method.toUpperCase();
5807
+ const reply = (status, value, write3) => ({ status, headers: { "content-type": "application/json" }, body: JSON.stringify(value), write: write3 });
5808
+ const fail = (status, error_code, msg2) => reply(status, { code: status, error_code, msg: msg2 });
5809
+ let body = {};
5810
+ try {
5811
+ if (request.body?.length) body = JSON.parse(request.body.toString("utf8"));
5812
+ } catch {
5813
+ return fail(400, "bad_json", "Could not parse request body as JSON");
5814
+ }
5815
+ const strip = (u) => {
5816
+ const { password: _p, ...rest } = u;
5817
+ return rest;
5818
+ };
5819
+ if (method === "GET" && path === "/health") return reply(200, { version: "agenttwin", name: "GoTrue", description: "GoTrue twin" });
5820
+ if (method === "GET" && path === "/settings") return reply(200, { external: { email: true, phone: false }, disable_signup: false, mailer_autoconfirm: true, phone_autoconfirm: false, sms_provider: "" });
5821
+ if (method === "GET" && path === "/.well-known/jwks.json") return reply(200, { keys: [] });
5822
+ if (method === "POST" && path === "/signup") {
5823
+ const email = String(body.email ?? "").trim().toLowerCase();
5824
+ if (!email) return fail(422, "validation_failed", "Signup requires a valid email");
5825
+ if (String(body.password ?? "").length < 6) return fail(422, "weak_password", "Password should be at least 6 characters.");
5826
+ if (this.users.has(userIdFor(email))) return fail(422, "user_already_exists", "User already registered");
5827
+ const user = this.create(email, String(body.password), body.data ?? body.options?.data ?? {});
5828
+ const refused = await this.onCreate?.(strip(user));
5829
+ if (refused) {
5830
+ this.users.delete(user.id);
5831
+ return fail(500, "unexpected_failure", `Database error saving new user: ${refused}`);
5832
+ }
5833
+ return reply(200, this.session(user), `signed up ${email}`);
5834
+ }
5835
+ if (method === "POST" && path === "/token") {
5836
+ const grant = request.url.searchParams.get("grant_type");
5837
+ if (grant === "password") {
5838
+ const user = this.users.get(userIdFor(String(body.email ?? "")));
5839
+ if (!user || user.password !== String(body.password ?? "")) return fail(400, "invalid_credentials", "Invalid login credentials");
5840
+ user.last_sign_in_at = this.now().toISOString();
5841
+ return reply(200, this.session(user), `signed in ${user.email}`);
5842
+ }
5843
+ if (grant === "refresh_token") {
5844
+ const id = this.refresh.get(String(body.refresh_token ?? ""));
5845
+ const user = id ? this.users.get(id) : void 0;
5846
+ if (!user) return fail(400, "refresh_token_not_found", "Invalid Refresh Token: Refresh Token Not Found");
5847
+ this.refresh.delete(String(body.refresh_token));
5848
+ return reply(200, this.session(user));
5849
+ }
5850
+ return fail(400, "unsupported_grant_type", `grant_type ${grant} is not supported by the AgentTwin Auth twin`);
5851
+ }
5852
+ if (path === "/user") {
5853
+ const user = this.current(request.headers);
5854
+ if (!user) return fail(403, "bad_jwt", "invalid JWT: unable to parse or verify signature, token is unverifiable");
5855
+ if (method === "GET") return reply(200, strip(user));
5856
+ if (method === "PUT") {
5857
+ if (body.email) user.email = String(body.email);
5858
+ if (body.password) user.password = String(body.password);
5859
+ if (body.data) user.user_metadata = { ...user.user_metadata, ...body.data };
5860
+ user.updated_at = this.now().toISOString();
5861
+ return reply(200, strip(user), `updated user ${user.id}`);
5862
+ }
5863
+ }
5864
+ if (method === "POST" && path === "/logout") return { status: 204, headers: {}, body: "" };
5865
+ if (path === "/admin/users" && method === "POST") {
5866
+ const email = String(body.email ?? "").trim().toLowerCase();
5867
+ if (!email) return fail(422, "validation_failed", "email is required");
5868
+ if (this.users.has(userIdFor(email))) return fail(422, "email_exists", "A user with this email address has already been registered");
5869
+ const user = this.create(email, body.password, body.user_metadata ?? {});
5870
+ const refused = await this.onCreate?.(strip(user));
5871
+ if (refused) {
5872
+ this.users.delete(user.id);
5873
+ return fail(500, "unexpected_failure", `Database error creating new user: ${refused}`);
5874
+ }
5875
+ return reply(200, strip(user), `created user ${email}`);
5876
+ }
5877
+ if (path === "/admin/users" && method === "GET") return reply(200, { users: this.list(), aud: "authenticated" });
5878
+ const one = /^\/admin\/users\/([^/]+)$/.exec(path);
5879
+ if (one) {
5880
+ const user = this.users.get(decodeURIComponent(one[1]));
5881
+ if (!user) return fail(404, "user_not_found", "User not found");
5882
+ if (method === "GET") return reply(200, strip(user));
5883
+ if (method === "DELETE") {
5884
+ this.users.delete(user.id);
5885
+ return reply(200, {}, `deleted user ${user.id}`);
5886
+ }
5887
+ if (method === "PUT") {
5888
+ if (body.user_metadata) user.user_metadata = { ...user.user_metadata, ...body.user_metadata };
5889
+ if (body.email) user.email = body.email;
5890
+ return reply(200, strip(user), `updated user ${user.id}`);
5891
+ }
5892
+ }
5893
+ return fail(501, "not_implemented", `AgentTwin Auth twin does not model ${method} /auth/v1${path}`);
5894
+ }
5895
+ };
5896
+ }
5897
+ });
5898
+
5899
+ // src/runtime/supabase-storage.ts
5900
+ var StorageLayer;
5901
+ var init_supabase_storage = __esm({
5902
+ "src/runtime/supabase-storage.ts"() {
5903
+ "use strict";
5904
+ StorageLayer = class {
5905
+ constructor(now = () => /* @__PURE__ */ new Date()) {
5906
+ this.now = now;
5907
+ }
5908
+ now;
5909
+ buckets = /* @__PURE__ */ new Map();
5910
+ objects = /* @__PURE__ */ new Map();
5911
+ key(bucket, name) {
5912
+ return `${bucket}/${name}`;
5913
+ }
5914
+ bucket(name, isPublic = false) {
5915
+ let b = this.buckets.get(name);
5916
+ if (!b) {
5917
+ b = { id: name, name, public: isPublic, created_at: this.now().toISOString() };
5918
+ this.buckets.set(name, b);
5919
+ }
5920
+ return b;
5921
+ }
5922
+ handle(request) {
5923
+ const path = decodeURIComponent(request.url.pathname.replace(/^\/storage\/v1/, ""));
5924
+ const method = request.method.toUpperCase();
5925
+ const reply = (status, value, write3, note) => ({ status, headers: { "content-type": "application/json" }, body: JSON.stringify(value), write: write3, note });
5926
+ const fail = (status, error, message) => reply(status, { statusCode: String(status), error, message });
5927
+ const json = () => {
5928
+ try {
5929
+ return request.body?.length ? JSON.parse(request.body.toString("utf8")) : {};
5930
+ } catch {
5931
+ return {};
5932
+ }
5933
+ };
5934
+ const header3 = (name) => {
5935
+ const v = request.headers[name];
5936
+ return Array.isArray(v) ? v[0] : v;
5937
+ };
5938
+ if (path === "/bucket" && method === "GET") return reply(200, [...this.buckets.values()]);
5939
+ if (path === "/bucket" && method === "POST") {
5940
+ const body = json();
5941
+ const name = String(body.name ?? body.id ?? "");
5942
+ if (!name) return fail(400, "invalid_request", "bucket name is required");
5943
+ if (this.buckets.has(name)) return fail(409, "Duplicate", "The resource already exists");
5944
+ this.bucket(name, !!body.public);
5945
+ return reply(200, { name }, `created bucket ${name}`);
5946
+ }
5947
+ const bucketOne = /^\/bucket\/([^/]+)$/.exec(path);
5948
+ if (bucketOne) {
5949
+ const b = this.buckets.get(bucketOne[1]);
5950
+ if (method === "GET") return b ? reply(200, b) : fail(404, "not_found", "Bucket not found");
5951
+ if (method === "DELETE") {
5952
+ this.buckets.delete(bucketOne[1]);
5953
+ return reply(200, { message: "Successfully deleted" }, `deleted bucket ${bucketOne[1]}`);
5954
+ }
5955
+ }
5956
+ const list2 = /^\/object\/list\/([^/]+)$/.exec(path);
5957
+ if (list2 && method === "POST") {
5958
+ const prefix = String(json().prefix ?? "");
5959
+ 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 } }));
5960
+ return reply(200, items);
5961
+ }
5962
+ const sign = /^\/object\/sign\/([^/]+)\/(.+)$/.exec(path);
5963
+ if (sign && method === "POST") return reply(200, { signedURL: `/object/sign/${sign[1]}/${sign[2]}?token=agenttwin-signed` });
5964
+ if (method === "DELETE" && /^\/object\/([^/]+)$/.test(path)) {
5965
+ const bucket = path.split("/")[2];
5966
+ const names = json().prefixes ?? [];
5967
+ const gone = names.filter((n) => this.objects.delete(this.key(bucket, n)));
5968
+ return reply(200, gone.map((name) => ({ name, bucket_id: bucket })), gone.length ? `deleted ${gone.length} object(s) from ${bucket}` : void 0);
5969
+ }
5970
+ const obj = /^\/object\/(?:(?:authenticated|public|sign)\/)?([^/]+)\/(.+)$/.exec(path);
5971
+ if (obj) {
5972
+ const [, bucket, name] = obj;
5973
+ const k = this.key(bucket, name);
5974
+ if (method === "POST" || method === "PUT") {
5975
+ if (method === "POST" && this.objects.has(k) && header3("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
5976
+ this.bucket(bucket);
5977
+ 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() });
5978
+ return reply(200, { Key: k, Id: k }, `uploaded ${k} (${request.body?.length ?? 0} bytes)`);
5979
+ }
5980
+ if (method === "GET" || method === "HEAD") {
5981
+ let o = this.objects.get(k), note;
5982
+ if (!o) {
5983
+ 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 };
5984
+ this.bucket(bucket);
5985
+ this.objects.set(k, o);
5986
+ note = `stand-in object ${k}: no file was uploaded there in this run, so a small text file was served`;
5987
+ }
5988
+ return { status: 200, headers: { "content-type": o.type, "content-length": String(o.body.length) }, body: "", bytes: method === "HEAD" ? Buffer.alloc(0) : o.body, note };
5989
+ }
5990
+ }
5991
+ return fail(501, "not_implemented", `AgentTwin Storage twin does not model ${method} /storage/v1${path}`);
5992
+ }
5993
+ };
5994
+ }
5995
+ });
5996
+
5683
5997
  // src/runtime/pack-log.ts
5684
5998
  import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
5685
5999
  import { join as join5 } from "path";
@@ -5778,7 +6092,7 @@ var init_pack_aliases = __esm({
5778
6092
  import { createServer as createServer3 } from "http";
5779
6093
  import { createServer as createNetServer } from "net";
5780
6094
  import { isDeepStrictEqual } from "util";
5781
- import { createHash as createHash6 } from "crypto";
6095
+ import { createHash as createHash7 } from "crypto";
5782
6096
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
5783
6097
  import { mkdir, mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile2 } from "fs/promises";
5784
6098
  import { tmpdir as tmpdir3 } from "os";
@@ -5796,13 +6110,15 @@ var init_http_world = __esm({
5796
6110
  init_enterprise_twins();
5797
6111
  init_adapters();
5798
6112
  init_postgrest();
6113
+ init_gotrue();
6114
+ init_supabase_storage();
5799
6115
  init_packs();
5800
6116
  init_pack_log();
5801
6117
  init_pack_aliases();
5802
6118
  init_compatible_packs();
5803
6119
  KEYED_PACKS = /* @__PURE__ */ new Set(["resend"]);
5804
- slackDirectMessageId = (user) => `D${createHash6("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
5805
- idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash6("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
6120
+ slackDirectMessageId = (user) => `D${createHash7("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
6121
+ idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash7("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
5806
6122
  HttpWorld = class {
5807
6123
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
5808
6124
  constructor(spec, seed, options = {}) {
@@ -5829,6 +6145,10 @@ var init_http_world = __esm({
5829
6145
  replayKeys = /* @__PURE__ */ new Map();
5830
6146
  sourceContext = new AsyncLocalStorage2();
5831
6147
  postgrest;
6148
+ /** Supabase Auth (/auth/v1) for the run: the pack's auth lane is not modelled, so users and sessions live here. */
6149
+ gotrue;
6150
+ /** Supabase Storage (/storage/v1): objects uploaded and downloaded in this run. */
6151
+ storage;
5832
6152
  /** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
5833
6153
  attachDatabase(url) {
5834
6154
  void this.postgrest?.close();
@@ -6543,7 +6863,7 @@ var init_http_world = __esm({
6543
6863
  return;
6544
6864
  }
6545
6865
  const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
6546
- const again = { ...last.envelope, envelope_id: createHash6("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" };
6866
+ 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
6867
  last.send(JSON.stringify(again));
6548
6868
  this.record(service.name, "twin", path, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
6549
6869
  json(200, { ok: true, retry_attempt: attempt });
@@ -6589,6 +6909,26 @@ var init_http_world = __esm({
6589
6909
  res.end(r.body);
6590
6910
  return;
6591
6911
  }
6912
+ if (name === "supabase" && path.startsWith("/auth/v1/")) {
6913
+ if (!this.gotrue) {
6914
+ this.gotrue = new GoTrueLayer();
6915
+ this.gotrue.onCreate = async (user) => this.postgrest?.addAuthUser(user);
6916
+ }
6917
+ const r = await this.gotrue.handle({ method, url, headers: req.headers, body });
6918
+ if (r.status === 501) this.rejectUnsupported(service.name, method, path, `supabase auth twin does not model ${method} ${path}`);
6919
+ else this.record(service.name, r.write ? "write" : r.status < 400 ? "read" : "rejected", path, r.write ?? `${method} ${path} \u2192 ${r.status}`);
6920
+ res.writeHead(r.status, r.headers);
6921
+ res.end(r.body);
6922
+ return;
6923
+ }
6924
+ if (name === "supabase" && path.startsWith("/storage/v1/")) {
6925
+ const r = (this.storage ??= new StorageLayer()).handle({ method, url, headers: req.headers, body });
6926
+ if (r.status === 501) this.rejectUnsupported(service.name, method, path, `supabase storage twin does not model ${method} ${path}`);
6927
+ else this.record(service.name, r.write ? "write" : r.status < 400 ? "read" : "rejected", path, r.write ?? r.note ?? `${method} ${path} \u2192 ${r.status}`);
6928
+ res.writeHead(r.status, r.headers);
6929
+ res.end(r.bytes ?? r.body);
6930
+ return;
6931
+ }
6592
6932
  let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
6593
6933
  if (name === "pinecone") {
6594
6934
  const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
@@ -6792,6 +7132,8 @@ var init_http_world = __esm({
6792
7132
  async close() {
6793
7133
  await this.postgrest?.close();
6794
7134
  this.postgrest = void 0;
7135
+ this.gotrue = void 0;
7136
+ this.storage = void 0;
6795
7137
  this.epoch++;
6796
7138
  for (const timer of this.timers) clearTimeout(timer);
6797
7139
  this.timers.clear();
@@ -6975,12 +7317,12 @@ var init_application_process = __esm({
6975
7317
  });
6976
7318
 
6977
7319
  // src/runtime/browser-process-windows.ts
6978
- import { randomUUID as randomUUID2 } from "crypto";
7320
+ import { randomUUID as randomUUID3 } from "crypto";
6979
7321
  import { execFile as execFile3 } from "child_process";
6980
7322
  import { promisify as promisify3 } from "util";
6981
7323
  import { win32 as win322 } from "path";
6982
7324
  function windowsBrowserProcess(executable, commands = run) {
6983
- const marker = "--agenttwin-browser-owner=" + randomUUID2();
7325
+ const marker = "--agenttwin-browser-owner=" + randomUUID3();
6984
7326
  const system = process.env.SystemRoot || process.env.SYSTEMROOT || "C:\\Windows";
6985
7327
  const powershell = win322.join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
6986
7328
  const taskkill = win322.join(system, "System32", "taskkill.exe");
@@ -7800,7 +8142,7 @@ var init_run_summary = __esm({
7800
8142
  });
7801
8143
 
7802
8144
  // src/runtime/generic-calls.ts
7803
- import { createHash as createHash7 } from "crypto";
8145
+ import { createHash as createHash8 } from "crypto";
7804
8146
  function canonical2(value) {
7805
8147
  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
8148
  }
@@ -8087,7 +8429,7 @@ var init_generic_calls = __esm({
8087
8429
  VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
8088
8430
  KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
8089
8431
  KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
8090
- digest = (value) => `sha256:${createHash7("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
8432
+ digest = (value) => `sha256:${createHash8("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
8091
8433
  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
8434
  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
8435
  outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
@@ -8630,7 +8972,7 @@ async function startTwinProxy(routes2) {
8630
8972
  const headers = {};
8631
8973
  const strip = route.auth === "passthrough" ? ["host", "proxy-connection", "proxy-authorization"] : SECRET;
8632
8974
  for (const [k, v] of Object.entries(req.headers)) if (v !== void 0 && !strip.includes(k)) headers[k] = v;
8633
- if (route.appCredential && typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
8975
+ if (typeof req.headers.authorization === "string" && /^Bearer \S{12,}$/.test(req.headers.authorization)) headers["x-agenttwin-app-authorization"] = req.headers.authorization;
8634
8976
  if (route.auth === "passthrough") headers["x-agenttwin-token"] = route.token;
8635
8977
  else if (route.auth === "x-api-key") headers["x-api-key"] = route.token;
8636
8978
  else headers.authorization = `Bearer ${route.token}`;
@@ -8810,16 +9152,25 @@ const removed=r=>r.auth==='passthrough'?['host']:SECRET;
8810
9152
  // 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
9153
  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
9154
  const originalFetch=globalThis.fetch;
9155
+ // A Google Fonts stylesheet for the families a request names, each marked latin (next/font keeps the subsets it asked for).
9156
+ const fontBody=(host,pathAndQuery)=>{
9157
+ if(!/googleapis/.test(host))return '';
9158
+ const query=new URLSearchParams(String(pathAndQuery).split('?')[1]||'');
9159
+ const families=query.getAll('family').map(f=>f.split(':')[0].replace(/\+/g,' ')).filter(Boolean);
9160
+ 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('');
9161
+ };
8813
9162
  if(originalFetch)globalThis.fetch=async function(input,init){
8814
9163
  let url;try{url=new URL(typeof input==='string'||input instanceof URL?String(input):input.url);}catch{return originalFetch(input,init);}
8815
9164
  if((url.protocol!=='http:'&&url.protocol!=='https:')||loopback(url.hostname))return originalFetch(input,init);
8816
9165
  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): an empty stylesheet or font, so rendering goes on offline.
8818
- if(!r&&/^fonts\.(googleapis|gstatic)\.com$/.test(bare(url.hostname)))return new Response('',{status:200,headers:{'content-type':/googleapis/.test(url.hostname)?'text/css':'font/woff2'}});
9166
+ // Web fonts a framework downloads while it renders (next/font): a stylesheet naming the fonts asked for and an empty
9167
+ // font file, so rendering goes on offline (an empty stylesheet is an error to next/font).
9168
+ 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
9169
  if(!r)throw blocked('fetch',url.hostname,url.port||(url.protocol==='https:'?443:80),method);
8820
9170
  if(process.env.AGENTTWIN_DEBUG_ROUTES)console.error('route-match '+url.hostname+' auth='+r.auth+' service='+r.service);
8821
9171
  const request=new Request(input,init),headers=new Headers(request.headers);
8822
- {const own=headers.get('authorization');if(r.appCredential&&own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
9172
+ // The app's own bearer token (a twin-issued key, a signed-in user's session) travels beside the twin credential.
9173
+ {const own=headers.get('authorization');if(own&&/^Bearer \S{12,}$/.test(own))headers.set('x-agenttwin-app-authorization',own);}
8823
9174
  for(const name of removed(r))headers.delete(name);const [name,value]=credential(r);headers.set(name,value);
8824
9175
  headers.set('x-agenttwin-original-host',url.hostname);const location=source();if(location)headers.set('x-agenttwin-source',location);
8825
9176
  // Forward the body as bytes: copying a keepalive Request whose body is a stream throws in Node's fetch (Upstash's
@@ -8837,15 +9188,25 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
8837
9188
  const callback=args.find(a=>typeof a==='function');
8838
9189
  if(options.socketPath)return original.apply(this,args);
8839
9190
  const host=url?url.hostname:(options.hostname||String(options.host||'localhost').replace(/:\d+$/,''));
9191
+ // Postgres over a secure WebSocket to this machine (Neon's serverless driver opens wss://<db host>/v2): the run's
9192
+ // database engine answers the upgrade on its own port, unencrypted, so the driver's frames reach it.
9193
+ if(scheme==='https'&&loopback(host)&&process.env.PGPORT){
9194
+ const h=Array.isArray(options.headers)?{}:(options.headers||{}),wsPath=String(options.path||(url?url.pathname+url.search:'/')),port=Number(options.port||url?.port||443);
9195
+ 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))){
9196
+ const {agent:_a,protocol:_p,createConnection:_c,_defaultAgent:_d,...plain}=options;
9197
+ return originalHttpRequest({...plain,protocol:'http:',host:'127.0.0.1',hostname:'127.0.0.1',port:Number(process.env.PGPORT),path:wsPath},callback);
9198
+ }
9199
+ }
8840
9200
  if(loopback(host))return original.apply(this,args);
8841
9201
  const method=String(options.method||'GET').toUpperCase(),requestPath=options.path||(url?url.pathname+url.search:'/');
8842
9202
  const r=match(host,String(requestPath).split('?')[0]);
8843
9203
  // Web fonts (next/font) over http(s): an empty answer from an in-memory socket, so rendering goes on offline.
8844
9204
  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: 0\r\nConnection: close\r\n\r\n');this.push(null);}done();}});
9205
+ const {Duplex}=require('node:stream'),type=/googleapis/.test(host)?'text/css':'font/woff2',body=Buffer.from(fontBody(host,requestPath));let sent=false;
9206
+ 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
9207
  socket.setTimeout=()=>socket;socket.setNoDelay=()=>socket;socket.setKeepAlive=()=>socket;socket.ref=()=>socket;socket.unref=()=>socket;
8848
- const {agent:_a,...plain}=options;
9208
+ // The answer comes from memory over plain HTTP: drop the https agent and protocol the client asked for.
9209
+ const {agent:_a,protocol:_p,...plain}=options;
8849
9210
  const req=originalHttpRequest({...plain,method,path:requestPath,host:'127.0.0.1',port:9,createConnection:()=>socket},callback);
8850
9211
  return req;
8851
9212
  }
@@ -8854,7 +9215,7 @@ for(const [mod,scheme] of [[http,'http'],[https,'https']]){
8854
9215
  const given=options.headers||{};
8855
9216
  for(const [k,v] of Array.isArray(given)?[]:Object.entries(given))if(!removed(r).includes(k.toLowerCase()))headers[k]=v;
8856
9217
  // 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
- if(r.appCredential){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;}
9218
+ {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
9219
  const [name,value]=credential(r);headers[name]=value;headers.host=target.host;headers['x-agenttwin-original-host']=host;
8859
9220
  const location=source();if(location)headers['x-agenttwin-source']=location;
8860
9221
  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 +9286,124 @@ require('node:module').syncBuiltinESMExports();
8925
9286
  }
8926
9287
  });
8927
9288
 
9289
+ // src/runtime/engines/ws-bridge.ts
9290
+ import { createHash as createHash9 } from "crypto";
9291
+ import { Duplex } from "stream";
9292
+ function bridgeWebSocket(socket, first, accept) {
9293
+ let buffer = first, upgraded = false;
9294
+ const shim = new Duplex({
9295
+ read() {
9296
+ },
9297
+ write(chunk, _enc, done) {
9298
+ if (!socket.destroyed) socket.write(frame2(2, Buffer.from(chunk)));
9299
+ done();
9300
+ },
9301
+ final(done) {
9302
+ if (!socket.destroyed) {
9303
+ socket.write(frame2(8, Buffer.alloc(0)));
9304
+ socket.end();
9305
+ }
9306
+ done();
9307
+ },
9308
+ destroy(error, done) {
9309
+ socket.destroy();
9310
+ done(error);
9311
+ }
9312
+ });
9313
+ shim.setNoDelay = () => shim;
9314
+ shim.setKeepAlive = () => shim;
9315
+ shim.setTimeout = () => shim;
9316
+ socket.on("error", () => shim.destroy());
9317
+ socket.on("close", () => shim.destroy());
9318
+ const pump = () => {
9319
+ if (!upgraded) {
9320
+ const end = buffer.indexOf("\r\n\r\n");
9321
+ if (end < 0) {
9322
+ if (buffer.length > 16384) socket.destroy();
9323
+ return;
9324
+ }
9325
+ const lines = buffer.subarray(0, end).toString("latin1").split("\r\n");
9326
+ buffer = buffer.subarray(end + 4);
9327
+ const headers = new Map(lines.slice(1).map((l) => {
9328
+ const i = l.indexOf(":");
9329
+ return [l.slice(0, i).trim().toLowerCase(), l.slice(i + 1).trim()];
9330
+ }));
9331
+ const key2 = headers.get("sec-websocket-key");
9332
+ if (!key2 || !/websocket/i.test(headers.get("upgrade") ?? "")) {
9333
+ 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");
9334
+ return;
9335
+ }
9336
+ const acceptKey = createHash9("sha1").update(key2 + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64");
9337
+ const protocol = headers.get("sec-websocket-protocol")?.split(",")[0]?.trim();
9338
+ socket.write(`HTTP/1.1 101 Switching Protocols\r
9339
+ Upgrade: websocket\r
9340
+ Connection: Upgrade\r
9341
+ Sec-WebSocket-Accept: ${acceptKey}\r
9342
+ ${protocol ? `Sec-WebSocket-Protocol: ${protocol}\r
9343
+ ` : ""}\r
9344
+ `);
9345
+ upgraded = true;
9346
+ accept(shim);
9347
+ }
9348
+ for (; ; ) {
9349
+ if (buffer.length < 2) return;
9350
+ const opcode = buffer[0] & 15, masked = (buffer[1] & 128) !== 0;
9351
+ let length = buffer[1] & 127, offset = 2;
9352
+ if (length === 126) {
9353
+ if (buffer.length < 4) return;
9354
+ length = buffer.readUInt16BE(2);
9355
+ offset = 4;
9356
+ } else if (length === 127) {
9357
+ if (buffer.length < 10) return;
9358
+ length = Number(buffer.readBigUInt64BE(2));
9359
+ offset = 10;
9360
+ }
9361
+ const mask = masked ? buffer.subarray(offset, offset + 4) : void 0;
9362
+ if (masked) offset += 4;
9363
+ if (buffer.length < offset + length) return;
9364
+ const payload = Buffer.from(buffer.subarray(offset, offset + length));
9365
+ buffer = buffer.subarray(offset + length);
9366
+ if (mask) for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i & 3];
9367
+ if (opcode === 0 || opcode === 1 || opcode === 2) {
9368
+ if (payload.length) shim.push(payload);
9369
+ } else if (opcode === 8) {
9370
+ if (!socket.destroyed) {
9371
+ socket.write(frame2(8, payload.subarray(0, 2)));
9372
+ socket.end();
9373
+ }
9374
+ shim.push(null);
9375
+ return;
9376
+ } else if (opcode === 9) socket.write(frame2(10, payload));
9377
+ }
9378
+ };
9379
+ socket.on("data", (chunk) => {
9380
+ buffer = Buffer.concat([buffer, chunk]);
9381
+ pump();
9382
+ });
9383
+ pump();
9384
+ }
9385
+ var looksLikeHttp, frame2;
9386
+ var init_ws_bridge = __esm({
9387
+ "src/runtime/engines/ws-bridge.ts"() {
9388
+ "use strict";
9389
+ looksLikeHttp = (chunk) => /^(GET|HEAD|POST) \//.test(chunk.subarray(0, 8).toString("latin1"));
9390
+ frame2 = (opcode, payload) => {
9391
+ const n = payload.length;
9392
+ const head = n < 126 ? Buffer.from([128 | opcode, n]) : n < 65536 ? Buffer.alloc(4) : Buffer.alloc(10);
9393
+ if (n >= 126 && n < 65536) {
9394
+ head[0] = 128 | opcode;
9395
+ head[1] = 126;
9396
+ head.writeUInt16BE(n, 2);
9397
+ } else if (n >= 65536) {
9398
+ head[0] = 128 | opcode;
9399
+ head[1] = 127;
9400
+ head.writeBigUInt64BE(BigInt(n), 2);
9401
+ }
9402
+ return Buffer.concat([head, payload]);
9403
+ };
9404
+ }
9405
+ });
9406
+
8928
9407
  // src/runtime/engines/postgres.ts
8929
9408
  import { createServer as createServer5 } from "net";
8930
9409
  function sqlTables(sql) {
@@ -8978,7 +9457,7 @@ async function startPostgresEngine(options = {}) {
8978
9457
  if (!POSTGRES_EXTENSIONS.includes(name)) throw new Error(`PostgreSQL extension ${name} is not available in the embedded engine`);
8979
9458
  const module = name.replace(/-/g, "_");
8980
9459
  try {
8981
- extensions[module] = (await import(`@electric-sql/pglite/contrib/${module}`))[module];
9460
+ extensions[module] = name === "vector" ? (await import("@electric-sql/pglite-pgvector")).vector : (await import(`@electric-sql/pglite/contrib/${module}`))[module];
8982
9461
  } catch (error) {
8983
9462
  throw new EngineUnavailable("postgres", `PGlite extension ${name} could not be loaded (${error instanceof Error ? error.message : String(error)})`);
8984
9463
  }
@@ -9227,6 +9706,7 @@ async function startPostgresEngine(options = {}) {
9227
9706
  socket.end();
9228
9707
  return;
9229
9708
  }
9709
+ if (type === "p") continue;
9230
9710
  batch.push({ type, body });
9231
9711
  if ("SQHcf".includes(type)) {
9232
9712
  const b = batch;
@@ -9236,7 +9716,17 @@ async function startPostgresEngine(options = {}) {
9236
9716
  }
9237
9717
  });
9238
9718
  };
9239
- const server = createServer5(accept);
9719
+ const server = createServer5((socket) => {
9720
+ socket.once("data", (first) => {
9721
+ if (looksLikeHttp(first)) bridgeWebSocket(socket, first, accept);
9722
+ else {
9723
+ accept(socket);
9724
+ socket.emit("data", first);
9725
+ }
9726
+ });
9727
+ socket.on("error", () => {
9728
+ });
9729
+ });
9240
9730
  await new Promise((resolve8, reject) => {
9241
9731
  server.once("error", reject);
9242
9732
  server.listen(0, "127.0.0.1", resolve8);
@@ -9308,10 +9798,10 @@ async function startPostgresEngine(options = {}) {
9308
9798
  for (const row of rows2) {
9309
9799
  const fields = Object.keys(row);
9310
9800
  if (!fields.length) {
9311
- await db.exec(`insert into ${quote2(table2)} default values`);
9801
+ await db.exec(`insert into ${quoteTable(table2)} default values`);
9312
9802
  continue;
9313
9803
  }
9314
- await db.query(`insert into ${quote2(table2)} (${fields.map(quote2).join(",")}) values (${fields.map((_, i) => `$${i + 1}`).join(",")})`, fields.map((c) => {
9804
+ await db.query(`insert into ${quoteTable(table2)} (${fields.map(quote2).join(",")}) values (${fields.map((_, i) => `$${i + 1}`).join(",")})`, fields.map((c) => {
9315
9805
  const v = row[c];
9316
9806
  return v !== null && typeof v === "object" ? JSON.stringify(v) : v ?? null;
9317
9807
  }));
@@ -9389,10 +9879,11 @@ function queryReadOnly(handle, sql) {
9389
9879
  function snapshotPublicTables(handle) {
9390
9880
  return hidden(handle, "snapshotPublic")();
9391
9881
  }
9392
- var LockWait, WRITE, TABLE, normalizeTable, isWriteSql, cstr, msg, int32, errorMessage, ready, quote2, plain, PUBLIC_SNAPSHOT_LIMITS, hidden;
9882
+ var LockWait, WRITE, TABLE, normalizeTable, isWriteSql, cstr, msg, int32, errorMessage, ready, quote2, quoteTable, plain, PUBLIC_SNAPSHOT_LIMITS, hidden;
9393
9883
  var init_postgres = __esm({
9394
9884
  "src/runtime/engines/postgres.ts"() {
9395
9885
  "use strict";
9886
+ init_ws_bridge();
9396
9887
  init_types();
9397
9888
  LockWait = class extends Error {
9398
9889
  };
@@ -9419,6 +9910,7 @@ var init_postgres = __esm({
9419
9910
  errorMessage = (code, message) => msg("E", Buffer.concat([cstr("SERROR"), cstr("VERROR"), cstr("C" + code), cstr("M" + message), Buffer.from([0])]));
9420
9911
  ready = (status) => msg("Z", Buffer.from(status));
9421
9912
  quote2 = (name) => '"' + name.replaceAll('"', '""') + '"';
9913
+ quoteTable = (name) => /^\w+\.\w+$/.test(name) ? name.split(".").map(quote2).join(".") : quote2(name);
9422
9914
  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
9915
  PUBLIC_SNAPSHOT_LIMITS = { tables: 200, columns: 100, rows: 1e3, bytes: 512 * 1024 };
9424
9916
  hidden = (handle, name) => {
@@ -9622,6 +10114,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
9622
10114
  }
9623
10115
  engines = await startLocalEngines(filesDir, spec);
9624
10116
  Object.assign(env, engines.env);
10117
+ applySettingAliases(env, spec.settingAliases);
9625
10118
  if (engines.env.DATABASE_URL) world.attachDatabase(engines.env.DATABASE_URL);
9626
10119
  let stdout = "", stderr = "", timedOut = false;
9627
10120
  const node = /(^|\/)node(\.exe)?$/.test(spec.command[0]);
@@ -9758,6 +10251,7 @@ var init_local = __esm({
9758
10251
  init_browser_execution();
9759
10252
  init_request_source();
9760
10253
  init_http_world();
10254
+ init_spec();
9761
10255
  init_evaluation();
9762
10256
  init_contracts();
9763
10257
  init_default_checks();
@@ -9769,7 +10263,7 @@ var init_local = __esm({
9769
10263
  });
9770
10264
 
9771
10265
  // src/runtime/scenarios.ts
9772
- import { createHash as createHash8 } from "crypto";
10266
+ import { createHash as createHash10 } from "crypto";
9773
10267
  import { mkdir as mkdir3, readFile as readFile6, readdir, writeFile as writeFile8 } from "fs/promises";
9774
10268
  import { join as join13 } from "path";
9775
10269
  import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
@@ -9830,7 +10324,7 @@ var init_scenarios = __esm({
9830
10324
  identifier = /^[a-z][a-z0-9_]{0,39}$/;
9831
10325
  object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
9832
10326
  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) => createHash8("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
10327
+ scenarioDigest = (scenario) => createHash10("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
9834
10328
  }
9835
10329
  });
9836
10330
 
@@ -9915,8 +10409,8 @@ var init_docker_engine = __esm({
9915
10409
  import postgres from "postgres";
9916
10410
  import { execFile as execFile7, spawn as spawn3 } from "child_process";
9917
10411
  import { promisify as promisify7, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
9918
- import { randomBytes as randomBytes2, randomUUID as randomUUID3 } from "crypto";
9919
- import { Duplex } from "stream";
10412
+ import { randomBytes as randomBytes3, randomUUID as randomUUID4 } from "crypto";
10413
+ import { Duplex as Duplex2 } from "stream";
9920
10414
  var exec6;
9921
10415
  var init_docker_postgres = __esm({
9922
10416
  "src/runtime/docker-postgres.ts"() {
@@ -9942,7 +10436,7 @@ import { promisify as promisify8 } from "util";
9942
10436
  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
10437
  import { tmpdir as tmpdir8 } from "os";
9944
10438
  import { join as join17 } from "path";
9945
- import { randomUUID as randomUUID4 } from "crypto";
10439
+ import { randomUUID as randomUUID5 } from "crypto";
9946
10440
  var exec7;
9947
10441
  var init_docker = __esm({
9948
10442
  "src/runtime/docker.ts"() {
@@ -10006,7 +10500,7 @@ var init_hosted_packs = __esm({
10006
10500
  // src/runtime/e2b.ts
10007
10501
  import { createRequire as createRequire3 } from "module";
10008
10502
  import { readFile as readFile11 } from "fs/promises";
10009
- import { randomBytes as randomBytes3 } from "crypto";
10503
+ import { randomBytes as randomBytes4 } from "crypto";
10010
10504
  import { homedir as homedir2 } from "os";
10011
10505
  import { join as join19 } from "path";
10012
10506
  var init_e2b = __esm({
@@ -10020,7 +10514,7 @@ var init_e2b = __esm({
10020
10514
  });
10021
10515
 
10022
10516
  // src/runtime/matrix.ts
10023
- import { createHash as createHash9 } from "crypto";
10517
+ import { createHash as createHash11 } from "crypto";
10024
10518
  import { mkdir as mkdir6, readFile as readFile12, writeFile as writeFile11 } from "fs/promises";
10025
10519
  import { join as join20, relative, resolve as resolve4 } from "path";
10026
10520
  var init_matrix = __esm({
@@ -10033,7 +10527,7 @@ var init_matrix = __esm({
10033
10527
  });
10034
10528
 
10035
10529
  // src/runtime/source-build.ts
10036
- import { createHash as createHash10 } from "crypto";
10530
+ import { createHash as createHash12 } from "crypto";
10037
10531
  import { lstat, readFile as readFile13, realpath as realpath4 } from "fs/promises";
10038
10532
  import { isAbsolute as isAbsolute2, join as join21, relative as relative2, resolve as resolve5, sep } from "path";
10039
10533
  import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
@@ -10048,7 +10542,7 @@ var init_source_build = __esm({
10048
10542
  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
10543
  import { tmpdir as tmpdir9 } from "os";
10050
10544
  import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join22, relative as relative3, resolve as resolve6, sep as sep2 } from "path";
10051
- import { createHash as createHash11, randomUUID as randomUUID5 } from "crypto";
10545
+ import { createHash as createHash13, randomUUID as randomUUID6 } from "crypto";
10052
10546
  async function stageApplication(root, files, destination) {
10053
10547
  const canonicalRoot = await realpath5(root);
10054
10548
  const digests = {};
@@ -10064,7 +10558,7 @@ async function stageApplication(root, files, destination) {
10064
10558
  const target = join22(destination, file);
10065
10559
  await mkdir7(dirname4(target), { recursive: true });
10066
10560
  await writeFile12(target, contents, { mode: 420 });
10067
- digests[file] = createHash11("sha256").update(contents).digest("hex");
10561
+ digests[file] = createHash13("sha256").update(contents).digest("hex");
10068
10562
  }
10069
10563
  return digests;
10070
10564
  }
@@ -10097,20 +10591,20 @@ init_contracts();
10097
10591
  init_run();
10098
10592
  init_git();
10099
10593
  import { createServer as createServer6 } from "http";
10100
- import { randomBytes as randomBytes4, randomUUID as randomUUID6, createHash as createHash12 } from "crypto";
10594
+ import { randomBytes as randomBytes5, randomUUID as randomUUID7, createHash as createHash14 } from "crypto";
10101
10595
  import { mkdir as mkdir8, mkdtemp as mkdtemp10, readFile as readFile15, readdir as readdir3, rename, rm as rm12, writeFile as writeFile13 } from "fs/promises";
10102
10596
  import { dirname as dirname5, join as join23, resolve as resolve7, relative as relative4, sep as sep3 } from "path";
10103
10597
  import { tmpdir as tmpdir10 } from "os";
10104
10598
  import { fileURLToPath as fileURLToPath3 } from "url";
10105
10599
  import { spawn as spawn5 } from "child_process";
10106
10600
  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) => createHash12("sha256").update(JSON.stringify(spec)).digest("hex");
10601
+ var hash2 = (spec) => createHash14("sha256").update(JSON.stringify(spec)).digest("hex");
10108
10602
  function duration(value) {
10109
10603
  if (!Number.isInteger(value) || value < 1 || value > 86400) throw new Error("ttlSeconds must be 1\u201386400");
10110
10604
  return value;
10111
10605
  }
10112
10606
  async function persist(directory2, session) {
10113
- const temporary = join23(directory2, `${randomUUID6()}.tmp`);
10607
+ const temporary = join23(directory2, `${randomUUID7()}.tmp`);
10114
10608
  await writeFile13(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
10115
10609
  await rename(temporary, join23(directory2, "session.json"));
10116
10610
  }
@@ -10234,7 +10728,7 @@ async function serveWorldSession(directory2) {
10234
10728
  world.reset();
10235
10729
  const report = await executeLocal(stage, spec, active.signal, world);
10236
10730
  if (stopping) throw new Error("World expired during execution");
10237
- const runId = randomUUID6();
10731
+ const runId = randomUUID7();
10238
10732
  let project = "local-workspace";
10239
10733
  try {
10240
10734
  project = JSON.parse(await readFile15(join23(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;