agenttwin 0.3.24 → 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 (21) hide show
  1. package/dist/api.js +710 -192
  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/5663-661e38f3ed101571.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/{6751.613adb085c9a5b06.js → 6751.d9c97d8c374550b0.js} +1 -1
  6. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-73183e77e91eaaa0.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-3a3a934622d409c3.js +1 -0
  8. package/dist/dashboard/assets/next/static/chunks/webpack-c3ef4a63a3242476.js +1 -0
  9. package/dist/dashboard/assets/next/static/css/aa701337c7b34139.css +1 -0
  10. package/dist/dashboard/index.html +2 -2
  11. package/dist/engine.js +20 -7
  12. package/dist/gateway.js +761 -196
  13. package/package.json +1 -1
  14. package/dist/dashboard/assets/next/static/chunks/1250-a3c859fd20517500.js +0 -1
  15. package/dist/dashboard/assets/next/static/chunks/5663-2ba656663ac4643f.js +0 -1
  16. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-2d0408d8f22d7921.js +0 -1
  17. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-0e0392368e0a891e.js +0 -1
  18. package/dist/dashboard/assets/next/static/chunks/webpack-ecd761d72719adb3.js +0 -1
  19. package/dist/dashboard/assets/next/static/css/1d1b20bd9fb076d4.css +0 -1
  20. /package/dist/dashboard/assets/next/static/{ztFPFZw3-M7E56BfRipIn → KSAqb4jD1gnp0t5kzwmoJ}/_buildManifest.js +0 -0
  21. /package/dist/dashboard/assets/next/static/{ztFPFZw3-M7E56BfRipIn → KSAqb4jD1gnp0t5kzwmoJ}/_ssgManifest.js +0 -0
package/dist/api.js CHANGED
@@ -679,17 +679,17 @@ var init_adapters = __esm({
679
679
 
680
680
  // src/runtime/packs.ts
681
681
  import { existsSync, readFileSync } from "fs";
682
- import { dirname, join as join2, resolve } from "path";
682
+ import { dirname, join as join3, resolve } from "path";
683
683
  import { fileURLToPath, pathToFileURL } from "url";
684
684
  function packsDir() {
685
685
  const here = dirname(fileURLToPath(import.meta.url));
686
- const candidates = [process.env.AGENTTWIN_TWINS_DIR, join2(here, "twins"), join2(here, "../twins"), resolve(here, "../../../twins/dist")];
687
- return candidates.find((dir) => !!dir && existsSync(join2(dir, "catalog.json")));
686
+ const candidates = [process.env.AGENTTWIN_TWINS_DIR, join3(here, "twins"), join3(here, "../twins"), resolve(here, "../../../twins/dist")];
687
+ return candidates.find((dir) => !!dir && existsSync(join3(dir, "catalog.json")));
688
688
  }
689
689
  function packCatalog() {
690
690
  if (cached !== void 0) return cached;
691
691
  const dir = packsDir();
692
- cached = dir ? JSON.parse(readFileSync(join2(dir, "catalog.json"), "utf8")) : null;
692
+ cached = dir ? JSON.parse(readFileSync(join3(dir, "catalog.json"), "utf8")) : null;
693
693
  return cached;
694
694
  }
695
695
  function loadPack(name) {
@@ -697,7 +697,7 @@ function loadPack(name) {
697
697
  if (!record3) throw new Error(`No twin pack named ${name}`);
698
698
  let factory = loaded.get(name);
699
699
  if (!factory) {
700
- const file = join2(packsDir(), "packs", name, "index.mjs");
700
+ const file = join3(packsDir(), "packs", name, "index.mjs");
701
701
  factory = import(pathToFileURL(file).href).then((mod) => {
702
702
  if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
703
703
  return mod.createTwinFetch;
@@ -1930,7 +1930,7 @@ var init_spec = __esm({
1930
1930
  // src/runtime/scenarios.ts
1931
1931
  import { createHash as createHash6 } from "crypto";
1932
1932
  import { mkdir, readFile as readFile3, readdir, writeFile as writeFile2 } from "fs/promises";
1933
- import { join as join3 } from "path";
1933
+ import { join as join4 } from "path";
1934
1934
  import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
1935
1935
  function parseScenario(value) {
1936
1936
  const fail2 = (detail) => {
@@ -1969,7 +1969,7 @@ function reference(ref) {
1969
1969
  }
1970
1970
  async function loadScenario(cwd, ref) {
1971
1971
  const { id, version } = reference(ref);
1972
- const path2 = join3(cwd, ".agenttwin/scenarios", id, `${version}.json`);
1972
+ const path2 = join4(cwd, ".agenttwin/scenarios", id, `${version}.json`);
1973
1973
  const bytes = await readFile3(path2);
1974
1974
  if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
1975
1975
  const scenario = parseScenario(JSON.parse(bytes.toString()));
@@ -2198,14 +2198,14 @@ var init_browser_process_windows = __esm({
2198
2198
  // src/runtime/browser-process.ts
2199
2199
  import { mkdtemp, writeFile as writeFile3, readFile as readFile4, rm } from "fs/promises";
2200
2200
  import { tmpdir } from "os";
2201
- import { join as join4 } from "path";
2201
+ import { join as join5 } from "path";
2202
2202
  import { execFile as execFile3 } from "child_process";
2203
2203
  import { promisify as promisify3 } from "util";
2204
2204
  async function ownBrowserProcess(executable) {
2205
2205
  if (process.platform === "win32") return withCleanup(windowsBrowserProcess(executable), async () => {
2206
2206
  });
2207
- const root = await mkdtemp(join4(tmpdir(), "agenttwin-browser-owner-"));
2208
- const pidFile = join4(root, "pid"), launcher = join4(root, "launch");
2207
+ const root = await mkdtemp(join5(tmpdir(), "agenttwin-browser-owner-"));
2208
+ const pidFile = join5(root, "pid"), launcher = join5(root, "launch");
2209
2209
  await writeFile3(launcher, `#!/bin/sh
2210
2210
  echo $$ > ${quote(pidFile)}
2211
2211
  exec ${quote(executable)} "$@"
@@ -2307,11 +2307,11 @@ var init_browser_process = __esm({
2307
2307
  // src/runtime/browser-directories.ts
2308
2308
  import { mkdtemp as mkdtemp2, mkdir as mkdir2, chown, chmod, rm as rm2 } from "fs/promises";
2309
2309
  import { tmpdir as tmpdir2 } from "os";
2310
- import { join as join5 } from "path";
2310
+ import { join as join6 } from "path";
2311
2311
  async function createBrowserDirectories(identity) {
2312
2312
  if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
2313
- const root = await mkdtemp2(join5(tmpdir2(), "agenttwin-browser-"));
2314
- const profile = join5(root, "profile"), artifacts = join5(root, "artifacts");
2313
+ const root = await mkdtemp2(join6(tmpdir2(), "agenttwin-browser-"));
2314
+ const profile = join6(root, "profile"), artifacts = join6(root, "artifacts");
2315
2315
  const close = () => rm2(root, { recursive: true, force: true });
2316
2316
  try {
2317
2317
  await mkdir2(profile, { mode: 448 });
@@ -2515,7 +2515,7 @@ var init_browser_execution = __esm({
2515
2515
  // src/runtime/request-source.ts
2516
2516
  import { mkdtemp as mkdtemp3, writeFile as writeFile4, readFile as readFile5, rm as rm3, realpath } from "fs/promises";
2517
2517
  import { tmpdir as tmpdir3 } from "os";
2518
- import { join as join6, resolve as resolve2 } from "path";
2518
+ import { join as join7, resolve as resolve2 } from "path";
2519
2519
  function parseRequestSource(raw, spec) {
2520
2520
  if (typeof raw !== "string" || raw.length > 1024) return;
2521
2521
  try {
@@ -2527,9 +2527,9 @@ function parseRequestSource(raw, spec) {
2527
2527
  }
2528
2528
  }
2529
2529
  async function createRequestSourceHook(app, spec, credentials2, runtime) {
2530
- const dir = await mkdtemp3(join6(tmpdir3(), "agenttwin-source-hook-"));
2531
- const path2 = join6(dir, "hook.cjs");
2532
- const violationsPath = join6(dir, "blocked.jsonl");
2530
+ const dir = await mkdtemp3(join7(tmpdir3(), "agenttwin-source-hook-"));
2531
+ const path2 = join7(dir, "hook.cjs");
2532
+ const violationsPath = join7(dir, "blocked.jsonl");
2533
2533
  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 };
2534
2534
  const hook = applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
2535
2535
  ` + String.raw`
@@ -3972,7 +3972,7 @@ var init_rest_adapters = __esm({
3972
3972
 
3973
3973
  // src/runtime/pack-log.ts
3974
3974
  import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
3975
- import { join as join7 } from "path";
3975
+ import { join as join8 } from "path";
3976
3976
  function packCollection(type, requestPath) {
3977
3977
  const segments = requestPath.split("/").filter(Boolean);
3978
3978
  const at = segments.findIndex((s) => s === type || singular2(s) === type || s.replace(/-/g, "_") === type || singular2(s.replace(/-/g, "_")) === type);
@@ -4012,7 +4012,7 @@ var init_pack_log = __esm({
4012
4012
  partial = /* @__PURE__ */ new Map();
4013
4013
  files() {
4014
4014
  if (!existsSync2(this.root)) return [];
4015
- return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join7(this.root, f)).sort();
4015
+ return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join8(this.root, f)).sort();
4016
4016
  }
4017
4017
  drain() {
4018
4018
  const out = [];
@@ -4050,7 +4050,7 @@ import { createHash as createHash9 } from "crypto";
4050
4050
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
4051
4051
  import { mkdir as mkdir3, mkdtemp as mkdtemp4, rm as rm4, writeFile as writeFile5 } from "fs/promises";
4052
4052
  import { tmpdir as tmpdir4 } from "os";
4053
- import { join as join8 } from "path";
4053
+ import { join as join9 } from "path";
4054
4054
  var idempotencyKeyDigest, HttpWorld;
4055
4055
  var init_http_world = __esm({
4056
4056
  "src/runtime/http-world.ts"() {
@@ -4488,22 +4488,22 @@ var init_http_world = __esm({
4488
4488
  async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
4489
4489
  const name = service.adapter.slice(PACK_PREFIX.length), meta2 = packRecord(name);
4490
4490
  if (this.twinClock && packCatalog()?.engine[meta2.generation]?.clockSupport !== "async-context-v1") throw new Error("Twin packs need rebuilding for per-run clock support");
4491
- const root = await mkdtemp4(join8(tmpdir4(), `agenttwin-pack-${name}-`));
4491
+ const root = await mkdtemp4(join9(tmpdir4(), `agenttwin-pack-${name}-`));
4492
4492
  this.packRoots.push(root);
4493
4493
  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" : "";
4494
4494
  const writeSeedLog = async (dir, text2) => {
4495
4495
  if (!text2) return;
4496
- await mkdir3(join8(dir, ".volter/world", meta2.logService), { recursive: true });
4497
- await writeFile5(join8(dir, ".volter/world", meta2.logService, "actions.jsonl"), text2);
4496
+ await mkdir3(join9(dir, ".volter/world", meta2.logService), { recursive: true });
4497
+ await writeFile5(join9(dir, ".volter/world", meta2.logService, "actions.jsonl"), text2);
4498
4498
  };
4499
4499
  let tenant = {}, credential;
4500
4500
  if (meta2.logService && meta2.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
4501
- const probe = await mkdtemp4(join8(tmpdir4(), `agenttwin-pack-${name}-probe-`));
4501
+ const probe = await mkdtemp4(join9(tmpdir4(), `agenttwin-pack-${name}-probe-`));
4502
4502
  try {
4503
4503
  await writeSeedLog(probe, worldSeed);
4504
4504
  const scratch = await (await loadPack(name))({ root: probe });
4505
4505
  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();
4506
- const probed = new PackActionTail(join8(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
4506
+ const probed = new PackActionTail(join9(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
4507
4507
  tenant = tenantFields(probed);
4508
4508
  credential = credentialAction(probed);
4509
4509
  } finally {
@@ -4515,7 +4515,7 @@ var init_http_world = __esm({
4515
4515
  await writeSeedLog(root, seeded);
4516
4516
  const twin = await (await loadPack(name))({ root });
4517
4517
  const baseHost = meta2.hosts[0]?.host ?? `${name}.twin.test`;
4518
- const log = new PackActionTail(join8(root, ".volter"));
4518
+ const log = new PackActionTail(join9(root, ".volter"));
4519
4519
  let issued = {};
4520
4520
  if (meta2.credentialDoor) {
4521
4521
  const r = await twin(new Request(`https://${baseHost}${meta2.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta2.credentialDoor.body ?? {}) }));
@@ -5157,10 +5157,10 @@ var init_contracts = __esm({
5157
5157
 
5158
5158
  // src/runtime/cost-model.ts
5159
5159
  import { readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
5160
- import { join as join9 } from "path";
5160
+ import { join as join10 } from "path";
5161
5161
  async function readCostConfig(cwd) {
5162
5162
  try {
5163
- const raw = JSON.parse(await readFile6(join9(cwd, COSTS_FILE), "utf8"));
5163
+ const raw = JSON.parse(await readFile6(join10(cwd, COSTS_FILE), "utf8"));
5164
5164
  return raw && typeof raw === "object" ? raw : void 0;
5165
5165
  } catch {
5166
5166
  return void 0;
@@ -6019,7 +6019,7 @@ import { execFile as execFile4 } from "child_process";
6019
6019
  import { mkdtemp as mkdtemp5, readFile as readFile7, rm as rm5, writeFile as writeFile7 } from "fs/promises";
6020
6020
  import { createServer as createServer2, request as httpRequest } from "http";
6021
6021
  import { tmpdir as tmpdir5 } from "os";
6022
- import { join as join10 } from "path";
6022
+ import { join as join11 } from "path";
6023
6023
  import { createSecureContext, TLSSocket } from "tls";
6024
6024
  import { promisify as promisify4 } from "util";
6025
6025
  function matchRoute(routes2, host, pathname) {
@@ -6044,7 +6044,7 @@ function rewrite(r, p) {
6044
6044
  return p;
6045
6045
  }
6046
6046
  async function runAuthority(dir) {
6047
- const ca = { key: join10(dir, "ca.key"), cert: join10(dir, "ca.pem") };
6047
+ const ca = { key: join11(dir, "ca.key"), cert: join11(dir, "ca.pem") };
6048
6048
  await run2("openssl", [
6049
6049
  "req",
6050
6050
  "-x509",
@@ -6075,7 +6075,7 @@ async function runAuthority(dir) {
6075
6075
  let ctx = contexts.get(host);
6076
6076
  if (!ctx) {
6077
6077
  ctx = (async () => {
6078
- const base = join10(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
6078
+ const base = join11(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
6079
6079
  await writeFile7(base + ".ext", `basicConstraints=critical,CA:FALSE
6080
6080
  keyUsage=critical,digitalSignature
6081
6081
  extendedKeyUsage=serverAuth
@@ -6094,7 +6094,7 @@ authorityKeyIdentifier=keyid,issuer
6094
6094
  };
6095
6095
  }
6096
6096
  async function startTwinProxy(routes2) {
6097
- const dir = await mkdtemp5(join10(tmpdir5(), "agenttwin-proxy-"));
6097
+ const dir = await mkdtemp5(join11(tmpdir5(), "agenttwin-proxy-"));
6098
6098
  const authority = await runAuthority(dir).catch((error) => {
6099
6099
  throw new Error(`The twin proxy needs the openssl command to make this run's certificate authority: ${error instanceof Error ? error.message : error}`);
6100
6100
  });
@@ -6212,7 +6212,7 @@ var init_twin_proxy = __esm({
6212
6212
  // src/runtime/twin-routing.ts
6213
6213
  import { mkdtemp as mkdtemp6, readFile as readFile8, rm as rm6, writeFile as writeFile8 } from "fs/promises";
6214
6214
  import { tmpdir as tmpdir6 } from "os";
6215
- import { join as join11 } from "path";
6215
+ import { join as join12 } from "path";
6216
6216
  function twinRoutes(services, world, models) {
6217
6217
  const routes2 = [];
6218
6218
  for (const service of services) {
@@ -6941,20 +6941,20 @@ var init_exit = __esm({
6941
6941
 
6942
6942
  // src/runtime/stage-worker.ts
6943
6943
  import { copyFile, rm as rm7 } from "fs/promises";
6944
- import { basename, dirname as dirname2, join as join12 } from "path";
6944
+ import { basename, dirname as dirname2, join as join13 } from "path";
6945
6945
  import { fileURLToPath as fileURLToPath2 } from "url";
6946
6946
  async function stageWorker(stage, runModuleUrl) {
6947
6947
  const modulePath = fileURLToPath2(runModuleUrl), directory = dirname2(modulePath);
6948
- const destination = join12(stage, "worker.js");
6948
+ const destination = join13(stage, "worker.js");
6949
6949
  const sourceDevelopment = basename(modulePath) === "run.ts" && basename(directory) === "commands" && basename(dirname2(directory)) === "src";
6950
6950
  if (!sourceDevelopment) {
6951
- await copyFile(join12(directory, "worker.js"), destination);
6951
+ await copyFile(join13(directory, "worker.js"), destination);
6952
6952
  return;
6953
6953
  }
6954
6954
  try {
6955
6955
  const { build: build2 } = await import("esbuild");
6956
6956
  await build2({
6957
- entryPoints: [join12(directory, "../runtime/worker.ts")],
6957
+ entryPoints: [join13(directory, "../runtime/worker.ts")],
6958
6958
  outfile: destination,
6959
6959
  bundle: true,
6960
6960
  platform: "node",
@@ -6990,7 +6990,7 @@ var init_offline = __esm({
6990
6990
 
6991
6991
  // src/runtime/credentials.ts
6992
6992
  import { homedir } from "os";
6993
- import { join as join13 } from "path";
6993
+ import { join as join14 } from "path";
6994
6994
  import { readFile as readFile9, mkdir as mkdir4, writeFile as writeFile9, chmod as chmod2, rm as rm8 } from "fs/promises";
6995
6995
  async function savedConnection() {
6996
6996
  try {
@@ -7005,13 +7005,13 @@ var path;
7005
7005
  var init_credentials = __esm({
7006
7006
  "src/runtime/credentials.ts"() {
7007
7007
  "use strict";
7008
- path = () => join13(homedir(), ".agenttwin", "credentials.json");
7008
+ path = () => join14(homedir(), ".agenttwin", "credentials.json");
7009
7009
  }
7010
7010
  });
7011
7011
 
7012
7012
  // src/runtime/remote.ts
7013
7013
  import { readFile as readFile10 } from "fs/promises";
7014
- import { join as join14 } from "path";
7014
+ import { join as join15 } from "path";
7015
7015
  function apiBase(value) {
7016
7016
  if (offline()) throw new CliError(OFFLINE_MESSAGE, { code: EXIT.USAGE });
7017
7017
  let url;
@@ -7029,7 +7029,7 @@ async function executeRemote(stage, spec, log, metadata = {}) {
7029
7029
  const token = process.env.AGENTTWIN_TOKEN || saved?.token;
7030
7030
  if (!token) throw new CliError("Sign in first with npx agenttwin login", { code: EXIT.BLOCKED });
7031
7031
  const files = /* @__PURE__ */ Object.create(null);
7032
- for (const file of spec.files) files[file] = (await readFile10(join14(stage, "app", file))).toString("base64");
7032
+ for (const file of spec.files) files[file] = (await readFile10(join15(stage, "app", file))).toString("base64");
7033
7033
  const headers = { authorization: `Bearer ${token}`, "content-type": "application/json" };
7034
7034
  const response = await fetch(`${base}/v1/runs`, { method: "POST", headers, body: JSON.stringify({ spec, files, ...metadata }), redirect: "error", signal: AbortSignal.timeout(15e3) });
7035
7035
  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 });
@@ -7077,8 +7077,8 @@ async function captureGit(cwd, previousHead) {
7077
7077
  }
7078
7078
  }
7079
7079
  return { head, branch: branch || "detached HEAD", totalCommits: Number(total), dirty: !!status, capturedAt: (/* @__PURE__ */ new Date()).toISOString(), commits: history ? history.split("\n").map((line) => {
7080
- const [sha4, date] = line.split(" ");
7081
- return { sha: sha4, date };
7080
+ const [sha6, date] = line.split(" ");
7081
+ return { sha: sha6, date };
7082
7082
  }) : [], changedFiles: [...new Set(changed.split("\n").filter(Boolean))].slice(0, 1e3), ...previousHead ? { previousHead } : {} };
7083
7083
  } catch {
7084
7084
  return void 0;
@@ -7087,9 +7087,9 @@ async function captureGit(cwd, previousHead) {
7087
7087
  function validateGit(value) {
7088
7088
  if (value === void 0) return void 0;
7089
7089
  const g = value;
7090
- const sha4 = (s) => typeof s === "string" && /^[a-f0-9]{40,64}$/.test(s);
7090
+ const sha6 = (s) => typeof s === "string" && /^[a-f0-9]{40,64}$/.test(s);
7091
7091
  const date = (s) => typeof s === "string" && s.length <= 40 && Number.isFinite(Date.parse(s));
7092
- 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");
7092
+ 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");
7093
7093
  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 } : {} };
7094
7094
  }
7095
7095
  var init_git = __esm({
@@ -7100,7 +7100,7 @@ var init_git = __esm({
7100
7100
 
7101
7101
  // src/runtime/hosted-packs.ts
7102
7102
  import { readFile as readFile11, readdir as readdir2 } from "fs/promises";
7103
- import { join as join15 } from "path";
7103
+ import { join as join16 } from "path";
7104
7104
  async function hostedPackFiles(spec) {
7105
7105
  const names = [...new Set(spec.services.flatMap((s) => s.adapter?.startsWith(PACK_PREFIX) ? [s.adapter.slice(PACK_PREFIX.length)] : []))];
7106
7106
  if (!names.length) return [];
@@ -7108,7 +7108,7 @@ async function hostedPackFiles(spec) {
7108
7108
  if (!root || !catalog) throw new Error("Installed twin packs are unavailable");
7109
7109
  const files = [];
7110
7110
  const add = async (path2) => {
7111
- files.push({ path: "twins/" + path2, data: await readFile11(join15(root, path2)) });
7111
+ files.push({ path: "twins/" + path2, data: await readFile11(join16(root, path2)) });
7112
7112
  };
7113
7113
  const engines = /* @__PURE__ */ new Set();
7114
7114
  for (const name of names) {
@@ -7119,7 +7119,7 @@ async function hostedPackFiles(spec) {
7119
7119
  for (const file of ["index.mjs", "LICENSE", "NOTICE"]) await add(`packs/${name}/${file}`);
7120
7120
  }
7121
7121
  const walk3 = async (dir) => {
7122
- for (const entry of await readdir2(join15(root, dir), { withFileTypes: true })) {
7122
+ for (const entry of await readdir2(join16(root, dir), { withFileTypes: true })) {
7123
7123
  const path2 = dir + "/" + entry.name;
7124
7124
  if (entry.isSymbolicLink()) throw new Error("Twin engine symlinks are unsupported");
7125
7125
  if (entry.isDirectory()) await walk3(path2);
@@ -7142,14 +7142,14 @@ import { createRequire } from "module";
7142
7142
  import { readFile as readFile12 } from "fs/promises";
7143
7143
  import { randomBytes as randomBytes4 } from "crypto";
7144
7144
  import { homedir as homedir2 } from "os";
7145
- import { join as join16 } from "path";
7145
+ import { join as join17 } from "path";
7146
7146
  async function executeE2B(stage, spec, log, signal) {
7147
7147
  signal?.throwIfAborted();
7148
7148
  const apiKey = process.env.E2B_API_KEY;
7149
7149
  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." });
7150
7150
  let saved = {};
7151
7151
  try {
7152
- saved = JSON.parse(await readFile12(join16(homedir2(), ".agenttwin/runtime.json"), "utf8"));
7152
+ saved = JSON.parse(await readFile12(join17(homedir2(), ".agenttwin/runtime.json"), "utf8"));
7153
7153
  } catch {
7154
7154
  }
7155
7155
  const template = process.env.E2B_TEMPLATE_ID ?? saved.templateId;
@@ -7170,12 +7170,12 @@ async function executeE2B(stage, spec, log, signal) {
7170
7170
  await sandbox.commands.run("mkdir -p /input/app && chmod 755 /input /input/app", { user: "root" });
7171
7171
  const upload = ["world.json", "worker.js", ...spec.files.map((f) => `app/${f}`)];
7172
7172
  try {
7173
- JSON.parse(await readFile12(join16(stage, "seed.json"), "utf8"));
7173
+ JSON.parse(await readFile12(join17(stage, "seed.json"), "utf8"));
7174
7174
  upload.push("seed.json");
7175
7175
  } catch {
7176
7176
  }
7177
7177
  for (const file of upload) {
7178
- await sandbox.files.write(`/input/${file}`, new Uint8Array(await readFile12(join16(stage, file))).buffer, { user: "root" });
7178
+ await sandbox.files.write(`/input/${file}`, new Uint8Array(await readFile12(join17(stage, file))).buffer, { user: "root" });
7179
7179
  }
7180
7180
  for (const file of await hostedPackFiles(spec)) {
7181
7181
  await sandbox.files.write("/input/" + file.path, new Uint8Array(file.data).buffer, { user: "root" });
@@ -7258,7 +7258,7 @@ var init_e2b = __esm({
7258
7258
  // src/runtime/matrix.ts
7259
7259
  import { createHash as createHash11 } from "crypto";
7260
7260
  import { mkdir as mkdir5, readFile as readFile13, writeFile as writeFile10 } from "fs/promises";
7261
- import { join as join17, relative, resolve as resolve4 } from "path";
7261
+ import { join as join18, relative, resolve as resolve4 } from "path";
7262
7262
  function filesDigest(sourceDigests) {
7263
7263
  const canonical4 = Object.keys(sourceDigests).sort().map((file) => `${file}:${sourceDigests[file]}`).join("\n");
7264
7264
  return createHash11("sha256").update(canonical4).digest("hex");
@@ -7347,13 +7347,13 @@ async function runSeedMatrix(cwd, opts) {
7347
7347
  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 });
7348
7348
  const baseSeed = normalizeSeed(opts.seed);
7349
7349
  const matrixName = `matrix-${createHash11("sha256").update(`${baseSeed}:${opts.seeds}`).digest("hex").slice(0, 8)}`;
7350
- const matrixDir = resolve4(cwd, opts.out ?? join17(".agenttwin/runs", matrixName));
7350
+ const matrixDir = resolve4(cwd, opts.out ?? join18(".agenttwin/runs", matrixName));
7351
7351
  await mkdir5(matrixDir, { recursive: true, mode: 448 });
7352
7352
  const results = [];
7353
7353
  for (let index = 0; index < opts.seeds; index++) {
7354
7354
  const seed = deriveSeed(baseSeed, index);
7355
7355
  opts.log(`Seed matrix ${index + 1}/${opts.seeds}: seed ${seed}`);
7356
- 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 });
7356
+ 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 });
7357
7357
  if (run3.seed !== seed) throw new CliError(`Run ${run3.runId} recorded seed ${run3.seed} instead of the requested derived seed ${seed}`);
7358
7358
  const { checks, allPassed } = checksOfReceipt(run3);
7359
7359
  results.push({
@@ -7367,7 +7367,7 @@ async function runSeedMatrix(cwd, opts) {
7367
7367
  allPassed
7368
7368
  });
7369
7369
  }
7370
- const first = JSON.parse(await readFile13(join17(matrixDir, "seed-0", "run.json"), "utf8"));
7370
+ const first = JSON.parse(await readFile13(join18(matrixDir, "seed-0", "run.json"), "utf8"));
7371
7371
  const report = buildMatrixReport({
7372
7372
  matrixId: matrixName,
7373
7373
  name: first.name,
@@ -7377,10 +7377,10 @@ async function runSeedMatrix(cwd, opts) {
7377
7377
  results,
7378
7378
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
7379
7379
  });
7380
- const reportPath = resolve4(cwd, opts.out ?? join17(matrixDir, "matrix.json"));
7381
- await mkdir5(opts.out && opts.out.endsWith(".json") ? join17(reportPath, "..") : matrixDir, { recursive: true, mode: 448 });
7380
+ const reportPath = resolve4(cwd, opts.out ?? join18(matrixDir, "matrix.json"));
7381
+ await mkdir5(opts.out && opts.out.endsWith(".json") ? join18(reportPath, "..") : matrixDir, { recursive: true, mode: 448 });
7382
7382
  await writeFile10(reportPath, JSON.stringify(report, null, 2) + "\n", { mode: 384 });
7383
- await writeFile10(join17(matrixDir, "matrix.md"), `${report.verdict.summary}
7383
+ await writeFile10(join18(matrixDir, "matrix.md"), `${report.verdict.summary}
7384
7384
 
7385
7385
  Report: ${relative(cwd, reportPath).split("\\").join("/")}
7386
7386
  `);
@@ -7402,7 +7402,7 @@ var init_matrix = __esm({
7402
7402
  // src/runtime/source-build.ts
7403
7403
  import { createHash as createHash12 } from "crypto";
7404
7404
  import { lstat, readFile as readFile14, realpath as realpath2 } from "fs/promises";
7405
- import { isAbsolute, join as join18, relative as relative2, resolve as resolve5, sep } from "path";
7405
+ import { isAbsolute, join as join19, relative as relative2, resolve as resolve5, sep } from "path";
7406
7406
  import { isDeepStrictEqual as isDeepStrictEqual8 } from "util";
7407
7407
  async function checkSourceBuild(directory, spec) {
7408
7408
  if (!spec.sourceBuild) return void 0;
@@ -7411,7 +7411,7 @@ async function checkSourceBuild(directory, spec) {
7411
7411
  };
7412
7412
  try {
7413
7413
  const preparedRoot = await realpath2(directory);
7414
- const sidecar = join18(preparedRoot, LOCAL_BUILD_FILE);
7414
+ const sidecar = join19(preparedRoot, LOCAL_BUILD_FILE);
7415
7415
  const info = await lstat(sidecar);
7416
7416
  if (!info.isFile() || info.isSymbolicLink() || info.size > 2 * 1024 * 1024) stale("local source record is missing, unsafe or exceeds bounds");
7417
7417
  const bytes = await readFile14(sidecar);
@@ -7435,7 +7435,7 @@ async function checkSourceBuild(directory, spec) {
7435
7435
  total += source.length;
7436
7436
  if (total > 30 * 1024 * 1024 || createHash12("sha256").update(source).digest("hex") !== expected) stale(`source changed: ${file}`);
7437
7437
  }
7438
- const artifact = join18(preparedRoot, "application.cjs");
7438
+ const artifact = join19(preparedRoot, "application.cjs");
7439
7439
  if (!(await lstat(artifact)).isFile() || await realpath2(artifact) !== resolve5(artifact) || (await lstat(artifact)).size > 20 * 1024 * 1024 || createHash12("sha256").update(await readFile14(artifact)).digest("hex") !== build2.bundleDigest) stale("compiled application changed");
7440
7440
  return { root, digest: spec.sourceBuild };
7441
7441
  } catch (error) {
@@ -7455,8 +7455,8 @@ var init_source_build = __esm({
7455
7455
  });
7456
7456
 
7457
7457
  // src/lib/files.ts
7458
- import { readdir as readdir3, readFile as readFile15, stat } from "fs/promises";
7459
- import { join as join19, relative as relative3, sep as sep2 } from "path";
7458
+ import { readdir as readdir3, readFile as readFile15, stat as stat2 } from "fs/promises";
7459
+ import { join as join20, relative as relative3, sep as sep2 } from "path";
7460
7460
  function shouldIgnoreDir(name) {
7461
7461
  return IGNORED_DIRS.has(name) || name === ".git";
7462
7462
  }
@@ -7476,7 +7476,7 @@ async function walkDir(root, maxFiles, budgetMs) {
7476
7476
  }
7477
7477
  entries.sort((a, b) => a.name.localeCompare(b.name));
7478
7478
  for (const entry of entries) {
7479
- const full = join19(dir, entry.name);
7479
+ const full = join20(dir, entry.name);
7480
7480
  if (entry.isDirectory()) {
7481
7481
  if (!shouldIgnoreDir(entry.name)) stack.push(full);
7482
7482
  } else if (entry.isFile()) {
@@ -7555,7 +7555,7 @@ var init_files = __esm({
7555
7555
  }
7556
7556
  async exists(path2) {
7557
7557
  try {
7558
- await stat(join19(this.cwd, path2));
7558
+ await stat2(join20(this.cwd, path2));
7559
7559
  return true;
7560
7560
  } catch {
7561
7561
  return false;
@@ -7564,9 +7564,9 @@ var init_files = __esm({
7564
7564
  async read(path2, maxBytes = MAX_BYTES2) {
7565
7565
  const cached2 = this.cache.contents.get(path2);
7566
7566
  if (cached2 !== void 0) return cached2;
7567
- const full = join19(this.cwd, path2);
7567
+ const full = join20(this.cwd, path2);
7568
7568
  try {
7569
- const info = await stat(full);
7569
+ const info = await stat2(full);
7570
7570
  if (!info.isFile()) return void 0;
7571
7571
  if (info.size > maxBytes) {
7572
7572
  this.cache.limits.push(`File excluded by size limit (${maxBytes} bytes): ${path2}`);
@@ -8418,12 +8418,12 @@ var init_dashboard_transfer = __esm({
8418
8418
 
8419
8419
  // src/inventory/store.ts
8420
8420
  import { mkdir as mkdir6, readFile as readFile16, writeFile as writeFile11 } from "fs/promises";
8421
- import { join as join20 } from "path";
8421
+ import { join as join21 } from "path";
8422
8422
  function storeDir(cwd) {
8423
- return join20(cwd, STORE_DIR);
8423
+ return join21(cwd, STORE_DIR);
8424
8424
  }
8425
8425
  function storePath(cwd, name) {
8426
- return join20(storeDir(cwd), name);
8426
+ return join21(storeDir(cwd), name);
8427
8427
  }
8428
8428
  async function ensureStore(cwd) {
8429
8429
  await mkdir6(storeDir(cwd), { recursive: true });
@@ -8601,7 +8601,7 @@ var init_sanitize = __esm({
8601
8601
 
8602
8602
  // src/commands/dashboard.ts
8603
8603
  import { cp, mkdir as mkdir7, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
8604
- import { basename as basename2, join as join21 } from "path";
8604
+ import { basename as basename2, join as join22 } from "path";
8605
8605
  import { fileURLToPath as fileURLToPath3 } from "url";
8606
8606
  function dashboardInventory(cwd, inventory) {
8607
8607
  return JSON.parse(sanitizeOutput(JSON.stringify({
@@ -8638,7 +8638,7 @@ __export(session_exports, {
8638
8638
  });
8639
8639
  import { spawn as spawn3, spawnSync } from "child_process";
8640
8640
  import { writeFile as writeFile13, readFile as readFile18 } from "fs/promises";
8641
- import { join as join22 } from "path";
8641
+ import { join as join23 } from "path";
8642
8642
  function sessionTask() {
8643
8643
  return `# Prepare this repository for AgentTwin
8644
8644
 
@@ -8663,7 +8663,7 @@ function installedOpenCode() {
8663
8663
  return spawnSync("opencode", ["--version"], { stdio: "ignore", timeout: 5e3 }).status === 0;
8664
8664
  }
8665
8665
  async function writeSessionTask(cwd) {
8666
- const path2 = join22(cwd, ".agenttwin/AGENT-TASK.md");
8666
+ const path2 = join23(cwd, ".agenttwin/AGENT-TASK.md");
8667
8667
  await writeFile13(path2, sessionTask(), "utf8");
8668
8668
  return path2;
8669
8669
  }
@@ -8679,7 +8679,7 @@ async function launchSession(cwd) {
8679
8679
  async function loadDashboardDiscovery(cwd, inventory, opts = {}) {
8680
8680
  let previousHead;
8681
8681
  try {
8682
- previousHead = JSON.parse(await readFile18(join22(cwd, ".agenttwin/git.json"), "utf8")).head;
8682
+ previousHead = JSON.parse(await readFile18(join23(cwd, ".agenttwin/git.json"), "utf8")).head;
8683
8683
  } catch {
8684
8684
  }
8685
8685
  const git2 = await captureGit(cwd, previousHead);
@@ -8687,7 +8687,7 @@ async function loadDashboardDiscovery(cwd, inventory, opts = {}) {
8687
8687
  if (opts.includeAgentDiscovery === false) return projectProducts(cwd, base, base);
8688
8688
  let raw;
8689
8689
  try {
8690
- raw = await readFile18(join22(cwd, ".agenttwin/agent-discovery.json"), "utf8");
8690
+ raw = await readFile18(join23(cwd, ".agenttwin/agent-discovery.json"), "utf8");
8691
8691
  } catch (error) {
8692
8692
  if (error.code === "ENOENT") return projectProducts(cwd, base, base);
8693
8693
  throw error;
@@ -8722,7 +8722,7 @@ __export(run_exports, {
8722
8722
  });
8723
8723
  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";
8724
8724
  import { tmpdir as tmpdir7 } from "os";
8725
- import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute2, join as join23, relative as relative4, resolve as resolve6, sep as sep3 } from "path";
8725
+ import { basename as basename3, dirname as dirname3, isAbsolute as isAbsolute2, join as join24, relative as relative4, resolve as resolve6, sep as sep3 } from "path";
8726
8726
  import { createHash as createHash13, randomUUID as randomUUID4 } from "crypto";
8727
8727
  async function stageApplication(root, files, destination) {
8728
8728
  const canonicalRoot = await realpath3(root);
@@ -8736,7 +8736,7 @@ async function stageApplication(root, files, destination) {
8736
8736
  const contents = await readFile19(source);
8737
8737
  bytes += contents.length;
8738
8738
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
8739
- const target = join23(destination, file);
8739
+ const target = join24(destination, file);
8740
8740
  await mkdir8(dirname3(target), { recursive: true });
8741
8741
  await writeFile14(target, contents, { mode: 420 });
8742
8742
  digests[file] = createHash13("sha256").update(contents).digest("hex");
@@ -8769,7 +8769,7 @@ async function runWorld(cwd, opts) {
8769
8769
  if (spec.workflowId) {
8770
8770
  let inventory;
8771
8771
  try {
8772
- inventory = JSON.parse(await readFile19(join23(inventoryRoot, ".agenttwin/inventory.json"), "utf8"));
8772
+ inventory = JSON.parse(await readFile19(join24(inventoryRoot, ".agenttwin/inventory.json"), "utf8"));
8773
8773
  } catch {
8774
8774
  throw new CliError("Linked workflow needs discovery inventory; run init first", { code: EXIT.BLOCKED });
8775
8775
  }
@@ -8793,20 +8793,20 @@ async function runWorld(cwd, opts) {
8793
8793
  throw new CliError(error instanceof Error ? error.message : String(error), { code: EXIT.USAGE });
8794
8794
  }
8795
8795
  }
8796
- const stage = await mkdtemp7(join23(tmpdir7(), "agenttwin-world-"));
8796
+ const stage = await mkdtemp7(join24(tmpdir7(), "agenttwin-world-"));
8797
8797
  try {
8798
- const sourceDigests = await stageApplication(dirname3(file), spec.files, join23(stage, "app"));
8799
- await writeFile14(join23(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
8800
- if (runtime === "e2b" && suppliedSeed) await writeFile14(join23(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
8798
+ const sourceDigests = await stageApplication(dirname3(file), spec.files, join24(stage, "app"));
8799
+ await writeFile14(join24(stage, "world.json"), JSON.stringify(spec), { mode: 420 });
8800
+ if (runtime === "e2b" && suppliedSeed) await writeFile14(join24(stage, "seed.json"), JSON.stringify({ seed: suppliedSeed }), { mode: 420 });
8801
8801
  const git2 = await captureGit(sourceBuild?.root ?? cwd);
8802
8802
  let project;
8803
8803
  try {
8804
- project = JSON.parse(await readFile19(join23(inventoryRoot, ".agenttwin/inventory.json"), "utf8")).name ?? basename3(cwd);
8804
+ project = JSON.parse(await readFile19(join24(inventoryRoot, ".agenttwin/inventory.json"), "utf8")).name ?? basename3(cwd);
8805
8805
  } catch {
8806
8806
  }
8807
8807
  if (runtime === "local" || runtime === "docker") {
8808
8808
  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.");
8809
- 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);
8809
+ 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);
8810
8810
  let sourceBuildEvidence;
8811
8811
  let sourceBuildError;
8812
8812
  if (sourceBuild) {
@@ -8826,9 +8826,9 @@ async function runWorld(cwd, opts) {
8826
8826
  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: createHash13("sha256").update(JSON.stringify(spec)).digest("hex"), provenance: "CLI-reported execution" };
8827
8827
  const out2 = resolve6(cwd, opts.out ?? `.agenttwin/runs/${runId2}`);
8828
8828
  await mkdir8(out2, { recursive: true });
8829
- const evidencePath = join23(out2, "run.json"), reportPath = join23(out2, "report.md");
8829
+ const evidencePath = join24(out2, "run.json"), reportPath = join24(out2, "report.md");
8830
8830
  await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
8831
- await writeFile14(join23(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
8831
+ await writeFile14(join24(out2, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
8832
8832
  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("/")}`];
8833
8833
  await writeFile14(reportPath, renderRunSummary({ ...receipt2, runId: runId2 }, { markdown: true, next, costs: await readCostConfig(cwd) }) + `
8834
8834
  Runner: CLI \xB7 Git: ${git2?.head ?? "unavailable"} \xB7 Seed: ${receipt2.seed}
@@ -8848,8 +8848,8 @@ Full evidence (activities, fault, initial and final state): run.json
8848
8848
  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");
8849
8849
  const out2 = resolve6(cwd, opts.out ?? `.agenttwin/runs/${receipt2.runId}`);
8850
8850
  await mkdir8(out2, { recursive: true });
8851
- const evidencePath = join23(out2, "run.json");
8852
- const reportPath = join23(out2, "report.md");
8851
+ const evidencePath = join24(out2, "run.json");
8852
+ const reportPath = join24(out2, "report.md");
8853
8853
  await writeFile14(evidencePath, JSON.stringify(receipt2, null, 2) + "\n", { mode: 384 });
8854
8854
  await writeFile14(reportPath, `# ${spec.name}: ${receipt2.status}
8855
8855
 
@@ -8886,11 +8886,11 @@ See run.json for assertions, service state, application output and isolation met
8886
8886
  };
8887
8887
  const out = resolve6(cwd, opts.out ?? `.agenttwin/runs/${runId}`);
8888
8888
  await mkdir8(out, { recursive: true });
8889
- await writeFile14(join23(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
8890
- await writeFile14(join23(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
8889
+ await writeFile14(join24(out, "run.json"), JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
8890
+ await writeFile14(join24(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
8891
8891
  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");
8892
- await writeFile14(join23(out, "report.md"), summary);
8893
- return { ...receipt, reportPath: join23(out, "report.md"), evidencePath: join23(out, "run.json") };
8892
+ await writeFile14(join24(out, "report.md"), summary);
8893
+ return { ...receipt, reportPath: join24(out, "report.md"), evidencePath: join24(out, "run.json") };
8894
8894
  } finally {
8895
8895
  await rm9(stage, { recursive: true, force: true });
8896
8896
  }
@@ -8920,12 +8920,12 @@ import { execFile as execFile8, spawn as spawn4 } from "child_process";
8920
8920
  import { promisify as promisify8 } from "util";
8921
8921
  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";
8922
8922
  import { tmpdir as tmpdir8 } from "os";
8923
- import { join as join24 } from "path";
8923
+ import { join as join25 } from "path";
8924
8924
  import { randomUUID as randomUUID5 } from "crypto";
8925
8925
  async function executeDocker(app, spec, opts = {}) {
8926
8926
  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.");
8927
8927
  opts.signal?.throwIfAborted();
8928
- const started = Date.now(), stage = await mkdtemp8(join24(tmpdir8(), "agenttwin-docker-"));
8928
+ const started = Date.now(), stage = await mkdtemp8(join25(tmpdir8(), "agenttwin-docker-"));
8929
8929
  const container = "agenttwin-" + randomUUID5();
8930
8930
  const world = new HttpWorld(spec, opts.seed);
8931
8931
  let hook;
@@ -8939,17 +8939,17 @@ async function executeDocker(app, spec, opts = {}) {
8939
8939
  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.");
8940
8940
  await exec6("docker", ["image", "inspect", image], { timeout: 1e4, maxBuffer: 1024 * 1024 });
8941
8941
  await chmod3(stage, 493);
8942
- const stagedApp = join24(stage, "app");
8942
+ const stagedApp = join25(stage, "app");
8943
8943
  const { stageApplication: stageApplication2 } = await Promise.resolve().then(() => (init_run(), run_exports));
8944
8944
  await stageApplication2(app, spec.files, stagedApp);
8945
- if (spec.postgres) database = await createDockerPostgres(spec.postgres.seedFile ? await readFile20(join24(stagedApp, spec.postgres.seedFile), "utf8") : "", opts.databaseImage, spec.postgres.clock);
8945
+ if (spec.postgres) database = await createDockerPostgres(spec.postgres.seedFile ? await readFile20(join25(stagedApp, spec.postgres.seedFile), "utf8") : "", opts.databaseImage, spec.postgres.clock);
8946
8946
  const credentials2 = await world.start(), initialState = world.snapshot();
8947
8947
  hook = await createRequestSourceHook(stagedApp, spec, credentials2, { root: "/app", violationsPath: "/tmp/agenttwin-blocked.jsonl", stdioViolations: true });
8948
- const support = join24(stage, "support");
8948
+ const support = join25(stage, "support");
8949
8949
  await mkdir9(support, { mode: 493 });
8950
- await copyFile2(hook.path, join24(support, "source.cjs"));
8951
- await chmod3(join24(support, "source.cjs"), 420);
8952
- await writeFile15(join24(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
8950
+ await copyFile2(hook.path, join25(support, "source.cjs"));
8951
+ await chmod3(join25(support, "source.cjs"), 420);
8952
+ await writeFile15(join25(support, "bridge.cjs"), stdioFetchHook(credentials2, !!database), { mode: 420 });
8953
8953
  const env = Object.entries(credentials2).flatMap(([name, c]) => ["--env", `AGENTTWIN_${name.toUpperCase()}_URL=${c.endpoint}`, "--env", `AGENTTWIN_${name.toUpperCase()}_TOKEN=${c.token}`]);
8954
8954
  let stdout = "", stderr = "", timedOut = false;
8955
8955
  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)];
@@ -10253,12 +10253,12 @@ var init_containers = __esm({
10253
10253
  });
10254
10254
 
10255
10255
  // src/discovery/detectors/cloud-creds.ts
10256
- import { stat as stat2 } from "fs/promises";
10256
+ import { stat as stat3 } from "fs/promises";
10257
10257
  import { homedir as homedir3 } from "os";
10258
- import { join as join28 } from "path";
10258
+ import { join as join29 } from "path";
10259
10259
  async function exists(path2) {
10260
10260
  try {
10261
- await stat2(path2);
10261
+ await stat3(path2);
10262
10262
  return true;
10263
10263
  } catch {
10264
10264
  return false;
@@ -10270,11 +10270,11 @@ var init_cloud_creds = __esm({
10270
10270
  "use strict";
10271
10271
  init_scoring();
10272
10272
  CREDENTIALS = [
10273
- { path: join28(homedir3(), ".aws", "config"), subject: "aws", title: "AWS" },
10274
- { path: join28(homedir3(), ".aws", "credentials"), subject: "aws", title: "AWS" },
10275
- { path: join28(homedir3(), ".config", "gcloud"), subject: "gcp", title: "Google Cloud" },
10276
- { path: join28(homedir3(), ".azure"), subject: "azure", title: "Azure" },
10277
- { path: join28(homedir3(), ".kube", "config"), subject: "kubernetes", title: "Kubernetes" }
10273
+ { path: join29(homedir3(), ".aws", "config"), subject: "aws", title: "AWS" },
10274
+ { path: join29(homedir3(), ".aws", "credentials"), subject: "aws", title: "AWS" },
10275
+ { path: join29(homedir3(), ".config", "gcloud"), subject: "gcp", title: "Google Cloud" },
10276
+ { path: join29(homedir3(), ".azure"), subject: "azure", title: "Azure" },
10277
+ { path: join29(homedir3(), ".kube", "config"), subject: "kubernetes", title: "Kubernetes" }
10278
10278
  ];
10279
10279
  cloudCredDetector = {
10280
10280
  id: "cloud-credentials",
@@ -10371,7 +10371,7 @@ import { createServer as createServer3 } from "http";
10371
10371
  import { connect } from "net";
10372
10372
  import { readFileSync as readFileSync2, rmSync, writeFileSync } from "fs";
10373
10373
  import { tmpdir as tmpdir11 } from "os";
10374
- import { join as join29 } from "path";
10374
+ import { join as join30 } from "path";
10375
10375
  function delay(ms) {
10376
10376
  return new Promise((resolve12) => setTimeout(resolve12, ms));
10377
10377
  }
@@ -10405,8 +10405,8 @@ function startProxy(onHost) {
10405
10405
  async function observeEgress(opts) {
10406
10406
  const hosts = /* @__PURE__ */ new Set();
10407
10407
  const { server, url } = await startProxy((host) => hosts.add(host));
10408
- const logFile = join29(tmpdir11(), `agenttwin-egress-${process.pid}.log`);
10409
- const hookFile = join29(tmpdir11(), `agenttwin-egress-hook-${process.pid}.cjs`);
10408
+ const logFile = join30(tmpdir11(), `agenttwin-egress-${process.pid}.log`);
10409
+ const hookFile = join30(tmpdir11(), `agenttwin-egress-hook-${process.pid}.cjs`);
10410
10410
  try {
10411
10411
  writeFileSync(hookFile, EGRESS_HOOK, "utf8");
10412
10412
  writeFileSync(logFile, "", "utf8");
@@ -12625,7 +12625,7 @@ var init_scope = __esm({
12625
12625
  import { spawn as spawn6 } from "child_process";
12626
12626
  import { mkdtemp as mkdtemp11, open, writeFile as writeFile19, rm as rm13, realpath as realpath6 } from "fs/promises";
12627
12627
  import { tmpdir as tmpdir12 } from "os";
12628
- import { join as join30, basename as basename4 } from "path";
12628
+ import { join as join31, basename as basename4 } from "path";
12629
12629
  function validHost(host) {
12630
12630
  const clean = host.toLowerCase();
12631
12631
  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");
@@ -13790,11 +13790,11 @@ async function runExport(opts) {
13790
13790
  const bundle = { schema: "export/v1", inventory, plan: plan ?? null };
13791
13791
  if (opts.out) {
13792
13792
  const { mkdir: mkdir14, writeFile: writeFile22 } = await import("fs/promises");
13793
- const { join: join35 } = await import("path");
13793
+ const { join: join36 } = await import("path");
13794
13794
  await mkdir14(opts.out, { recursive: true });
13795
- await writeFile22(join35(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
13795
+ await writeFile22(join36(opts.out, "inventory.json"), `${JSON.stringify(inventory, null, 2)}
13796
13796
  `, "utf8");
13797
- if (plan) await writeFile22(join35(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
13797
+ if (plan) await writeFile22(join36(opts.out, "plan.json"), `${JSON.stringify(plan, null, 2)}
13798
13798
  `, "utf8");
13799
13799
  return { schema: "export/v1", out: opts.out, wrote: ["inventory.json", ...plan ? ["plan.json"] : []] };
13800
13800
  }
@@ -13851,12 +13851,13 @@ function gatewayConnection(url) {
13851
13851
  }
13852
13852
 
13853
13853
  // src/runtime/gateway-postgres.ts
13854
- import { readFile } from "fs/promises";
13854
+ import { readFile, rename, stat } from "fs/promises";
13855
+ import { join } from "path";
13855
13856
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
13856
13857
 
13857
13858
  // src/runtime/gateway-schema.ts
13858
13859
  var definitions = {
13859
- 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"],
13860
+ 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"],
13860
13861
  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"],
13861
13862
  external_identities: ["provider text, issuer text, subject text, account_id uuid not null, primary key(provider,issuer,subject)", "provider issuer subject"],
13862
13863
  account_tokens: ["token_hash text primary key, account_id uuid not null, kind text not null check(kind in ('primary','cli'))", "token_hash"],
@@ -13873,8 +13874,13 @@ var definitions = {
13873
13874
  oauth_tokens: ["token_hash text primary key, client_id text not null, scopes text[], expires_at bigint", "token_hash"],
13874
13875
  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"],
13875
13876
  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"],
13876
- 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"]
13877
+ 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"],
13878
+ 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"],
13879
+ 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"],
13880
+ 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"],
13881
+ 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"]
13877
13882
  };
13883
+ var GATEWAY_SCHEMA_VERSION = 2;
13878
13884
  var tables = Object.keys(definitions);
13879
13885
 
13880
13886
  // src/runtime/gateway-records.ts
@@ -13897,7 +13903,11 @@ var flat = {
13897
13903
  oauthTokens: "oauth_tokens",
13898
13904
  githubInstallations: "github_installations",
13899
13905
  githubEvents: "github_pr_events",
13900
- githubChecks: "github_checks"
13906
+ githubChecks: "github_checks",
13907
+ teamMembers: "team_members",
13908
+ teamInvites: "team_invites",
13909
+ orgTokens: "org_tokens",
13910
+ auditEvents: "audit_events"
13901
13911
  };
13902
13912
  var renames = {
13903
13913
  accounts: { id: "account_id", label: "workspace_label" },
@@ -13914,7 +13924,10 @@ var renames = {
13914
13924
  oauth_tokens: { hash: "token_hash", expires: "expires_at" },
13915
13925
  github_installations: { owner: "github_owner" },
13916
13926
  github_pr_events: { number: "pr_number" },
13917
- github_checks: { number: "pr_number" }
13927
+ github_checks: { number: "pr_number" },
13928
+ team_invites: { id: "invite_id" },
13929
+ org_tokens: { id: "token_id" },
13930
+ audit_events: { id: "event_id" }
13918
13931
  };
13919
13932
  var column = (t, k) => renames[t]?.[k] ?? k.replace(/[A-Z]/g, (c) => "_" + c.toLowerCase());
13920
13933
  var nested = {
@@ -14049,7 +14062,7 @@ function assemble(rows2, shape2) {
14049
14062
  var meta = "gateway.migration_state";
14050
14063
  async function load(tx) {
14051
14064
  const [version] = await tx.unsafe("select version,revision,shape from " + meta + " where singleton");
14052
- if (version?.version !== 1) throw Error("Expected gateway relational schema v1");
14065
+ if (version?.version !== GATEWAY_SCHEMA_VERSION) throw Error(`Expected gateway relational schema v${GATEWAY_SCHEMA_VERSION}`);
14053
14066
  const rows2 = emptyRows();
14054
14067
  for (const t of tables) {
14055
14068
  for (const { record: record3 } of await tx.unsafe("select row_to_json(t) as record from gateway." + t + " t")) {
@@ -14333,21 +14346,21 @@ function appManifest(publicUrl) {
14333
14346
 
14334
14347
  // src/runtime/github-app-registration.ts
14335
14348
  import { randomBytes as randomBytes2, timingSafeEqual as timingSafeEqual2, createHash as createHash4 } from "crypto";
14336
- import { readFile as readFile2, rename, writeFile } from "fs/promises";
14337
- import { join } from "path";
14349
+ import { readFile as readFile2, rename as rename2, writeFile } from "fs/promises";
14350
+ import { join as join2 } from "path";
14338
14351
  var FILE = "github-app.json";
14339
14352
  async function loadRegisteredApp(directory) {
14340
14353
  try {
14341
- const app = JSON.parse(await readFile2(join(directory, FILE), "utf8"));
14354
+ const app = JSON.parse(await readFile2(join2(directory, FILE), "utf8"));
14342
14355
  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;
14343
14356
  } catch {
14344
14357
  return void 0;
14345
14358
  }
14346
14359
  }
14347
14360
  async function saveRegisteredApp(directory, app) {
14348
- const temp = join(directory, `${FILE}.${randomBytes2(6).toString("hex")}.tmp`);
14361
+ const temp = join2(directory, `${FILE}.${randomBytes2(6).toString("hex")}.tmp`);
14349
14362
  await writeFile(temp, JSON.stringify(app, null, 2) + "\n", { mode: 384 });
14350
- await rename(temp, join(directory, FILE));
14363
+ await rename2(temp, join2(directory, FILE));
14351
14364
  }
14352
14365
  var appOptions = (app) => ({ slug: app.slug, webhookSecret: app.webhookSecret });
14353
14366
  var appCredentials = (app) => ({ appId: String(app.id), privateKey: app.privateKey });
@@ -14399,7 +14412,7 @@ import { createSign } from "crypto";
14399
14412
  import { execFile as execFile12 } from "child_process";
14400
14413
  import { mkdtemp as mkdtemp12, rm as rm14 } from "fs/promises";
14401
14414
  import { tmpdir as tmpdir13 } from "os";
14402
- import { join as join31 } from "path";
14415
+ import { join as join32 } from "path";
14403
14416
  import { promisify as promisify11 } from "util";
14404
14417
 
14405
14418
  // src/runtime/pr-check.ts
@@ -14416,13 +14429,13 @@ import { execFile as execFile9 } from "child_process";
14416
14429
  import { promisify as promisify9 } from "util";
14417
14430
  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";
14418
14431
  import { tmpdir as tmpdir10 } from "os";
14419
- import { dirname as dirname5, join as join27, relative as relative6, resolve as resolve9, sep as sep6 } from "path";
14432
+ import { dirname as dirname5, join as join28, relative as relative6, resolve as resolve9, sep as sep6 } from "path";
14420
14433
 
14421
14434
  // src/runtime/callable.ts
14422
14435
  init_entrypoints();
14423
14436
  import { build } from "esbuild";
14424
14437
  import { readFile as readFile21, realpath as realpath4, writeFile as writeFile16 } from "fs/promises";
14425
- import { resolve as resolve7, relative as relative5, isAbsolute as isAbsolute3, sep as sep4, join as join25, extname } from "path";
14438
+ import { resolve as resolve7, relative as relative5, isAbsolute as isAbsolute3, sep as sep4, join as join26, extname } from "path";
14426
14439
  import { createHash as createHash14 } from "crypto";
14427
14440
  var digest4 = (value) => createHash14("sha256").update(value).digest("hex");
14428
14441
  var object5 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
@@ -14503,7 +14516,7 @@ for(const [index,call]of invocation.calls.entries()){
14503
14516
  }})().catch(error=>{console.error(error);process.exitCode=1;})${options.exitWhenDone ? `.finally(()=>setTimeout(()=>process.exit(),1000).unref())` : ""};`;
14504
14517
  const sources = {};
14505
14518
  let bytes = 0;
14506
- 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) {
14519
+ 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) {
14507
14520
  plugin.onLoad({ filter: /.*/ }, async (args) => {
14508
14521
  const path2 = await realpath4(args.path), rel = relative5(canonical4, path2);
14509
14522
  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);
@@ -14518,7 +14531,7 @@ for(const [index,call]of invocation.calls.entries()){
14518
14531
  } }] });
14519
14532
  const code = built.outputFiles[0].contents;
14520
14533
  if (code.length > 20 * 1024 * 1024) throw new Error("Callable bundle exceeds 20 MiB");
14521
- await writeFile16(join25(out, "application.cjs"), code, { flag: "wx", mode: 384 });
14534
+ await writeFile16(join26(out, "application.cjs"), code, { flag: "wx", mode: 384 });
14522
14535
  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." };
14523
14536
  }
14524
14537
 
@@ -14528,7 +14541,7 @@ init_source_build();
14528
14541
  // src/runtime/protected-callable.ts
14529
14542
  import { createHash as createHash15 } from "crypto";
14530
14543
  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";
14531
- import { dirname as dirname4, join as join26, resolve as resolve8, sep as sep5 } from "path";
14544
+ import { dirname as dirname4, join as join27, resolve as resolve8, sep as sep5 } from "path";
14532
14545
  import { tmpdir as tmpdir9 } from "os";
14533
14546
  init_source_build();
14534
14547
  var hash2 = (bytes) => createHash15("sha256").update(bytes).digest("hex");
@@ -14560,7 +14573,7 @@ async function stageTrustedBuildFiles(cwd, out, files) {
14560
14573
  total += bytes.length;
14561
14574
  if (total > 34 * 1024 * 1024) throw Error("Trusted dependency closure exceeds bounds");
14562
14575
  if (hash2(bytes) !== expected) throw Error("Trusted dependency or resolution metadata changed: " + file + "; restore the baseline installation or review a new regression");
14563
- const target = join26(out, file);
14576
+ const target = join27(out, file);
14564
14577
  await mkdir10(dirname4(target), { recursive: true });
14565
14578
  await writeFile17(target, bytes, { mode: 420 });
14566
14579
  }
@@ -14583,7 +14596,7 @@ function parseRegression(v) {
14583
14596
  }
14584
14597
  async function runProtectedCheck(cwd, opts) {
14585
14598
  const result2 = { schema: "agenttwin/protected-check-v1", status: "incomplete", candidateRevision: "", baselineRevision: "", specDigest: "", candidateBuildDigest: void 0, sourceDigests: {}, runtime: opts.runtime ?? "docker", protection: "", receipt: null, reason: "" };
14586
- const stage = await mkdtemp10(join27(tmpdir10(), "agenttwin-regression-"));
14599
+ const stage = await mkdtemp10(join28(tmpdir10(), "agenttwin-regression-"));
14587
14600
  await chmod4(stage, 493);
14588
14601
  try {
14589
14602
  if (!opts.baseline) throw new Error("An explicit trusted baseline commit SHA is required; candidate-owned checks cannot approve a patch");
@@ -14604,13 +14617,13 @@ async function runProtectedCheck(cwd, opts) {
14604
14617
  totalBytes += bytes.length;
14605
14618
  if (totalBytes > 100 * 1024 * 1024) throw new Error("Candidate files exceed 100 MiB");
14606
14619
  if (revision === result2.candidateRevision) result2.sourceDigests[file] = hash3(bytes);
14607
- const dest = join27(directory, file);
14620
+ const dest = join28(directory, file);
14608
14621
  await mkdir11(resolve9(dest, ".."), { recursive: true });
14609
14622
  await writeFile18(dest, bytes, { mode: 420 });
14610
14623
  };
14611
14624
  let executionSpec = regression.spec;
14612
14625
  if (regression.callable) {
14613
- const source = join27(stage, ".source"), compiled = join27(stage, ".compiled");
14626
+ const source = join28(stage, ".source"), compiled = join28(stage, ".compiled");
14614
14627
  await mkdir11(source);
14615
14628
  await mkdir11(compiled);
14616
14629
  for (const file of ["package-lock.json", "npm-shrinkwrap.json"]) {
@@ -14628,8 +14641,8 @@ async function runProtectedCheck(cwd, opts) {
14628
14641
  executionSpec = { ...regression.spec, sourceBuild: result2.candidateBuildDigest };
14629
14642
  const artifact = regression.spec.command[1];
14630
14643
  if (!artifact || !regression.spec.files.includes(artifact) || !artifact.endsWith("application.cjs")) throw Error("Protected callable artifact path is invalid");
14631
- await mkdir11(dirname5(join27(stage, artifact)), { recursive: true });
14632
- await copyFile3(join27(compiled, "application.cjs"), join27(stage, artifact));
14644
+ await mkdir11(dirname5(join28(stage, artifact)), { recursive: true });
14645
+ await copyFile3(join28(compiled, "application.cjs"), join28(stage, artifact));
14633
14646
  for (const file of regression.spec.files.filter((file2) => file2 !== artifact)) await stageGitFile(file, result2.baselineRevision, stage);
14634
14647
  } else for (const file of regression.spec.files) {
14635
14648
  await stageGitFile(file, file === regression.spec.postgres?.seedFile ? result2.baselineRevision : result2.candidateRevision, stage);
@@ -14675,8 +14688,8 @@ async function resolveBase(cwd, explicit, head) {
14675
14688
  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);
14676
14689
  for (const ref of candidates) {
14677
14690
  try {
14678
- const sha4 = (await git(cwd, "rev-parse", "--verify", `${ref}^{commit}`)).trim();
14679
- return explicit ? sha4 : (await git(cwd, "merge-base", sha4, head)).trim();
14691
+ const sha6 = (await git(cwd, "rev-parse", "--verify", `${ref}^{commit}`)).trim();
14692
+ return explicit ? sha6 : (await git(cwd, "merge-base", sha6, head)).trim();
14680
14693
  } catch {
14681
14694
  }
14682
14695
  }
@@ -14870,7 +14883,7 @@ init_run_summary();
14870
14883
  init_cost_model();
14871
14884
  var COMMENT_MARKER = "<!-- agenttwin-check -->";
14872
14885
  var ICON = { pass: "\u2705", fail: "\u274C", warn: "\u26A0\uFE0F", incomplete: "\u23F8\uFE0F" };
14873
- var short2 = (sha4) => sha4.slice(0, 7);
14886
+ var short2 = (sha6) => sha6.slice(0, 7);
14874
14887
  var cell = (s) => s.replace(/\|/g, "\\|").replace(/\n/g, " ");
14875
14888
  var pathLabel = (path2) => path2.replace(/^\/(v\d+\/)?/, "").replace(/_/g, " ");
14876
14889
  function result(r) {
@@ -15019,23 +15032,36 @@ async function installationToken(app, installationId) {
15019
15032
  if (!response.ok) throw new Error(`GitHub installation token \u2192 ${response.status}`);
15020
15033
  return (await response.json()).token;
15021
15034
  }
15022
- async function fetchPullRequest(dir, event, token, serverUrl) {
15023
- const git2 = (...args) => exec9("git", ["-C", dir, ...args], { timeout: 12e4, maxBuffer: 20 * 1024 * 1024 });
15035
+ async function mergeBase(event, token, apiUrl = "https://api.github.com") {
15036
+ try {
15037
+ const response = await fetch(`${apiUrl}/repos/${event.repository}/compare/${event.baseSha}...${event.headSha}`, {
15038
+ headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28", "user-agent": "agenttwin-check" },
15039
+ signal: AbortSignal.timeout(15e3)
15040
+ });
15041
+ const sha6 = response.ok ? (await response.json()).merge_base_commit?.sha : void 0;
15042
+ return sha6 && /^[0-9a-f]{40}$/.test(sha6) ? sha6 : event.baseSha;
15043
+ } catch {
15044
+ return event.baseSha;
15045
+ }
15046
+ }
15047
+ async function fetchPullRequest(dir, event, token, serverUrl, base) {
15048
+ const git2 = (...args) => exec9("git", ["-C", dir, ...args], { timeout: 3e5, maxBuffer: 20 * 1024 * 1024 });
15024
15049
  const auth = `http.extraHeader=Authorization: Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
15025
15050
  await git2("init", "-q");
15026
- await git2("-c", auth, "fetch", "-q", "--filter=blob:none", "--depth=200", `${serverUrl}/${event.repository}.git`, event.baseSha, event.headSha);
15051
+ await git2("-c", auth, "fetch", "-q", "--depth=1", `${serverUrl}/${event.repository}.git`, .../* @__PURE__ */ new Set([event.headSha, base, event.baseSha]));
15027
15052
  await git2("checkout", "-q", "--detach", event.headSha);
15028
15053
  }
15029
15054
  async function runHostedCheck(event, app, opts = {}) {
15030
15055
  const token = await installationToken(app, event.installationId);
15031
15056
  const target = { token, repository: event.repository, sha: event.headSha, pullRequest: event.number, ...app.apiUrl ? { apiUrl: app.apiUrl } : {}, ...opts.detailsUrl ? { detailsUrl: opts.detailsUrl } : {} };
15032
15057
  const runId = await startCheckRun(target);
15033
- const dir = await mkdtemp12(join31(tmpdir13(), "agenttwin-pr-"));
15058
+ const dir = await mkdtemp12(join32(tmpdir13(), "agenttwin-pr-"));
15034
15059
  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() };
15035
15060
  try {
15036
- await fetchPullRequest(dir, event, token, opts.serverUrl ?? "https://github.com");
15061
+ const compareBase = await mergeBase(event, token, app.apiUrl);
15062
+ await fetchPullRequest(dir, event, token, opts.serverUrl ?? "https://github.com", compareBase);
15037
15063
  const runtime = opts.runtime ?? (opts.runnerImage ? "docker" : void 0);
15038
- const report = await runPrCheck(dir, { base: event.baseSha, head: event.headSha, execute: !!runtime, ...runtime ? { runtime } : {}, log: opts.log });
15064
+ const report = await runPrCheck(dir, { base: compareBase, head: event.headSha, execute: !!runtime, ...runtime ? { runtime } : {}, log: opts.log });
15039
15065
  const run3 = await publishCheckRun(report, target, runId);
15040
15066
  await upsertComment(report, target).catch((error) => opts.log?.(`PR comment skipped: ${error instanceof Error ? error.message : String(error)}`));
15041
15067
  const untested = report.touched.filter((w) => !w.covered && w.operations.some((o) => o.changed));
@@ -15545,9 +15571,9 @@ init_dashboard_transfer();
15545
15571
  import { generateRegistrationOptions, verifyRegistrationResponse, generateAuthenticationOptions, verifyAuthenticationResponse } from "@simplewebauthn/server";
15546
15572
  import { isDeepStrictEqual as isDeepStrictEqual9 } from "util";
15547
15573
  import { createServer as createServer4 } from "http";
15548
- import { createHash as createHash25, randomBytes as randomBytes9, randomUUID as randomUUID7, timingSafeEqual as timingSafeEqual7 } from "crypto";
15549
- import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile21, rename as rename2, mkdtemp as mkdtemp13, rm as rm16 } from "fs/promises";
15550
- import { resolve as resolve11, join as join34, dirname as dirname6, extname as extname2 } from "path";
15574
+ import { createHash as createHash27, randomBytes as randomBytes11, randomUUID as randomUUID9, timingSafeEqual as timingSafeEqual7 } from "crypto";
15575
+ import { mkdir as mkdir13, readFile as readFile26, writeFile as writeFile21, rename as rename3, mkdtemp as mkdtemp13, rm as rm16 } from "fs/promises";
15576
+ import { resolve as resolve11, join as join35, dirname as dirname6, extname as extname2 } from "path";
15551
15577
  import { tmpdir as tmpdir14 } from "os";
15552
15578
 
15553
15579
  // src/runtime/transcription.ts
@@ -15649,13 +15675,13 @@ init_spec();
15649
15675
  init_postgres_clock();
15650
15676
  init_application_clock();
15651
15677
  import { readFile as readFile25, readdir as readdir4 } from "fs/promises";
15652
- import { join as join33 } from "path";
15678
+ import { join as join34 } from "path";
15653
15679
 
15654
15680
  // src/runtime/repair-proof.ts
15655
15681
  init_run_summary();
15656
15682
  import { createHash as createHash23, randomUUID as randomUUID6 } from "crypto";
15657
15683
  import { mkdir as mkdir12, readFile as readFile24, rm as rm15, writeFile as writeFile20 } from "fs/promises";
15658
- import { isAbsolute as isAbsolute4, join as join32, relative as relative7, resolve as resolve10, sep as sep7 } from "path";
15684
+ import { isAbsolute as isAbsolute4, join as join33, relative as relative7, resolve as resolve10, sep as sep7 } from "path";
15659
15685
 
15660
15686
  // src/runtime/receipt-sync.ts
15661
15687
  var text = (v, max) => typeof v === "string" && v.length <= max;
@@ -15736,8 +15762,289 @@ function captureAnalytics(event) {
15736
15762
  });
15737
15763
  }
15738
15764
 
15765
+ // package.json
15766
+ var package_default = {
15767
+ name: "agenttwin",
15768
+ version: "0.3.26",
15769
+ description: "AgentTwin builds digital twins for testing AI agents. The current CLI prepares supported Node.js workflows with synthetic services, failures, and outcome checks.",
15770
+ mcpName: "io.github.Sashank-Singh/agenttwin",
15771
+ keywords: [
15772
+ "agent",
15773
+ "ai",
15774
+ "testing",
15775
+ "simulation",
15776
+ "sandbox",
15777
+ "twin",
15778
+ "cli",
15779
+ "agenttwin",
15780
+ "agent-testing",
15781
+ "ai-agent-testing",
15782
+ "workflow-testing",
15783
+ "nodejs",
15784
+ "digital-twin",
15785
+ "test-automation",
15786
+ "agent-testing-tool"
15787
+ ],
15788
+ type: "module",
15789
+ bin: {
15790
+ agenttwin: "dist/cli.js"
15791
+ },
15792
+ files: [
15793
+ "dist",
15794
+ "README.md",
15795
+ "LICENSE"
15796
+ ],
15797
+ engines: {
15798
+ node: ">=20.0.0"
15799
+ },
15800
+ license: "MIT",
15801
+ scripts: {
15802
+ build: "tsup",
15803
+ dev: "tsx src/cli.ts",
15804
+ typecheck: "tsc --noEmit",
15805
+ test: "vitest run",
15806
+ prepublishOnly: "npm run typecheck && npm run build && npm test -- --maxWorkers 2",
15807
+ "start:api": "node dist/gateway.js"
15808
+ },
15809
+ publishConfig: {
15810
+ access: "public"
15811
+ },
15812
+ dependencies: {
15813
+ "@babel/parser": "^7.29.11",
15814
+ "@electric-sql/pglite": "0.5.13",
15815
+ "@electric-sql/pglite-socket": "0.2.16",
15816
+ "@simplewebauthn/browser": "^14.0.0",
15817
+ "@simplewebauthn/server": "^14.0.3",
15818
+ bson: "^6.10.4",
15819
+ e2b: "^2.52.1",
15820
+ esbuild: "0.28.2",
15821
+ "openid-client": "^6.8.8",
15822
+ pg: "^8.23.1",
15823
+ playwright: "1.64.1",
15824
+ postgres: "3.4.9",
15825
+ tsx: "^4.23.15",
15826
+ yaml: "^2.9.1"
15827
+ },
15828
+ devDependencies: {
15829
+ "@anthropic-ai/sdk": "0.133.0",
15830
+ "@aws-sdk/client-dynamodb": "^3.1161.0",
15831
+ "@aws-sdk/client-s3": "^3.1160.0",
15832
+ "@aws-sdk/client-secrets-manager": "^3.1161.0",
15833
+ "@aws-sdk/client-sns": "^3.1161.0",
15834
+ "@aws-sdk/client-sqs": "^3.1161.0",
15835
+ "@composio/core": "0.18.0",
15836
+ "@slack/web-api": "^7.19.0",
15837
+ "@types/node": "^26.6.4",
15838
+ "@types/pg": "^8.23.1",
15839
+ express: "^4.22.3",
15840
+ ioredis: "^5.11.1",
15841
+ mongodb: "^7.8.0",
15842
+ nodemailer: "^10.3.1",
15843
+ openai: "7.32.0",
15844
+ stripe: "^23.0.0",
15845
+ tsup: "^8.5.1",
15846
+ typescript: "^7.0.2",
15847
+ vitest: "^5.0.3"
15848
+ },
15849
+ homepage: "https://agenttwin.si/",
15850
+ repository: {
15851
+ type: "git",
15852
+ url: "git+https://github.com/Sashank-Singh/AgentTwin.git"
15853
+ }
15854
+ };
15855
+
15856
+ // src/lib/version.ts
15857
+ var VERSION = package_default.version;
15858
+
15859
+ // src/runtime/scim.ts
15860
+ import { randomBytes as randomBytes10, randomUUID as randomUUID8, createHash as createHash26 } from "crypto";
15861
+
15862
+ // src/runtime/teams.ts
15863
+ import { createHash as createHash25, randomBytes as randomBytes9, randomUUID as randomUUID7 } from "crypto";
15864
+ var TEAM_ROLES = ["admin", "member", "viewer"];
15865
+ var INVITE_DAYS = 7;
15866
+ var AUDIT_LIMIT = 5e3;
15867
+ var sha4 = (value) => createHash25("sha256").update(value).digest("hex");
15868
+ var isRole = (value) => typeof value === "string" && TEAM_ROLES.includes(value);
15869
+ function resolveWorkspace(state, person, orgToken) {
15870
+ if (orgToken) return { workspace: person, role: orgToken.role, actorId: `token:${orgToken.id}`, actorLabel: `API token "${orgToken.label}"`, shared: true };
15871
+ const label2 = person.identity?.email ?? person.identity?.name ?? person.label;
15872
+ if (person.activeWorkspace && person.activeWorkspace !== person.id) {
15873
+ const membership = (state.teamMembers ?? []).find((m) => m.accountId === person.activeWorkspace && m.memberId === person.id);
15874
+ const workspace = membership && state.accounts.find((a) => a.id === membership.accountId && a.active);
15875
+ if (membership && workspace) return { workspace, role: membership.role, actorId: person.id, actorLabel: label2, shared: true };
15876
+ }
15877
+ return { workspace: person, role: "admin", actorId: person.id, actorLabel: label2, shared: (state.teamMembers ?? []).some((m) => m.accountId === person.id) };
15878
+ }
15879
+ function workspacesOf(state, person) {
15880
+ return [
15881
+ { id: person.id, name: person.label, role: "admin", personal: true },
15882
+ ...(state.teamMembers ?? []).filter((m) => m.memberId === person.id).flatMap((m) => {
15883
+ const w = state.accounts.find((a) => a.id === m.accountId && a.active);
15884
+ return w ? [{ id: w.id, name: w.label, role: m.role, personal: false }] : [];
15885
+ })
15886
+ ];
15887
+ }
15888
+ function teamView(state, workspace, role) {
15889
+ const owner = { memberId: workspace.id, name: workspace.identity?.name ?? workspace.label, email: workspace.identity?.email, role: "admin", owner: true };
15890
+ const members = (state.teamMembers ?? []).filter((m) => m.accountId === workspace.id).map((m) => {
15891
+ const a = state.accounts.find((x) => x.id === m.memberId);
15892
+ return { memberId: m.memberId, name: a?.identity?.name ?? a?.label ?? "Removed account", email: a?.identity?.email, role: m.role, addedAt: m.addedAt, owner: false };
15893
+ });
15894
+ 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 })) : [];
15895
+ return { workspace: { id: workspace.id, name: workspace.label }, role, members: [owner, ...members], invites };
15896
+ }
15897
+ function createInvite(state, workspaceId, email, role, invitedBy) {
15898
+ const code = randomBytes9(24).toString("base64url");
15899
+ 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 };
15900
+ state.teamInvites = [...(state.teamInvites ?? []).filter((i) => !(i.accountId === workspaceId && i.email === invite.email && !i.acceptedBy)), invite];
15901
+ return { invite, code };
15902
+ }
15903
+ function acceptInvite(state, person, code) {
15904
+ const invite = (state.teamInvites ?? []).find((i) => i.codeHash === sha4(code));
15905
+ if (!invite || invite.acceptedBy || invite.expiresAt <= Date.now()) return { error: "invite_invalid" };
15906
+ if (!person.identity?.email || person.identity.email.toLowerCase() !== invite.email) return { error: "invite_email_mismatch", email: invite.email };
15907
+ if (invite.accountId === person.id) return { error: "invite_own_workspace" };
15908
+ invite.acceptedBy = person.id;
15909
+ invite.acceptedAt = (/* @__PURE__ */ new Date()).toISOString();
15910
+ const existing = (state.teamMembers ?? []).find((m) => m.accountId === invite.accountId && m.memberId === person.id);
15911
+ if (existing) existing.role = invite.role;
15912
+ else state.teamMembers = [...state.teamMembers ?? [], { accountId: invite.accountId, memberId: person.id, role: invite.role, addedAt: invite.acceptedAt, addedBy: invite.invitedBy }];
15913
+ person.activeWorkspace = invite.accountId;
15914
+ return { invite };
15915
+ }
15916
+ function createOrgToken(state, workspaceId, label2, role, createdBy) {
15917
+ const token = `at_org_${randomBytes9(32).toString("hex")}`;
15918
+ const record3 = { tokenHash: sha4(token), id: randomUUID7(), accountId: workspaceId, label: label2, role, createdAt: (/* @__PURE__ */ new Date()).toISOString(), createdBy };
15919
+ state.orgTokens = [...state.orgTokens ?? [], record3];
15920
+ return { token, record: record3 };
15921
+ }
15922
+ var findOrgToken = (state, token) => token.startsWith("at_org_") ? (state.orgTokens ?? []).find((t) => t.tokenHash === sha4(token)) : void 0;
15923
+ var publicToken = (t) => ({ id: t.id, label: t.label, role: t.role, createdAt: t.createdAt, createdBy: t.createdBy });
15924
+ function recordAudit(state, event) {
15925
+ const entry = { id: randomUUID7(), at: (/* @__PURE__ */ new Date()).toISOString(), ...event };
15926
+ const all = [...state.auditEvents ?? [], entry];
15927
+ const mine = all.filter((e) => e.accountId === event.accountId);
15928
+ state.auditEvents = mine.length > AUDIT_LIMIT ? all.filter((e) => e.accountId !== event.accountId || mine.indexOf(e) >= mine.length - AUDIT_LIMIT) : all;
15929
+ return entry;
15930
+ }
15931
+ 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")}`;
15932
+ function adminOnly(method, path2) {
15933
+ 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";
15934
+ }
15935
+
15936
+ // src/runtime/scim.ts
15937
+ var SCIM_USER = "urn:ietf:params:scim:schemas:core:2.0:User";
15938
+ var LIST = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
15939
+ var PATCH = "urn:ietf:params:scim:api:messages:2.0:PatchOp";
15940
+ var ERROR = "urn:ietf:params:scim:api:messages:2.0:Error";
15941
+ var sha5 = (v) => createHash26("sha256").update(v).digest("hex");
15942
+ var scimError = (status, detail, scimType) => ({ status, body: { schemas: [ERROR], status: String(status), detail, ...scimType ? { scimType } : {} } });
15943
+ function userOf(store, workspaceId, a, base) {
15944
+ const m = (store.teamMembers ?? []).find((x) => x.accountId === workspaceId && x.memberId === a.id);
15945
+ const [givenName, ...rest] = (a.identity?.name ?? "").split(/\s+/);
15946
+ return {
15947
+ schemas: [SCIM_USER],
15948
+ id: a.id,
15949
+ userName: a.identity?.email ?? a.label,
15950
+ active: !!m && a.active,
15951
+ name: { formatted: a.identity?.name ?? "", givenName: givenName ?? "", familyName: rest.join(" ") },
15952
+ displayName: a.identity?.name ?? a.label,
15953
+ emails: a.identity?.email ? [{ value: a.identity.email, primary: true, type: "work" }] : [],
15954
+ roles: m ? [{ value: m.role, primary: true }] : [],
15955
+ meta: { resourceType: "User", location: `${base}/scim/v2/Users/${a.id}` }
15956
+ };
15957
+ }
15958
+ var inWorkspace = (store, workspaceId, a) => a.provisionedBy === workspaceId || (store.teamMembers ?? []).some((m) => m.accountId === workspaceId && m.memberId === a.id);
15959
+ var emailOf = (input) => {
15960
+ const primary = Array.isArray(input.emails) ? (input.emails.find((e) => e?.primary) ?? input.emails[0])?.value : void 0;
15961
+ const value = typeof primary === "string" ? primary : typeof input.userName === "string" ? input.userName : "";
15962
+ return value.trim().toLowerCase();
15963
+ };
15964
+ 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];
15965
+ var roleOf = (input) => {
15966
+ const v = Array.isArray(input.roles) ? input.roles[0]?.value : void 0;
15967
+ return isRole(v) ? v : void 0;
15968
+ };
15969
+ function setActive(store, workspaceId, a, active2, role) {
15970
+ const members = store.teamMembers ?? [];
15971
+ const existing = members.find((m) => m.accountId === workspaceId && m.memberId === a.id);
15972
+ if (active2) {
15973
+ if (a.provisionedBy === workspaceId) a.active = true;
15974
+ if (!existing) store.teamMembers = [...members, { accountId: workspaceId, memberId: a.id, role: role ?? "member", addedAt: (/* @__PURE__ */ new Date()).toISOString(), addedBy: "scim" }];
15975
+ else if (role) existing.role = role;
15976
+ if (!a.activeWorkspace) a.activeWorkspace = workspaceId;
15977
+ } else {
15978
+ store.teamMembers = members.filter((m) => m !== existing);
15979
+ if (a.activeWorkspace === workspaceId) delete a.activeWorkspace;
15980
+ if (a.provisionedBy === workspaceId) {
15981
+ a.active = false;
15982
+ a.cliTokens = [];
15983
+ a.tokenHash = sha5(randomBytes10(32).toString("hex"));
15984
+ store.sessions = (store.sessions ?? []).filter((s) => s.accountId !== a.id);
15985
+ }
15986
+ }
15987
+ }
15988
+ function handleScim(store, workspaceId, method, path2, query, input, base) {
15989
+ 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." }] } };
15990
+ 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 }] } };
15991
+ if (path2 === "/scim/v2/Users" && method === "GET") {
15992
+ const filter = query.get("filter") ?? "";
15993
+ const match = filter.match(/^userName eq "([^"]+)"$/i);
15994
+ if (filter && !match) return scimError(400, 'Only filter=userName eq "\u2026" is supported.', "invalidFilter");
15995
+ const all = store.accounts.filter((a) => inWorkspace(store, workspaceId, a) && a.id !== workspaceId && (!match || a.identity?.email?.toLowerCase() === match[1].toLowerCase()));
15996
+ const start = Math.max(1, Number(query.get("startIndex") ?? 1) || 1), count = Math.min(200, Math.max(0, Number(query.get("count") ?? 100) || 100));
15997
+ const page2 = all.slice(start - 1, start - 1 + count);
15998
+ return { status: 200, body: { schemas: [LIST], totalResults: all.length, startIndex: start, itemsPerPage: page2.length, Resources: page2.map((a) => userOf(store, workspaceId, a, base)) } };
15999
+ }
16000
+ if (path2 === "/scim/v2/Users" && method === "POST") {
16001
+ const email = emailOf(input ?? {});
16002
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) return scimError(400, "userName or a primary email is required.", "invalidValue");
16003
+ const existing = store.accounts.find((a) => a.identity?.email?.toLowerCase() === email);
16004
+ if (existing && inWorkspace(store, workspaceId, existing)) return scimError(409, "A user with this userName already exists.", "uniqueness");
16005
+ if (existing) return scimError(409, "This email already has its own AgentTwin account. Invite it from the Team page instead.", "uniqueness");
16006
+ if (store.accounts.length >= 1e4) return scimError(507, "Account capacity reached.");
16007
+ 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 };
16008
+ store.accounts.push(account2);
16009
+ setActive(store, workspaceId, account2, input?.active !== false, roleOf(input ?? {}));
16010
+ return { status: 201, body: userOf(store, workspaceId, account2, base), audit: { action: "scim.user_created", subject: account2.id, details: { email } } };
16011
+ }
16012
+ const one = path2.match(/^\/scim\/v2\/Users\/([0-9a-f-]{36})$/);
16013
+ if (!one) return scimError(404, "Not found.");
16014
+ const account = store.accounts.find((a) => a.id === one[1] && a.id !== workspaceId && inWorkspace(store, workspaceId, a));
16015
+ if (!account) return scimError(404, "User not found.");
16016
+ if (method === "GET") return { status: 200, body: userOf(store, workspaceId, account, base) };
16017
+ if (method === "DELETE") {
16018
+ setActive(store, workspaceId, account, false);
16019
+ return { status: 204, body: null, audit: { action: "scim.user_deleted", subject: account.id } };
16020
+ }
16021
+ if (method === "PUT" || method === "PATCH") {
16022
+ let active2, role, name;
16023
+ if (method === "PUT") {
16024
+ active2 = input?.active !== false;
16025
+ role = roleOf(input ?? {});
16026
+ name = nameOf(input ?? {}, account.identity?.email ?? "");
16027
+ } else {
16028
+ if (!Array.isArray(input?.schemas) || !input.schemas.includes(PATCH) || !Array.isArray(input?.Operations)) return scimError(400, "Send a PatchOp with Operations.", "invalidSyntax");
16029
+ for (const op2 of input.Operations) {
16030
+ if (String(op2?.op).toLowerCase() !== "replace" && String(op2?.op).toLowerCase() !== "add") continue;
16031
+ const values = op2.path ? { [op2.path]: op2.value } : op2.value ?? {};
16032
+ if ("active" in values) active2 = values.active === true || values.active === "true" || values.active === "True";
16033
+ if ("displayName" in values && typeof values.displayName === "string") name = values.displayName;
16034
+ if ("roles" in values) role = roleOf({ roles: values.roles });
16035
+ }
16036
+ }
16037
+ if (name && account.provisionedBy === workspaceId) account.identity = { ...account.identity, name };
16038
+ const wasActive = (store.teamMembers ?? []).some((m) => m.accountId === workspaceId && m.memberId === account.id) && account.active;
16039
+ if (active2 !== void 0 || role) setActive(store, workspaceId, account, active2 ?? wasActive, role);
16040
+ const now = (store.teamMembers ?? []).some((m) => m.accountId === workspaceId && m.memberId === account.id) && account.active;
16041
+ 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 } } : {} } };
16042
+ }
16043
+ return scimError(405, "Method not allowed.");
16044
+ }
16045
+
15739
16046
  // src/runtime/gateway.ts
15740
- var hash6 = (value) => createHash25("sha256").update(value).digest("hex");
16047
+ var hash6 = (value) => createHash27("sha256").update(value).digest("hex");
15741
16048
  function uploadPath(path2) {
15742
16049
  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");
15743
16050
  return path2;
@@ -15795,7 +16102,7 @@ async function startGateway(opts) {
15795
16102
  const voiceControllers = /* @__PURE__ */ new Map();
15796
16103
  const directory = resolve11(opts.directory);
15797
16104
  await mkdir13(directory, { recursive: true, mode: 448 });
15798
- const storePath2 = join34(directory, "state.json");
16105
+ const storePath2 = join35(directory, "state.json");
15799
16106
  const database = opts.databaseUrl ? await openGatewayPostgres(opts.databaseUrl) : void 0;
15800
16107
  let store;
15801
16108
  if (database) store = database.state;
@@ -15827,9 +16134,9 @@ async function startGateway(opts) {
15827
16134
  try {
15828
16135
  if (database) await database.write(snapshot);
15829
16136
  else {
15830
- const path2 = join34(directory, `state-${randomUUID7()}.tmp`);
16137
+ const path2 = join35(directory, `state-${randomUUID9()}.tmp`);
15831
16138
  await writeFile21(path2, snapshot, { mode: 384 });
15832
- await rename2(path2, storePath2);
16139
+ await rename3(path2, storePath2);
15833
16140
  }
15834
16141
  committedWorkflows = workflowView;
15835
16142
  } catch (error) {
@@ -15845,7 +16152,7 @@ async function startGateway(opts) {
15845
16152
  const oauth = createOAuth(store, save, issuer);
15846
16153
  for (const thread of store.chats ?? []) {
15847
16154
  const last = thread.messages.at(-1);
15848
- 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 });
16155
+ 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 });
15849
16156
  }
15850
16157
  await save();
15851
16158
  store.jobs = store.jobs.filter((j) => Date.parse(j.createdAt) > Date.now() - 30 * 864e5);
@@ -15869,16 +16176,16 @@ async function startGateway(opts) {
15869
16176
  if (!store.accounts.some((a) => a.id === item.job.accountId && a.active)) throw new Error("Account revoked before execution");
15870
16177
  item.job.status = "running";
15871
16178
  await save();
15872
- workspace = await mkdtemp13(join34(tmpdir14(), "agenttwin-api-run-"));
16179
+ workspace = await mkdtemp13(join35(tmpdir14(), "agenttwin-api-run-"));
15873
16180
  for (const [file, encoded] of Object.entries(item.files)) {
15874
- const destination = join34(workspace, uploadPath(file));
16181
+ const destination = join35(workspace, uploadPath(file));
15875
16182
  await mkdir13(dirname6(destination), { recursive: true });
15876
16183
  await writeFile21(destination, Buffer.from(encoded, "base64"), { mode: 384 });
15877
16184
  }
15878
- await writeFile21(join34(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
16185
+ await writeFile21(join35(workspace, "agenttwin.world.json"), JSON.stringify(item.spec));
15879
16186
  if (item.spec.workflowId) {
15880
- await mkdir13(join34(workspace, ".agenttwin"));
15881
- await writeFile21(join34(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
16187
+ await mkdir13(join35(workspace, ".agenttwin"));
16188
+ await writeFile21(join35(workspace, ".agenttwin/inventory.json"), JSON.stringify({ workflows: [{ id: item.spec.workflowId }] }));
15882
16189
  }
15883
16190
  const receipt = await runWorld(workspace, { runtime: "e2b", seed: item.seed, signal: controllers.get(item.job.id)?.signal, log: () => {
15884
16191
  } });
@@ -15915,7 +16222,7 @@ async function startGateway(opts) {
15915
16222
  const devices = /* @__PURE__ */ new Map();
15916
16223
  let hashing = 0;
15917
16224
  let localOnboardingUntil = 0;
15918
- const dummyPassword = randomBytes9(16).toString("hex") + ":" + randomBytes9(64).toString("hex");
16225
+ const dummyPassword = randomBytes11(16).toString("hex") + ":" + randomBytes11(64).toString("hex");
15919
16226
  const budget = requestBudget(opts.requestsPerMinute);
15920
16227
  const githubStates = /* @__PURE__ */ new Map();
15921
16228
  const registered = opts.githubApp ? void 0 : await loadRegisteredApp(directory);
@@ -16044,7 +16351,7 @@ async function startGateway(opts) {
16044
16351
  admitted = true;
16045
16352
  if (await oauth(req, res, path2)) return;
16046
16353
  if (path2 === "/healthz" && req.method === "GET") {
16047
- send(res, 200, { status: stopping ? "stopping" : "ok" });
16354
+ send(res, 200, { status: stopping ? "stopping" : "ok", version: VERSION });
16048
16355
  return;
16049
16356
  }
16050
16357
  if (!storageHealthy) {
@@ -16287,17 +16594,32 @@ async function startGateway(opts) {
16287
16594
  const identity = await socialAuth.finish(transaction, requestUrl.searchParams);
16288
16595
  let owner = store.accounts.find((a) => a.externalIdentities?.some((i) => i.provider === identity.provider && i.issuer === identity.issuer && i.subject === identity.subject));
16289
16596
  if (!owner) {
16290
- if (store.accounts.some((a) => a.identity?.email === identity.email)) {
16597
+ const realm = opts.socialAuth?.ssoRealms?.find((r) => r.issuer === identity.issuer);
16598
+ const provisioned = realm?.workspace ? store.accounts.find((a) => a.provisionedBy === realm.workspace && a.identity?.email?.toLowerCase() === identity.email.toLowerCase() && !a.externalIdentities?.length) : void 0;
16599
+ if (provisioned) {
16600
+ provisioned.externalIdentities = [{ provider: identity.provider, issuer: identity.issuer, subject: identity.subject }];
16601
+ owner = provisioned;
16602
+ } else if (store.accounts.some((a) => a.identity?.email === identity.email)) {
16291
16603
  redirect((transaction.signup ? "/signup/" : "/login/") + "?auth_error=existing_account");
16292
16604
  return;
16293
16605
  }
16294
- if (store.accounts.length >= 1e4) throw new Error("account_capacity");
16295
- 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 } : {} };
16296
- store.accounts.push(owner);
16606
+ if (!owner && store.accounts.length >= 1e4) throw new Error("account_capacity");
16607
+ 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 } : {} };
16608
+ if (!store.accounts.includes(owner)) store.accounts.push(owner);
16297
16609
  captureAnalytics({ event: "account_created", distinctId: owner.id, properties: { method: identity.provider, realm: identity.organization || identity.issuer } });
16298
16610
  }
16299
16611
  if (!owner.active) throw new Error("account_inactive");
16300
- const secret = randomBytes9(32).toString("hex");
16612
+ const ssoRealm = opts.socialAuth?.ssoRealms?.find((r) => r.issuer === identity.issuer);
16613
+ const shared = ssoRealm?.workspace ? store.accounts.find((a) => a.id === ssoRealm.workspace && a.active) : void 0;
16614
+ if (shared && shared.id !== owner.id) {
16615
+ const member = (store.teamMembers ?? []).some((m) => m.accountId === shared.id && m.memberId === owner.id);
16616
+ if (!member && ssoRealm.autoJoin !== false) {
16617
+ store.teamMembers = [...store.teamMembers ?? [], { accountId: shared.id, memberId: owner.id, role: ssoRealm.role ?? "member", addedAt: (/* @__PURE__ */ new Date()).toISOString(), addedBy: `sso:${ssoRealm.id}` }];
16618
+ recordAudit(store, { accountId: shared.id, actorId: owner.id, actorLabel: identity.email, action: "member.joined", subject: owner.id, details: { role: ssoRealm.role ?? "member", via: "sso" } });
16619
+ }
16620
+ if ((member || ssoRealm.autoJoin !== false) && !owner.activeWorkspace) owner.activeWorkspace = shared.id;
16621
+ }
16622
+ const secret = randomBytes11(32).toString("hex");
16301
16623
  store.sessions = (store.sessions ?? []).filter((s) => s.expires > Date.now());
16302
16624
  const owned = store.sessions.filter((s) => s.accountId === owner.id);
16303
16625
  if (owned.length >= 10) store.sessions = store.sessions.filter((s) => s !== owned[0]);
@@ -16318,7 +16640,7 @@ async function startGateway(opts) {
16318
16640
  send(res, 429, { error: "Try again shortly." });
16319
16641
  return;
16320
16642
  }
16321
- const secret = randomBytes9(32).toString("hex"), code = randomBytes9(5).toString("hex").toUpperCase();
16643
+ const secret = randomBytes11(32).toString("hex"), code = randomBytes11(5).toString("hex").toUpperCase();
16322
16644
  devices.set(digest5(secret), { code, expires: Date.now() + 6e5, lastPoll: 0 });
16323
16645
  send(res, 200, { deviceCode: secret, userCode: code, verificationUrl, expiresIn: 600 });
16324
16646
  return;
@@ -16339,7 +16661,7 @@ async function startGateway(opts) {
16339
16661
  }
16340
16662
  const rpID = requestUrl.hostname === "localhost" || requestUrl.hostname === "127.0.0.1" ? "localhost" : new URL(origin).hostname;
16341
16663
  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 })) });
16342
- const challengeId = randomBytes9(16).toString("hex");
16664
+ const challengeId = randomBytes11(16).toString("hex");
16343
16665
  challengeStore(passkeyChallenges, challengeId, options.challenge, 12e4);
16344
16666
  send(res, 200, { options, challengeId });
16345
16667
  return;
@@ -16386,7 +16708,7 @@ async function startGateway(opts) {
16386
16708
  const credentialId = typeof input.credentialId === "string" ? input.credentialId.slice(0, 1024) : "";
16387
16709
  const owner = credentialId ? store.accounts.find((a) => a.active && (a.passkeys ?? []).some((k) => k.id === credentialId)) : void 0;
16388
16710
  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" });
16389
- const challengeId = randomBytes9(16).toString("hex");
16711
+ const challengeId = randomBytes11(16).toString("hex");
16390
16712
  challengeStore(passkeyChallenges, challengeId, options.challenge, 12e4);
16391
16713
  send(res, 200, { options, challengeId });
16392
16714
  return;
@@ -16417,7 +16739,7 @@ async function startGateway(opts) {
16417
16739
  return;
16418
16740
  }
16419
16741
  key2.counter = verification.authenticationInfo.newCounter;
16420
- const secret = randomBytes9(32).toString("hex");
16742
+ const secret = randomBytes11(32).toString("hex");
16421
16743
  store.sessions = (store.sessions ?? []).filter((s) => s.expires > Date.now());
16422
16744
  const owned = store.sessions.filter((s) => s.accountId === owner.id);
16423
16745
  if (owned.length >= 10) store.sessions = store.sessions.filter((s) => s !== owned[0]);
@@ -16514,7 +16836,7 @@ async function startGateway(opts) {
16514
16836
  send(res, 429, { error: "account_capacity" });
16515
16837
  return;
16516
16838
  }
16517
- a = { id: randomUUID7(), tokenHash: hash6(randomBytes9(32).toString("hex")), label: workspace, active: true, usageDay: "", runs: 0, identity: { email: parsed.email, name, passwordHash: encoded } };
16839
+ a = { id: randomUUID9(), tokenHash: hash6(randomBytes11(32).toString("hex")), label: workspace, active: true, usageDay: "", runs: 0, identity: { email: parsed.email, name, passwordHash: encoded } };
16518
16840
  store.accounts.push(a);
16519
16841
  captureAnalytics({ event: "account_created", distinctId: a.id, properties: { method: "email", realm: "password" } });
16520
16842
  } else {
@@ -16524,7 +16846,7 @@ async function startGateway(opts) {
16524
16846
  return;
16525
16847
  }
16526
16848
  }
16527
- const secret = randomBytes9(32).toString("hex");
16849
+ const secret = randomBytes11(32).toString("hex");
16528
16850
  store.sessions = (store.sessions ?? []).filter((s) => s.expires > Date.now());
16529
16851
  const owned = store.sessions.filter((s) => s.accountId === a.id);
16530
16852
  if (owned.length >= 10) store.sessions = store.sessions.filter((s) => s !== owned[0]);
@@ -16634,8 +16956,8 @@ async function startGateway(opts) {
16634
16956
  send(res, 400, { error: "label_required" });
16635
16957
  return;
16636
16958
  }
16637
- const accessToken = `at_user_${randomBytes9(32).toString("hex")}`;
16638
- const account2 = { id: randomUUID7(), tokenHash: hash6(accessToken), label: data.label, active: true, usageDay: "", runs: 0 };
16959
+ const accessToken = `at_user_${randomBytes11(32).toString("hex")}`;
16960
+ const account2 = { id: randomUUID9(), tokenHash: hash6(accessToken), label: data.label, active: true, usageDay: "", runs: 0 };
16639
16961
  if (store.accounts.length >= 1e4) {
16640
16962
  send(res, 429, { error: "account_capacity" });
16641
16963
  return;
@@ -16661,12 +16983,18 @@ async function startGateway(opts) {
16661
16983
  send(res, 200, { revoked: true });
16662
16984
  return;
16663
16985
  }
16664
- 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));
16665
- if (!account) {
16986
+ const orgToken = token ? findOrgToken(store, token) : void 0;
16987
+ 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));
16988
+ if (!found) {
16666
16989
  res.setHeader("WWW-Authenticate", `Bearer resource_metadata="${issuer}/.well-known/oauth-protected-resource"`);
16667
16990
  send(res, 401, { error: "unauthorized" });
16668
16991
  return;
16669
16992
  }
16993
+ let account = found;
16994
+ if (orgToken && path2.startsWith("/v1/auth/") && path2 !== "/v1/auth/me") {
16995
+ send(res, 403, { error: "organization_token_not_allowed" });
16996
+ return;
16997
+ }
16670
16998
  if (path2 === "/v1/dev/workspace" && req.method === "POST" && opts.localDevelopment && ["127.0.0.1", "localhost"].includes(opts.host ?? "") && verificationUrl === "http://localhost:3000/onboarding/") {
16671
16999
  if (token || !session || origin !== "http://localhost:3000") {
16672
17000
  send(res, 403, { error: "browser_session_required" });
@@ -16714,7 +17042,7 @@ async function startGateway(opts) {
16714
17042
  return;
16715
17043
  }
16716
17044
  const previousIdentity = account.identity, previousSessions = store.sessions;
16717
- const secret = randomBytes9(32).toString("hex");
17045
+ const secret = randomBytes11(32).toString("hex");
16718
17046
  account.identity = { ...account.identity, passwordHash: encoded };
16719
17047
  store.sessions = [...store.sessions.filter((s) => s.accountId !== account.id), { accountId: account.id, hash: digest5(secret), expires: Date.now() + 7 * 864e5 }];
16720
17048
  try {
@@ -16737,7 +17065,7 @@ async function startGateway(opts) {
16737
17065
  return;
16738
17066
  }
16739
17067
  account.cliTokens = (account.cliTokens ?? []).filter((t) => t !== hash6(token));
16740
- if (account.tokenHash === hash6(token)) account.tokenHash = hash6(randomBytes9(32).toString("hex"));
17068
+ if (account.tokenHash === hash6(token)) account.tokenHash = hash6(randomBytes11(32).toString("hex"));
16741
17069
  await save();
16742
17070
  send(res, 200, { signedOut: true });
16743
17071
  return;
@@ -16750,7 +17078,7 @@ async function startGateway(opts) {
16750
17078
  send(res, 400, { error: "Code not found or expired. Run agenttwin login again." });
16751
17079
  return;
16752
17080
  }
16753
- const accessToken = `at_user_${randomBytes9(32).toString("hex")}`;
17081
+ const accessToken = `at_user_${randomBytes11(32).toString("hex")}`;
16754
17082
  account.cliTokens = [...(account.cliTokens ?? []).slice(-9), hash6(accessToken)];
16755
17083
  device.accountId = account.id;
16756
17084
  await save();
@@ -16784,8 +17112,198 @@ async function startGateway(opts) {
16784
17112
  send(res, 200, { user: profile(account) });
16785
17113
  return;
16786
17114
  }
17115
+ const person = account, team = resolveWorkspace(store, person, orgToken);
17116
+ const audit = (action, subject, details) => recordAudit(store, { accountId: team.workspace.id, actorId: team.actorId, actorLabel: team.actorLabel, action, ...subject ? { subject } : {}, ...details ? { details } : {} });
16787
17117
  if (path2 === "/v1/auth/me" && req.method === "GET") {
16788
- send(res, 200, { user: profile(account) });
17118
+ 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) } });
17119
+ return;
17120
+ }
17121
+ if ((path2 === "/v1/team/join" || path2 === "/v1/team/switch") && req.method === "POST") {
17122
+ if (orgToken) {
17123
+ send(res, 403, { error: "organization_token_not_allowed" });
17124
+ return;
17125
+ }
17126
+ const input = await body(req, 8192);
17127
+ if (path2 === "/v1/team/join") {
17128
+ const result2 = acceptInvite(store, person, typeof input.code === "string" ? input.code : "");
17129
+ if ("error" in result2) {
17130
+ 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.` } : {} });
17131
+ return;
17132
+ }
17133
+ 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 } });
17134
+ await save();
17135
+ send(res, 200, { joined: true, workspaceId: result2.invite.accountId, role: result2.invite.role });
17136
+ return;
17137
+ }
17138
+ const target = typeof input.workspaceId === "string" ? input.workspaceId : "";
17139
+ if (!workspacesOf(store, person).some((w) => w.id === target)) {
17140
+ send(res, 404, { error: "workspace_not_found" });
17141
+ return;
17142
+ }
17143
+ if (target === person.id) delete person.activeWorkspace;
17144
+ else person.activeWorkspace = target;
17145
+ await save();
17146
+ send(res, 200, { workspaceId: target });
17147
+ return;
17148
+ }
17149
+ if (path2.startsWith("/v1/team/members/") && req.method === "DELETE" && path2.slice(17) === person.id && !orgToken && team.workspace.id !== person.id) {
17150
+ store.teamMembers = (store.teamMembers ?? []).filter((m) => !(m.accountId === team.workspace.id && m.memberId === person.id));
17151
+ delete person.activeWorkspace;
17152
+ audit("member.left", person.id);
17153
+ await save();
17154
+ send(res, 200, { left: true });
17155
+ return;
17156
+ }
17157
+ account = team.workspace;
17158
+ if (team.role === "viewer" && !["GET", "HEAD"].includes(req.method ?? "")) {
17159
+ send(res, 403, { error: "viewer_read_only", message: "Viewers can see this workspace but not change it. Ask an admin for the member role." });
17160
+ return;
17161
+ }
17162
+ if (team.role !== "admin" && adminOnly(req.method ?? "", path2)) {
17163
+ send(res, 403, { error: "admin_required" });
17164
+ return;
17165
+ }
17166
+ if (path2.startsWith("/scim/v2/")) {
17167
+ if (!orgToken || team.role !== "admin") {
17168
+ send(res, 403, scimError(403, "SCIM needs an organization token with the admin role.").body);
17169
+ return;
17170
+ }
17171
+ const method = req.method ?? "GET";
17172
+ const input = ["POST", "PUT", "PATCH"].includes(method) ? await body(req, 1024 * 1024) : void 0;
17173
+ const result2 = handleScim(store, team.workspace.id, method, path2, requestUrl.searchParams, input, issuer);
17174
+ if (result2.audit) {
17175
+ audit(result2.audit.action, result2.audit.subject, result2.audit.details);
17176
+ await save();
17177
+ }
17178
+ if (result2.status === 204) {
17179
+ res.writeHead(204, { "cache-control": "no-store" });
17180
+ res.end();
17181
+ return;
17182
+ }
17183
+ send(res, result2.status, result2.body);
17184
+ return;
17185
+ }
17186
+ if (!["GET", "HEAD"].includes(req.method ?? "") && !path2.startsWith("/v1/team/") && team.shared) {
17187
+ res.once("finish", () => {
17188
+ if (res.statusCode < 400) {
17189
+ audit(auditAction(req.method ?? "", path2), void 0, { status: res.statusCode });
17190
+ save().catch(() => {
17191
+ });
17192
+ }
17193
+ });
17194
+ }
17195
+ if (path2 === "/v1/team" && req.method === "GET") {
17196
+ send(res, 200, teamView(store, team.workspace, team.role));
17197
+ return;
17198
+ }
17199
+ if (path2 === "/v1/team/invites" && req.method === "POST") {
17200
+ const input = await body(req, 8192);
17201
+ const email = typeof input.email === "string" ? input.email.trim().toLowerCase() : "";
17202
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) || email.length > 254) {
17203
+ send(res, 400, { error: "Enter a valid email address." });
17204
+ return;
17205
+ }
17206
+ if (!isRole(input.role)) {
17207
+ send(res, 400, { error: "Role must be admin, member or viewer." });
17208
+ return;
17209
+ }
17210
+ if ((store.teamInvites ?? []).filter((i) => i.accountId === team.workspace.id && !i.acceptedBy && i.expiresAt > Date.now()).length >= 100) {
17211
+ send(res, 429, { error: "Too many pending invites. Revoke some first." });
17212
+ return;
17213
+ }
17214
+ const { invite, code } = createInvite(store, team.workspace.id, email, input.role, team.actorId);
17215
+ audit("invite.created", invite.id, { email, role: invite.role });
17216
+ await save();
17217
+ 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` });
17218
+ return;
17219
+ }
17220
+ const teamMatch = path2.match(/^\/v1\/team\/(invites|members|tokens)\/([0-9a-f-]{36})$/);
17221
+ if (teamMatch && req.method === "DELETE") {
17222
+ const [, kind, id] = teamMatch;
17223
+ if (kind === "invites") {
17224
+ const before = store.teamInvites?.length ?? 0;
17225
+ store.teamInvites = (store.teamInvites ?? []).filter((i) => !(i.id === id && i.accountId === team.workspace.id && !i.acceptedBy));
17226
+ if (store.teamInvites.length === before) {
17227
+ send(res, 404, { error: "not_found" });
17228
+ return;
17229
+ }
17230
+ audit("invite.revoked", id);
17231
+ }
17232
+ if (kind === "tokens") {
17233
+ const before = store.orgTokens?.length ?? 0;
17234
+ store.orgTokens = (store.orgTokens ?? []).filter((t) => !(t.id === id && t.accountId === team.workspace.id));
17235
+ if (store.orgTokens.length === before) {
17236
+ send(res, 404, { error: "not_found" });
17237
+ return;
17238
+ }
17239
+ audit("token.revoked", id);
17240
+ }
17241
+ if (kind === "members") {
17242
+ if (team.role !== "admin") {
17243
+ send(res, 403, { error: "admin_required" });
17244
+ return;
17245
+ }
17246
+ const removed = (store.teamMembers ?? []).find((m) => m.accountId === team.workspace.id && m.memberId === id);
17247
+ if (!removed) {
17248
+ send(res, 404, { error: "not_found" });
17249
+ return;
17250
+ }
17251
+ store.teamMembers = (store.teamMembers ?? []).filter((m) => m !== removed);
17252
+ const who = store.accounts.find((a) => a.id === id);
17253
+ if (who?.activeWorkspace === team.workspace.id) delete who.activeWorkspace;
17254
+ audit("member.removed", id, { role: removed.role });
17255
+ }
17256
+ await save();
17257
+ send(res, 200, { removed: true });
17258
+ return;
17259
+ }
17260
+ if (teamMatch && teamMatch[1] === "members" && req.method === "PATCH") {
17261
+ const input = await body(req, 8192);
17262
+ if (!isRole(input.role)) {
17263
+ send(res, 400, { error: "Role must be admin, member or viewer." });
17264
+ return;
17265
+ }
17266
+ const member = (store.teamMembers ?? []).find((m) => m.accountId === team.workspace.id && m.memberId === teamMatch[2]);
17267
+ if (!member) {
17268
+ send(res, 404, { error: "not_found" });
17269
+ return;
17270
+ }
17271
+ const from = member.role;
17272
+ member.role = input.role;
17273
+ audit("member.role_changed", member.memberId, { from, to: input.role });
17274
+ await save();
17275
+ send(res, 200, { memberId: member.memberId, role: member.role });
17276
+ return;
17277
+ }
17278
+ if (path2 === "/v1/team/tokens" && req.method === "GET") {
17279
+ send(res, 200, { tokens: (store.orgTokens ?? []).filter((t) => t.accountId === team.workspace.id).map(publicToken) });
17280
+ return;
17281
+ }
17282
+ if (path2 === "/v1/team/tokens" && req.method === "POST") {
17283
+ const input = await body(req, 8192);
17284
+ const label2 = typeof input.label === "string" ? input.label.trim().slice(0, 80) : "";
17285
+ if (!label2) {
17286
+ send(res, 400, { error: 'Give the token a name, such as "CI".' });
17287
+ return;
17288
+ }
17289
+ const role = input.role === void 0 ? "member" : input.role;
17290
+ if (!isRole(role)) {
17291
+ send(res, 400, { error: "Role must be admin, member or viewer." });
17292
+ return;
17293
+ }
17294
+ if ((store.orgTokens ?? []).filter((t) => t.accountId === team.workspace.id).length >= 50) {
17295
+ send(res, 429, { error: "This workspace has 50 tokens. Revoke one first." });
17296
+ return;
17297
+ }
17298
+ const { token: secret, record: record3 } = createOrgToken(store, team.workspace.id, label2, role, team.actorId);
17299
+ audit("token.created", record3.id, { label: label2, role });
17300
+ await save();
17301
+ send(res, 201, { token: secret, ...publicToken(record3) });
17302
+ return;
17303
+ }
17304
+ if (path2 === "/v1/team/audit" && req.method === "GET") {
17305
+ const events = (store.auditEvents ?? []).filter((e) => e.accountId === team.workspace.id);
17306
+ send(res, 200, { events: events.slice(-500).reverse() });
16789
17307
  return;
16790
17308
  }
16791
17309
  if (path2 === "/v1/github/app" && req.method === "GET") {
@@ -16808,7 +17326,7 @@ async function startGateway(opts) {
16808
17326
  send(res, 429, { error: "Too many pending installs. Try again shortly." });
16809
17327
  return;
16810
17328
  }
16811
- const state = randomBytes9(24).toString("hex");
17329
+ const state = randomBytes11(24).toString("hex");
16812
17330
  githubStates.set(state, { accountId: account.id, origin, expires: Date.now() + 15 * 6e4 });
16813
17331
  send(res, 200, { url: installUrl(githubApp, state) });
16814
17332
  return;
@@ -17031,7 +17549,7 @@ async function startGateway(opts) {
17031
17549
  send(res, 429, { error: "receipt_capacity" });
17032
17550
  return;
17033
17551
  }
17034
- const id = randomUUID7();
17552
+ const id = randomUUID9();
17035
17553
  const job = { id, accountId: account.id, status: "completed", createdAt: receipt.createdAt, receipt: { ...receipt, apiJobId: id } };
17036
17554
  store.jobs.push(job);
17037
17555
  await save();
@@ -17133,7 +17651,7 @@ async function startGateway(opts) {
17133
17651
  return;
17134
17652
  }
17135
17653
  store.jobs = store.jobs.filter((j) => Date.parse(j.createdAt) > Date.now() - 30 * 864e5);
17136
- const job = { id: randomUUID7(), accountId: account.id, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString(), name: spec.name, workflowId: spec.workflowId, project, ...idempotencyKey ? { idempotencyKey, requestDigest } : {} };
17654
+ const job = { id: randomUUID9(), accountId: account.id, status: "queued", createdAt: (/* @__PURE__ */ new Date()).toISOString(), name: spec.name, workflowId: spec.workflowId, project, ...idempotencyKey ? { idempotencyKey, requestDigest } : {} };
17137
17655
  account.runs++;
17138
17656
  store.jobs.push(job);
17139
17657
  await save();
@@ -17216,7 +17734,7 @@ async function startGateway(opts) {
17216
17734
  send(res, 429, { error: "workflow_capacity" });
17217
17735
  return;
17218
17736
  }
17219
- workflow = { id: createId || randomUUID7(), accountId: account.id, project, revision: 1, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), spec, status: "draft" };
17737
+ workflow = { id: createId || randomUUID9(), accountId: account.id, project, revision: 1, updatedAt: (/* @__PURE__ */ new Date()).toISOString(), spec, status: "draft" };
17220
17738
  store.workflows.push(workflow);
17221
17739
  } else {
17222
17740
  const index = store.workflows.indexOf(workflow);
@@ -17337,7 +17855,7 @@ async function startGateway(opts) {
17337
17855
  return;
17338
17856
  }
17339
17857
  if (!thread) {
17340
- thread = { id: randomUUID7(), accountId: account.id, project, messages: [] };
17858
+ thread = { id: randomUUID9(), accountId: account.id, project, messages: [] };
17341
17859
  store.chats.push(thread);
17342
17860
  }
17343
17861
  if (thread.messages.length >= 200) {
@@ -17355,7 +17873,7 @@ async function startGateway(opts) {
17355
17873
  chatControllers.set(account.id, controller);
17356
17874
  const timeout = setTimeout(() => controller.abort(), 45e3);
17357
17875
  const context2 = { project, discoveryDigest: inventory ? hash6(JSON.stringify(inventory)) : null, jobId: job?.id ?? null };
17358
- thread.messages.push({ id: randomUUID7(), role: "user", content: input.content.trim(), requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17876
+ thread.messages.push({ id: randomUUID9(), role: "user", content: input.content.trim(), requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17359
17877
  try {
17360
17878
  await save();
17361
17879
  const receipt = job?.receipt;
@@ -17373,12 +17891,12 @@ async function startGateway(opts) {
17373
17891
  send(res, 401, { error: "unauthorized" });
17374
17892
  return;
17375
17893
  }
17376
- thread.messages.push({ id: randomUUID7(), role: "assistant", content, requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17894
+ thread.messages.push({ id: randomUUID9(), role: "assistant", content, requestId: input.requestId, createdAt: (/* @__PURE__ */ new Date()).toISOString(), context: context2 });
17377
17895
  await save();
17378
17896
  send(res, 200, { thread });
17379
17897
  } catch (error) {
17380
17898
  const code = controller.signal.aborted ? "model_timeout" : error instanceof Error && /^model_[a-z0-9_]+$/.test(error.message) ? error.message : "model_unavailable";
17381
- 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 });
17899
+ 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 });
17382
17900
  await save();
17383
17901
  send(res, 502, { error: code, thread });
17384
17902
  } finally {