agenttwin 0.3.35 → 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.
- package/dist/api.js +2118 -828
- package/dist/dashboard/assets/next/static/chunks/{webpack-e75a66f5f98ea674.js → webpack-b1e92d10ff1fbc69.js} +1 -1
- package/dist/dashboard/index.html +2 -2
- package/dist/engine.js +3014 -1205
- package/dist/gateway.js +2112 -822
- package/dist/worker.js +341 -12
- package/dist/world-host.js +559 -65
- package/package.json +6 -1
- /package/dist/dashboard/assets/next/static/{KHyBySEGTsVqoDj5pH2e6 → RsIyq0Rz3py_mKuoIqn42}/_buildManifest.js +0 -0
- /package/dist/dashboard/assets/next/static/{KHyBySEGTsVqoDj5pH2e6 → RsIyq0Rz3py_mKuoIqn42}/_ssgManifest.js +0 -0
package/dist/worker.js
CHANGED
|
@@ -350,7 +350,7 @@ import { spawn as spawn2 } from "child_process";
|
|
|
350
350
|
import { createServer as createServer3 } from "http";
|
|
351
351
|
import { createServer as createNetServer } from "net";
|
|
352
352
|
import { isDeepStrictEqual } from "util";
|
|
353
|
-
import { createHash as
|
|
353
|
+
import { createHash as createHash7 } from "crypto";
|
|
354
354
|
import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
|
|
355
355
|
|
|
356
356
|
// src/runtime/request-source.ts
|
|
@@ -1183,7 +1183,7 @@ var RedisScripts = class {
|
|
|
1183
1183
|
var WRITE_HINT = /^(set|setnx|setex|psetex|getset|getdel|getex|mset|msetnx|incr|incrby|incrbyfloat|decr|decrby|append|setrange|del|unlink|expire|pexpire|expireat|pexpireat|persist|rename|renamenx|copy|hset|hsetnx|hmset|hdel|hincrby|hincrbyfloat|lpush|rpush|lpop|rpop|lset|lrem|ltrim|linsert|lmove|rpoplpush|sadd|srem|spop|smove|zadd|zrem|zincrby|zpopmin|zpopmax|flushdb|flushall)$/;
|
|
1184
1184
|
|
|
1185
1185
|
// src/runtime/engines/types.ts
|
|
1186
|
-
var 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"];
|
|
1186
|
+
var 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"];
|
|
1187
1187
|
|
|
1188
1188
|
// src/runtime/engines/host.ts
|
|
1189
1189
|
import { execFile as execFile4 } from "child_process";
|
|
@@ -5031,7 +5031,7 @@ function parseWorld(value) {
|
|
|
5031
5031
|
const services = /* @__PURE__ */ new Map();
|
|
5032
5032
|
const requestPathFaults = /* @__PURE__ */ new Set();
|
|
5033
5033
|
for (const service of v.services) {
|
|
5034
|
-
if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(
|
|
5034
|
+
if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid(`service names must be unique lowercase identifiers (${object2(service) && typeof service.name === "string" ? services.has(service.name) ? `${service.name} appears twice` : `${JSON.stringify(service.name)} is not one` : "a service has no name"})`);
|
|
5035
5035
|
const item = service;
|
|
5036
5036
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
5037
5037
|
if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio", "upstash-redis", ...ENTERPRISE_ADAPTERS].includes(String(item.adapter)) && !isGeneratedAdapter(item.adapter) && !isPackAdapter(item.adapter)) invalid("unsupported service adapter");
|
|
@@ -5169,6 +5169,11 @@ function parseWorld(value) {
|
|
|
5169
5169
|
}
|
|
5170
5170
|
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");
|
|
5171
5171
|
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");
|
|
5172
|
+
if (v.settingAliases !== void 0) {
|
|
5173
|
+
if (!object2(v.settingAliases) || Object.keys(v.settingAliases).length > 100) invalid("settingAliases must be an object of at most 100 settings");
|
|
5174
|
+
for (const [name, key2] of Object.entries(v.settingAliases))
|
|
5175
|
+
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");
|
|
5176
|
+
}
|
|
5172
5177
|
if (v.env !== void 0) {
|
|
5173
5178
|
if (!object2(v.env) || Object.keys(v.env).length > 200) invalid("env must be an object of at most 200 string variables");
|
|
5174
5179
|
for (const [key2, value2] of Object.entries(v.env)) {
|
|
@@ -5217,10 +5222,13 @@ function parseWorld(value) {
|
|
|
5217
5222
|
origins.add(mapping.origin);
|
|
5218
5223
|
}
|
|
5219
5224
|
}
|
|
5220
|
-
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"];
|
|
5225
|
+
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"];
|
|
5221
5226
|
if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
|
|
5222
5227
|
return v;
|
|
5223
5228
|
}
|
|
5229
|
+
function applySettingAliases(env, aliases) {
|
|
5230
|
+
for (const [name, key2] of Object.entries(aliases ?? {})) if (!env[name] && env[key2]) env[name] = env[key2];
|
|
5231
|
+
}
|
|
5224
5232
|
|
|
5225
5233
|
// src/runtime/postgrest.ts
|
|
5226
5234
|
import { createRequire as createRequire2 } from "module";
|
|
@@ -5238,6 +5246,20 @@ var PostgrestLayer = class _PostgrestLayer {
|
|
|
5238
5246
|
return this.pool.end().catch(() => {
|
|
5239
5247
|
});
|
|
5240
5248
|
}
|
|
5249
|
+
/**
|
|
5250
|
+
* A Supabase Auth user as a row of auth.users, as GoTrue writes it: the project's own triggers on that table (a
|
|
5251
|
+
* profile, a workspace) run. Returns the database's error when one refuses it; a project without the table is fine.
|
|
5252
|
+
*/
|
|
5253
|
+
async addAuthUser(u) {
|
|
5254
|
+
try {
|
|
5255
|
+
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)
|
|
5256
|
+
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)]);
|
|
5257
|
+
return void 0;
|
|
5258
|
+
} catch (error) {
|
|
5259
|
+
const e = error;
|
|
5260
|
+
return e.code === "42P01" || e.code === "3F000" ? void 0 : e.message ?? String(error);
|
|
5261
|
+
}
|
|
5262
|
+
}
|
|
5241
5263
|
foreignKeys() {
|
|
5242
5264
|
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"
|
|
5243
5265
|
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]
|
|
@@ -5333,7 +5355,7 @@ var PostgrestLayer = class _PostgrestLayer {
|
|
|
5333
5355
|
const cols = await this.columns(table2, "r", params.get("select") ?? "*");
|
|
5334
5356
|
return `WITH r AS (${sql2} RETURNING *) SELECT coalesce(json_agg(x), '[]'::json) AS rows FROM (SELECT ${cols} FROM r) x`;
|
|
5335
5357
|
};
|
|
5336
|
-
let sql, status = 200;
|
|
5358
|
+
let sql, status = 200, perRow = false;
|
|
5337
5359
|
const method = request.method.toUpperCase();
|
|
5338
5360
|
if (method === "GET" || method === "HEAD") {
|
|
5339
5361
|
const order = (params.get("order") ?? "").split(",").filter(Boolean).map((o) => {
|
|
@@ -5342,7 +5364,8 @@ var PostgrestLayer = class _PostgrestLayer {
|
|
|
5342
5364
|
});
|
|
5343
5365
|
const limit = Number(params.get("limit")), offset = Number(params.get("offset"));
|
|
5344
5366
|
const cols = await this.columns(table2, "t", params.get("select") ?? "*");
|
|
5345
|
-
|
|
5367
|
+
perRow = true;
|
|
5368
|
+
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`;
|
|
5346
5369
|
} else if (method === "POST") {
|
|
5347
5370
|
const rows3 = Array.isArray(payload) ? payload : [payload ?? {}];
|
|
5348
5371
|
const keys = [...new Set(rows3.flatMap((r) => Object.keys(r)))];
|
|
@@ -5363,7 +5386,8 @@ var PostgrestLayer = class _PostgrestLayer {
|
|
|
5363
5386
|
} else if (method === "DELETE") {
|
|
5364
5387
|
sql = await returning(`DELETE FROM ${t}${_PostgrestLayer.where(params, values)}`);
|
|
5365
5388
|
} else return reply(405, { code: "PGRST117", message: `Unsupported HTTP method: ${method}` });
|
|
5366
|
-
const
|
|
5389
|
+
const result = await this.pool.query(sql, values);
|
|
5390
|
+
const rows2 = perRow ? result.rows.map((r) => r.row) : result.rows[0]?.rows ?? [];
|
|
5367
5391
|
const range = { "content-range": `0-${Math.max(rows2.length - 1, 0)}/${/count=exact/.test(prefer) ? rows2.length : "*"}` };
|
|
5368
5392
|
if (method !== "GET" && /return=minimal/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
|
|
5369
5393
|
if (method !== "GET" && !/return=representation/.test(prefer)) return reply(method === "POST" ? 201 : 204, void 0, range);
|
|
@@ -5377,6 +5401,284 @@ var PostgrestLayer = class _PostgrestLayer {
|
|
|
5377
5401
|
}
|
|
5378
5402
|
};
|
|
5379
5403
|
|
|
5404
|
+
// src/runtime/gotrue.ts
|
|
5405
|
+
import { createHash as createHash6, createHmac, randomBytes as randomBytes2, randomUUID as randomUUID3 } from "crypto";
|
|
5406
|
+
var b64url = (v) => Buffer.from(v).toString("base64url");
|
|
5407
|
+
var userIdFor = (email) => {
|
|
5408
|
+
const h = createHash6("sha256").update(`agenttwin-user:${email.toLowerCase()}`).digest("hex");
|
|
5409
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
5410
|
+
};
|
|
5411
|
+
var GoTrueLayer = class {
|
|
5412
|
+
constructor(secret = randomBytes2(32).toString("hex"), now = () => /* @__PURE__ */ new Date()) {
|
|
5413
|
+
this.secret = secret;
|
|
5414
|
+
this.now = now;
|
|
5415
|
+
}
|
|
5416
|
+
secret;
|
|
5417
|
+
now;
|
|
5418
|
+
users = /* @__PURE__ */ new Map();
|
|
5419
|
+
refresh = /* @__PURE__ */ new Map();
|
|
5420
|
+
/** Called when a user is created (sign-up, admin create); a returned message fails the call as GoTrue does. */
|
|
5421
|
+
onCreate;
|
|
5422
|
+
/** Users written so far, for the run's evidence. */
|
|
5423
|
+
list() {
|
|
5424
|
+
return [...this.users.values()].map(({ password: _p, ...u }) => u);
|
|
5425
|
+
}
|
|
5426
|
+
sign(claims) {
|
|
5427
|
+
const head = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" })), body = b64url(JSON.stringify(claims));
|
|
5428
|
+
return `${head}.${body}.${b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest())}`;
|
|
5429
|
+
}
|
|
5430
|
+
verify(token) {
|
|
5431
|
+
const [head, body, sig] = token.split(".");
|
|
5432
|
+
if (!head || !body || !sig) return void 0;
|
|
5433
|
+
if (b64url(createHmac("sha256", this.secret).update(`${head}.${body}`).digest()) !== sig) return void 0;
|
|
5434
|
+
try {
|
|
5435
|
+
const c = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
5436
|
+
return typeof c.exp === "number" && c.exp * 1e3 < this.now().getTime() ? void 0 : c;
|
|
5437
|
+
} catch {
|
|
5438
|
+
return void 0;
|
|
5439
|
+
}
|
|
5440
|
+
}
|
|
5441
|
+
create(email, password, meta = {}) {
|
|
5442
|
+
const at = this.now().toISOString(), id = userIdFor(email);
|
|
5443
|
+
const user = {
|
|
5444
|
+
id,
|
|
5445
|
+
aud: "authenticated",
|
|
5446
|
+
role: "authenticated",
|
|
5447
|
+
email,
|
|
5448
|
+
phone: "",
|
|
5449
|
+
email_confirmed_at: at,
|
|
5450
|
+
confirmed_at: at,
|
|
5451
|
+
last_sign_in_at: at,
|
|
5452
|
+
app_metadata: { provider: "email", providers: ["email"] },
|
|
5453
|
+
user_metadata: meta,
|
|
5454
|
+
identities: [],
|
|
5455
|
+
created_at: at,
|
|
5456
|
+
updated_at: at,
|
|
5457
|
+
is_anonymous: false,
|
|
5458
|
+
password
|
|
5459
|
+
};
|
|
5460
|
+
this.users.set(id, user);
|
|
5461
|
+
return user;
|
|
5462
|
+
}
|
|
5463
|
+
session(user) {
|
|
5464
|
+
const iat = Math.floor(this.now().getTime() / 1e3), expires_in = 3600;
|
|
5465
|
+
const refresh_token = randomUUID3().replace(/-/g, "");
|
|
5466
|
+
this.refresh.set(refresh_token, user.id);
|
|
5467
|
+
const { password: _p, ...publicUser } = user;
|
|
5468
|
+
const access_token = this.sign({
|
|
5469
|
+
aud: "authenticated",
|
|
5470
|
+
exp: iat + expires_in,
|
|
5471
|
+
iat,
|
|
5472
|
+
iss: "supabase",
|
|
5473
|
+
sub: user.id,
|
|
5474
|
+
email: user.email,
|
|
5475
|
+
phone: "",
|
|
5476
|
+
role: "authenticated",
|
|
5477
|
+
app_metadata: user.app_metadata,
|
|
5478
|
+
user_metadata: user.user_metadata,
|
|
5479
|
+
aal: "aal1",
|
|
5480
|
+
amr: [{ method: "password", timestamp: iat }],
|
|
5481
|
+
session_id: randomUUID3(),
|
|
5482
|
+
is_anonymous: false
|
|
5483
|
+
});
|
|
5484
|
+
return { access_token, token_type: "bearer", expires_in, expires_at: iat + expires_in, refresh_token, user: publicUser };
|
|
5485
|
+
}
|
|
5486
|
+
bearer(headers) {
|
|
5487
|
+
const raw = headers["x-agenttwin-app-authorization"] ?? headers.authorization;
|
|
5488
|
+
const v = Array.isArray(raw) ? raw[0] : raw;
|
|
5489
|
+
return v?.startsWith("Bearer ") ? v.slice(7) : void 0;
|
|
5490
|
+
}
|
|
5491
|
+
current(headers) {
|
|
5492
|
+
const token = this.bearer(headers);
|
|
5493
|
+
const claims = token ? this.verify(token) : void 0;
|
|
5494
|
+
return typeof claims?.sub === "string" ? this.users.get(claims.sub) : void 0;
|
|
5495
|
+
}
|
|
5496
|
+
/** Answer one /auth/v1 request; `write` says whether it changed users (for the run's events). */
|
|
5497
|
+
async handle(request) {
|
|
5498
|
+
const path = request.url.pathname.replace(/^\/auth\/v1/, "").replace(/\/$/, "") || "/";
|
|
5499
|
+
const method = request.method.toUpperCase();
|
|
5500
|
+
const reply = (status, value, write3) => ({ status, headers: { "content-type": "application/json" }, body: JSON.stringify(value), write: write3 });
|
|
5501
|
+
const fail = (status, error_code, msg) => reply(status, { code: status, error_code, msg });
|
|
5502
|
+
let body = {};
|
|
5503
|
+
try {
|
|
5504
|
+
if (request.body?.length) body = JSON.parse(request.body.toString("utf8"));
|
|
5505
|
+
} catch {
|
|
5506
|
+
return fail(400, "bad_json", "Could not parse request body as JSON");
|
|
5507
|
+
}
|
|
5508
|
+
const strip = (u) => {
|
|
5509
|
+
const { password: _p, ...rest } = u;
|
|
5510
|
+
return rest;
|
|
5511
|
+
};
|
|
5512
|
+
if (method === "GET" && path === "/health") return reply(200, { version: "agenttwin", name: "GoTrue", description: "GoTrue twin" });
|
|
5513
|
+
if (method === "GET" && path === "/settings") return reply(200, { external: { email: true, phone: false }, disable_signup: false, mailer_autoconfirm: true, phone_autoconfirm: false, sms_provider: "" });
|
|
5514
|
+
if (method === "GET" && path === "/.well-known/jwks.json") return reply(200, { keys: [] });
|
|
5515
|
+
if (method === "POST" && path === "/signup") {
|
|
5516
|
+
const email = String(body.email ?? "").trim().toLowerCase();
|
|
5517
|
+
if (!email) return fail(422, "validation_failed", "Signup requires a valid email");
|
|
5518
|
+
if (String(body.password ?? "").length < 6) return fail(422, "weak_password", "Password should be at least 6 characters.");
|
|
5519
|
+
if (this.users.has(userIdFor(email))) return fail(422, "user_already_exists", "User already registered");
|
|
5520
|
+
const user = this.create(email, String(body.password), body.data ?? body.options?.data ?? {});
|
|
5521
|
+
const refused = await this.onCreate?.(strip(user));
|
|
5522
|
+
if (refused) {
|
|
5523
|
+
this.users.delete(user.id);
|
|
5524
|
+
return fail(500, "unexpected_failure", `Database error saving new user: ${refused}`);
|
|
5525
|
+
}
|
|
5526
|
+
return reply(200, this.session(user), `signed up ${email}`);
|
|
5527
|
+
}
|
|
5528
|
+
if (method === "POST" && path === "/token") {
|
|
5529
|
+
const grant = request.url.searchParams.get("grant_type");
|
|
5530
|
+
if (grant === "password") {
|
|
5531
|
+
const user = this.users.get(userIdFor(String(body.email ?? "")));
|
|
5532
|
+
if (!user || user.password !== String(body.password ?? "")) return fail(400, "invalid_credentials", "Invalid login credentials");
|
|
5533
|
+
user.last_sign_in_at = this.now().toISOString();
|
|
5534
|
+
return reply(200, this.session(user), `signed in ${user.email}`);
|
|
5535
|
+
}
|
|
5536
|
+
if (grant === "refresh_token") {
|
|
5537
|
+
const id = this.refresh.get(String(body.refresh_token ?? ""));
|
|
5538
|
+
const user = id ? this.users.get(id) : void 0;
|
|
5539
|
+
if (!user) return fail(400, "refresh_token_not_found", "Invalid Refresh Token: Refresh Token Not Found");
|
|
5540
|
+
this.refresh.delete(String(body.refresh_token));
|
|
5541
|
+
return reply(200, this.session(user));
|
|
5542
|
+
}
|
|
5543
|
+
return fail(400, "unsupported_grant_type", `grant_type ${grant} is not supported by the AgentTwin Auth twin`);
|
|
5544
|
+
}
|
|
5545
|
+
if (path === "/user") {
|
|
5546
|
+
const user = this.current(request.headers);
|
|
5547
|
+
if (!user) return fail(403, "bad_jwt", "invalid JWT: unable to parse or verify signature, token is unverifiable");
|
|
5548
|
+
if (method === "GET") return reply(200, strip(user));
|
|
5549
|
+
if (method === "PUT") {
|
|
5550
|
+
if (body.email) user.email = String(body.email);
|
|
5551
|
+
if (body.password) user.password = String(body.password);
|
|
5552
|
+
if (body.data) user.user_metadata = { ...user.user_metadata, ...body.data };
|
|
5553
|
+
user.updated_at = this.now().toISOString();
|
|
5554
|
+
return reply(200, strip(user), `updated user ${user.id}`);
|
|
5555
|
+
}
|
|
5556
|
+
}
|
|
5557
|
+
if (method === "POST" && path === "/logout") return { status: 204, headers: {}, body: "" };
|
|
5558
|
+
if (path === "/admin/users" && method === "POST") {
|
|
5559
|
+
const email = String(body.email ?? "").trim().toLowerCase();
|
|
5560
|
+
if (!email) return fail(422, "validation_failed", "email is required");
|
|
5561
|
+
if (this.users.has(userIdFor(email))) return fail(422, "email_exists", "A user with this email address has already been registered");
|
|
5562
|
+
const user = this.create(email, body.password, body.user_metadata ?? {});
|
|
5563
|
+
const refused = await this.onCreate?.(strip(user));
|
|
5564
|
+
if (refused) {
|
|
5565
|
+
this.users.delete(user.id);
|
|
5566
|
+
return fail(500, "unexpected_failure", `Database error creating new user: ${refused}`);
|
|
5567
|
+
}
|
|
5568
|
+
return reply(200, strip(user), `created user ${email}`);
|
|
5569
|
+
}
|
|
5570
|
+
if (path === "/admin/users" && method === "GET") return reply(200, { users: this.list(), aud: "authenticated" });
|
|
5571
|
+
const one = /^\/admin\/users\/([^/]+)$/.exec(path);
|
|
5572
|
+
if (one) {
|
|
5573
|
+
const user = this.users.get(decodeURIComponent(one[1]));
|
|
5574
|
+
if (!user) return fail(404, "user_not_found", "User not found");
|
|
5575
|
+
if (method === "GET") return reply(200, strip(user));
|
|
5576
|
+
if (method === "DELETE") {
|
|
5577
|
+
this.users.delete(user.id);
|
|
5578
|
+
return reply(200, {}, `deleted user ${user.id}`);
|
|
5579
|
+
}
|
|
5580
|
+
if (method === "PUT") {
|
|
5581
|
+
if (body.user_metadata) user.user_metadata = { ...user.user_metadata, ...body.user_metadata };
|
|
5582
|
+
if (body.email) user.email = body.email;
|
|
5583
|
+
return reply(200, strip(user), `updated user ${user.id}`);
|
|
5584
|
+
}
|
|
5585
|
+
}
|
|
5586
|
+
return fail(501, "not_implemented", `AgentTwin Auth twin does not model ${method} /auth/v1${path}`);
|
|
5587
|
+
}
|
|
5588
|
+
};
|
|
5589
|
+
|
|
5590
|
+
// src/runtime/supabase-storage.ts
|
|
5591
|
+
var StorageLayer = class {
|
|
5592
|
+
constructor(now = () => /* @__PURE__ */ new Date()) {
|
|
5593
|
+
this.now = now;
|
|
5594
|
+
}
|
|
5595
|
+
now;
|
|
5596
|
+
buckets = /* @__PURE__ */ new Map();
|
|
5597
|
+
objects = /* @__PURE__ */ new Map();
|
|
5598
|
+
key(bucket, name) {
|
|
5599
|
+
return `${bucket}/${name}`;
|
|
5600
|
+
}
|
|
5601
|
+
bucket(name, isPublic = false) {
|
|
5602
|
+
let b = this.buckets.get(name);
|
|
5603
|
+
if (!b) {
|
|
5604
|
+
b = { id: name, name, public: isPublic, created_at: this.now().toISOString() };
|
|
5605
|
+
this.buckets.set(name, b);
|
|
5606
|
+
}
|
|
5607
|
+
return b;
|
|
5608
|
+
}
|
|
5609
|
+
handle(request) {
|
|
5610
|
+
const path = decodeURIComponent(request.url.pathname.replace(/^\/storage\/v1/, ""));
|
|
5611
|
+
const method = request.method.toUpperCase();
|
|
5612
|
+
const reply = (status, value, write3, note) => ({ status, headers: { "content-type": "application/json" }, body: JSON.stringify(value), write: write3, note });
|
|
5613
|
+
const fail = (status, error, message) => reply(status, { statusCode: String(status), error, message });
|
|
5614
|
+
const json = () => {
|
|
5615
|
+
try {
|
|
5616
|
+
return request.body?.length ? JSON.parse(request.body.toString("utf8")) : {};
|
|
5617
|
+
} catch {
|
|
5618
|
+
return {};
|
|
5619
|
+
}
|
|
5620
|
+
};
|
|
5621
|
+
const header3 = (name) => {
|
|
5622
|
+
const v = request.headers[name];
|
|
5623
|
+
return Array.isArray(v) ? v[0] : v;
|
|
5624
|
+
};
|
|
5625
|
+
if (path === "/bucket" && method === "GET") return reply(200, [...this.buckets.values()]);
|
|
5626
|
+
if (path === "/bucket" && method === "POST") {
|
|
5627
|
+
const body = json();
|
|
5628
|
+
const name = String(body.name ?? body.id ?? "");
|
|
5629
|
+
if (!name) return fail(400, "invalid_request", "bucket name is required");
|
|
5630
|
+
if (this.buckets.has(name)) return fail(409, "Duplicate", "The resource already exists");
|
|
5631
|
+
this.bucket(name, !!body.public);
|
|
5632
|
+
return reply(200, { name }, `created bucket ${name}`);
|
|
5633
|
+
}
|
|
5634
|
+
const bucketOne = /^\/bucket\/([^/]+)$/.exec(path);
|
|
5635
|
+
if (bucketOne) {
|
|
5636
|
+
const b = this.buckets.get(bucketOne[1]);
|
|
5637
|
+
if (method === "GET") return b ? reply(200, b) : fail(404, "not_found", "Bucket not found");
|
|
5638
|
+
if (method === "DELETE") {
|
|
5639
|
+
this.buckets.delete(bucketOne[1]);
|
|
5640
|
+
return reply(200, { message: "Successfully deleted" }, `deleted bucket ${bucketOne[1]}`);
|
|
5641
|
+
}
|
|
5642
|
+
}
|
|
5643
|
+
const list2 = /^\/object\/list\/([^/]+)$/.exec(path);
|
|
5644
|
+
if (list2 && method === "POST") {
|
|
5645
|
+
const prefix = String(json().prefix ?? "");
|
|
5646
|
+
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 } }));
|
|
5647
|
+
return reply(200, items);
|
|
5648
|
+
}
|
|
5649
|
+
const sign = /^\/object\/sign\/([^/]+)\/(.+)$/.exec(path);
|
|
5650
|
+
if (sign && method === "POST") return reply(200, { signedURL: `/object/sign/${sign[1]}/${sign[2]}?token=agenttwin-signed` });
|
|
5651
|
+
if (method === "DELETE" && /^\/object\/([^/]+)$/.test(path)) {
|
|
5652
|
+
const bucket = path.split("/")[2];
|
|
5653
|
+
const names = json().prefixes ?? [];
|
|
5654
|
+
const gone = names.filter((n) => this.objects.delete(this.key(bucket, n)));
|
|
5655
|
+
return reply(200, gone.map((name) => ({ name, bucket_id: bucket })), gone.length ? `deleted ${gone.length} object(s) from ${bucket}` : void 0);
|
|
5656
|
+
}
|
|
5657
|
+
const obj = /^\/object\/(?:(?:authenticated|public|sign)\/)?([^/]+)\/(.+)$/.exec(path);
|
|
5658
|
+
if (obj) {
|
|
5659
|
+
const [, bucket, name] = obj;
|
|
5660
|
+
const k = this.key(bucket, name);
|
|
5661
|
+
if (method === "POST" || method === "PUT") {
|
|
5662
|
+
if (method === "POST" && this.objects.has(k) && header3("x-upsert") !== "true") return fail(400, "Duplicate", "The resource already exists");
|
|
5663
|
+
this.bucket(bucket);
|
|
5664
|
+
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() });
|
|
5665
|
+
return reply(200, { Key: k, Id: k }, `uploaded ${k} (${request.body?.length ?? 0} bytes)`);
|
|
5666
|
+
}
|
|
5667
|
+
if (method === "GET" || method === "HEAD") {
|
|
5668
|
+
let o = this.objects.get(k), note;
|
|
5669
|
+
if (!o) {
|
|
5670
|
+
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 };
|
|
5671
|
+
this.bucket(bucket);
|
|
5672
|
+
this.objects.set(k, o);
|
|
5673
|
+
note = `stand-in object ${k}: no file was uploaded there in this run, so a small text file was served`;
|
|
5674
|
+
}
|
|
5675
|
+
return { status: 200, headers: { "content-type": o.type, "content-length": String(o.body.length) }, body: "", bytes: method === "HEAD" ? Buffer.alloc(0) : o.body, note };
|
|
5676
|
+
}
|
|
5677
|
+
}
|
|
5678
|
+
return fail(501, "not_implemented", `AgentTwin Storage twin does not model ${method} /storage/v1${path}`);
|
|
5679
|
+
}
|
|
5680
|
+
};
|
|
5681
|
+
|
|
5380
5682
|
// src/runtime/pack-log.ts
|
|
5381
5683
|
import { closeSync, existsSync as existsSync2, openSync, readdirSync as readdirSync2, readSync, statSync } from "fs";
|
|
5382
5684
|
import { join as join6 } from "path";
|
|
@@ -5465,8 +5767,8 @@ function aliasRequest(pack, host, url) {
|
|
|
5465
5767
|
import { tmpdir as tmpdir4 } from "os";
|
|
5466
5768
|
import { join as join7 } from "path";
|
|
5467
5769
|
var KEYED_PACKS = /* @__PURE__ */ new Set(["resend"]);
|
|
5468
|
-
var slackDirectMessageId = (user) => `D${
|
|
5469
|
-
var idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${
|
|
5770
|
+
var slackDirectMessageId = (user) => `D${createHash7("sha256").update(user).digest("hex").slice(0, 16).toUpperCase()}`;
|
|
5771
|
+
var idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash7("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
|
|
5470
5772
|
var HttpWorld = class {
|
|
5471
5773
|
/** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
|
|
5472
5774
|
constructor(spec, seed, options = {}) {
|
|
@@ -5493,6 +5795,10 @@ var HttpWorld = class {
|
|
|
5493
5795
|
replayKeys = /* @__PURE__ */ new Map();
|
|
5494
5796
|
sourceContext = new AsyncLocalStorage2();
|
|
5495
5797
|
postgrest;
|
|
5798
|
+
/** Supabase Auth (/auth/v1) for the run: the pack's auth lane is not modelled, so users and sessions live here. */
|
|
5799
|
+
gotrue;
|
|
5800
|
+
/** Supabase Storage (/storage/v1): objects uploaded and downloaded in this run. */
|
|
5801
|
+
storage;
|
|
5496
5802
|
/** The run's PostgreSQL: a pack's PostgREST paths (/rest/v1/<table>) are served from it, so the app's own tables answer. */
|
|
5497
5803
|
attachDatabase(url) {
|
|
5498
5804
|
void this.postgrest?.close();
|
|
@@ -6207,7 +6513,7 @@ var HttpWorld = class {
|
|
|
6207
6513
|
return;
|
|
6208
6514
|
}
|
|
6209
6515
|
const attempt = Number(last.envelope.retry_attempt ?? 0) + 1;
|
|
6210
|
-
const again = { ...last.envelope, envelope_id:
|
|
6516
|
+
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" };
|
|
6211
6517
|
last.send(JSON.stringify(again));
|
|
6212
6518
|
this.record(service.name, "twin", path, `redelivered ${String(last.envelope.type ?? "envelope")} (retry_attempt ${attempt}, as after a lost acknowledgment)`);
|
|
6213
6519
|
json(200, { ok: true, retry_attempt: attempt });
|
|
@@ -6253,6 +6559,26 @@ var HttpWorld = class {
|
|
|
6253
6559
|
res.end(r.body);
|
|
6254
6560
|
return;
|
|
6255
6561
|
}
|
|
6562
|
+
if (name === "supabase" && path.startsWith("/auth/v1/")) {
|
|
6563
|
+
if (!this.gotrue) {
|
|
6564
|
+
this.gotrue = new GoTrueLayer();
|
|
6565
|
+
this.gotrue.onCreate = async (user) => this.postgrest?.addAuthUser(user);
|
|
6566
|
+
}
|
|
6567
|
+
const r = await this.gotrue.handle({ method, url, headers: req.headers, body });
|
|
6568
|
+
if (r.status === 501) this.rejectUnsupported(service.name, method, path, `supabase auth twin does not model ${method} ${path}`);
|
|
6569
|
+
else this.record(service.name, r.write ? "write" : r.status < 400 ? "read" : "rejected", path, r.write ?? `${method} ${path} \u2192 ${r.status}`);
|
|
6570
|
+
res.writeHead(r.status, r.headers);
|
|
6571
|
+
res.end(r.body);
|
|
6572
|
+
return;
|
|
6573
|
+
}
|
|
6574
|
+
if (name === "supabase" && path.startsWith("/storage/v1/")) {
|
|
6575
|
+
const r = (this.storage ??= new StorageLayer()).handle({ method, url, headers: req.headers, body });
|
|
6576
|
+
if (r.status === 501) this.rejectUnsupported(service.name, method, path, `supabase storage twin does not model ${method} ${path}`);
|
|
6577
|
+
else this.record(service.name, r.write ? "write" : r.status < 400 ? "read" : "rejected", path, r.write ?? r.note ?? `${method} ${path} \u2192 ${r.status}`);
|
|
6578
|
+
res.writeHead(r.status, r.headers);
|
|
6579
|
+
res.end(r.bytes ?? r.body);
|
|
6580
|
+
return;
|
|
6581
|
+
}
|
|
6256
6582
|
let host = String(req.headers["x-agenttwin-original-host"] ?? (raw ? req.headers.host?.replace(/:\d+$/, "") : void 0) ?? baseHost);
|
|
6257
6583
|
if (name === "pinecone") {
|
|
6258
6584
|
const m = /^([a-z0-9-]+?)-[a-z0-9]+\.svc\.[a-z0-9.-]*pinecone\.io$/.exec(host);
|
|
@@ -6456,6 +6782,8 @@ var HttpWorld = class {
|
|
|
6456
6782
|
async close() {
|
|
6457
6783
|
await this.postgrest?.close();
|
|
6458
6784
|
this.postgrest = void 0;
|
|
6785
|
+
this.gotrue = void 0;
|
|
6786
|
+
this.storage = void 0;
|
|
6459
6787
|
this.epoch++;
|
|
6460
6788
|
for (const timer of this.timers) clearTimeout(timer);
|
|
6461
6789
|
this.timers.clear();
|
|
@@ -7086,14 +7414,14 @@ import { join as join9 } from "path";
|
|
|
7086
7414
|
var formatMoney = (m) => new Intl.NumberFormat("en-US", { style: "currency", currency: m.currency.length === 3 ? m.currency : "USD" }).format(m.amount);
|
|
7087
7415
|
|
|
7088
7416
|
// src/runtime/generic-calls.ts
|
|
7089
|
-
import { createHash as
|
|
7417
|
+
import { createHash as createHash8 } from "crypto";
|
|
7090
7418
|
var WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
7091
7419
|
var READ_LIKE = /\/(search|query|lookup|count|batch\/read|completions|embeddings|responses|count_tokens|graphql\/query)$/i;
|
|
7092
7420
|
var MODEL_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|mistral\.ai|groq\.com|cohere\.ai)$/i;
|
|
7093
7421
|
var VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
|
|
7094
7422
|
var KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
|
|
7095
7423
|
var KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
|
|
7096
|
-
var digest = (value) => `sha256:${
|
|
7424
|
+
var digest = (value) => `sha256:${createHash8("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
|
|
7097
7425
|
function canonical2(value) {
|
|
7098
7426
|
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);
|
|
7099
7427
|
}
|
|
@@ -7827,6 +8155,7 @@ async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid:
|
|
|
7827
8155
|
env[`AGENTTWIN_${name.toUpperCase()}_URL`] = credential.endpoint;
|
|
7828
8156
|
env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = credential.token;
|
|
7829
8157
|
}
|
|
8158
|
+
applySettingAliases(env, spec.settingAliases);
|
|
7830
8159
|
if (spec.command[0] !== "node") throw new Error(`The isolated runner runs Node applications; run ${spec.command[0]} workflows locally with npx agenttwin (they use the twin proxy).`);
|
|
7831
8160
|
hook = await createRequestSourceHook(join10(input, "app"), spec, credentials, { root: join10(input, "app"), violationsFd: 3 });
|
|
7832
8161
|
await chmod2(dirname2(hook.path), 493);
|