agenttwin 0.3.25 → 0.3.26

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.
Files changed (23) hide show
  1. package/dist/api.js +600 -189
  2. package/dist/dashboard/assets/next/static/chunks/{1018.4871a8dd0f112c38.js → 1018.66d31bb49c376d17.js} +1 -1
  3. package/dist/dashboard/assets/next/static/chunks/1937-f5553afe6a14cf73.js +1 -0
  4. package/dist/dashboard/assets/next/static/chunks/{2743-a0efd6f4aeb11cc5.js → 2743-72610a5d5a3f8462.js} +1 -1
  5. package/dist/dashboard/assets/next/static/chunks/5663-661e38f3ed101571.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/{6751.613adb085c9a5b06.js → 6751.d9c97d8c374550b0.js} +1 -1
  7. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-73183e77e91eaaa0.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-3a3a934622d409c3.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/v2/page-fc4df4912ce3af44.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/{webpack-7171b2b838217ab1.js → webpack-c3ef4a63a3242476.js} +1 -1
  11. package/dist/dashboard/assets/next/static/css/aa701337c7b34139.css +1 -0
  12. package/dist/dashboard/index.html +2 -2
  13. package/dist/engine.js +20 -7
  14. package/dist/gateway.js +651 -193
  15. package/package.json +1 -1
  16. package/dist/dashboard/assets/next/static/chunks/1250-7571b1a697f6bb4a.js +0 -1
  17. package/dist/dashboard/assets/next/static/chunks/5663-2ba656663ac4643f.js +0 -1
  18. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-2d0408d8f22d7921.js +0 -1
  19. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-0e0392368e0a891e.js +0 -1
  20. package/dist/dashboard/assets/next/static/chunks/app/v2/page-3e86fffabfa87d88.js +0 -1
  21. package/dist/dashboard/assets/next/static/css/1d1b20bd9fb076d4.css +0 -1
  22. /package/dist/dashboard/assets/next/static/{S50QwVNd9oAThVehzZ6V7 → KSAqb4jD1gnp0t5kzwmoJ}/_buildManifest.js +0 -0
  23. /package/dist/dashboard/assets/next/static/{S50QwVNd9oAThVehzZ6V7 → KSAqb4jD1gnp0t5kzwmoJ}/_ssgManifest.js +0 -0
package/dist/gateway.js CHANGED
@@ -128,16 +128,17 @@ function schemaDDL() {
128
128
  if (table2 === "run_receipts") fk("account_id,job_id", "runs(account_id,job_id)");
129
129
  if (table2 === "chat_messages") fk("thread_id", "chat_threads(thread_id)");
130
130
  if (table2 === "oauth_tokens") fk("client_id", "oauth_clients(client_id)");
131
+ if (table2 === "team_members") fk("member_id", "accounts(account_id)");
131
132
  if (table2 === "github_pr_events" || table2 === "github_checks") fk("installation_id", "github_installations(installation_id)");
132
133
  return "create table gateway." + table2 + " (" + [columns, "position integer not null", "source_fields text[] not null", ...refs].join(",") + ")";
133
134
  });
134
135
  }
135
- var definitions, tables;
136
+ var definitions, V2_TABLES, GATEWAY_SCHEMA_VERSION, tables;
136
137
  var init_gateway_schema = __esm({
137
138
  "src/runtime/gateway-schema.ts"() {
138
139
  "use strict";
139
140
  definitions = {
140
- accounts: ["account_id uuid primary key, workspace_label text not null, active boolean not null, workspace_profile json, organization text, email text unique, display_name text, password_hash text, email_verified boolean, usage_day text, runs integer, chat_usage_day text, chat_requests integer, voice_usage_day text, voice_requests integer", "account_id"],
141
+ accounts: ["account_id uuid primary key, workspace_label text not null, active boolean not null, workspace_profile json, organization text, email text unique, display_name text, password_hash text, email_verified boolean, usage_day text, runs integer, chat_usage_day text, chat_requests integer, voice_usage_day text, voice_requests integer, active_workspace uuid, provisioned_by uuid", "account_id"],
141
142
  projects: ["project_id uuid primary key, account_id uuid not null, name text not null, inventory json, listed boolean not null, is_latest boolean not null, sync_order integer, unique(account_id,name), unique(account_id,project_id)", "project_id"],
142
143
  external_identities: ["provider text, issuer text, subject text, account_id uuid not null, primary key(provider,issuer,subject)", "provider issuer subject"],
143
144
  account_tokens: ["token_hash text primary key, account_id uuid not null, kind text not null check(kind in ('primary','cli'))", "token_hash"],
@@ -154,8 +155,14 @@ var init_gateway_schema = __esm({
154
155
  oauth_tokens: ["token_hash text primary key, client_id text not null, scopes text[], expires_at bigint", "token_hash"],
155
156
  github_installations: ["installation_id bigint primary key, account_id uuid, github_owner text, repositories text[], setup_action text, created_at text, suspended boolean, removed boolean not null", "installation_id"],
156
157
  github_pr_events: ["event_id bigint primary key, installation_id bigint not null, repository text, pr_number integer, head_sha text, base_sha text, action text, received_at text, title text", "event_id"],
157
- github_checks: ["check_id bigint primary key, installation_id bigint not null, repository text, pr_number integer, head_sha text, base_sha text, verdict text, title text, headline text, at_risk json, failed integer, checks integer, untested integer, services text[], url text, created_at text", "check_id"]
158
+ github_checks: ["check_id bigint primary key, installation_id bigint not null, repository text, pr_number integer, head_sha text, base_sha text, verdict text, title text, headline text, at_risk json, failed integer, checks integer, untested integer, services text[], url text, created_at text", "check_id"],
159
+ team_members: ["account_id uuid not null, member_id uuid not null, role text not null check(role in ('admin','member','viewer')), added_at text, added_by text, primary key(account_id,member_id)", "account_id member_id"],
160
+ team_invites: ["invite_id uuid primary key, account_id uuid not null, email text not null, role text not null check(role in ('admin','member','viewer')), code_hash text not null unique, expires_at bigint not null, created_at text, invited_by text, accepted_by uuid, accepted_at text", "invite_id"],
161
+ org_tokens: ["token_hash text primary key, token_id uuid not null unique, account_id uuid not null, label text, role text not null check(role in ('admin','member','viewer')), created_at text, created_by text", "token_hash"],
162
+ audit_events: ["event_id uuid primary key, account_id uuid not null, at text not null, actor_id text, actor_label text, action text not null, subject text, details json", "event_id"]
158
163
  };
164
+ V2_TABLES = ["team_members", "team_invites", "org_tokens", "audit_events"];
165
+ GATEWAY_SCHEMA_VERSION = 2;
159
166
  tables = Object.keys(definitions);
160
167
  }
161
168
  });
@@ -304,7 +311,11 @@ var init_gateway_records = __esm({
304
311
  oauthTokens: "oauth_tokens",
305
312
  githubInstallations: "github_installations",
306
313
  githubEvents: "github_pr_events",
307
- githubChecks: "github_checks"
314
+ githubChecks: "github_checks",
315
+ teamMembers: "team_members",
316
+ teamInvites: "team_invites",
317
+ orgTokens: "org_tokens",
318
+ auditEvents: "audit_events"
308
319
  };
309
320
  renames = {
310
321
  accounts: { id: "account_id", label: "workspace_label" },
@@ -321,7 +332,10 @@ var init_gateway_records = __esm({
321
332
  oauth_tokens: { hash: "token_hash", expires: "expires_at" },
322
333
  github_installations: { owner: "github_owner" },
323
334
  github_pr_events: { number: "pr_number" },
324
- github_checks: { number: "pr_number" }
335
+ github_checks: { number: "pr_number" },
336
+ team_invites: { id: "invite_id" },
337
+ org_tokens: { id: "token_id" },
338
+ audit_events: { id: "event_id" }
325
339
  };
326
340
  column = (t, k) => renames[t]?.[k] ?? k.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
327
341
  nested = {
@@ -339,14 +353,17 @@ var init_gateway_records = __esm({
339
353
  var gateway_postgres_exports = {};
340
354
  __export(gateway_postgres_exports, {
341
355
  importGatewayState: () => importGatewayState,
356
+ importJsonStateOnStart: () => importJsonStateOnStart,
342
357
  openGatewayPostgres: () => openGatewayPostgres,
343
- temporaryDatabaseError: () => temporaryDatabaseError
358
+ temporaryDatabaseError: () => temporaryDatabaseError,
359
+ upgradeGatewaySchema: () => upgradeGatewaySchema
344
360
  });
345
- import { readFile } from "fs/promises";
361
+ import { readFile, rename, stat } from "fs/promises";
362
+ import { join } from "path";
346
363
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
347
364
  async function load(tx) {
348
365
  const [version] = await tx.unsafe("select version,revision,shape from " + meta + " where singleton");
349
- if (version?.version !== 1) throw Error("Expected gateway relational schema v1");
366
+ if (version?.version !== GATEWAY_SCHEMA_VERSION) throw Error(`Expected gateway relational schema v${GATEWAY_SCHEMA_VERSION}`);
350
367
  const rows2 = emptyRows();
351
368
  for (const t of tables) {
352
369
  for (const { record: record3 } of await tx.unsafe("select row_to_json(t) as record from gateway." + t + " t")) {
@@ -396,7 +413,7 @@ async function importGatewayState(url, file) {
396
413
  await tx.unsafe("create unique index one_latest_project on gateway.projects(account_id) where is_latest");
397
414
  await tx.unsafe("create unique index one_primary_token on gateway.account_tokens(account_id) where kind='primary'");
398
415
  await tx.unsafe("create table " + meta + " (singleton boolean primary key check(singleton), version integer not null, revision bigint not null, shape json not null)");
399
- await tx.unsafe("insert into " + meta + " values(true,1,1,$1::text::json)", [JSON.stringify(shape2)]);
416
+ await tx.unsafe("insert into " + meta + " values(true," + GATEWAY_SCHEMA_VERSION + ",1,$1::text::json)", [JSON.stringify(shape2)]);
400
417
  await applyChanges(tx, emptyRows(), rows2);
401
418
  if (!isDeepStrictEqual2((await load(tx)).state, state)) throw Error("Import did not round trip; rolling back");
402
419
  });
@@ -404,6 +421,38 @@ async function importGatewayState(url, file) {
404
421
  await sql.end();
405
422
  }
406
423
  }
424
+ async function importJsonStateOnStart(url, directory) {
425
+ const file = join(directory, "state.json");
426
+ try {
427
+ await stat(file);
428
+ } catch (error) {
429
+ if (error.code === "ENOENT") return void 0;
430
+ throw error;
431
+ }
432
+ await importGatewayState(url, file);
433
+ const kept = join(directory, `state.json.imported-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`);
434
+ await rename(file, kept);
435
+ return kept;
436
+ }
437
+ async function upgrade(tx) {
438
+ await tx.unsafe("select pg_advisory_xact_lock(723690104)");
439
+ const [current] = await tx.unsafe("select version from " + meta + " where singleton for update");
440
+ if (current?.version === GATEWAY_SCHEMA_VERSION) return;
441
+ if (current?.version !== 1) throw Error("Unknown gateway schema version " + current?.version);
442
+ await tx.unsafe("alter table gateway.accounts add column active_workspace uuid, add column provisioned_by uuid");
443
+ const ddl = schemaDDL();
444
+ for (const t of V2_TABLES) await tx.unsafe(ddl[tables.indexOf(t)]);
445
+ await tx.unsafe("update " + meta + " set version=" + GATEWAY_SCHEMA_VERSION + " where singleton");
446
+ }
447
+ async function upgradeGatewaySchema(url) {
448
+ const sql = gatewayConnection(url);
449
+ try {
450
+ const present = await sql.begin("isolation level repeatable read read only", async (tx) => (await tx.unsafe("select to_regclass('gateway.migration_state') is not null as present"))[0]?.present);
451
+ if (present) await sql.begin("", upgrade);
452
+ } finally {
453
+ await sql.end();
454
+ }
455
+ }
407
456
  function temporaryDatabaseError(error) {
408
457
  return error instanceof Error && (connectionErrors.has(error.code ?? "") || // pg-pool emits plain Errors (no SQLSTATE) for handshake and checkout timeouts.
409
458
  error.message === "Connection terminated due to connection timeout" || error.message === "timeout exceeded when trying to connect" || error.message === "Connection terminated unexpectedly");
@@ -1081,17 +1130,17 @@ var init_adapters = __esm({
1081
1130
 
1082
1131
  // src/runtime/packs.ts
1083
1132
  import { existsSync, readFileSync } from "fs";
1084
- import { dirname, join as join2, resolve } from "path";
1133
+ import { dirname, join as join3, resolve } from "path";
1085
1134
  import { fileURLToPath, pathToFileURL } from "url";
1086
1135
  function packsDir() {
1087
1136
  const here = dirname(fileURLToPath(import.meta.url));
1088
- const candidates = [process.env.AGENTTWIN_TWINS_DIR, join2(here, "twins"), join2(here, "../twins"), resolve(here, "../../../twins/dist")];
1089
- return candidates.find((dir) => !!dir && existsSync(join2(dir, "catalog.json")));
1137
+ const candidates = [process.env.AGENTTWIN_TWINS_DIR, join3(here, "twins"), join3(here, "../twins"), resolve(here, "../../../twins/dist")];
1138
+ return candidates.find((dir) => !!dir && existsSync(join3(dir, "catalog.json")));
1090
1139
  }
1091
1140
  function packCatalog() {
1092
1141
  if (cached !== void 0) return cached;
1093
1142
  const dir = packsDir();
1094
- cached = dir ? JSON.parse(readFileSync(join2(dir, "catalog.json"), "utf8")) : null;
1143
+ cached = dir ? JSON.parse(readFileSync(join3(dir, "catalog.json"), "utf8")) : null;
1095
1144
  return cached;
1096
1145
  }
1097
1146
  function loadPack(name) {
@@ -1099,7 +1148,7 @@ function loadPack(name) {
1099
1148
  if (!record3) throw new Error(`No twin pack named ${name}`);
1100
1149
  let factory = loaded.get(name);
1101
1150
  if (!factory) {
1102
- const file = join2(packsDir(), "packs", name, "index.mjs");
1151
+ const file = join3(packsDir(), "packs", name, "index.mjs");
1103
1152
  factory = import(pathToFileURL(file).href).then((mod) => {
1104
1153
  if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
1105
1154
  return mod.createTwinFetch;
@@ -2332,7 +2381,7 @@ var init_spec = __esm({
2332
2381
  // src/runtime/scenarios.ts
2333
2382
  import { createHash as createHash7 } from "crypto";
2334
2383
  import { mkdir, readFile as readFile3, readdir, writeFile as writeFile2 } from "fs/promises";
2335
- import { join as join3 } from "path";
2384
+ import { join as join4 } from "path";
2336
2385
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
2337
2386
  function parseScenario(value) {
2338
2387
  const fail2 = (detail) => {
@@ -2371,7 +2420,7 @@ function reference(ref) {
2371
2420
  }
2372
2421
  async function loadScenario(cwd, ref) {
2373
2422
  const { id, version } = reference(ref);
2374
- const path2 = join3(cwd, ".agenttwin/scenarios", id, `${version}.json`);
2423
+ const path2 = join4(cwd, ".agenttwin/scenarios", id, `${version}.json`);
2375
2424
  const bytes = await readFile3(path2);
2376
2425
  if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
2377
2426
  const scenario = parseScenario(JSON.parse(bytes.toString()));
@@ -2600,14 +2649,14 @@ var init_browser_process_windows = __esm({
2600
2649
  // src/runtime/browser-process.ts
2601
2650
  import { mkdtemp, writeFile as writeFile3, readFile as readFile4, rm } from "fs/promises";
2602
2651
  import { tmpdir } from "os";
2603
- import { join as join4 } from "path";
2652
+ import { join as join5 } from "path";
2604
2653
  import { execFile as execFile3 } from "child_process";
2605
2654
  import { promisify as promisify3 } from "util";
2606
2655
  async function ownBrowserProcess(executable) {
2607
2656
  if (process.platform === "win32") return withCleanup(windowsBrowserProcess(executable), async () => {
2608
2657
  });
2609
- const root = await mkdtemp(join4(tmpdir(), "agenttwin-browser-owner-"));
2610
- const pidFile = join4(root, "pid"), launcher = join4(root, "launch");
2658
+ const root = await mkdtemp(join5(tmpdir(), "agenttwin-browser-owner-"));
2659
+ const pidFile = join5(root, "pid"), launcher = join5(root, "launch");
2611
2660
  await writeFile3(launcher, `#!/bin/sh
2612
2661
  echo $$ > ${quote(pidFile)}
2613
2662
  exec ${quote(executable)} "$@"
@@ -2709,11 +2758,11 @@ var init_browser_process = __esm({
2709
2758
  // src/runtime/browser-directories.ts
2710
2759
  import { mkdtemp as mkdtemp2, mkdir as mkdir2, chown, chmod, rm as rm2 } from "fs/promises";
2711
2760
  import { tmpdir as tmpdir2 } from "os";
2712
- import { join as join5 } from "path";
2761
+ import { join as join6 } from "path";
2713
2762
  async function createBrowserDirectories(identity) {
2714
2763
  if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
2715
- const root = await mkdtemp2(join5(tmpdir2(), "agenttwin-browser-"));
2716
- const profile = join5(root, "profile"), artifacts = join5(root, "artifacts");
2764
+ const root = await mkdtemp2(join6(tmpdir2(), "agenttwin-browser-"));
2765
+ const profile = join6(root, "profile"), artifacts = join6(root, "artifacts");
2717
2766
  const close = () => rm2(root, { recursive: true, force: true });
2718
2767
  try {
2719
2768
  await mkdir2(profile, { mode: 448 });
@@ -2917,7 +2966,7 @@ var init_browser_execution = __esm({
2917
2966
  // src/runtime/request-source.ts
2918
2967
  import { mkdtemp as mkdtemp3, writeFile as writeFile4, readFile as readFile5, rm as rm3, realpath } from "fs/promises";
2919
2968
  import { tmpdir as tmpdir3 } from "os";
2920
- import { join as join6, resolve as resolve2 } from "path";
2969
+ import { join as join7, resolve as resolve2 } from "path";
2921
2970
  function parseRequestSource(raw, spec) {
2922
2971
  if (typeof raw !== "string" || raw.length > 1024) return;
2923
2972
  try {
@@ -2929,9 +2978,9 @@ function parseRequestSource(raw, spec) {
2929
2978
  }
2930
2979
  }
2931
2980
  async function createRequestSourceHook(app, spec, credentials2, runtime) {
2932
- const dir = await mkdtemp3(join6(tmpdir3(), "agenttwin-source-hook-"));
2933
- const path2 = join6(dir, "hook.cjs");
2934
- const violationsPath = join6(dir, "blocked.jsonl");
2981
+ const dir = await mkdtemp3(join7(tmpdir3(), "agenttwin-source-hook-"));
2982
+ const path2 = join7(dir, "hook.cjs");
2983
+ const violationsPath = join7(dir, "blocked.jsonl");
2935
2984
  const config = { root: runtime?.root ?? await realpath(resolve2(app)), files: spec.files, origins: Object.values(credentials2).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials2[r.service]])), routing: !!spec.fetchRoutes, violationsFd: runtime?.violationsFd, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
2936
2985
  const hook = applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
2937
2986
  ` + String.raw`
@@ -4374,7 +4423,7 @@ var init_rest_adapters = __esm({
4374
4423
 
4375
4424
  // src/runtime/pack-log.ts
4376
4425
  import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
4377
- import { join as join7 } from "path";
4426
+ import { join as join8 } from "path";
4378
4427
  function packCollection(type, requestPath) {
4379
4428
  const segments = requestPath.split("/").filter(Boolean);
4380
4429
  const at = segments.findIndex((s) => s === type || singular2(s) === type || s.replace(/-/g, "_") === type || singular2(s.replace(/-/g, "_")) === type);
@@ -4414,7 +4463,7 @@ var init_pack_log = __esm({
4414
4463
  partial = /* @__PURE__ */ new Map();
4415
4464
  files() {
4416
4465
  if (!existsSync2(this.root)) return [];
4417
- return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join7(this.root, f)).sort();
4466
+ return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join8(this.root, f)).sort();
4418
4467
  }
4419
4468
  drain() {
4420
4469
  const out = [];
@@ -4452,7 +4501,7 @@ import { createHash as createHash10 } from "crypto";
4452
4501
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4453
4502
  import { mkdir as mkdir3, mkdtemp as mkdtemp4, rm as rm4, writeFile as writeFile5 } from "fs/promises";
4454
4503
  import { tmpdir as tmpdir4 } from "os";
4455
- import { join as join8 } from "path";
4504
+ import { join as join9 } from "path";
4456
4505
  var idempotencyKeyDigest, HttpWorld;
4457
4506
  var init_http_world = __esm({
4458
4507
  "src/runtime/http-world.ts"() {
@@ -4890,22 +4939,22 @@ var init_http_world = __esm({
4890
4939
  async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
4891
4940
  const name = service.adapter.slice(PACK_PREFIX.length), meta2 = packRecord(name);
4892
4941
  if (this.twinClock && packCatalog()?.engine[meta2.generation]?.clockSupport !== "async-context-v1") throw new Error("Twin packs need rebuilding for per-run clock support");
4893
- const root = await mkdtemp4(join8(tmpdir4(), `agenttwin-pack-${name}-`));
4942
+ const root = await mkdtemp4(join9(tmpdir4(), `agenttwin-pack-${name}-`));
4894
4943
  this.packRoots.push(root);
4895
4944
  const worldSeed = meta2.logService ? JSON.stringify({ id: `twin:${meta2.logService}:world_seed.record:seed:agenttwin`, service: meta2.logService, op: "set", operation: "world_seed.record", subject: { type: "_world_seed", id: "seed" }, occurredAt: new Date(twinNowMs(Date.now())).toISOString(), actor: { kind: "system" }, fields: { value: new SeedStream(this.seed, `pack-world:${service.name}`).nextHex(64) } }) + "\n" : "";
4896
4945
  const writeSeedLog = async (dir, text2) => {
4897
4946
  if (!text2) return;
4898
- await mkdir3(join8(dir, ".volter/world", meta2.logService), { recursive: true });
4899
- await writeFile5(join8(dir, ".volter/world", meta2.logService, "actions.jsonl"), text2);
4947
+ await mkdir3(join9(dir, ".volter/world", meta2.logService), { recursive: true });
4948
+ await writeFile5(join9(dir, ".volter/world", meta2.logService, "actions.jsonl"), text2);
4900
4949
  };
4901
4950
  let tenant = {}, credential;
4902
4951
  if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
4903
- const probe = await mkdtemp4(join8(tmpdir4(), `agenttwin-pack-${name}-probe-`));
4952
+ const probe = await mkdtemp4(join9(tmpdir4(), `agenttwin-pack-${name}-probe-`));
4904
4953
  try {
4905
4954
  await writeSeedLog(probe, worldSeed);
4906
4955
  const scratch = await (await loadPack(name))({ root: probe });
4907
4956
  await (await scratch(new Request(`https://${meta2.hosts[0]?.host ?? `${name}.twin.test`}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }))).arrayBuffer();
4908
- const probed = new PackActionTail(join8(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
4957
+ const probed = new PackActionTail(join9(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
4909
4958
  tenant = tenantFields(probed);
4910
4959
  credential = credentialAction(probed);
4911
4960
  } finally {
@@ -4917,7 +4966,7 @@ var init_http_world = __esm({
4917
4966
  await writeSeedLog(root, seeded);
4918
4967
  const twin = await (await loadPack(name))({ root });
4919
4968
  const baseHost = meta2.hosts[0]?.host ?? `${name}.twin.test`;
4920
- const log = new PackActionTail(join8(root, ".volter"));
4969
+ const log = new PackActionTail(join9(root, ".volter"));
4921
4970
  let issued = {};
4922
4971
  if (meta2.credentialDoor) {
4923
4972
  const r = await twin(new Request(`https://${baseHost}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
@@ -5559,10 +5608,10 @@ var init_contracts = __esm({
5559
5608
 
5560
5609
  // src/runtime/cost-model.ts
5561
5610
  import { readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
5562
- import { join as join9 } from "path";
5611
+ import { join as join10 } from "path";
5563
5612
  async function readCostConfig(cwd) {
5564
5613
  try {
5565
- const raw = JSON.parse(await readFile6(join9(cwd, COSTS_FILE), "utf8"));
5614
+ const raw = JSON.parse(await readFile6(join10(cwd, COSTS_FILE), "utf8"));
5566
5615
  return raw && typeof raw === "object" ? raw : void 0;
5567
5616
  } catch {
5568
5617
  return void 0;
@@ -6421,7 +6470,7 @@ import { execFile as execFile4 } from "child_process";
6421
6470
  import { mkdtemp as mkdtemp5, readFile as readFile7, rm as rm5, writeFile as writeFile7 } from "fs/promises";
6422
6471
  import { createServer as createServer2, request as httpRequest } from "http";
6423
6472
  import { tmpdir as tmpdir5 } from "os";
6424
- import { join as join10 } from "path";
6473
+ import { join as join11 } from "path";
6425
6474
  import { createSecureContext, TLSSocket } from "tls";
6426
6475
  import { promisify as promisify4 } from "util";
6427
6476
  function matchRoute(routes2, host, pathname) {
@@ -6446,7 +6495,7 @@ function rewrite(r, p) {
6446
6495
  return p;
6447
6496
  }
6448
6497
  async function runAuthority(dir) {
6449
- const ca = { key: join10(dir, "ca.key"), cert: join10(dir, "ca.pem") };
6498
+ const ca = { key: join11(dir, "ca.key"), cert: join11(dir, "ca.pem") };
6450
6499
  await run2("openssl", [
6451
6500
  "req",
6452
6501
  "-x509",
@@ -6477,7 +6526,7 @@ async function runAuthority(dir) {
6477
6526
  let ctx = contexts.get(host);
6478
6527
  if (!ctx) {
6479
6528
  ctx = (async () => {
6480
- const base = join10(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
6529
+ const base = join11(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
6481
6530
  await writeFile7(base + ".ext", `basicConstraints=critical,CA:FALSE
6482
6531
  keyUsage=critical,digitalSignature
6483
6532
  extendedKeyUsage=serverAuth
@@ -6496,7 +6545,7 @@ authorityKeyIdentifier=keyid,issuer
6496
6545
  };
6497
6546
  }
6498
6547
  async function startTwinProxy(routes2) {
6499
- const dir = await mkdtemp5(join10(tmpdir5(), "agenttwin-proxy-"));
6548
+ const dir = await mkdtemp5(join11(tmpdir5(), "agenttwin-proxy-"));
6500
6549
  const authority = await runAuthority(dir).catch((error) => {
6501
6550
  throw new Error(`The twin proxy needs the openssl command to make this run's certificate authority: ${error instanceof Error ? error.message : error}`);
6502
6551
  });
@@ -6614,7 +6663,7 @@ var init_twin_proxy = __esm({
6614
6663
  // src/runtime/twin-routing.ts
6615
6664
  import { mkdtemp as mkdtemp6, readFile as readFile8, rm as rm6, writeFile as writeFile8 } from "fs/promises";
6616
6665
  import { tmpdir as tmpdir6 } from "os";
6617
- import { join as join11 } from "path";
6666
+ import { join as join12 } from "path";
6618
6667
  function twinRoutes(services, world, models) {
6619
6668
  const routes2 = [];
6620
6669
  for (const service of services) {
@@ -7343,20 +7392,20 @@ var init_exit = __esm({
7343
7392
 
7344
7393
  // src/runtime/stage-worker.ts
7345
7394
  import { copyFile, rm as rm7 } from "fs/promises";
7346
- import { basename, dirname as dirname2, join as join12 } from "path";
7395
+ import { basename, dirname as dirname2, join as join13 } from "path";
7347
7396
  import { fileURLToPath as fileURLToPath2 } from "url";
7348
7397
  async function stageWorker(stage, runModuleUrl) {
7349
7398
  const modulePath = fileURLToPath2(runModuleUrl), directory = dirname2(modulePath);
7350
- const destination = join12(stage, "worker.js");
7399
+ const destination = join13(stage, "worker.js");
7351
7400
  const sourceDevelopment = basename(modulePath) === "run.ts" && basename(directory) === "commands" && basename(dirname2(directory)) === "src";
7352
7401
  if (!sourceDevelopment) {
7353
- await copyFile(join12(directory, "worker.js"), destination);
7402
+ await copyFile(join13(directory, "worker.js"), destination);
7354
7403
  return;
7355
7404
  }
7356
7405
  try {
7357
7406
  const { build: build2 } = await import("esbuild");
7358
7407
  await build2({
7359
- entryPoints: [join12(directory, "../runtime/worker.ts")],
7408
+ entryPoints: [join13(directory, "../runtime/worker.ts")],
7360
7409
  outfile: destination,
7361
7410
  bundle: true,
7362
7411
  platform: "node",
@@ -7392,7 +7441,7 @@ var init_offline = __esm({
7392
7441
 
7393
7442
  // src/runtime/credentials.ts
7394
7443
  import { homedir } from "os";
7395
- import { join as join13 } from "path";
7444
+ import { join as join14 } from "path";
7396
7445
  import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile9, chmod as chmod2, rm as rm8 } from "fs/promises";
7397
7446
  async function savedConnection() {
7398
7447
  try {
@@ -7407,13 +7456,13 @@ var path;
7407
7456
  var init_credentials = __esm({
7408
7457
  "src/runtime/credentials.ts"() {
7409
7458
  "use strict";
7410
- path = () => join13(homedir(), ".agenttwin", "credentials.json");
7459
+ path = () => join14(homedir(), ".agenttwin", "credentials.json");
7411
7460
  }
7412
7461
  });
7413
7462
 
7414
7463
  // src/runtime/remote.ts
7415
7464
  import { readFile as readFile10 } from "fs/promises";
7416
- import { join as join14 } from "path";
7465
+ import { join as join15 } from "path";
7417
7466
  function apiBase(value) {
7418
7467
  if (offline()) throw new CliError(OFFLINE_MESSAGE, { code: EXIT.USAGE });
7419
7468
  let url;
@@ -7431,7 +7480,7 @@ async function executeRemote(stage, spec, log, metadata = {}) {
7431
7480
  const token = process.env.AGENTTWIN_TOKEN || saved?.token;
7432
7481
  if (!token) throw new CliError("Sign in first with npx agenttwin login", { code: EXIT.BLOCKED });
7433
7482
  const files = /* @__PURE__ */ Object.create(null);
7434
- for (const file of spec.files) files[file] = (await readFile10(join14(stage, "app", file))).toString("base64");
7483
+ for (const file of spec.files) files[file] = (await readFile10(join15(stage, "app", file))).toString("base64");
7435
7484
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
7436
7485
  const response = await fetch(`${base}/v1/runs`, { method: "POST", headers, body: JSON.stringify({ spec, files, ...metadata }), redirect: "error", signal: AbortSignal.timeout(15e3) });
7437
7486
  if (!response.ok) throw new CliError(`AgentTwin API rejected run (${response.status}): ${await response.text()}`, { code: response.status === 401 || response.status === 429 ? EXIT.BLOCKED : EXIT.ERROR });
@@ -7479,8 +7528,8 @@ async function captureGit(cwd, previousHead) {
7479
7528
  }
7480
7529
  }
7481
7530
  return { head, branch: branch || "detached HEAD", totalCommits: Number(total), dirty: !!status, capturedAt: (/* @__PURE__ */ new Date()).toISOString(), commits: history ? history.split("\n").map((line) => {
7482
- const [sha4, date] = line.split(" ");
7483
- return { sha: sha4, date };
7531
+ const [sha6, date] = line.split(" ");
7532
+ return { sha: sha6, date };
7484
7533
  }) : [], changedFiles: [...new Set(changed.split("\n").filter(Boolean))].slice(0, 1e3), ...previousHead ? { previousHead } : {} };
7485
7534
  } catch {
7486
7535
  return void 0;
@@ -7489,9 +7538,9 @@ async function captureGit(cwd, previousHead) {
7489
7538
  function validateGit(value) {
7490
7539
  if (value === void 0) return void 0;
7491
7540
  const g = value;
7492
- const sha4 = (s) => typeof s === "string" && /^[a-f0-9]{40,64}$/.test(s);
7541
+ const sha6 = (s) => typeof s === "string" && /^[a-f0-9]{40,64}$/.test(s);
7493
7542
  const date = (s) => typeof s === "string" && s.length <= 40 && Number.isFinite(Date.parse(s));
7494
- if (!g || !sha4(g.head) || g.previousHead !== void 0 && !sha4(g.previousHead) || typeof g.branch !== "string" || g.branch.length > 240 || /[\x00-\x1f]/.test(g.branch) || !Number.isSafeInteger(g.totalCommits) || g.totalCommits < 0 || typeof g.dirty !== "boolean" || !date(g.capturedAt) || !Array.isArray(g.commits) || g.commits.length > 100 || g.commits.some((c) => !sha4(c.sha) || !date(c.date)) || !Array.isArray(g.changedFiles) || g.changedFiles.length > 1e3 || g.changedFiles.some((p) => typeof p !== "string" || p.length > 500 || p.startsWith("/") || p.includes("\\") || p.split("/").includes("..") || /[\x00-\x1f]/.test(p))) throw new Error("Invalid Git metadata");
7543
+ if (!g || !sha6(g.head) || g.previousHead !== void 0 && !sha6(g.previousHead) || typeof g.branch !== "string" || g.branch.length > 240 || /[\x00-\x1f]/.test(g.branch) || !Number.isSafeInteger(g.totalCommits) || g.totalCommits < 0 || typeof g.dirty !== "boolean" || !date(g.capturedAt) || !Array.isArray(g.commits) || g.commits.length > 100 || g.commits.some((c) => !sha6(c.sha) || !date(c.date)) || !Array.isArray(g.changedFiles) || g.changedFiles.length > 1e3 || g.changedFiles.some((p) => typeof p !== "string" || p.length > 500 || p.startsWith("/") || p.includes("\\") || p.split("/").includes("..") || /[\x00-\x1f]/.test(p))) throw new Error("Invalid Git metadata");
7495
7544
  return { head: g.head, branch: g.branch, totalCommits: g.totalCommits, dirty: g.dirty, capturedAt: g.capturedAt, commits: g.commits.map((c) => ({ sha: c.sha, date: c.date })), changedFiles: [...g.changedFiles], ...g.previousHead ? { previousHead: g.previousHead } : {} };
7496
7545
  }
7497
7546
  var init_git = __esm({
@@ -7502,7 +7551,7 @@ var init_git = __esm({
7502
7551
 
7503
7552
  // src/runtime/hosted-packs.ts
7504
7553
  import { readFile as readFile11, readdir as readdir2 } from "fs/promises";
7505
- import { join as join15 } from "path";
7554
+ import { join as join16 } from "path";
7506
7555
  async function hostedPackFiles(spec) {
7507
7556
  const names = [...new Set(spec.services.flatMap((s) => s.adapter?.startsWith(PACK_PREFIX) ? [s.adapter.slice(PACK_PREFIX.length)] : []))];
7508
7557
  if (!names.length) return [];
@@ -7510,7 +7559,7 @@ async function hostedPackFiles(spec) {
7510
7559
  if (!root || !catalog) throw new Error("Installed twin packs are unavailable");
7511
7560
  const files = [];
7512
7561
  const add = async (path2) => {
7513
- files.push({ path: "twins/" + path2, data: await readFile11(join15(root, path2)) });
7562
+ files.push({ path: "twins/" + path2, data: await readFile11(join16(root, path2)) });
7514
7563
  };
7515
7564
  const engines = /* @__PURE__ */ new Set();
7516
7565
  for (const name of names) {
@@ -7521,7 +7570,7 @@ async function hostedPackFiles(spec) {
7521
7570
  for (const file of ["index.mjs", "LICENSE", "NOTICE"]) await add(`packs/${name}/${file}`);
7522
7571
  }
7523
7572
  const walk3 = async (dir) => {
7524
- for (const entry of await readdir2(join15(root, dir), { withFileTypes: true })) {
7573
+ for (const entry of await readdir2(join16(root, dir), { withFileTypes: true })) {
7525
7574
  const path2 = dir + "/" + entry.name;
7526
7575
  if (entry.isSymbolicLink()) throw new Error("Twin engine symlinks are unsupported");
7527
7576
  if (entry.isDirectory()) await walk3(path2);
@@ -7544,14 +7593,14 @@ import { createRequire } from "module";
7544
7593
  import { readFile as readFile12 } from "fs/promises";
7545
7594
  import { randomBytes as randomBytes6 } from "crypto";
7546
7595
  import { homedir as homedir2 } from "os";
7547
- import { join as join16 } from "path";
7596
+ import { join as join17 } from "path";
7548
7597
  async function executeE2B(stage, spec, log, signal) {
7549
7598
  signal?.throwIfAborted();
7550
7599
  const apiKey = process.env.E2B_API_KEY;
7551
7600
  if (!apiKey) throw new CliError("E2B_API_KEY is not configured", { code: EXIT.BLOCKED, action: "Set E2B_API_KEY in your shell. It remains on the host and is never passed to the application." });
7552
7601
  let saved = {};
7553
7602
  try {
7554
- saved = JSON.parse(await readFile12(join16(homedir2(), ".agenttwin/runtime.json"), "utf8"));
7603
+ saved = JSON.parse(await readFile12(join17(homedir2(), ".agenttwin/runtime.json"), "utf8"));
7555
7604
  } catch {
7556
7605
  }
7557
7606
  const template = process.env.E2B_TEMPLATE_ID ?? saved.templateId;
@@ -7572,12 +7621,12 @@ async function executeE2B(stage, spec, log, signal) {
7572
7621
  await sandbox.commands.run("mkdir -p /input/app && chmod 755 /input /input/app", { user: "root" });
7573
7622
  const upload = ["world.json", "worker.js", ...spec.files.map((f) => `app/${f}`)];
7574
7623
  try {
7575
- JSON.parse(await readFile12(join16(stage, "seed.json"), "utf8"));
7624
+ JSON.parse(await readFile12(join17(stage, "seed.json"), "utf8"));
7576
7625
  upload.push("seed.json");
7577
7626
  } catch {
7578
7627
  }
7579
7628
  for (const file of upload) {
7580
- await sandbox.files.write(`/input/${file}`, new Uint8Array(await readFile12(join16(stage, file))).buffer, { user: "root" });
7629
+ await sandbox.files.write(`/input/${file}`, new Uint8Array(await readFile12(join17(stage, file))).buffer, { user: "root" });
7581
7630
  }
7582
7631
  for (const file of await hostedPackFiles(spec)) {
7583
7632
  await sandbox.files.write("/input/" + file.path, new Uint8Array(file.data).buffer, { user: "root" });
@@ -7660,7 +7709,7 @@ var init_e2b = __esm({
7660
7709
  // src/runtime/matrix.ts
7661
7710
  import { createHash as createHash12 } from "crypto";
7662
7711
  import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
7663
- import { join as join17, relative, resolve as resolve4 } from "path";
7712
+ import { join as join18, relative, resolve as resolve4 } from "path";
7664
7713
  function filesDigest(sourceDigests) {
7665
7714
  const canonical4 = Object.keys(sourceDigests).sort().map((file) => `${file}:${sourceDigests[file]}`).join("\n");
7666
7715
  return createHash12("sha256").update(canonical4).digest("hex");
@@ -7749,13 +7798,13 @@ async function runSeedMatrix(cwd, opts) {
7749
7798
  if (!Number.isInteger(opts.seeds) || opts.seeds < 1 || opts.seeds > MAX_SEEDS) throw new CliError(`--seeds must be an integer between 1 and ${MAX_SEEDS}`, { code: EXIT.USAGE });
7750
7799
  const baseSeed = normalizeSeed(opts.seed);
7751
7800
  const matrixName = `matrix-${createHash12("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
7752
- const matrixDir = resolve4(cwd, opts.out ?? join17(".agenttwin/runs", matrixName));
7801
+ const matrixDir = resolve4(cwd, opts.out ?? join18(".agenttwin/runs", matrixName));
7753
7802
  await mkdir5(matrixDir, { recursive: true, mode: 448 });
7754
7803
  const results = [];
7755
7804
  for (let index = 0; index < opts.seeds; index++) {
7756
7805
  const seed = deriveSeed(baseSeed, index);
7757
7806
  opts.log(`Seed matrix ${index + 1}/${opts.seeds}: seed ${seed}`);
7758
- const run3 = await runWorld(cwd, { file: opts.file, fault: opts.fault, out: join17(relative(cwd, matrixDir).split("\\").join("/"), `seed-${index}`), seed, runtime: "local", log: opts.log, signal: opts.signal });
7807
+ const run3 = await runWorld(cwd, { file: opts.file, fault: opts.fault, out: join18(relative(cwd, matrixDir).split("\\").join("/"), `seed-${index}`), seed, runtime: "local", log: opts.log, signal: opts.signal });
7759
7808
  if (run3.seed !== seed) throw new CliError(`Run ${run3.runId} recorded seed ${run3.seed} instead of the requested derived seed ${seed}`);
7760
7809
  const { checks, allPassed } = checksOfReceipt(run3);
7761
7810
  results.push({
@@ -7769,7 +7818,7 @@ async function runSeedMatrix(cwd, opts) {
7769
7818
  allPassed
7770
7819
  });
7771
7820
  }
7772
- const first = JSON.parse(await readFile13(join17(matrixDir, "seed-0", "run.json"), "utf8"));
7821
+ const first = JSON.parse(await readFile13(join18(matrixDir, "seed-0", "run.json"), "utf8"));
7773
7822
  const report = buildMatrixReport({
7774
7823
  matrixId: matrixName,
7775
7824
  name: first.name,
@@ -7779,10 +7828,10 @@ async function runSeedMatrix(cwd, opts) {
7779
7828
  results,
7780
7829
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
7781
7830
  });
7782
- const reportPath = resolve4(cwd, opts.out ?? join17(matrixDir, "matrix.json"));
7783
- await mkdir5(opts.out && opts.out.endsWith(".json") ? join17(reportPath, "..") : matrixDir, { recursive: true, mode: 448 });
7831
+ const reportPath = resolve4(cwd, opts.out ?? join18(matrixDir, "matrix.json"));
7832
+ await mkdir5(opts.out && opts.out.endsWith(".json") ? join18(reportPath, "..") : matrixDir, { recursive: true, mode: 448 });
7784
7833
  await writeFile10(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
7785
- await writeFile10(join17(matrixDir, "matrix.md"), `${report.verdict.summary}
7834
+ await writeFile10(join18(matrixDir, "matrix.md"), `${report.verdict.summary}
7786
7835
 
7787
7836
  Report: ${relative(cwd, reportPath).split("\\").join("/")}
7788
7837
  `);
@@ -7804,7 +7853,7 @@ var init_matrix = __esm({
7804
7853
  // src/runtime/source-build.ts
7805
7854
  import { createHash as createHash13 } from "crypto";
7806
7855
  import { lstat, readFile as readFile14, realpath as realpath2 } from "fs/promises";
7807
- import { isAbsolute, join as join18, relative as relative2, resolve as resolve5, sep } from "path";
7856
+ import { isAbsolute, join as join19, relative as relative2, resolve as resolve5, sep } from "path";
7808
7857
  import { isDeepStrictEqual as isDeepStrictEqual8 } from "util";
7809
7858
  async function checkSourceBuild(directory, spec) {
7810
7859
  if (!spec.sourceBuild) return void 0;
@@ -7813,7 +7862,7 @@ async function checkSourceBuild(directory, spec) {
7813
7862
  };
7814
7863
  try {
7815
7864
  const preparedRoot = await realpath2(directory);
7816
- const sidecar = join18(preparedRoot, LOCAL_BUILD_FILE);
7865
+ const sidecar = join19(preparedRoot, LOCAL_BUILD_FILE);
7817
7866
  const info = await lstat(sidecar);
7818
7867
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2 * 1024 * 1024) stale("local source record is missing, unsafe or exceeds bounds");
7819
7868
  const bytes = await readFile14(sidecar);
@@ -7837,7 +7886,7 @@ async function checkSourceBuild(directory, spec) {
7837
7886
  total += source.length;
7838
7887
  if (total > 30 * 1024 * 1024 || createHash13("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
7839
7888
  }
7840
- const artifact = join18(preparedRoot, "application.cjs");
7889
+ const artifact = join19(preparedRoot, "application.cjs");
7841
7890
  if (!(await lstat(artifact)).isFile() || await realpath2(artifact) !== resolve5(artifact) || (await lstat(artifact)).size > 20 * 1024 * 1024 || createHash13("sha256").update(await readFile14(artifact)).digest("hex") !== build2.bundleDigest) stale("compiled application changed");
7842
7891
  return { root, digest: spec.sourceBuild };
7843
7892
  } catch (error) {
@@ -7857,8 +7906,8 @@ var init_source_build = __esm({
7857
7906
  });
7858
7907
 
7859
7908
  // src/lib/files.ts
7860
- import { readdir as readdir3, readFile as readFile15, stat } from "fs/promises";
7861
- import { join as join19, relative as relative3, sep as sep2 } from "path";
7909
+ import { readdir as readdir3, readFile as readFile15, stat as stat2 } from "fs/promises";
7910
+ import { join as join20, relative as relative3, sep as sep2 } from "path";
7862
7911
  function shouldIgnoreDir(name) {
7863
7912
  return IGNORED_DIRS.has(name) || name === ".git";
7864
7913
  }
@@ -7878,7 +7927,7 @@ async function walkDir(root, maxFiles, budgetMs) {
7878
7927
  }
7879
7928
  entries.sort((a, b) => a.name.localeCompare(b.name));
7880
7929
  for (const entry of entries) {
7881
- const full = join19(dir, entry.name);
7930
+ const full = join20(dir, entry.name);
7882
7931
  if (entry.isDirectory()) {
7883
7932
  if (!shouldIgnoreDir(entry.name)) stack.push(full);
7884
7933
  } else if (entry.isFile()) {
@@ -7957,7 +8006,7 @@ var init_files = __esm({
7957
8006
  }
7958
8007
  async exists(path2) {
7959
8008
  try {
7960
- await stat(join19(this.cwd, path2));
8009
+ await stat2(join20(this.cwd, path2));
7961
8010
  return true;
7962
8011
  } catch {
7963
8012
  return false;
@@ -7966,9 +8015,9 @@ var init_files = __esm({
7966
8015
  async read(path2, maxBytes = MAX_BYTES2) {
7967
8016
  const cached2 = this.cache.contents.get(path2);
7968
8017
  if (cached2 !== void 0) return cached2;
7969
- const full = join19(this.cwd, path2);
8018
+ const full = join20(this.cwd, path2);
7970
8019
  try {
7971
- const info = await stat(full);
8020
+ const info = await stat2(full);
7972
8021
  if (!info.isFile()) return void 0;
7973
8022
  if (info.size > maxBytes) {
7974
8023
  this.cache.limits.push(`File excluded by size limit (${maxBytes} bytes): ${path2}`);
@@ -8820,12 +8869,12 @@ var init_dashboard_transfer = __esm({
8820
8869
 
8821
8870
  // src/inventory/store.ts
8822
8871
  import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile11 } from "fs/promises";
8823
- import { join as join20 } from "path";
8872
+ import { join as join21 } from "path";
8824
8873
  function storeDir(cwd) {
8825
- return join20(cwd, STORE_DIR);
8874
+ return join21(cwd, STORE_DIR);
8826
8875
  }
8827
8876
  function storePath(cwd, name) {
8828
- return join20(storeDir(cwd), name);
8877
+ return join21(storeDir(cwd), name);
8829
8878
  }
8830
8879
  async function ensureStore(cwd) {
8831
8880
  await mkdir6(storeDir(cwd), { recursive: true });
@@ -9003,7 +9052,7 @@ var init_sanitize = __esm({
9003
9052
 
9004
9053
  // src/commands/dashboard.ts
9005
9054
  import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
9006
- import { basename as basename2, join as join21 } from "path";
9055
+ import { basename as basename2, join as join22 } from "path";
9007
9056
  import { fileURLToPath as fileURLToPath3 } from "url";
9008
9057
  function dashboardInventory(cwd, inventory) {
9009
9058
  return JSON.parse(sanitizeOutput(JSON.stringify({
@@ -9040,7 +9089,7 @@ __export(session_exports, {
9040
9089
  });
9041
9090
  import { spawn as spawn3, spawnSync } from "child_process";
9042
9091
  import { writeFile as writeFile13, readFile as readFile18 } from "fs/promises";
9043
- import { join as join22 } from "path";
9092
+ import { join as join23 } from "path";
9044
9093
  function sessionTask() {
9045
9094
  return `# Prepare this repository for AgentTwin
9046
9095
 
@@ -9065,7 +9114,7 @@ function installedOpenCode() {
9065
9114
  return spawnSync("opencode", ["--version"], { stdio: "ignore", timeout: 5e3 }).status === 0;
9066
9115
  }
9067
9116
  async function writeSessionTask(cwd) {
9068
- const path2 = join22(cwd, ".agenttwin/AGENT-TASK.md");
9117
+ const path2 = join23(cwd, ".agenttwin/AGENT-TASK.md");
9069
9118
  await writeFile13(path2, sessionTask(), "utf8");
9070
9119
  return path2;
9071
9120
  }
@@ -9081,7 +9130,7 @@ async function launchSession(cwd) {
9081
9130
  async function loadDashboardDiscovery(cwd, inventory, opts = {}) {
9082
9131
  let previousHead;
9083
9132
  try {
9084
- previousHead = JSON.parse(await readFile18(join22(cwd, ".agenttwin/git.json"), "utf8")).head;
9133
+ previousHead = JSON.parse(await readFile18(join23(cwd, ".agenttwin/git.json"), "utf8")).head;
9085
9134
  } catch {
9086
9135
  }
9087
9136
  const git2 = await captureGit(cwd, previousHead);
@@ -9089,7 +9138,7 @@ async function loadDashboardDiscovery(cwd, inventory, opts = {}) {
9089
9138
  if (opts.includeAgentDiscovery === false) return projectProducts(cwd, base, base);
9090
9139
  let raw;
9091
9140
  try {
9092
- raw = await readFile18(join22(cwd, ".agenttwin/agent-discovery.json"), "utf8");
9141
+ raw = await readFile18(join23(cwd, ".agenttwin/agent-discovery.json"), "utf8");
9093
9142
  } catch (error) {
9094
9143
  if (error.code === "ENOENT") return projectProducts(cwd, base, base);
9095
9144
  throw error;
@@ -9124,7 +9173,7 @@ __export(run_exports, {
9124
9173
  });
9125
9174
  import { mkdtemp as mkdtemp7, mkdir as mkdir8, readFile as readFile19, writeFile as writeFile14, realpath as realpath3, lstat as lstat2, rm as rm9 } from "fs/promises";
9126
9175
  import { tmpdir as tmpdir7 } from "os";
9127
- import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute2, join as join23, relative as relative4, resolve as resolve6, sep as sep3 } from "path";
9176
+ import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute2, join as join24, relative as relative4, resolve as resolve6, sep as sep3 } from "path";
9128
9177
  import { createHash as createHash14, randomUUID as randomUUID4 } from "crypto";
9129
9178
  async function stageApplication(root, files, destination) {
9130
9179
  const canonicalRoot = await realpath3(root);
@@ -9138,7 +9187,7 @@ async function stageApplication(root, files, destination) {
9138
9187
  const contents = await readFile19(source);
9139
9188
  bytes += contents.length;
9140
9189
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
9141
- const target = join23(destination, file);
9190
+ const target = join24(destination, file);
9142
9191
  await mkdir8(dirname3(target), { recursive: true });
9143
9192
  await writeFile14(target, contents, { mode: 420 });
9144
9193
  digests[file] = createHash14("sha256").update(contents).digest("hex");
@@ -9171,7 +9220,7 @@ async function runWorld(cwd, opts) {
9171
9220
  if (spec.workflowId) {
9172
9221
  let inventory;
9173
9222
  try {
9174
- inventory = JSON.parse(await readFile19(join23(inventoryRoot, ".agenttwin/inventory.json"), "utf8"));
9223
+ inventory = JSON.parse(await readFile19(join24(inventoryRoot, ".agenttwin/inventory.json"), "utf8"));
9175
9224
  } catch {
9176
9225
  throw new CliError("Linked workflow needs discovery inventory; run init first", { code: EXIT.BLOCKED });
9177
9226
  }
@@ -9195,20 +9244,20 @@ async function runWorld(cwd, opts) {
9195
9244
  throw new CliError(error instanceof Error ? error.message : String(error), { code: EXIT.USAGE });
9196
9245
  }
9197
9246
  }
9198
- const stage = await mkdtemp7(join23(tmpdir7(), "agenttwin-world-"));
9247
+ const stage = await mkdtemp7(join24(tmpdir7(), "agenttwin-world-"));
9199
9248
  try {
9200
- const sourceDigests = await stageApplication(dirname3(file), spec.files, join23(stage, "app"));
9201
- await writeFile14(join23(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
9202
- if (runtime === "e2b" && suppliedSeed) await writeFile14(join23(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
9249
+ const sourceDigests = await stageApplication(dirname3(file), spec.files, join24(stage, "app"));
9250
+ await writeFile14(join24(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
9251
+ if (runtime === "e2b" && suppliedSeed) await writeFile14(join24(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
9203
9252
  const git2 = await captureGit(sourceBuild?.root ?? cwd);
9204
9253
  let project;
9205
9254
  try {
9206
- project = JSON.parse(await readFile19(join23(inventoryRoot, ".agenttwin/inventory.json"), "utf8")).name ?? basename3(cwd);
9255
+ project = JSON.parse(await readFile19(join24(inventoryRoot, ".agenttwin/inventory.json"), "utf8")).name ?? basename3(cwd);
9207
9256
  } catch {
9208
9257
  }
9209
9258
  if (runtime === "local" || runtime === "docker") {
9210
9259
  opts.log(runtime === "docker" ? "Running in a read-only Docker container without network access; service state and grading remain outside the container." : "Testing through the CLI with in-process service twins. No cloud VM or containers.");
9211
- const report2 = runtime === "docker" ? await executeDocker(join23(stage, "app"), spec, { signal: opts.signal, seed: suppliedSeed }) : await executeLocal(join23(stage, "app"), spec, opts.signal, void 0, suppliedSeed);
9260
+ const report2 = runtime === "docker" ? await executeDocker(join24(stage, "app"), spec, { signal: opts.signal, seed: suppliedSeed }) : await executeLocal(join24(stage, "app"), spec, opts.signal, void 0, suppliedSeed);
9212
9261
  let sourceBuildEvidence;
9213
9262
  let sourceBuildError;
9214
9263
  if (sourceBuild) {
@@ -9228,9 +9277,9 @@ async function runWorld(cwd, opts) {
9228
9277
  const receipt2 = { ...report2, ...sourceBuildEvidence ? { sourceBuild: sourceBuildEvidence } : {}, ...sourceBuildError ? { executionError: sourceBuildError } : {}, sourceDirectory: relative4(cwd, dirname3(file)).split(sep3).join("/"), runId: runId2, runtime, project, git: git2, createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: createHash14("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
9229
9278
  const out2 = resolve6(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
9230
9279
  await mkdir8(out2, { recursive: true });
9231
- const evidencePath = join23(out2, "run.json"), reportPath = join23(out2, "report.md");
9280
+ const evidencePath = join24(out2, "run.json"), reportPath = join24(out2, "report.md");
9232
9281
  await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
9233
- await writeFile14(join23(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
9282
+ await writeFile14(join24(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
9234
9283
  const next = receipt2.status === "passed" ? [`Replay: agenttwin replay .agenttwin/runs/${runId2}/run.json`] : [`See the evidence and a fix task: agenttwin receipt --id ${runId2}`, `After fixing, rerun: agenttwin run --file ${relative4(cwd, file).split(sep3).join("/")}`];
9235
9284
  await writeFile14(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
9236
9285
  Runner: CLI \xB7 Git: ${git2?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
@@ -9250,8 +9299,8 @@ Full evidence (activities, fault, initial and final state): run.json
9250
9299
  if (receipt2.specDigest !== expectedSpec || !reportedSources || Object.keys(reportedSources).length !== Object.keys(sourceDigests).length || Object.entries(sourceDigests).some(([path2, digest6]) => reportedSources[path2] !== digest6)) throw new CliError("Hosted receipt does not match the submitted source/specification");
9251
9300
  const out2 = resolve6(cwd, opts.out ?? `.agenttwin/runs/${receipt2.runId}`);
9252
9301
  await mkdir8(out2, { recursive: true });
9253
- const evidencePath = join23(out2, "run.json");
9254
- const reportPath = join23(out2, "report.md");
9302
+ const evidencePath = join24(out2, "run.json");
9303
+ const reportPath = join24(out2, "report.md");
9255
9304
  await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
9256
9305
  await writeFile14(reportPath, `# ${spec.name}: ${receipt2.status}
9257
9306
 
@@ -9288,11 +9337,11 @@ See run.json for assertions, service state, application output and isolation met
9288
9337
  };
9289
9338
  const out = resolve6(cwd, opts.out ?? `.agenttwin/runs/${runId}`);
9290
9339
  await mkdir8(out, { recursive: true });
9291
- await writeFile14(join23(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
9292
- await writeFile14(join23(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
9340
+ await writeFile14(join24(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
9341
+ await writeFile14(join24(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
9293
9342
  const summary = [`# ${spec.name}: ${report.status}`, "", `Run: ${runId}`, `Image: ${image}`, "", "## Assertions", "", ...report.assertions.map((a) => `- ${a.passed ? "PASS" : "FAIL"} ${a.service}${a.path}: expected ${a.count}, observed ${a.actual}`), "", "## Infrastructure assertions", "", ...(report.infrastructureAssertions ?? []).map((a) => `- ${a.passed ? "PASS" : "FAIL"} ${a.service}: ${JSON.stringify(a.actual)}`), "", "## Coverage", "", report.coverage, "", "External networking disabled. Only explicitly listed source files were uploaded. New state and tokens are created for each run.", "", "See run.json for application output, faults, events, and initial/final state.", ""].join("\n");
9294
- await writeFile14(join23(out, "report.md"), summary);
9295
- return { ...receipt, reportPath: join23(out, "report.md"), evidencePath: join23(out, "run.json") };
9343
+ await writeFile14(join24(out, "report.md"), summary);
9344
+ return { ...receipt, reportPath: join24(out, "report.md"), evidencePath: join24(out, "run.json") };
9296
9345
  } finally {
9297
9346
  await rm9(stage, { recursive: true, force: true });
9298
9347
  }
@@ -9322,12 +9371,12 @@ import { execFile as execFile8, spawn as spawn4 } from "child_process";
9322
9371
  import { promisify as promisify8 } from "util";
9323
9372
  import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir9, mkdtemp as mkdtemp8, readFile as readFile20, rm as rm10, writeFile as writeFile15 } from "fs/promises";
9324
9373
  import { tmpdir as tmpdir8 } from "os";
9325
- import { join as join24 } from "path";
9374
+ import { join as join25 } from "path";
9326
9375
  import { randomUUID as randomUUID5 } from "crypto";
9327
9376
  async function executeDocker(app, spec, opts = {}) {
9328
9377
  if (spec.redis || spec.browser || spec.background) throw new Error("Docker stdio execution currently supports Node HTTP workflows with optional tagged SQL only; Redis, browser and background execution are unsupported.");
9329
9378
  opts.signal?.throwIfAborted();
9330
- const started = Date.now(), stage = await mkdtemp8(join24(tmpdir8(), "agenttwin-docker-"));
9379
+ const started = Date.now(), stage = await mkdtemp8(join25(tmpdir8(), "agenttwin-docker-"));
9331
9380
  const container = "agenttwin-" + randomUUID5();
9332
9381
  const world = new HttpWorld(spec, opts.seed);
9333
9382
  let hook;
@@ -9341,17 +9390,17 @@ async function executeDocker(app, spec, opts = {}) {
9341
9390
  if (!/^(?:sha256:[a-f0-9]{64}|[-\w./:]+@sha256:[a-f0-9]{64})$/.test(image)) throw new Error("Docker runner image must resolve to an immutable sha256 image ID or digest.");
9342
9391
  await exec6("docker", ["image", "inspect", image], { timeout: 1e4, maxBuffer: 1024 * 1024 });
9343
9392
  await chmod3(stage, 493);
9344
- const stagedApp = join24(stage, "app");
9393
+ const stagedApp = join25(stage, "app");
9345
9394
  const { stageApplication: stageApplication2 } = await Promise.resolve().then(() => (init_run(), run_exports));
9346
9395
  await stageApplication2(app, spec.files, stagedApp);
9347
- if (spec.postgres) database = await createDockerPostgres(spec.postgres.seedFile ? await readFile20(join24(stagedApp, spec.postgres.seedFile), "utf8") : "", opts.databaseImage, spec.postgres.clock);
9396
+ if (spec.postgres) database = await createDockerPostgres(spec.postgres.seedFile ? await readFile20(join25(stagedApp, spec.postgres.seedFile), "utf8") : "", opts.databaseImage, spec.postgres.clock);
9348
9397
  const credentials2 = await world.start(), initialState = world.snapshot();
9349
9398
  hook = await createRequestSourceHook(stagedApp, spec, credentials2, { root: "/app", violationsPath: "/tmp/agenttwin-blocked.jsonl", stdioViolations: true });
9350
- const support = join24(stage, "support");
9399
+ const support = join25(stage, "support");
9351
9400
  await mkdir9(support, { mode: 493 });
9352
- await copyFile2(hook.path, join24(support, "source.cjs"));
9353
- await chmod3(join24(support, "source.cjs"), 420);
9354
- await writeFile15(join24(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
9401
+ await copyFile2(hook.path, join25(support, "source.cjs"));
9402
+ await chmod3(join25(support, "source.cjs"), 420);
9403
+ await writeFile15(join25(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
9355
9404
  const env = Object.entries(credentials2).flatMap(([name, c]) => ["--env", `AGENTTWIN_${name.toUpperCase()}_URL=${c.endpoint}`, "--env", `AGENTTWIN_${name.toUpperCase()}_TOKEN=${c.token}`]);
9356
9405
  let stdout = "", stderr = "", timedOut = false;
9357
9406
  const args = ["run", "--pull", "never", "--interactive", "--name", container, "--network", "none", "--read-only", "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--user", "65534:65534", "--pids-limit", "128", "--memory", "512m", "--cpus", "1", "--tmpfs", "/tmp:rw,noexec,nosuid,size=64m", "--mount", `type=bind,src=${stagedApp},dst=/app,readonly`, "--mount", `type=bind,src=${support},dst=/agenttwin,readonly`, "--workdir", "/app", "--env", "NODE_ENV=test", ...env, "--entrypoint", "node", image, "--require", "/agenttwin/bridge.cjs", "--require", "/agenttwin/source.cjs", ...spec.command.slice(1)];
@@ -10655,12 +10704,12 @@ var init_containers = __esm({
10655
10704
  });
10656
10705
 
10657
10706
  // src/discovery/detectors/cloud-creds.ts
10658
- import { stat as stat2 } from "fs/promises";
10707
+ import { stat as stat3 } from "fs/promises";
10659
10708
  import { homedir as homedir3 } from "os";
10660
- import { join as join28 } from "path";
10709
+ import { join as join29 } from "path";
10661
10710
  async function exists(path2) {
10662
10711
  try {
10663
- await stat2(path2);
10712
+ await stat3(path2);
10664
10713
  return true;
10665
10714
  } catch {
10666
10715
  return false;
@@ -10672,11 +10721,11 @@ var init_cloud_creds = __esm({
10672
10721
  "use strict";
10673
10722
  init_scoring();
10674
10723
  CREDENTIALS = [
10675
- { path: join28(homedir3(), ".aws", "config"), subject: "aws", title: "AWS" },
10676
- { path: join28(homedir3(), ".aws", "credentials"), subject: "aws", title: "AWS" },
10677
- { path: join28(homedir3(), ".config", "gcloud"), subject: "gcp", title: "Google Cloud" },
10678
- { path: join28(homedir3(), ".azure"), subject: "azure", title: "Azure" },
10679
- { path: join28(homedir3(), ".kube", "config"), subject: "kubernetes", title: "Kubernetes" }
10724
+ { path: join29(homedir3(), ".aws", "config"), subject: "aws", title: "AWS" },
10725
+ { path: join29(homedir3(), ".aws", "credentials"), subject: "aws", title: "AWS" },
10726
+ { path: join29(homedir3(), ".config", "gcloud"), subject: "gcp", title: "Google Cloud" },
10727
+ { path: join29(homedir3(), ".azure"), subject: "azure", title: "Azure" },
10728
+ { path: join29(homedir3(), ".kube", "config"), subject: "kubernetes", title: "Kubernetes" }
10680
10729
  ];
10681
10730
  cloudCredDetector = {
10682
10731
  id: "cloud-credentials",
@@ -10773,7 +10822,7 @@ import { createServer as createServer3 } from "http";
10773
10822
  import { connect } from "net";
10774
10823
  import { readFileSync as readFileSync2, rmSync, writeFileSync } from "fs";
10775
10824
  import { tmpdir as tmpdir11 } from "os";
10776
- import { join as join29 } from "path";
10825
+ import { join as join30 } from "path";
10777
10826
  function delay(ms) {
10778
10827
  return new Promise((resolve12) => setTimeout(resolve12, ms));
10779
10828
  }
@@ -10807,8 +10856,8 @@ function startProxy(onHost) {
10807
10856
  async function observeEgress(opts) {
10808
10857
  const hosts = /* @__PURE__ */ new Set();
10809
10858
  const { server, url } = await startProxy((host) => hosts.add(host));
10810
- const logFile = join29(tmpdir11(), `agenttwin-egress-${process.pid}.log`);
10811
- const hookFile = join29(tmpdir11(), `agenttwin-egress-hook-${process.pid}.cjs`);
10859
+ const logFile = join30(tmpdir11(), `agenttwin-egress-${process.pid}.log`);
10860
+ const hookFile = join30(tmpdir11(), `agenttwin-egress-hook-${process.pid}.cjs`);
10812
10861
  try {
10813
10862
  writeFileSync(hookFile, EGRESS_HOOK, "utf8");
10814
10863
  writeFileSync(logFile, "", "utf8");
@@ -13027,7 +13076,7 @@ var init_scope = __esm({
13027
13076
  import { spawn as spawn6 } from "child_process";
13028
13077
  import { mkdtemp as mkdtemp11, open, writeFile as writeFile19, rm as rm13, realpath as realpath6 } from "fs/promises";
13029
13078
  import { tmpdir as tmpdir12 } from "os";
13030
- import { join as join30, basename as basename4 } from "path";
13079
+ import { join as join31, basename as basename4 } from "path";
13031
13080
  function validHost(host) {
13032
13081
  const clean = host.toLowerCase();
13033
13082
  if (clean.length > 253 || !/^[a-z0-9][a-z0-9.-]*$/.test(clean) || clean.includes("..")) throw new Error("Expected a hostname without scheme, path, credentials or port");
@@ -14192,11 +14241,11 @@ async function runExport(opts) {
14192
14241
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
14193
14242
  if (opts.out) {
14194
14243
  const { mkdir: mkdir14, writeFile: writeFile22 } = await import("fs/promises");
14195
- const { join: join35 } = await import("path");
14244
+ const { join: join36 } = await import("path");
14196
14245
  await mkdir14(opts.out, { recursive: true });
14197
- await writeFile22(join35(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
14246
+ await writeFile22(join36(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
14198
14247
  `, "utf8");
14199
- if (plan) await writeFile22(join35(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
14248
+ if (plan) await writeFile22(join36(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
14200
14249
  `, "utf8");
14201
14250
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
14202
14251
  }
@@ -14250,7 +14299,9 @@ var parseSsoRealms = (value) => {
14250
14299
  if (!issuer || !clientId || !clientSecret || !organization) throw new Error(`AGENTTWIN_SSO_REALMS entry '${id}' needs issuer, clientId, clientSecret and organization.`);
14251
14300
  validUrl(issuer);
14252
14301
  seen.add(id);
14253
- realms.push({ id, issuer, clientId, clientSecret, organization, domains });
14302
+ const workspace = typeof item.workspace === "string" && /^[0-9a-f-]{36}$/.test(item.workspace) ? item.workspace : void 0;
14303
+ const role = item.role === "admin" || item.role === "member" || item.role === "viewer" ? item.role : void 0;
14304
+ realms.push({ id, issuer, clientId, clientSecret, organization, domains, ...workspace ? { workspace } : {}, ...role ? { role } : {}, ...item.autoJoin === false ? { autoJoin: false } : {} });
14254
14305
  }
14255
14306
  return realms;
14256
14307
  };
@@ -14623,21 +14674,21 @@ function updatePreparationAgent(item, input, now = Date.now()) {
14623
14674
 
14624
14675
  // src/runtime/github-app-registration.ts
14625
14676
  import { randomBytes as randomBytes4, timingSafeEqual as timingSafeEqual4, createHash as createHash5 } from "crypto";
14626
- import { readFile as readFile2, rename, writeFile } from "fs/promises";
14627
- import { join } from "path";
14677
+ import { readFile as readFile2, rename as rename2, writeFile } from "fs/promises";
14678
+ import { join as join2 } from "path";
14628
14679
  var FILE = "github-app.json";
14629
14680
  async function loadRegisteredApp(directory) {
14630
14681
  try {
14631
- const app = JSON.parse(await readFile2(join(directory, FILE), "utf8"));
14682
+ const app = JSON.parse(await readFile2(join2(directory, FILE), "utf8"));
14632
14683
  return app?.schema === "agenttwin/github-app-v1" && Number.isSafeInteger(app.id) && typeof app.slug === "string" && typeof app.webhookSecret === "string" && typeof app.privateKey === "string" ? app : void 0;
14633
14684
  } catch {
14634
14685
  return void 0;
14635
14686
  }
14636
14687
  }
14637
14688
  async function saveRegisteredApp(directory, app) {
14638
- const temp = join(directory, `${FILE}.${randomBytes4(6).toString("hex")}.tmp`);
14689
+ const temp = join2(directory, `${FILE}.${randomBytes4(6).toString("hex")}.tmp`);
14639
14690
  await writeFile(temp, JSON.stringify(app, null, 2) + "\n", { mode: 384 });
14640
- await rename(temp, join(directory, FILE));
14691
+ await rename2(temp, join2(directory, FILE));
14641
14692
  }
14642
14693
  var appOptions = (app) => ({ slug: app.slug, webhookSecret: app.webhookSecret });
14643
14694
  var appCredentials = (app) => ({ appId: String(app.id), privateKey: app.privateKey });
@@ -14689,7 +14740,7 @@ import { createSign } from "crypto";
14689
14740
  import { execFile as execFile12 } from "child_process";
14690
14741
  import { mkdtemp as mkdtemp12, rm as rm14 } from "fs/promises";
14691
14742
  import { tmpdir as tmpdir13 } from "os";
14692
- import { join as join31 } from "path";
14743
+ import { join as join32 } from "path";
14693
14744
  import { promisify as promisify11 } from "util";
14694
14745
 
14695
14746
  // src/runtime/pr-check.ts
@@ -14706,13 +14757,13 @@ import { execFile as execFile9 } from "child_process";
14706
14757
  import { promisify as promisify9 } from "util";
14707
14758
  import { chmod as chmod4, mkdir as mkdir11, mkdtemp as mkdtemp10, readFile as readFile23, writeFile as writeFile18, rm as rm12, copyFile as copyFile3 } from "fs/promises";
14708
14759
  import { tmpdir as tmpdir10 } from "os";
14709
- import { dirname as dirname5, join as join27, relative as relative6, resolve as resolve9, sep as sep6 } from "path";
14760
+ import { dirname as dirname5, join as join28, relative as relative6, resolve as resolve9, sep as sep6 } from "path";
14710
14761
 
14711
14762
  // src/runtime/callable.ts
14712
14763
  init_entrypoints();
14713
14764
  import { build } from "esbuild";
14714
14765
  import { readFile as readFile21, realpath as realpath4, writeFile as writeFile16 } from "fs/promises";
14715
- import { resolve as resolve7, relative as relative5, isAbsolute as isAbsolute3, sep as sep4, join as join25, extname } from "path";
14766
+ import { resolve as resolve7, relative as relative5, isAbsolute as isAbsolute3, sep as sep4, join as join26, extname } from "path";
14716
14767
  import { createHash as createHash15 } from "crypto";
14717
14768
  var digest4 = (value) => createHash15("sha256").update(value).digest("hex");
14718
14769
  var object5 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -14793,7 +14844,7 @@ for(const [index,call]of invocation.calls.entries()){
14793
14844
  }})().catch(error=>{console.error(error);process.exitCode=1;})${options.exitWhenDone ? `.finally(()=>setTimeout(()=>process.exit(),1000).unref())` : ""};`;
14794
14845
  const sources = {};
14795
14846
  let bytes = 0;
14796
- const built = await build({ absWorkingDir: canonical4, stdin: { contents: driver, resolveDir: canonical4, sourcefile: "agenttwin-invocation.mjs", loader: "js" }, bundle: true, platform: "node", target: "node22", format: "cjs", write: false, metafile: true, logLevel: "silent", ...options.sourceMaps ? { sourcemap: "inline", sourcesContent: false, outfile: join25(canonical4, "application.cjs") } : {}, plugins: [{ name: "bounded-project-source", setup(plugin) {
14847
+ const built = await build({ absWorkingDir: canonical4, stdin: { contents: driver, resolveDir: canonical4, sourcefile: "agenttwin-invocation.mjs", loader: "js" }, bundle: true, platform: "node", target: "node22", format: "cjs", write: false, metafile: true, logLevel: "silent", ...options.sourceMaps ? { sourcemap: "inline", sourcesContent: false, outfile: join26(canonical4, "application.cjs") } : {}, plugins: [{ name: "bounded-project-source", setup(plugin) {
14797
14848
  plugin.onLoad({ filter: /.*/ }, async (args) => {
14798
14849
  const path2 = await realpath4(args.path), rel = relative5(canonical4, path2);
14799
14850
  if (isAbsolute3(rel) || rel === ".." || rel.startsWith(".." + sep4) || rel.split(sep4).some((part) => /^(?:\.env.*|\.git|\.ssh|\.aws)$/.test(part)) || !/\.(?:[cm]?[jt]s|tsx|jsx|json)$/.test(path2)) throw new Error("Build input is outside approved project JavaScript/TypeScript/JSON: " + rel);
@@ -14808,7 +14859,7 @@ for(const [index,call]of invocation.calls.entries()){
14808
14859
  } }] });
14809
14860
  const code = built.outputFiles[0].contents;
14810
14861
  if (code.length > 20 * 1024 * 1024) throw new Error("Callable bundle exceeds 20 MiB");
14811
- await writeFile16(join25(out, "application.cjs"), code, { flag: "wx", mode: 384 });
14862
+ await writeFile16(join26(out, "application.cjs"), code, { flag: "wx", mode: 384 });
14812
14863
  return { schema: "agenttwin/callable-build-v1", entrypoint, export: selected.name, invocation, sourceDigests: sources, invocationDigest: digest4(driver), bundleDigest: digest4(code), files: ["application.cjs"], command: ["node", "application.cjs"], coverage: "Actual exported application source; only explicitly configured invocation and dependency bindings are covered. No application scripts executed during compilation." };
14813
14864
  }
14814
14865
 
@@ -14818,7 +14869,7 @@ init_source_build();
14818
14869
  // src/runtime/protected-callable.ts
14819
14870
  import { createHash as createHash16 } from "crypto";
14820
14871
  import { lstat as lstat3, readFile as readFile22, realpath as realpath5, mkdir as mkdir10, writeFile as writeFile17, mkdtemp as mkdtemp9, rm as rm11 } from "fs/promises";
14821
- import { dirname as dirname4, join as join26, resolve as resolve8, sep as sep5 } from "path";
14872
+ import { dirname as dirname4, join as join27, resolve as resolve8, sep as sep5 } from "path";
14822
14873
  import { tmpdir as tmpdir9 } from "os";
14823
14874
  init_source_build();
14824
14875
  var hash3 = (bytes) => createHash16("sha256").update(bytes).digest("hex");
@@ -14850,7 +14901,7 @@ async function stageTrustedBuildFiles(cwd, out, files) {
14850
14901
  total += bytes.length;
14851
14902
  if (total > 34 * 1024 * 1024) throw Error("Trusted dependency closure exceeds bounds");
14852
14903
  if (hash3(bytes) !== expected) throw Error("Trusted dependency or resolution metadata changed: " + file + "; restore the baseline installation or review a new regression");
14853
- const target = join26(out, file);
14904
+ const target = join27(out, file);
14854
14905
  await mkdir10(dirname4(target), { recursive: true });
14855
14906
  await writeFile17(target, bytes, { mode: 420 });
14856
14907
  }
@@ -14873,7 +14924,7 @@ function parseRegression(v) {
14873
14924
  }
14874
14925
  async function runProtectedCheck(cwd, opts) {
14875
14926
  const result2 = { schema: "agenttwin/protected-check-v1", status: "incomplete", candidateRevision: "", baselineRevision: "", specDigest: "", candidateBuildDigest: void 0, sourceDigests: {}, runtime: opts.runtime ?? "docker", protection: "", receipt: null, reason: "" };
14876
- const stage = await mkdtemp10(join27(tmpdir10(), "agenttwin-regression-"));
14927
+ const stage = await mkdtemp10(join28(tmpdir10(), "agenttwin-regression-"));
14877
14928
  await chmod4(stage, 493);
14878
14929
  try {
14879
14930
  if (!opts.baseline) throw new Error("An explicit trusted baseline commit SHA is required; candidate-owned checks cannot approve a patch");
@@ -14894,13 +14945,13 @@ async function runProtectedCheck(cwd, opts) {
14894
14945
  totalBytes += bytes.length;
14895
14946
  if (totalBytes > 100 * 1024 * 1024) throw new Error("Candidate files exceed 100 MiB");
14896
14947
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash4(bytes);
14897
- const dest = join27(directory, file);
14948
+ const dest = join28(directory, file);
14898
14949
  await mkdir11(resolve9(dest, ".."), { recursive: true });
14899
14950
  await writeFile18(dest, bytes, { mode: 420 });
14900
14951
  };
14901
14952
  let executionSpec = regression.spec;
14902
14953
  if (regression.callable) {
14903
- const source = join27(stage, ".source"), compiled = join27(stage, ".compiled");
14954
+ const source = join28(stage, ".source"), compiled = join28(stage, ".compiled");
14904
14955
  await mkdir11(source);
14905
14956
  await mkdir11(compiled);
14906
14957
  for (const file of ["package-lock.json", "npm-shrinkwrap.json"]) {
@@ -14918,8 +14969,8 @@ async function runProtectedCheck(cwd, opts) {
14918
14969
  executionSpec = { ...regression.spec, sourceBuild: result2.candidateBuildDigest };
14919
14970
  const artifact = regression.spec.command[1];
14920
14971
  if (!artifact || !regression.spec.files.includes(artifact) || !artifact.endsWith("application.cjs")) throw Error("Protected callable artifact path is invalid");
14921
- await mkdir11(dirname5(join27(stage, artifact)), { recursive: true });
14922
- await copyFile3(join27(compiled, "application.cjs"), join27(stage, artifact));
14972
+ await mkdir11(dirname5(join28(stage, artifact)), { recursive: true });
14973
+ await copyFile3(join28(compiled, "application.cjs"), join28(stage, artifact));
14923
14974
  for (const file of regression.spec.files.filter((file2) => file2 !== artifact)) await stageGitFile(file, result2.baselineRevision, stage);
14924
14975
  } else for (const file of regression.spec.files) {
14925
14976
  await stageGitFile(file, file === regression.spec.postgres?.seedFile ? result2.baselineRevision : result2.candidateRevision, stage);
@@ -14965,8 +15016,8 @@ async function resolveBase(cwd, explicit, head) {
14965
15016
  const candidates = explicit ? [explicit] : [process.env.GITHUB_BASE_REF && `origin/${process.env.GITHUB_BASE_REF}`, "origin/HEAD", "origin/main", "origin/master", "main", "master"].filter((c) => !!c);
14966
15017
  for (const ref of candidates) {
14967
15018
  try {
14968
- const sha4 = (await git(cwd, "rev-parse", "--verify", `${ref}^{commit}`)).trim();
14969
- return explicit ? sha4 : (await git(cwd, "merge-base", sha4, head)).trim();
15019
+ const sha6 = (await git(cwd, "rev-parse", "--verify", `${ref}^{commit}`)).trim();
15020
+ return explicit ? sha6 : (await git(cwd, "merge-base", sha6, head)).trim();
14970
15021
  } catch {
14971
15022
  }
14972
15023
  }
@@ -15160,7 +15211,7 @@ init_run_summary();
15160
15211
  init_cost_model();
15161
15212
  var COMMENT_MARKER = "<!-- agenttwin-check -->";
15162
15213
  var ICON = { pass: "\u2705", fail: "\u274C", warn: "\u26A0\uFE0F", incomplete: "\u23F8\uFE0F" };
15163
- var short2 = (sha4) => sha4.slice(0, 7);
15214
+ var short2 = (sha6) => sha6.slice(0, 7);
15164
15215
  var cell = (s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
15165
15216
  var pathLabel = (path2) => path2.replace(/^\/(v\d+\/)?/, "").replace(/_/g, " ");
15166
15217
  function result(r) {
@@ -15315,8 +15366,8 @@ async function mergeBase(event, token, apiUrl = "https://api.github.com") {
15315
15366
  headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "agenttwin-check" },
15316
15367
  signal: AbortSignal.timeout(15e3)
15317
15368
  });
15318
- const sha4 = response.ok ? (await response.json()).merge_base_commit?.sha : void 0;
15319
- return sha4 && /^[0-9a-f]{40}$/.test(sha4) ? sha4 : event.baseSha;
15369
+ const sha6 = response.ok ? (await response.json()).merge_base_commit?.sha : void 0;
15370
+ return sha6 && /^[0-9a-f]{40}$/.test(sha6) ? sha6 : event.baseSha;
15320
15371
  } catch {
15321
15372
  return event.baseSha;
15322
15373
  }
@@ -15332,7 +15383,7 @@ async function runHostedCheck(event, app, opts = {}) {
15332
15383
  const token = await installationToken(app, event.installationId);
15333
15384
  const target = { token, repository: event.repository, sha: event.headSha, pullRequest: event.number, ...app.apiUrl ? { apiUrl: app.apiUrl } : {}, ...opts.detailsUrl ? { detailsUrl: opts.detailsUrl } : {} };
15334
15385
  const runId = await startCheckRun(target);
15335
- const dir = await mkdtemp12(join31(tmpdir13(), "agenttwin-pr-"));
15386
+ const dir = await mkdtemp12(join32(tmpdir13(), "agenttwin-pr-"));
15336
15387
  const base = { installationId: event.installationId, repository: event.repository, number: event.number, ...event.title ? { title: event.title } : {}, headSha: event.headSha, baseSha: event.baseSha, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
15337
15388
  try {
15338
15389
  const compareBase = await mergeBase(event, token, app.apiUrl);
@@ -15690,9 +15741,9 @@ init_dashboard_transfer();
15690
15741
  import { generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server";
15691
15742
  import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
15692
15743
  import { createServer as createServer4 } from "http";
15693
- import { createHash as createHash25, randomBytes as randomBytes9, randomUUID as randomUUID7, timingSafeEqual as timingSafeEqual7 } from "crypto";
15694
- import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile21, rename as rename2, mkdtemp as mkdtemp13, rm as rm16 } from "fs/promises";
15695
- import { resolve as resolve11, join as join34, dirname as dirname6, extname as extname2 } from "path";
15744
+ import { createHash as createHash27, randomBytes as randomBytes11, randomUUID as randomUUID9, timingSafeEqual as timingSafeEqual7 } from "crypto";
15745
+ import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile21, rename as rename3, mkdtemp as mkdtemp13, rm as rm16 } from "fs/promises";
15746
+ import { resolve as resolve11, join as join35, dirname as dirname6, extname as extname2 } from "path";
15696
15747
  import { tmpdir as tmpdir14 } from "os";
15697
15748
 
15698
15749
  // src/runtime/transcription.ts
@@ -15794,13 +15845,13 @@ init_spec();
15794
15845
  init_postgres_clock();
15795
15846
  init_application_clock();
15796
15847
  import { readFile as readFile25, readdir as readdir4 } from "fs/promises";
15797
- import { join as join33 } from "path";
15848
+ import { join as join34 } from "path";
15798
15849
 
15799
15850
  // src/runtime/repair-proof.ts
15800
15851
  init_run_summary();
15801
15852
  import { createHash as createHash23, randomUUID as randomUUID6 } from "crypto";
15802
15853
  import { mkdir as mkdir12, readFile as readFile24, rm as rm15, writeFile as writeFile20 } from "fs/promises";
15803
- import { isAbsolute as isAbsolute4, join as join32, relative as relative7, resolve as resolve10, sep as sep7 } from "path";
15854
+ import { isAbsolute as isAbsolute4, join as join33, relative as relative7, resolve as resolve10, sep as sep7 } from "path";
15804
15855
 
15805
15856
  // src/runtime/receipt-sync.ts
15806
15857
  var text = (v, max) => typeof v === "string" && v.length <= max;
@@ -15884,7 +15935,7 @@ function captureAnalytics(event) {
15884
15935
  // package.json
15885
15936
  var package_default = {
15886
15937
  name: "agenttwin",
15887
- version: "0.3.25",
15938
+ version: "0.3.26",
15888
15939
  description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
15889
15940
  mcpName: "io.github.Sashank-Singh/agenttwin",
15890
15941
  keywords: [
@@ -15975,8 +16026,195 @@ var package_default = {
15975
16026
  // src/lib/version.ts
15976
16027
  var VERSION = package_default.version;
15977
16028
 
16029
+ // src/runtime/scim.ts
16030
+ import { randomBytes as randomBytes10, randomUUID as randomUUID8, createHash as createHash26 } from "crypto";
16031
+
16032
+ // src/runtime/teams.ts
16033
+ import { createHash as createHash25, randomBytes as randomBytes9, randomUUID as randomUUID7 } from "crypto";
16034
+ var TEAM_ROLES = ["admin", "member", "viewer"];
16035
+ var INVITE_DAYS = 7;
16036
+ var AUDIT_LIMIT = 5e3;
16037
+ var sha4 = (value) => createHash25("sha256").update(value).digest("hex");
16038
+ var isRole = (value) => typeof value === "string" && TEAM_ROLES.includes(value);
16039
+ function resolveWorkspace(state, person, orgToken) {
16040
+ if (orgToken) return { workspace: person, role: orgToken.role, actorId: `token:${orgToken.id}`, actorLabel: `API token "${orgToken.label}"`, shared: true };
16041
+ const label2 = person.identity?.email ?? person.identity?.name ?? person.label;
16042
+ if (person.activeWorkspace && person.activeWorkspace !== person.id) {
16043
+ const membership = (state.teamMembers ?? []).find((m) => m.accountId === person.activeWorkspace && m.memberId === person.id);
16044
+ const workspace = membership && state.accounts.find((a) => a.id === membership.accountId && a.active);
16045
+ if (membership && workspace) return { workspace, role: membership.role, actorId: person.id, actorLabel: label2, shared: true };
16046
+ }
16047
+ return { workspace: person, role: "admin", actorId: person.id, actorLabel: label2, shared: (state.teamMembers ?? []).some((m) => m.accountId === person.id) };
16048
+ }
16049
+ function workspacesOf(state, person) {
16050
+ return [
16051
+ { id: person.id, name: person.label, role: "admin", personal: true },
16052
+ ...(state.teamMembers ?? []).filter((m) => m.memberId === person.id).flatMap((m) => {
16053
+ const w = state.accounts.find((a) => a.id === m.accountId && a.active);
16054
+ return w ? [{ id: w.id, name: w.label, role: m.role, personal: false }] : [];
16055
+ })
16056
+ ];
16057
+ }
16058
+ function teamView(state, workspace, role) {
16059
+ const owner = { memberId: workspace.id, name: workspace.identity?.name ?? workspace.label, email: workspace.identity?.email, role: "admin", owner: true };
16060
+ const members = (state.teamMembers ?? []).filter((m) => m.accountId === workspace.id).map((m) => {
16061
+ const a = state.accounts.find((x) => x.id === m.memberId);
16062
+ return { memberId: m.memberId, name: a?.identity?.name ?? a?.label ?? "Removed account", email: a?.identity?.email, role: m.role, addedAt: m.addedAt, owner: false };
16063
+ });
16064
+ const invites = role === "admin" ? (state.teamInvites ?? []).filter((i) => i.accountId === workspace.id && !i.acceptedBy && i.expiresAt > Date.now()).map((i) => ({ id: i.id, email: i.email, role: i.role, expiresAt: new Date(i.expiresAt).toISOString(), createdAt: i.createdAt })) : [];
16065
+ return { workspace: { id: workspace.id, name: workspace.label }, role, members: [owner, ...members], invites };
16066
+ }
16067
+ function createInvite(state, workspaceId, email, role, invitedBy) {
16068
+ const code = randomBytes9(24).toString("base64url");
16069
+ const invite = { id: randomUUID7(), accountId: workspaceId, email: email.toLowerCase(), role, codeHash: sha4(code), expiresAt: Date.now() + INVITE_DAYS * 864e5, createdAt: (/* @__PURE__ */ new Date()).toISOString(), invitedBy };
16070
+ state.teamInvites = [...(state.teamInvites ?? []).filter((i) => !(i.accountId === workspaceId && i.email === invite.email && !i.acceptedBy)), invite];
16071
+ return { invite, code };
16072
+ }
16073
+ function acceptInvite(state, person, code) {
16074
+ const invite = (state.teamInvites ?? []).find((i) => i.codeHash === sha4(code));
16075
+ if (!invite || invite.acceptedBy || invite.expiresAt <= Date.now()) return { error: "invite_invalid" };
16076
+ if (!person.identity?.email || person.identity.email.toLowerCase() !== invite.email) return { error: "invite_email_mismatch", email: invite.email };
16077
+ if (invite.accountId === person.id) return { error: "invite_own_workspace" };
16078
+ invite.acceptedBy = person.id;
16079
+ invite.acceptedAt = (/* @__PURE__ */ new Date()).toISOString();
16080
+ const existing = (state.teamMembers ?? []).find((m) => m.accountId === invite.accountId && m.memberId === person.id);
16081
+ if (existing) existing.role = invite.role;
16082
+ else state.teamMembers = [...state.teamMembers ?? [], { accountId: invite.accountId, memberId: person.id, role: invite.role, addedAt: invite.acceptedAt, addedBy: invite.invitedBy }];
16083
+ person.activeWorkspace = invite.accountId;
16084
+ return { invite };
16085
+ }
16086
+ function createOrgToken(state, workspaceId, label2, role, createdBy) {
16087
+ const token = `at_org_${randomBytes9(32).toString("hex")}`;
16088
+ const record3 = { tokenHash: sha4(token), id: randomUUID7(), accountId: workspaceId, label: label2, role, createdAt: (/* @__PURE__ */ new Date()).toISOString(), createdBy };
16089
+ state.orgTokens = [...state.orgTokens ?? [], record3];
16090
+ return { token, record: record3 };
16091
+ }
16092
+ var findOrgToken = (state, token) => token.startsWith("at_org_") ? (state.orgTokens ?? []).find((t) => t.tokenHash === sha4(token)) : void 0;
16093
+ var publicToken = (t) => ({ id: t.id, label: t.label, role: t.role, createdAt: t.createdAt, createdBy: t.createdBy });
16094
+ function recordAudit(state, event) {
16095
+ const entry = { id: randomUUID7(), at: (/* @__PURE__ */ new Date()).toISOString(), ...event };
16096
+ const all = [...state.auditEvents ?? [], entry];
16097
+ const mine = all.filter((e) => e.accountId === event.accountId);
16098
+ state.auditEvents = mine.length > AUDIT_LIMIT ? all.filter((e) => e.accountId !== event.accountId || mine.indexOf(e) >= mine.length - AUDIT_LIMIT) : all;
16099
+ return entry;
16100
+ }
16101
+ var auditAction = (method, path2) => `${method} ${path2.replace(/^(\/v1\/projects\/)[^/]+/, "$1:id").replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, ":id").replace(/\/\d+(?=\/|$)/g, "/:n")}`;
16102
+ function adminOnly(method, path2) {
16103
+ return path2.startsWith("/v1/team/invites") || path2.startsWith("/v1/team/tokens") || path2.startsWith("/v1/team/members/") && method === "PATCH" || path2 === "/v1/team/audit" || path2.startsWith("/v1/projects/") && method === "DELETE" || path2 === "/v1/oauth/clients" && method === "POST" || path2 === "/v1/github/install";
16104
+ }
16105
+
16106
+ // src/runtime/scim.ts
16107
+ var SCIM_USER = "urn:ietf:params:scim:schemas:core:2.0:User";
16108
+ var LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
16109
+ var PATCH = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
16110
+ var ERROR = "urn:ietf:params:scim:api:messages:2.0:Error";
16111
+ var sha5 = (v) => createHash26("sha256").update(v).digest("hex");
16112
+ var scimError = (status, detail, scimType) => ({ status, body: { schemas: [ERROR], status: String(status), detail, ...scimType ? { scimType } : {} } });
16113
+ function userOf(store, workspaceId, a, base) {
16114
+ const m = (store.teamMembers ?? []).find((x) => x.accountId === workspaceId && x.memberId === a.id);
16115
+ const [givenName, ...rest] = (a.identity?.name ?? "").split(/\s+/);
16116
+ return {
16117
+ schemas: [SCIM_USER],
16118
+ id: a.id,
16119
+ userName: a.identity?.email ?? a.label,
16120
+ active: !!m && a.active,
16121
+ name: { formatted: a.identity?.name ?? "", givenName: givenName ?? "", familyName: rest.join(" ") },
16122
+ displayName: a.identity?.name ?? a.label,
16123
+ emails: a.identity?.email ? [{ value: a.identity.email, primary: true, type: "work" }] : [],
16124
+ roles: m ? [{ value: m.role, primary: true }] : [],
16125
+ meta: { resourceType: "User", location: `${base}/scim/v2/Users/${a.id}` }
16126
+ };
16127
+ }
16128
+ var inWorkspace = (store, workspaceId, a) => a.provisionedBy === workspaceId || (store.teamMembers ?? []).some((m) => m.accountId === workspaceId && m.memberId === a.id);
16129
+ var emailOf = (input) => {
16130
+ const primary = Array.isArray(input.emails) ? (input.emails.find((e) => e?.primary) ?? input.emails[0])?.value : void 0;
16131
+ const value = typeof primary === "string" ? primary : typeof input.userName === "string" ? input.userName : "";
16132
+ return value.trim().toLowerCase();
16133
+ };
16134
+ var nameOf = (input, email) => typeof input.displayName === "string" && input.displayName.trim() || [input.name?.givenName, input.name?.familyName].filter((v) => typeof v === "string" && v).join(" ") || email.split("@")[0];
16135
+ var roleOf = (input) => {
16136
+ const v = Array.isArray(input.roles) ? input.roles[0]?.value : void 0;
16137
+ return isRole(v) ? v : void 0;
16138
+ };
16139
+ function setActive(store, workspaceId, a, active2, role) {
16140
+ const members = store.teamMembers ?? [];
16141
+ const existing = members.find((m) => m.accountId === workspaceId && m.memberId === a.id);
16142
+ if (active2) {
16143
+ if (a.provisionedBy === workspaceId) a.active = true;
16144
+ if (!existing) store.teamMembers = [...members, { accountId: workspaceId, memberId: a.id, role: role ?? "member", addedAt: (/* @__PURE__ */ new Date()).toISOString(), addedBy: "scim" }];
16145
+ else if (role) existing.role = role;
16146
+ if (!a.activeWorkspace) a.activeWorkspace = workspaceId;
16147
+ } else {
16148
+ store.teamMembers = members.filter((m) => m !== existing);
16149
+ if (a.activeWorkspace === workspaceId) delete a.activeWorkspace;
16150
+ if (a.provisionedBy === workspaceId) {
16151
+ a.active = false;
16152
+ a.cliTokens = [];
16153
+ a.tokenHash = sha5(randomBytes10(32).toString("hex"));
16154
+ store.sessions = (store.sessions ?? []).filter((s) => s.accountId !== a.id);
16155
+ }
16156
+ }
16157
+ }
16158
+ function handleScim(store, workspaceId, method, path2, query, input, base) {
16159
+ if (path2 === "/scim/v2/ServiceProviderConfig" && method === "GET") return { status: 200, body: { schemas: ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"], patch: { supported: true }, bulk: { supported: false, maxOperations: 0, maxPayloadSize: 0 }, filter: { supported: true, maxResults: 200 }, changePassword: { supported: false }, sort: { supported: false }, etag: { supported: false }, authenticationSchemes: [{ type: "oauthbearertoken", name: "OAuth Bearer Token", description: "An AgentTwin organization token with the admin role." }] } };
16160
+ if (path2 === "/scim/v2/Schemas" || path2 === "/scim/v2/ResourceTypes") return { status: 200, body: { schemas: [LIST], totalResults: 1, Resources: [path2.endsWith("Schemas") ? { id: SCIM_USER, name: "User" } : { id: "User", name: "User", endpoint: "/Users", schema: SCIM_USER }] } };
16161
+ if (path2 === "/scim/v2/Users" && method === "GET") {
16162
+ const filter = query.get("filter") ?? "";
16163
+ const match = filter.match(/^userName eq "([^"]+)"$/i);
16164
+ if (filter && !match) return scimError(400, 'Only filter=userName eq "\u2026" is supported.', "invalidFilter");
16165
+ const all = store.accounts.filter((a) => inWorkspace(store, workspaceId, a) && a.id !== workspaceId && (!match || a.identity?.email?.toLowerCase() === match[1].toLowerCase()));
16166
+ const start = Math.max(1, Number(query.get("startIndex") ?? 1) || 1), count = Math.min(200, Math.max(0, Number(query.get("count") ?? 100) || 100));
16167
+ const page2 = all.slice(start - 1, start - 1 + count);
16168
+ return { status: 200, body: { schemas: [LIST], totalResults: all.length, startIndex: start, itemsPerPage: page2.length, Resources: page2.map((a) => userOf(store, workspaceId, a, base)) } };
16169
+ }
16170
+ if (path2 === "/scim/v2/Users" && method === "POST") {
16171
+ const email = emailOf(input ?? {});
16172
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return scimError(400, "userName or a primary email is required.", "invalidValue");
16173
+ const existing = store.accounts.find((a) => a.identity?.email?.toLowerCase() === email);
16174
+ if (existing && inWorkspace(store, workspaceId, existing)) return scimError(409, "A user with this userName already exists.", "uniqueness");
16175
+ if (existing) return scimError(409, "This email already has its own AgentTwin account. Invite it from the Team page instead.", "uniqueness");
16176
+ if (store.accounts.length >= 1e4) return scimError(507, "Account capacity reached.");
16177
+ const account2 = { id: randomUUID8(), label: nameOf(input ?? {}, email), active: true, usageDay: "", runs: 0, tokenHash: sha5(randomBytes10(32).toString("hex")), identity: { email, name: nameOf(input ?? {}, email) }, provisionedBy: workspaceId };
16178
+ store.accounts.push(account2);
16179
+ setActive(store, workspaceId, account2, input?.active !== false, roleOf(input ?? {}));
16180
+ return { status: 201, body: userOf(store, workspaceId, account2, base), audit: { action: "scim.user_created", subject: account2.id, details: { email } } };
16181
+ }
16182
+ const one = path2.match(/^\/scim\/v2\/Users\/([0-9a-f-]{36})$/);
16183
+ if (!one) return scimError(404, "Not found.");
16184
+ const account = store.accounts.find((a) => a.id === one[1] && a.id !== workspaceId && inWorkspace(store, workspaceId, a));
16185
+ if (!account) return scimError(404, "User not found.");
16186
+ if (method === "GET") return { status: 200, body: userOf(store, workspaceId, account, base) };
16187
+ if (method === "DELETE") {
16188
+ setActive(store, workspaceId, account, false);
16189
+ return { status: 204, body: null, audit: { action: "scim.user_deleted", subject: account.id } };
16190
+ }
16191
+ if (method === "PUT" || method === "PATCH") {
16192
+ let active2, role, name;
16193
+ if (method === "PUT") {
16194
+ active2 = input?.active !== false;
16195
+ role = roleOf(input ?? {});
16196
+ name = nameOf(input ?? {}, account.identity?.email ?? "");
16197
+ } else {
16198
+ if (!Array.isArray(input?.schemas) || !input.schemas.includes(PATCH) || !Array.isArray(input?.Operations)) return scimError(400, "Send a PatchOp with Operations.", "invalidSyntax");
16199
+ for (const op2 of input.Operations) {
16200
+ if (String(op2?.op).toLowerCase() !== "replace" && String(op2?.op).toLowerCase() !== "add") continue;
16201
+ const values = op2.path ? { [op2.path]: op2.value } : op2.value ?? {};
16202
+ if ("active" in values) active2 = values.active === true || values.active === "true" || values.active === "True";
16203
+ if ("displayName" in values && typeof values.displayName === "string") name = values.displayName;
16204
+ if ("roles" in values) role = roleOf({ roles: values.roles });
16205
+ }
16206
+ }
16207
+ if (name && account.provisionedBy === workspaceId) account.identity = { ...account.identity, name };
16208
+ const wasActive = (store.teamMembers ?? []).some((m) => m.accountId === workspaceId && m.memberId === account.id) && account.active;
16209
+ if (active2 !== void 0 || role) setActive(store, workspaceId, account, active2 ?? wasActive, role);
16210
+ const now = (store.teamMembers ?? []).some((m) => m.accountId === workspaceId && m.memberId === account.id) && account.active;
16211
+ return { status: 200, body: userOf(store, workspaceId, account, base), audit: { action: now === wasActive ? "scim.user_updated" : now ? "scim.user_activated" : "scim.user_deactivated", subject: account.id, ...role ? { details: { role } } : {} } };
16212
+ }
16213
+ return scimError(405, "Method not allowed.");
16214
+ }
16215
+
15978
16216
  // src/runtime/gateway.ts
15979
- var hash6 = (value) => createHash25("sha256").update(value).digest("hex");
16217
+ var hash6 = (value) => createHash27("sha256").update(value).digest("hex");
15980
16218
  function uploadPath(path2) {
15981
16219
  if (!path2 || path2.startsWith("/") || path2.includes("\\") || path2.includes("\0") || path2.split("/").some((p) => !p || p === "." || p === ".." || /^(\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc|credentials.*)$/i.test(p)) || /\.(pem|key|p12|pfx)$/i.test(path2)) throw new Error("Unsafe uploaded file path");
15982
16220
  return path2;
@@ -16034,7 +16272,7 @@ async function startGateway(opts) {
16034
16272
  const voiceControllers = /* @__PURE__ */ new Map();
16035
16273
  const directory = resolve11(opts.directory);
16036
16274
  await mkdir13(directory, { recursive: true, mode: 448 });
16037
- const storePath2 = join34(directory, "state.json");
16275
+ const storePath2 = join35(directory, "state.json");
16038
16276
  const database = opts.databaseUrl ? await openGatewayPostgres(opts.databaseUrl) : void 0;
16039
16277
  let store;
16040
16278
  if (database) store = database.state;
@@ -16066,9 +16304,9 @@ async function startGateway(opts) {
16066
16304
  try {
16067
16305
  if (database) await database.write(snapshot);
16068
16306
  else {
16069
- const path2 = join34(directory, `state-${randomUUID7()}.tmp`);
16307
+ const path2 = join35(directory, `state-${randomUUID9()}.tmp`);
16070
16308
  await writeFile21(path2, snapshot, { mode: 384 });
16071
- await rename2(path2, storePath2);
16309
+ await rename3(path2, storePath2);
16072
16310
  }
16073
16311
  committedWorkflows = workflowView;
16074
16312
  } catch (error) {
@@ -16084,7 +16322,7 @@ async function startGateway(opts) {
16084
16322
  const oauth = createOAuth(store, save, issuer);
16085
16323
  for (const thread of store.chats ?? []) {
16086
16324
  const last = thread.messages.at(-1);
16087
- if (last?.role === "user") thread.messages.push({ id: randomUUID7(), role: "assistant", content: "The API restarted before this response completed. Your message is saved.", error: "model_interrupted", requestId: last.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: last.context });
16325
+ if (last?.role === "user") thread.messages.push({ id: randomUUID9(), role: "assistant", content: "The API restarted before this response completed. Your message is saved.", error: "model_interrupted", requestId: last.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: last.context });
16088
16326
  }
16089
16327
  await save();
16090
16328
  store.jobs = store.jobs.filter((j) => Date.parse(j.createdAt) > Date.now() - 30 * 864e5);
@@ -16108,16 +16346,16 @@ async function startGateway(opts) {
16108
16346
  if (!store.accounts.some((a) => a.id === item.job.accountId && a.active)) throw new Error("Account revoked before execution");
16109
16347
  item.job.status = "running";
16110
16348
  await save();
16111
- workspace = await mkdtemp13(join34(tmpdir14(), "agenttwin-api-run-"));
16349
+ workspace = await mkdtemp13(join35(tmpdir14(), "agenttwin-api-run-"));
16112
16350
  for (const [file, encoded] of Object.entries(item.files)) {
16113
- const destination = join34(workspace, uploadPath(file));
16351
+ const destination = join35(workspace, uploadPath(file));
16114
16352
  await mkdir13(dirname6(destination), { recursive: true });
16115
16353
  await writeFile21(destination, Buffer.from(encoded, "base64"), { mode: 384 });
16116
16354
  }
16117
- await writeFile21(join34(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
16355
+ await writeFile21(join35(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
16118
16356
  if (item.spec.workflowId) {
16119
- await mkdir13(join34(workspace, ".agenttwin"));
16120
- await writeFile21(join34(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
16357
+ await mkdir13(join35(workspace, ".agenttwin"));
16358
+ await writeFile21(join35(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
16121
16359
  }
16122
16360
  const receipt = await runWorld(workspace, { runtime: "e2b", seed: item.seed, signal: controllers.get(item.job.id)?.signal, log: () => {
16123
16361
  } });
@@ -16154,7 +16392,7 @@ async function startGateway(opts) {
16154
16392
  const devices = /* @__PURE__ */ new Map();
16155
16393
  let hashing = 0;
16156
16394
  let localOnboardingUntil = 0;
16157
- const dummyPassword = randomBytes9(16).toString("hex") + ":" + randomBytes9(64).toString("hex");
16395
+ const dummyPassword = randomBytes11(16).toString("hex") + ":" + randomBytes11(64).toString("hex");
16158
16396
  const budget = requestBudget(opts.requestsPerMinute);
16159
16397
  const githubStates = /* @__PURE__ */ new Map();
16160
16398
  const registered = opts.githubApp ? void 0 : await loadRegisteredApp(directory);
@@ -16526,17 +16764,32 @@ async function startGateway(opts) {
16526
16764
  const identity = await socialAuth.finish(transaction, requestUrl.searchParams);
16527
16765
  let owner = store.accounts.find((a) => a.externalIdentities?.some((i) => i.provider === identity.provider && i.issuer === identity.issuer && i.subject === identity.subject));
16528
16766
  if (!owner) {
16529
- if (store.accounts.some((a) => a.identity?.email === identity.email)) {
16767
+ const realm = opts.socialAuth?.ssoRealms?.find((r) => r.issuer === identity.issuer);
16768
+ const provisioned = realm?.workspace ? store.accounts.find((a) => a.provisionedBy === realm.workspace && a.identity?.email?.toLowerCase() === identity.email.toLowerCase() && !a.externalIdentities?.length) : void 0;
16769
+ if (provisioned) {
16770
+ provisioned.externalIdentities = [{ provider: identity.provider, issuer: identity.issuer, subject: identity.subject }];
16771
+ owner = provisioned;
16772
+ } else if (store.accounts.some((a) => a.identity?.email === identity.email)) {
16530
16773
  redirect((transaction.signup ? "/signup/" : "/login/") + "?auth_error=existing_account");
16531
16774
  return;
16532
16775
  }
16533
- if (store.accounts.length >= 1e4) throw new Error("account_capacity");
16534
- owner = { id: randomUUID7(), tokenHash: hash6(randomBytes9(32).toString("hex")), label: identity.name + "'s workspace", active: true, usageDay: "", runs: 0, identity: { email: identity.email, name: identity.name }, externalIdentities: [{ provider: identity.provider, issuer: identity.issuer, subject: identity.subject }], ...identity.organization ? { organization: identity.organization } : {} };
16535
- store.accounts.push(owner);
16776
+ if (!owner && store.accounts.length >= 1e4) throw new Error("account_capacity");
16777
+ if (!owner) owner = { id: randomUUID9(), tokenHash: hash6(randomBytes11(32).toString("hex")), label: identity.name + "'s workspace", active: true, usageDay: "", runs: 0, identity: { email: identity.email, name: identity.name }, externalIdentities: [{ provider: identity.provider, issuer: identity.issuer, subject: identity.subject }], ...identity.organization ? { organization: identity.organization } : {} };
16778
+ if (!store.accounts.includes(owner)) store.accounts.push(owner);
16536
16779
  captureAnalytics({ event: "account_created", distinctId: owner.id, properties: { method: identity.provider, realm: identity.organization || identity.issuer } });
16537
16780
  }
16538
16781
  if (!owner.active) throw new Error("account_inactive");
16539
- const secret = randomBytes9(32).toString("hex");
16782
+ const ssoRealm = opts.socialAuth?.ssoRealms?.find((r) => r.issuer === identity.issuer);
16783
+ const shared = ssoRealm?.workspace ? store.accounts.find((a) => a.id === ssoRealm.workspace && a.active) : void 0;
16784
+ if (shared && shared.id !== owner.id) {
16785
+ const member = (store.teamMembers ?? []).some((m) => m.accountId === shared.id && m.memberId === owner.id);
16786
+ if (!member && ssoRealm.autoJoin !== false) {
16787
+ store.teamMembers = [...store.teamMembers ?? [], { accountId: shared.id, memberId: owner.id, role: ssoRealm.role ?? "member", addedAt: (/* @__PURE__ */ new Date()).toISOString(), addedBy: `sso:${ssoRealm.id}` }];
16788
+ recordAudit(store, { accountId: shared.id, actorId: owner.id, actorLabel: identity.email, action: "member.joined", subject: owner.id, details: { role: ssoRealm.role ?? "member", via: "sso" } });
16789
+ }
16790
+ if ((member || ssoRealm.autoJoin !== false) && !owner.activeWorkspace) owner.activeWorkspace = shared.id;
16791
+ }
16792
+ const secret = randomBytes11(32).toString("hex");
16540
16793
  store.sessions = (store.sessions ?? []).filter((s) => s.expires > Date.now());
16541
16794
  const owned = store.sessions.filter((s) => s.accountId === owner.id);
16542
16795
  if (owned.length >= 10) store.sessions = store.sessions.filter((s) => s !== owned[0]);
@@ -16557,7 +16810,7 @@ async function startGateway(opts) {
16557
16810
  send(res, 429, { error: "Try again shortly." });
16558
16811
  return;
16559
16812
  }
16560
- const secret = randomBytes9(32).toString("hex"), code = randomBytes9(5).toString("hex").toUpperCase();
16813
+ const secret = randomBytes11(32).toString("hex"), code = randomBytes11(5).toString("hex").toUpperCase();
16561
16814
  devices.set(digest5(secret), { code, expires: Date.now() + 6e5, lastPoll: 0 });
16562
16815
  send(res, 200, { deviceCode: secret, userCode: code, verificationUrl, expiresIn: 600 });
16563
16816
  return;
@@ -16578,7 +16831,7 @@ async function startGateway(opts) {
16578
16831
  }
16579
16832
  const rpID = requestUrl.hostname === "localhost" || requestUrl.hostname === "127.0.0.1" ? "localhost" : new URL(origin).hostname;
16580
16833
  const options = await generateRegistrationOptions({ rpName: "AgentTwin", rpID, userName: owner.identity?.email ?? owner.label, userDisplayName: owner.identity?.name ?? owner.label, excludeCredentials: (owner.passkeys ?? []).map((k) => ({ id: k.id })) });
16581
- const challengeId = randomBytes9(16).toString("hex");
16834
+ const challengeId = randomBytes11(16).toString("hex");
16582
16835
  challengeStore(passkeyChallenges, challengeId, options.challenge, 12e4);
16583
16836
  send(res, 200, { options, challengeId });
16584
16837
  return;
@@ -16625,7 +16878,7 @@ async function startGateway(opts) {
16625
16878
  const credentialId = typeof input.credentialId === "string" ? input.credentialId.slice(0, 1024) : "";
16626
16879
  const owner = credentialId ? store.accounts.find((a) => a.active && (a.passkeys ?? []).some((k) => k.id === credentialId)) : void 0;
16627
16880
  const options = await generateAuthenticationOptions({ rpID: requestUrl.hostname === "localhost" || requestUrl.hostname === "127.0.0.1" ? "localhost" : new URL(origin).hostname, allowCredentials: credentialId && owner ? [{ id: credentialId }] : void 0, userVerification: "preferred" });
16628
- const challengeId = randomBytes9(16).toString("hex");
16881
+ const challengeId = randomBytes11(16).toString("hex");
16629
16882
  challengeStore(passkeyChallenges, challengeId, options.challenge, 12e4);
16630
16883
  send(res, 200, { options, challengeId });
16631
16884
  return;
@@ -16656,7 +16909,7 @@ async function startGateway(opts) {
16656
16909
  return;
16657
16910
  }
16658
16911
  key2.counter = verification.authenticationInfo.newCounter;
16659
- const secret = randomBytes9(32).toString("hex");
16912
+ const secret = randomBytes11(32).toString("hex");
16660
16913
  store.sessions = (store.sessions ?? []).filter((s) => s.expires > Date.now());
16661
16914
  const owned = store.sessions.filter((s) => s.accountId === owner.id);
16662
16915
  if (owned.length >= 10) store.sessions = store.sessions.filter((s) => s !== owned[0]);
@@ -16753,7 +17006,7 @@ async function startGateway(opts) {
16753
17006
  send(res, 429, { error: "account_capacity" });
16754
17007
  return;
16755
17008
  }
16756
- a = { id: randomUUID7(), tokenHash: hash6(randomBytes9(32).toString("hex")), label: workspace, active: true, usageDay: "", runs: 0, identity: { email: parsed.email, name, passwordHash: encoded } };
17009
+ a = { id: randomUUID9(), tokenHash: hash6(randomBytes11(32).toString("hex")), label: workspace, active: true, usageDay: "", runs: 0, identity: { email: parsed.email, name, passwordHash: encoded } };
16757
17010
  store.accounts.push(a);
16758
17011
  captureAnalytics({ event: "account_created", distinctId: a.id, properties: { method: "email", realm: "password" } });
16759
17012
  } else {
@@ -16763,7 +17016,7 @@ async function startGateway(opts) {
16763
17016
  return;
16764
17017
  }
16765
17018
  }
16766
- const secret = randomBytes9(32).toString("hex");
17019
+ const secret = randomBytes11(32).toString("hex");
16767
17020
  store.sessions = (store.sessions ?? []).filter((s) => s.expires > Date.now());
16768
17021
  const owned = store.sessions.filter((s) => s.accountId === a.id);
16769
17022
  if (owned.length >= 10) store.sessions = store.sessions.filter((s) => s !== owned[0]);
@@ -16873,8 +17126,8 @@ async function startGateway(opts) {
16873
17126
  send(res, 400, { error: "label_required" });
16874
17127
  return;
16875
17128
  }
16876
- const accessToken = `at_user_${randomBytes9(32).toString("hex")}`;
16877
- const account2 = { id: randomUUID7(), tokenHash: hash6(accessToken), label: data.label, active: true, usageDay: "", runs: 0 };
17129
+ const accessToken = `at_user_${randomBytes11(32).toString("hex")}`;
17130
+ const account2 = { id: randomUUID9(), tokenHash: hash6(accessToken), label: data.label, active: true, usageDay: "", runs: 0 };
16878
17131
  if (store.accounts.length >= 1e4) {
16879
17132
  send(res, 429, { error: "account_capacity" });
16880
17133
  return;
@@ -16900,12 +17153,18 @@ async function startGateway(opts) {
16900
17153
  send(res, 200, { revoked: true });
16901
17154
  return;
16902
17155
  }
16903
- const account = store.accounts.find((a) => a.active && (grant ? a.id === grant.client.accountId : token ? a.tokenHash === hash6(token) || a.cliTokens?.includes(hash6(token)) : a.id === session?.accountId));
16904
- if (!account) {
17156
+ const orgToken = token ? findOrgToken(store, token) : void 0;
17157
+ const found = store.accounts.find((a) => a.active && (orgToken ? a.id === orgToken.accountId : grant ? a.id === grant.client.accountId : token ? a.tokenHash === hash6(token) || a.cliTokens?.includes(hash6(token)) : a.id === session?.accountId));
17158
+ if (!found) {
16905
17159
  res.setHeader("WWW-Authenticate", `Bearer resource_metadata="${issuer}/.well-known/oauth-protected-resource"`);
16906
17160
  send(res, 401, { error: "unauthorized" });
16907
17161
  return;
16908
17162
  }
17163
+ let account = found;
17164
+ if (orgToken && path2.startsWith("/v1/auth/") && path2 !== "/v1/auth/me") {
17165
+ send(res, 403, { error: "organization_token_not_allowed" });
17166
+ return;
17167
+ }
16909
17168
  if (path2 === "/v1/dev/workspace" && req.method === "POST" && opts.localDevelopment && ["127.0.0.1", "localhost"].includes(opts.host ?? "") && verificationUrl === "http://localhost:3000/onboarding/") {
16910
17169
  if (token || !session || origin !== "http://localhost:3000") {
16911
17170
  send(res, 403, { error: "browser_session_required" });
@@ -16953,7 +17212,7 @@ async function startGateway(opts) {
16953
17212
  return;
16954
17213
  }
16955
17214
  const previousIdentity = account.identity, previousSessions = store.sessions;
16956
- const secret = randomBytes9(32).toString("hex");
17215
+ const secret = randomBytes11(32).toString("hex");
16957
17216
  account.identity = { ...account.identity, passwordHash: encoded };
16958
17217
  store.sessions = [...store.sessions.filter((s) => s.accountId !== account.id), { accountId: account.id, hash: digest5(secret), expires: Date.now() + 7 * 864e5 }];
16959
17218
  try {
@@ -16976,7 +17235,7 @@ async function startGateway(opts) {
16976
17235
  return;
16977
17236
  }
16978
17237
  account.cliTokens = (account.cliTokens ?? []).filter((t) => t !== hash6(token));
16979
- if (account.tokenHash === hash6(token)) account.tokenHash = hash6(randomBytes9(32).toString("hex"));
17238
+ if (account.tokenHash === hash6(token)) account.tokenHash = hash6(randomBytes11(32).toString("hex"));
16980
17239
  await save();
16981
17240
  send(res, 200, { signedOut: true });
16982
17241
  return;
@@ -16989,7 +17248,7 @@ async function startGateway(opts) {
16989
17248
  send(res, 400, { error: "Code not found or expired. Run agenttwin login again." });
16990
17249
  return;
16991
17250
  }
16992
- const accessToken = `at_user_${randomBytes9(32).toString("hex")}`;
17251
+ const accessToken = `at_user_${randomBytes11(32).toString("hex")}`;
16993
17252
  account.cliTokens = [...(account.cliTokens ?? []).slice(-9), hash6(accessToken)];
16994
17253
  device.accountId = account.id;
16995
17254
  await save();
@@ -17023,8 +17282,198 @@ async function startGateway(opts) {
17023
17282
  send(res, 200, { user: profile(account) });
17024
17283
  return;
17025
17284
  }
17285
+ const person = account, team = resolveWorkspace(store, person, orgToken);
17286
+ const audit = (action, subject, details) => recordAudit(store, { accountId: team.workspace.id, actorId: team.actorId, actorLabel: team.actorLabel, action, ...subject ? { subject } : {}, ...details ? { details } : {} });
17026
17287
  if (path2 === "/v1/auth/me" && req.method === "GET") {
17027
- send(res, 200, { user: profile(account) });
17288
+ send(res, 200, { user: { ...profile(person), team: { workspaceId: team.workspace.id, workspace: team.workspace.label, role: team.role, shared: team.shared }, workspaces: orgToken ? [] : workspacesOf(store, person) } });
17289
+ return;
17290
+ }
17291
+ if ((path2 === "/v1/team/join" || path2 === "/v1/team/switch") && req.method === "POST") {
17292
+ if (orgToken) {
17293
+ send(res, 403, { error: "organization_token_not_allowed" });
17294
+ return;
17295
+ }
17296
+ const input = await body(req, 8192);
17297
+ if (path2 === "/v1/team/join") {
17298
+ const result2 = acceptInvite(store, person, typeof input.code === "string" ? input.code : "");
17299
+ if ("error" in result2) {
17300
+ send(res, result2.error === "invite_invalid" ? 404 : 403, { error: result2.error, ...result2.error === "invite_email_mismatch" ? { message: `This invite is for ${result2.email}. Sign in with that email to accept it.` } : {} });
17301
+ return;
17302
+ }
17303
+ recordAudit(store, { accountId: result2.invite.accountId, actorId: person.id, actorLabel: person.identity?.email ?? person.label, action: "member.joined", subject: person.id, details: { role: result2.invite.role } });
17304
+ await save();
17305
+ send(res, 200, { joined: true, workspaceId: result2.invite.accountId, role: result2.invite.role });
17306
+ return;
17307
+ }
17308
+ const target = typeof input.workspaceId === "string" ? input.workspaceId : "";
17309
+ if (!workspacesOf(store, person).some((w) => w.id === target)) {
17310
+ send(res, 404, { error: "workspace_not_found" });
17311
+ return;
17312
+ }
17313
+ if (target === person.id) delete person.activeWorkspace;
17314
+ else person.activeWorkspace = target;
17315
+ await save();
17316
+ send(res, 200, { workspaceId: target });
17317
+ return;
17318
+ }
17319
+ if (path2.startsWith("/v1/team/members/") && req.method === "DELETE" && path2.slice(17) === person.id && !orgToken && team.workspace.id !== person.id) {
17320
+ store.teamMembers = (store.teamMembers ?? []).filter((m) => !(m.accountId === team.workspace.id && m.memberId === person.id));
17321
+ delete person.activeWorkspace;
17322
+ audit("member.left", person.id);
17323
+ await save();
17324
+ send(res, 200, { left: true });
17325
+ return;
17326
+ }
17327
+ account = team.workspace;
17328
+ if (team.role === "viewer" && !["GET", "HEAD"].includes(req.method ?? "")) {
17329
+ send(res, 403, { error: "viewer_read_only", message: "Viewers can see this workspace but not change it. Ask an admin for the member role." });
17330
+ return;
17331
+ }
17332
+ if (team.role !== "admin" && adminOnly(req.method ?? "", path2)) {
17333
+ send(res, 403, { error: "admin_required" });
17334
+ return;
17335
+ }
17336
+ if (path2.startsWith("/scim/v2/")) {
17337
+ if (!orgToken || team.role !== "admin") {
17338
+ send(res, 403, scimError(403, "SCIM needs an organization token with the admin role.").body);
17339
+ return;
17340
+ }
17341
+ const method = req.method ?? "GET";
17342
+ const input = ["POST", "PUT", "PATCH"].includes(method) ? await body(req, 1024 * 1024) : void 0;
17343
+ const result2 = handleScim(store, team.workspace.id, method, path2, requestUrl.searchParams, input, issuer);
17344
+ if (result2.audit) {
17345
+ audit(result2.audit.action, result2.audit.subject, result2.audit.details);
17346
+ await save();
17347
+ }
17348
+ if (result2.status === 204) {
17349
+ res.writeHead(204, { "cache-control": "no-store" });
17350
+ res.end();
17351
+ return;
17352
+ }
17353
+ send(res, result2.status, result2.body);
17354
+ return;
17355
+ }
17356
+ if (!["GET", "HEAD"].includes(req.method ?? "") && !path2.startsWith("/v1/team/") && team.shared) {
17357
+ res.once("finish", () => {
17358
+ if (res.statusCode < 400) {
17359
+ audit(auditAction(req.method ?? "", path2), void 0, { status: res.statusCode });
17360
+ save().catch(() => {
17361
+ });
17362
+ }
17363
+ });
17364
+ }
17365
+ if (path2 === "/v1/team" && req.method === "GET") {
17366
+ send(res, 200, teamView(store, team.workspace, team.role));
17367
+ return;
17368
+ }
17369
+ if (path2 === "/v1/team/invites" && req.method === "POST") {
17370
+ const input = await body(req, 8192);
17371
+ const email = typeof input.email === "string" ? input.email.trim().toLowerCase() : "";
17372
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254) {
17373
+ send(res, 400, { error: "Enter a valid email address." });
17374
+ return;
17375
+ }
17376
+ if (!isRole(input.role)) {
17377
+ send(res, 400, { error: "Role must be admin, member or viewer." });
17378
+ return;
17379
+ }
17380
+ if ((store.teamInvites ?? []).filter((i) => i.accountId === team.workspace.id && !i.acceptedBy && i.expiresAt > Date.now()).length >= 100) {
17381
+ send(res, 429, { error: "Too many pending invites. Revoke some first." });
17382
+ return;
17383
+ }
17384
+ const { invite, code } = createInvite(store, team.workspace.id, email, input.role, team.actorId);
17385
+ audit("invite.created", invite.id, { email, role: invite.role });
17386
+ await save();
17387
+ send(res, 201, { invite: { id: invite.id, email: invite.email, role: invite.role, expiresAt: new Date(invite.expiresAt).toISOString() }, url: `${new URL(verificationUrl).origin}/dashboard/?invite=${encodeURIComponent(code)}#team` });
17388
+ return;
17389
+ }
17390
+ const teamMatch = path2.match(/^\/v1\/team\/(invites|members|tokens)\/([0-9a-f-]{36})$/);
17391
+ if (teamMatch && req.method === "DELETE") {
17392
+ const [, kind, id] = teamMatch;
17393
+ if (kind === "invites") {
17394
+ const before = store.teamInvites?.length ?? 0;
17395
+ store.teamInvites = (store.teamInvites ?? []).filter((i) => !(i.id === id && i.accountId === team.workspace.id && !i.acceptedBy));
17396
+ if (store.teamInvites.length === before) {
17397
+ send(res, 404, { error: "not_found" });
17398
+ return;
17399
+ }
17400
+ audit("invite.revoked", id);
17401
+ }
17402
+ if (kind === "tokens") {
17403
+ const before = store.orgTokens?.length ?? 0;
17404
+ store.orgTokens = (store.orgTokens ?? []).filter((t) => !(t.id === id && t.accountId === team.workspace.id));
17405
+ if (store.orgTokens.length === before) {
17406
+ send(res, 404, { error: "not_found" });
17407
+ return;
17408
+ }
17409
+ audit("token.revoked", id);
17410
+ }
17411
+ if (kind === "members") {
17412
+ if (team.role !== "admin") {
17413
+ send(res, 403, { error: "admin_required" });
17414
+ return;
17415
+ }
17416
+ const removed = (store.teamMembers ?? []).find((m) => m.accountId === team.workspace.id && m.memberId === id);
17417
+ if (!removed) {
17418
+ send(res, 404, { error: "not_found" });
17419
+ return;
17420
+ }
17421
+ store.teamMembers = (store.teamMembers ?? []).filter((m) => m !== removed);
17422
+ const who = store.accounts.find((a) => a.id === id);
17423
+ if (who?.activeWorkspace === team.workspace.id) delete who.activeWorkspace;
17424
+ audit("member.removed", id, { role: removed.role });
17425
+ }
17426
+ await save();
17427
+ send(res, 200, { removed: true });
17428
+ return;
17429
+ }
17430
+ if (teamMatch && teamMatch[1] === "members" && req.method === "PATCH") {
17431
+ const input = await body(req, 8192);
17432
+ if (!isRole(input.role)) {
17433
+ send(res, 400, { error: "Role must be admin, member or viewer." });
17434
+ return;
17435
+ }
17436
+ const member = (store.teamMembers ?? []).find((m) => m.accountId === team.workspace.id && m.memberId === teamMatch[2]);
17437
+ if (!member) {
17438
+ send(res, 404, { error: "not_found" });
17439
+ return;
17440
+ }
17441
+ const from = member.role;
17442
+ member.role = input.role;
17443
+ audit("member.role_changed", member.memberId, { from, to: input.role });
17444
+ await save();
17445
+ send(res, 200, { memberId: member.memberId, role: member.role });
17446
+ return;
17447
+ }
17448
+ if (path2 === "/v1/team/tokens" && req.method === "GET") {
17449
+ send(res, 200, { tokens: (store.orgTokens ?? []).filter((t) => t.accountId === team.workspace.id).map(publicToken) });
17450
+ return;
17451
+ }
17452
+ if (path2 === "/v1/team/tokens" && req.method === "POST") {
17453
+ const input = await body(req, 8192);
17454
+ const label2 = typeof input.label === "string" ? input.label.trim().slice(0, 80) : "";
17455
+ if (!label2) {
17456
+ send(res, 400, { error: 'Give the token a name, such as "CI".' });
17457
+ return;
17458
+ }
17459
+ const role = input.role === void 0 ? "member" : input.role;
17460
+ if (!isRole(role)) {
17461
+ send(res, 400, { error: "Role must be admin, member or viewer." });
17462
+ return;
17463
+ }
17464
+ if ((store.orgTokens ?? []).filter((t) => t.accountId === team.workspace.id).length >= 50) {
17465
+ send(res, 429, { error: "This workspace has 50 tokens. Revoke one first." });
17466
+ return;
17467
+ }
17468
+ const { token: secret, record: record3 } = createOrgToken(store, team.workspace.id, label2, role, team.actorId);
17469
+ audit("token.created", record3.id, { label: label2, role });
17470
+ await save();
17471
+ send(res, 201, { token: secret, ...publicToken(record3) });
17472
+ return;
17473
+ }
17474
+ if (path2 === "/v1/team/audit" && req.method === "GET") {
17475
+ const events = (store.auditEvents ?? []).filter((e) => e.accountId === team.workspace.id);
17476
+ send(res, 200, { events: events.slice(-500).reverse() });
17028
17477
  return;
17029
17478
  }
17030
17479
  if (path2 === "/v1/github/app" && req.method === "GET") {
@@ -17047,7 +17496,7 @@ async function startGateway(opts) {
17047
17496
  send(res, 429, { error: "Too many pending installs. Try again shortly." });
17048
17497
  return;
17049
17498
  }
17050
- const state = randomBytes9(24).toString("hex");
17499
+ const state = randomBytes11(24).toString("hex");
17051
17500
  githubStates.set(state, { accountId: account.id, origin, expires: Date.now() + 15 * 6e4 });
17052
17501
  send(res, 200, { url: installUrl(githubApp, state) });
17053
17502
  return;
@@ -17270,7 +17719,7 @@ async function startGateway(opts) {
17270
17719
  send(res, 429, { error: "receipt_capacity" });
17271
17720
  return;
17272
17721
  }
17273
- const id = randomUUID7();
17722
+ const id = randomUUID9();
17274
17723
  const job = { id, accountId: account.id, status: "completed", createdAt: receipt.createdAt, receipt: { ...receipt, apiJobId: id } };
17275
17724
  store.jobs.push(job);
17276
17725
  await save();
@@ -17372,7 +17821,7 @@ async function startGateway(opts) {
17372
17821
  return;
17373
17822
  }
17374
17823
  store.jobs = store.jobs.filter((j) => Date.parse(j.createdAt) > Date.now() - 30 * 864e5);
17375
- const job = { id: randomUUID7(), accountId: account.id, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString(), name: spec.name, workflowId: spec.workflowId, project, ...idempotencyKey ? { idempotencyKey, requestDigest } : {} };
17824
+ const job = { id: randomUUID9(), accountId: account.id, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString(), name: spec.name, workflowId: spec.workflowId, project, ...idempotencyKey ? { idempotencyKey, requestDigest } : {} };
17376
17825
  account.runs++;
17377
17826
  store.jobs.push(job);
17378
17827
  await save();
@@ -17455,7 +17904,7 @@ async function startGateway(opts) {
17455
17904
  send(res, 429, { error: "workflow_capacity" });
17456
17905
  return;
17457
17906
  }
17458
- workflow = { id: createId || randomUUID7(), accountId: account.id, project, revision: 1, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), spec, status: "draft" };
17907
+ workflow = { id: createId || randomUUID9(), accountId: account.id, project, revision: 1, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), spec, status: "draft" };
17459
17908
  store.workflows.push(workflow);
17460
17909
  } else {
17461
17910
  const index = store.workflows.indexOf(workflow);
@@ -17576,7 +18025,7 @@ async function startGateway(opts) {
17576
18025
  return;
17577
18026
  }
17578
18027
  if (!thread) {
17579
- thread = { id: randomUUID7(), accountId: account.id, project, messages: [] };
18028
+ thread = { id: randomUUID9(), accountId: account.id, project, messages: [] };
17580
18029
  store.chats.push(thread);
17581
18030
  }
17582
18031
  if (thread.messages.length >= 200) {
@@ -17594,7 +18043,7 @@ async function startGateway(opts) {
17594
18043
  chatControllers.set(account.id, controller);
17595
18044
  const timeout = setTimeout(() => controller.abort(), 45e3);
17596
18045
  const context2 = { project, discoveryDigest: inventory ? hash6(JSON.stringify(inventory)) : null, jobId: job?.id ?? null };
17597
- thread.messages.push({ id: randomUUID7(), role: "user", content: input.content.trim(), requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
18046
+ thread.messages.push({ id: randomUUID9(), role: "user", content: input.content.trim(), requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17598
18047
  try {
17599
18048
  await save();
17600
18049
  const receipt = job?.receipt;
@@ -17612,12 +18061,12 @@ async function startGateway(opts) {
17612
18061
  send(res, 401, { error: "unauthorized" });
17613
18062
  return;
17614
18063
  }
17615
- thread.messages.push({ id: randomUUID7(), role: "assistant", content, requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
18064
+ thread.messages.push({ id: randomUUID9(), role: "assistant", content, requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17616
18065
  await save();
17617
18066
  send(res, 200, { thread });
17618
18067
  } catch (error) {
17619
18068
  const code = controller.signal.aborted ? "model_timeout" : error instanceof Error && /^model_[a-z0-9_]+$/.test(error.message) ? error.message : "model_unavailable";
17620
- thread.messages.push({ id: randomUUID7(), role: "assistant", content: "No response was completed. Your message is saved; retry after resolving the model connection.", error: code, requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
18069
+ thread.messages.push({ id: randomUUID9(), role: "assistant", content: "No response was completed. Your message is saved; retry after resolving the model connection.", error: code, requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17621
18070
  await save();
17622
18071
  send(res, 502, { error: code, thread });
17623
18072
  } finally {
@@ -17703,6 +18152,15 @@ if (process.argv[2] === "--import-state") {
17703
18152
  console.log("Gateway state import verified");
17704
18153
  process.exit(0);
17705
18154
  }
18155
+ if (databaseUrl) {
18156
+ const { upgradeGatewaySchema: upgradeGatewaySchema2 } = await Promise.resolve().then(() => (init_gateway_postgres(), gateway_postgres_exports));
18157
+ await upgradeGatewaySchema2(databaseUrl);
18158
+ }
18159
+ if (databaseUrl && process.env.AGENTTWIN_GATEWAY_IMPORT_ON_START === "1") {
18160
+ const { importJsonStateOnStart: importJsonStateOnStart2 } = await Promise.resolve().then(() => (init_gateway_postgres(), gateway_postgres_exports));
18161
+ const imported = await importJsonStateOnStart2(databaseUrl, process.env.AGENTTWIN_STATE_DIR ?? "/data/agenttwin");
18162
+ if (imported) console.log(`Gateway state imported into Postgres; JSON kept at ${imported}`);
18163
+ }
17706
18164
  var port = Number(process.env.PORT ?? 8080);
17707
18165
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid PORT");
17708
18166
  var gateway = await startGateway({ databaseUrl, githubApp: githubAppFromEnv(process.env), publicUrl: process.env.AGENTTWIN_API_PUBLIC_URL, emailVerification: emailVerificationFromEnv(process.env), socialAuth: socialAuthFromEnv(process.env), directory: process.env.AGENTTWIN_STATE_DIR ?? "/data/agenttwin", adminToken: process.env.AGENTTWIN_ADMIN_TOKEN ?? "", host: process.env.AGENTTWIN_GATEWAY_HOST ?? "0.0.0.0", dashboardDirectory: fileURLToPath4(new URL("./dashboard/", import.meta.url)), allowedOrigins: (process.env.AGENTTWIN_DASHBOARD_ORIGINS ?? "").split(",").map((origin) => origin.trim()).filter(Boolean), port });