agenttwin 0.3.22 → 0.3.24

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 (171) hide show
  1. package/dist/api.js +1335 -729
  2. package/dist/dashboard/assets/next/static/chunks/{1250-7571b1a697f6bb4a.js → 1250-a3c859fd20517500.js} +1 -1
  3. package/dist/dashboard/assets/next/static/chunks/{2743-a0efd6f4aeb11cc5.js → 2743-72610a5d5a3f8462.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/5663-2ba656663ac4643f.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/app/v2/page-fc4df4912ce3af44.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/{webpack-be6e526fd530c797.js → webpack-ecd761d72719adb3.js} +1 -1
  7. package/dist/dashboard/index.html +2 -2
  8. package/dist/engine.js +2025 -1415
  9. package/dist/gateway.js +1411 -807
  10. package/dist/twins/catalog.json +20 -18
  11. package/dist/twins/engine/v2/agenttwin-clock.mjs +2 -0
  12. package/dist/twins/engine/v2/chunks/{4CPL6MPF.mjs → 52CMXHSV.mjs} +1 -1
  13. package/dist/twins/engine/v2/chunks/B2VTT7PF.mjs +2 -0
  14. package/dist/twins/engine/{v3/chunks/2CHBP57N.mjs → v2/chunks/HZDHKUD5.mjs} +1 -1
  15. package/dist/twins/engine/v2/chunks/IVRB2YOK.mjs +8 -0
  16. package/dist/twins/engine/v2/chunks/{YSJQQVUM.mjs → MPX7J53E.mjs} +1 -1
  17. package/dist/twins/engine/v2/chunks/{SQSP35HM.mjs → RFZW5KCO.mjs} +1 -1
  18. package/dist/twins/engine/v2/react-dom_client.mjs +1 -1
  19. package/dist/twins/engine/v2/react-dom_server.mjs +1 -1
  20. package/dist/twins/engine/v2/react.mjs +1 -1
  21. package/dist/twins/engine/v2/react_jsx-runtime.mjs +1 -1
  22. package/dist/twins/engine/v2/volter_world-core.mjs +103 -109
  23. package/dist/twins/engine/v2/volter_world-core_app-route.mjs +1 -1
  24. package/dist/twins/engine/v2/volter_world-core_network-policy.mjs +1 -1
  25. package/dist/twins/engine/v3/agenttwin-clock.mjs +2 -0
  26. package/dist/twins/engine/v3/chunks/{MFH2VZPP.mjs → 2EG5AD6A.mjs} +1 -1
  27. package/dist/twins/engine/v3/chunks/{C46M5U3Q.mjs → 5QGCNQS3.mjs} +1 -1
  28. package/dist/twins/engine/v3/chunks/{O7HGPMXG.mjs → 5WNKAVCT.mjs} +1 -1
  29. package/dist/twins/engine/v3/chunks/7D6PDVOF.mjs +11 -0
  30. package/dist/twins/engine/v3/chunks/B2VTT7PF.mjs +2 -0
  31. package/dist/twins/engine/v3/chunks/{N5BL5RDF.mjs → F72NFZTW.mjs} +131 -140
  32. package/dist/twins/engine/v3/chunks/{TY4LDBVH.mjs → GY2CTF2C.mjs} +1 -1
  33. package/dist/twins/engine/v3/chunks/{MWCO5UV3.mjs → GZESXXB2.mjs} +1 -1
  34. package/dist/twins/engine/{v2/chunks/2CHBP57N.mjs → v3/chunks/HZDHKUD5.mjs} +1 -1
  35. package/dist/twins/engine/v3/chunks/{WPATONSC.mjs → IC6JHXCF.mjs} +1 -1
  36. package/dist/twins/engine/v3/chunks/{5PWRY4UK.mjs → JLOGZJDO.mjs} +1 -1
  37. package/dist/twins/engine/v3/chunks/{2YSSPA5O.mjs → K7NBWSIY.mjs} +1 -1
  38. package/dist/twins/engine/v3/chunks/{WGUCFQK6.mjs → T4VKXHGB.mjs} +1 -1
  39. package/dist/twins/engine/v3/chunks/{AWOWH2H5.mjs → UAP25HWH.mjs} +1 -1
  40. package/dist/twins/engine/v3/chunks/{VDIRUSCM.mjs → UKHKF3CP.mjs} +1 -1
  41. package/dist/twins/engine/v3/chunks/{PLB7HTON.mjs → VJIL5WLL.mjs} +1 -1
  42. package/dist/twins/engine/v3/chunks/{7XRKSFFJ.mjs → ZIV3ZV6R.mjs} +1 -1
  43. package/dist/twins/engine/v3/react_jsx-runtime.mjs +1 -1
  44. package/dist/twins/engine/v3/volter_world-core.mjs +1 -1
  45. package/dist/twins/engine/v3/volter_world-ui.mjs +1 -1
  46. package/dist/twins/packs/ahrefs/NOTICE +1 -1
  47. package/dist/twins/packs/ai-gateway/NOTICE +1 -1
  48. package/dist/twins/packs/airtable/NOTICE +1 -1
  49. package/dist/twins/packs/algolia/NOTICE +1 -1
  50. package/dist/twins/packs/ambientcg/NOTICE +1 -1
  51. package/dist/twins/packs/anthropic/NOTICE +1 -1
  52. package/dist/twins/packs/assemblyai/NOTICE +1 -1
  53. package/dist/twins/packs/aws/NOTICE +1 -1
  54. package/dist/twins/packs/azure/NOTICE +1 -1
  55. package/dist/twins/packs/azureformrecognizer/NOTICE +1 -1
  56. package/dist/twins/packs/bitly/NOTICE +1 -1
  57. package/dist/twins/packs/bluesky/NOTICE +1 -1
  58. package/dist/twins/packs/calcom/NOTICE +1 -1
  59. package/dist/twins/packs/clerk/NOTICE +1 -1
  60. package/dist/twins/packs/cloudflare/NOTICE +1 -1
  61. package/dist/twins/packs/cohere/NOTICE +1 -1
  62. package/dist/twins/packs/datadog/NOTICE +1 -1
  63. package/dist/twins/packs/deepinfra/NOTICE +1 -1
  64. package/dist/twins/packs/deepseek/NOTICE +1 -1
  65. package/dist/twins/packs/discord/NOTICE +1 -1
  66. package/dist/twins/packs/duckduckgo/NOTICE +1 -1
  67. package/dist/twins/packs/dynadot/NOTICE +1 -1
  68. package/dist/twins/packs/e2b/NOTICE +1 -1
  69. package/dist/twins/packs/elevenlabs/NOTICE +1 -1
  70. package/dist/twins/packs/expo/NOTICE +1 -1
  71. package/dist/twins/packs/fal/NOTICE +1 -1
  72. package/dist/twins/packs/figma/NOTICE +1 -1
  73. package/dist/twins/packs/firecrawl/NOTICE +1 -1
  74. package/dist/twins/packs/fireworks/NOTICE +1 -1
  75. package/dist/twins/packs/fly/NOTICE +1 -1
  76. package/dist/twins/packs/gcs/NOTICE +1 -1
  77. package/dist/twins/packs/gemini/NOTICE +1 -1
  78. package/dist/twins/packs/github/NOTICE +1 -1
  79. package/dist/twins/packs/github/index.mjs +1 -1
  80. package/dist/twins/packs/googleads/NOTICE +1 -1
  81. package/dist/twins/packs/googlemaps/NOTICE +1 -1
  82. package/dist/twins/packs/googleoauth/NOTICE +1 -1
  83. package/dist/twins/packs/hackernews/NOTICE +1 -1
  84. package/dist/twins/packs/huggingface/NOTICE +1 -1
  85. package/dist/twins/packs/inngest/NOTICE +1 -1
  86. package/dist/twins/packs/inngest/index.mjs +1 -1
  87. package/dist/twins/packs/instagram/NOTICE +1 -1
  88. package/dist/twins/packs/jira/NOTICE +1 -1
  89. package/dist/twins/packs/langfuse/NOTICE +1 -1
  90. package/dist/twins/packs/linear/NOTICE +1 -1
  91. package/dist/twins/packs/linear/index.mjs +1 -1
  92. package/dist/twins/packs/linkedin/NOTICE +1 -1
  93. package/dist/twins/packs/livekit/NOTICE +1 -1
  94. package/dist/twins/packs/mailgun/NOTICE +1 -1
  95. package/dist/twins/packs/mapbox/NOTICE +1 -1
  96. package/dist/twins/packs/merge/NOTICE +1 -1
  97. package/dist/twins/packs/mistral/NOTICE +1 -1
  98. package/dist/twins/packs/mixpanel/NOTICE +1 -1
  99. package/dist/twins/packs/mongodb/NOTICE +1 -1
  100. package/dist/twins/packs/moonshot/NOTICE +1 -1
  101. package/dist/twins/packs/notion/NOTICE +1 -1
  102. package/dist/twins/packs/npm-registry/NOTICE +1 -1
  103. package/dist/twins/packs/oa-treasury/NOTICE +1 -1
  104. package/dist/twins/packs/openai/NOTICE +1 -1
  105. package/dist/twins/packs/openrouter/NOTICE +1 -1
  106. package/dist/twins/packs/openweather/NOTICE +1 -1
  107. package/dist/twins/packs/paypal/NOTICE +1 -1
  108. package/dist/twins/packs/pinecone/NOTICE +1 -1
  109. package/dist/twins/packs/plain/NOTICE +1 -1
  110. package/dist/twins/packs/plain/index.mjs +1 -1
  111. package/dist/twins/packs/planetscale/NOTICE +1 -1
  112. package/dist/twins/packs/polar/NOTICE +1 -1
  113. package/dist/twins/packs/polyhaven/NOTICE +1 -1
  114. package/dist/twins/packs/postmark/NOTICE +1 -1
  115. package/dist/twins/packs/reddit/NOTICE +1 -1
  116. package/dist/twins/packs/redis/NOTICE +1 -1
  117. package/dist/twins/packs/replicate/NOTICE +1 -1
  118. package/dist/twins/packs/resend/NOTICE +1 -1
  119. package/dist/twins/packs/runhuman/NOTICE +1 -1
  120. package/dist/twins/packs/scrapecreators/NOTICE +1 -1
  121. package/dist/twins/packs/segment/NOTICE +1 -1
  122. package/dist/twins/packs/sendblue/NOTICE +1 -1
  123. package/dist/twins/packs/sendgrid/NOTICE +1 -1
  124. package/dist/twins/packs/sentry/NOTICE +1 -1
  125. package/dist/twins/packs/sigstore/NOTICE +1 -1
  126. package/dist/twins/packs/slack/NOTICE +1 -1
  127. package/dist/twins/packs/smtp/NOTICE +1 -1
  128. package/dist/twins/packs/snowflake/NOTICE +1 -1
  129. package/dist/twins/packs/stigg/NOTICE +1 -1
  130. package/dist/twins/packs/stigg/index.mjs +1 -1
  131. package/dist/twins/packs/stream/NOTICE +1 -1
  132. package/dist/twins/packs/stripe/NOTICE +1 -1
  133. package/dist/twins/packs/supabase/NOTICE +1 -1
  134. package/dist/twins/packs/supermemory/NOTICE +1 -1
  135. package/dist/twins/packs/svix/NOTICE +1 -1
  136. package/dist/twins/packs/tavily/NOTICE +1 -1
  137. package/dist/twins/packs/telegram/NOTICE +1 -1
  138. package/dist/twins/packs/temporal/NOTICE +1 -1
  139. package/dist/twins/packs/temporal/index.mjs +1 -1
  140. package/dist/twins/packs/tiktok/NOTICE +1 -1
  141. package/dist/twins/packs/tinybird/NOTICE +1 -1
  142. package/dist/twins/packs/togetherai/NOTICE +1 -1
  143. package/dist/twins/packs/tremendous/NOTICE +1 -1
  144. package/dist/twins/packs/tripo/NOTICE +1 -1
  145. package/dist/twins/packs/tunnel/NOTICE +1 -1
  146. package/dist/twins/packs/twelvelabs/NOTICE +1 -1
  147. package/dist/twins/packs/twilio/NOTICE +1 -1
  148. package/dist/twins/packs/twitch/NOTICE +1 -1
  149. package/dist/twins/packs/upstash/NOTICE +1 -1
  150. package/dist/twins/packs/upstashvector/NOTICE +1 -1
  151. package/dist/twins/packs/vercel/NOTICE +1 -1
  152. package/dist/twins/packs/veriff/NOTICE +1 -1
  153. package/dist/twins/packs/vgauth/NOTICE +1 -1
  154. package/dist/twins/packs/vital/NOTICE +1 -1
  155. package/dist/twins/packs/volteridentity/NOTICE +1 -1
  156. package/dist/twins/packs/webrisk/NOTICE +1 -1
  157. package/dist/twins/packs/worldlabs/NOTICE +1 -1
  158. package/dist/twins/packs/x/NOTICE +1 -1
  159. package/dist/twins/packs/xai/NOTICE +1 -1
  160. package/dist/twins/packs/xidentity/NOTICE +1 -1
  161. package/dist/twins/packs/xidentity/index.mjs +1 -1
  162. package/dist/twins/packs/youtube/NOTICE +1 -1
  163. package/dist/worker.js +1518 -180
  164. package/dist/world-host.js +797 -263
  165. package/package.json +2 -2
  166. package/dist/dashboard/assets/next/static/chunks/5663-403316746afad10e.js +0 -1
  167. package/dist/dashboard/assets/next/static/chunks/app/v2/page-3e86fffabfa87d88.js +0 -1
  168. package/dist/twins/engine/v2/chunks/OYLYKZGD.mjs +0 -2
  169. package/dist/twins/engine/v3/chunks/OYLYKZGD.mjs +0 -2
  170. /package/dist/dashboard/assets/next/static/{8f121VqXS9LLPMmYd1SRn → ztFPFZw3-M7E56BfRipIn}/_buildManifest.js +0 -0
  171. /package/dist/dashboard/assets/next/static/{8f121VqXS9LLPMmYd1SRn → ztFPFZw3-M7E56BfRipIn}/_ssgManifest.js +0 -0
@@ -10,6 +10,9 @@ function validApplicationClock(value) {
10
10
  const now = value.now;
11
11
  return typeof now === "string" && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z$/.test(now) && Number.isFinite(Date.parse(now)) && new Date(now).toISOString() === now;
12
12
  }
13
+ function applicationClockEvidence(clock) {
14
+ return clock ? { now: clock.now, scope: "date-wall-clock" } : void 0;
15
+ }
13
16
  function applicationClockHook(clock) {
14
17
  if (!clock) return "";
15
18
  if (!validApplicationClock(clock)) throw new Error("Invalid applicationClock");
@@ -32,6 +35,31 @@ var init_application_clock = __esm({
32
35
  }
33
36
  });
34
37
 
38
+ // src/runtime/twin-clock.ts
39
+ import { AsyncLocalStorage } from "async_hooks";
40
+ function withTwinClock(clock, action) {
41
+ if (clock !== void 0 && !validTwinClock(clock)) throw new Error("Invalid twin clock");
42
+ return context.run(clock?.now, action);
43
+ }
44
+ function twinNowMs(fallback) {
45
+ const now = context.getStore();
46
+ return now === void 0 ? fallback : Date.parse(now);
47
+ }
48
+ var validTwinClock, key, registry, context, twinNowSeconds, twinClockEvidence;
49
+ var init_twin_clock = __esm({
50
+ "src/runtime/twin-clock.ts"() {
51
+ "use strict";
52
+ init_application_clock();
53
+ validTwinClock = validApplicationClock;
54
+ key = /* @__PURE__ */ Symbol.for("agenttwin.twinClock.v1");
55
+ registry = globalThis;
56
+ context = registry[key] ?? new AsyncLocalStorage();
57
+ if (!registry[key]) Object.defineProperty(registry, key, { value: context });
58
+ twinNowSeconds = (fallback) => Math.floor(twinNowMs(fallback * 1e3) / 1e3);
59
+ twinClockEvidence = (clock) => clock ? { now: clock.now, scope: "twin-wall-clock" } : void 0;
60
+ }
61
+ });
62
+
35
63
  // src/runtime/request-source.ts
36
64
  import { mkdtemp, writeFile, readFile, rm, realpath } from "fs/promises";
37
65
  import { tmpdir } from "os";
@@ -50,7 +78,7 @@ async function createRequestSourceHook(app, spec, credentials, runtime) {
50
78
  const dir = await mkdtemp(join(tmpdir(), "agenttwin-source-hook-"));
51
79
  const path = join(dir, "hook.cjs");
52
80
  const violationsPath = join(dir, "blocked.jsonl");
53
- const config = { root: runtime?.root ?? await realpath(resolve(app)), files: spec.files, origins: Object.values(credentials).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials[r.service]])), routing: !!spec.fetchRoutes, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
81
+ const config = { root: runtime?.root ?? await realpath(resolve(app)), files: spec.files, origins: Object.values(credentials).map((c) => new URL(c.endpoint).origin), routes: Object.fromEntries((spec.fetchRoutes ?? []).map((r) => [r.origin, credentials[r.service]])), routing: !!spec.fetchRoutes, violationsFd: runtime?.violationsFd, stdioViolations: !!runtime?.stdioViolations, violationsPath: runtime?.violationsPath ?? violationsPath };
54
82
  const hook = applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
55
83
  ` + String.raw`
56
84
  const http=require('node:http'),https=require('node:https'),path=require('node:path'),{fileURLToPath}=require('node:url');
@@ -62,7 +90,7 @@ if(originalFetch)globalThis.fetch=async function(input,init){
62
90
  let url;try{url=new URL(typeof input==='string'||input instanceof URL?input:input.url);}catch{throw new Error('AgentTwin fetch requires an absolute URL');}
63
91
  const route=Object.hasOwn(config.routes,url.origin)?config.routes[url.origin]:undefined;
64
92
  if(config.routing&&!route&&!origins.has(url.origin)){
65
- if(!blockedOrigins.has(url.origin)&&blockedOrigins.size<100){blockedOrigins.add(url.origin);const violation={origin:url.origin.slice(0,2048),reason:'unmapped-fetch-origin'};if(config.stdioViolations)process.stdout.write('\n\x1eAGENTTWIN_FETCH_V1:'+JSON.stringify({kind:'violation',...violation})+'\n');else require('node:fs').appendFileSync(config.violationsPath,JSON.stringify(violation)+'\n');}
93
+ if(!blockedOrigins.has(url.origin)&&blockedOrigins.size<100){blockedOrigins.add(url.origin);const violation={origin:url.origin.slice(0,2048),reason:'unmapped-fetch-origin'};if(config.violationsFd!==undefined)require('node:fs').writeSync(config.violationsFd,JSON.stringify(violation)+'\n');else if(config.stdioViolations)process.stdout.write('\n\x1eAGENTTWIN_FETCH_V1:'+JSON.stringify({kind:'violation',...violation})+'\n');else require('node:fs').appendFileSync(config.violationsPath,JSON.stringify(violation)+'\n');}
66
94
  throw new Error('AgentTwin blocked fetch to an unmapped origin: '+url.origin);
67
95
  }
68
96
  if(!route&&!origins.has(url.origin))return originalFetch(input,init);
@@ -76,7 +104,7 @@ if(originalFetch)globalThis.fetch=async function(input,init){
76
104
  };
77
105
  const plainHttp={request:http.request,get:http.get};
78
106
  const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
79
- function blockNode(origin){if(!blockedOrigins.has(origin)&&blockedOrigins.size<100){blockedOrigins.add(origin);const violation={origin:origin.slice(0,2048),reason:'unmapped-http-origin'};if(config.stdioViolations)process.stdout.write('\n\x1eAGENTTWIN_FETCH_V1:'+JSON.stringify({kind:'violation',...violation})+'\n');else require('node:fs').appendFileSync(config.violationsPath,JSON.stringify(violation)+'\n');}throw new Error('AgentTwin blocked a request to an unmapped origin: '+origin);}
107
+ function blockNode(origin){if(!blockedOrigins.has(origin)&&blockedOrigins.size<100){blockedOrigins.add(origin);const violation={origin:origin.slice(0,2048),reason:'unmapped-http-origin'};if(config.violationsFd!==undefined)require('node:fs').writeSync(config.violationsFd,JSON.stringify(violation)+'\n');else if(config.stdioViolations)process.stdout.write('\n\x1eAGENTTWIN_FETCH_V1:'+JSON.stringify({kind:'violation',...violation})+'\n');else require('node:fs').appendFileSync(config.violationsPath,JSON.stringify(violation)+'\n');}throw new Error('AgentTwin blocked a request to an unmapped origin: '+origin);}
80
108
  // SDKs on node:http/https (Stripe, Slack via axios) reach mapped vendor origins only through their twin.
81
109
  function routeNode(method,route,url,options,index,args){
82
110
  const target=new URL(route.endpoint),headers={};
@@ -125,14 +153,14 @@ function nextId(rows2, prefix, sequence) {
125
153
  function chargeFor(intent, data, sequence) {
126
154
  const charges = data["/v1/charges"];
127
155
  if (!charges || intent.latest_charge) return;
128
- const charge = { id: nextId(charges, "ch", sequence), object: "charge", amount: intent.amount, amount_refunded: 0, currency: intent.currency, customer: intent.customer ?? null, payment_intent: intent.id, paid: true, refunded: false, status: "succeeded", created: 17e8, livemode: false };
156
+ const charge = { id: nextId(charges, "ch", sequence), object: "charge", amount: intent.amount, amount_refunded: 0, currency: intent.currency, customer: intent.customer ?? null, payment_intent: intent.id, paid: true, refunded: false, status: "succeeded", created: twinNowSeconds(17e8), livemode: false };
129
157
  charges.push(charge);
130
158
  intent.latest_charge = charge.id;
131
159
  }
132
160
  function metadataOf(params) {
133
- const entries = Object.entries(params).filter(([key]) => /^metadata\[[^\]]+\]$/.test(key));
161
+ const entries = Object.entries(params).filter(([key2]) => /^metadata\[[^\]]+\]$/.test(key2));
134
162
  if (params.metadata && typeof params.metadata === "object" && !Array.isArray(params.metadata)) return params.metadata;
135
- return Object.fromEntries(entries.map(([key, value]) => [key.slice(9, -1), String(value)]));
163
+ return Object.fromEntries(entries.map(([key2, value]) => [key2.slice(9, -1), String(value)]));
136
164
  }
137
165
  function refundOperation(method, id, params, data, sequence) {
138
166
  const collection = "/v1/refunds", refunds = data[collection], charges = data["/v1/charges"];
@@ -170,12 +198,12 @@ function refundOperation(method, id, params, data, sequence) {
170
198
  if (amount > remaining) return { ...stripeError(400, "amount_too_large", `Refund amount (${amount}) is greater than unrefunded amount on charge (${remaining})`, "amount"), collection };
171
199
  if (params.reason !== void 0 && !["duplicate", "fraudulent", "requested_by_customer"].includes(String(params.reason))) return { ...stripeError(400, "parameter_invalid", "reason must be duplicate, fraudulent or requested_by_customer", "reason"), collection };
172
200
  if (refunds.length >= 1e4) return { ...stripeError(429, "world_capacity", "World record capacity reached"), collection };
173
- const refund = { id: nextId(refunds, "re", sequence), object: "refund", amount, currency: charge.currency, charge: charge.id, payment_intent: charge.payment_intent ?? null, reason: params.reason ?? null, metadata: metadataOf(params), status: "succeeded", created: 17e8 };
201
+ const refund = { id: nextId(refunds, "re", sequence), object: "refund", amount, currency: charge.currency, charge: charge.id, payment_intent: charge.payment_intent ?? null, reason: params.reason ?? null, metadata: metadataOf(params), status: "succeeded", created: twinNowSeconds(17e8) };
174
202
  refunds.push(refund);
175
203
  charge.amount_refunded = Number(charge.amount_refunded ?? 0) + amount;
176
204
  charge.refunded = charge.amount_refunded === charge.amount;
177
205
  const events = data["/v1/events"];
178
- if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: 17e8, livemode: false, data: { object: structuredClone(charge) } });
206
+ if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: twinNowSeconds(17e8), livemode: false, data: { object: structuredClone(charge) } });
179
207
  return { status: 200, body: refund, collection, record: structuredClone(refund), operation: "write" };
180
208
  }
181
209
  function readOnlyOperation(method, resource, id, params, data) {
@@ -225,10 +253,10 @@ function stripeOperation(method, path, params, data, sequence) {
225
253
  return { status: payment === "pm_card_chargeDeclined" ? 402 : 200, body: payment === "pm_card_chargeDeclined" ? { error: { type: "card_error", code: "card_declined", decline_code: "generic_decline", message: "Your card was declined.", payment_intent: structuredClone(row) } } : row, collection, record: structuredClone(row), operation: "write" };
226
254
  }
227
255
  const form = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, v])), nested = {};
228
- for (const [key, value] of Object.entries(form)) {
229
- const m = /^([^[]+)((?:\[[^\]]*\])+)$/.exec(key);
256
+ for (const [key2, value] of Object.entries(form)) {
257
+ const m = /^([^[]+)((?:\[[^\]]*\])+)$/.exec(key2);
230
258
  if (!m) {
231
- nested[key] = value;
259
+ nested[key2] = value;
232
260
  continue;
233
261
  }
234
262
  const path2 = [m[1], ...[...m[2].matchAll(/\[([^\]]*)\]/g)].map((x) => x[1])];
@@ -242,7 +270,7 @@ function stripeOperation(method, path, params, data, sequence) {
242
270
  const prefix = resource === "customers" ? "cus" : "pi";
243
271
  let suffix = sequence;
244
272
  while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
245
- const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: 17e8, livemode: false };
273
+ const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: twinNowSeconds(17e8), livemode: false };
246
274
  if (resource === "customers") {
247
275
  if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
248
276
  Object.assign(created2, { email: null, name: null, description: null, metadata: {}, ...nested });
@@ -259,7 +287,7 @@ function stripeOperation(method, path, params, data, sequence) {
259
287
  }
260
288
  if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
261
289
  if (resource === "payment_intents") {
262
- for (const key of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key] !== void 0) created2[key] = nested[key];
290
+ for (const key2 of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key2] !== void 0) created2[key2] = nested[key2];
263
291
  }
264
292
  if (resource === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
265
293
  rows2.push(created2);
@@ -271,6 +299,7 @@ var stripeError;
271
299
  var init_stripe_adapter = __esm({
272
300
  "src/runtime/stripe-adapter.ts"() {
273
301
  "use strict";
302
+ init_twin_clock();
274
303
  stripeError = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
275
304
  }
276
305
  });
@@ -470,7 +499,7 @@ var init_composio_twin = __esm({
470
499
  "use strict";
471
500
  SEND = ["GMAIL_SEND_EMAIL", "GMAIL_SEND_MESSAGE"];
472
501
  object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
473
- known = (v, keys) => Object.keys(v).every((key) => keys.includes(key));
502
+ known = (v, keys) => Object.keys(v).every((key2) => keys.includes(key2));
474
503
  list = (v) => v === void 0 ? void 0 : typeof v === "string" && v.length <= 4096 ? v.split(",") : null;
475
504
  composioOperation = (method, path, params, _headers, data, sequence) => {
476
505
  const match = /^\/api\/v3(?:\.1)?\/(.+)$/.exec(path);
@@ -529,7 +558,7 @@ var init_google_oauth_twin = __esm({
529
558
  "src/runtime/google-oauth-twin.ts"() {
530
559
  "use strict";
531
560
  googleOAuthOperation = (method, path, params, headers, data, sequence) => {
532
- if (method !== "POST" || path !== "/token" || Object.keys(params).some((key) => !["client_id", "client_secret", "grant_type", "refresh_token"].includes(key)) || headers.dpop) return;
561
+ if (method !== "POST" || path !== "/token" || Object.keys(params).some((key2) => !["client_id", "client_secret", "grant_type", "refresh_token"].includes(key2)) || headers.dpop) return;
533
562
  const error = (status, code) => ({ status, collection: "/tokens", body: { error: code } });
534
563
  if (params.grant_type !== "refresh_token") return;
535
564
  if (typeof params.client_id !== "string" || typeof params.refresh_token !== "string" || !params.client_id || !params.refresh_token) return error(400, "invalid_request");
@@ -601,9 +630,9 @@ function githubOperation(method, path, params, _headers, data, sequence) {
601
630
  if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
602
631
  if (params.status !== void 0 && !["queued", "in_progress", "completed"].includes(String(params.status))) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "status", code: "invalid" }] });
603
632
  if (params.conclusion !== void 0 && !["success", "failure", "neutral", "cancelled", "skipped", "timed_out"].includes(String(params.conclusion))) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "conclusion", code: "invalid" }] });
604
- const run2 = { id: `github_at_${sequence}`, name: params.name, head_sha: params.head_sha, status: str(params.status) ?? (params.conclusion !== void 0 ? "completed" : "queued"), conclusion: params.conclusion === void 0 ? null : params.conclusion, repo, html_url: null, started_at: iso(), completed_at: params.conclusion === void 0 ? null : iso() };
605
- rows(data, "/check-runs").push(run2);
606
- return created("/check-runs", structuredClone(run2), run2);
633
+ const run3 = { id: `github_at_${sequence}`, name: params.name, head_sha: params.head_sha, status: str(params.status) ?? (params.conclusion !== void 0 ? "completed" : "queued"), conclusion: params.conclusion === void 0 ? null : params.conclusion, repo, html_url: null, started_at: iso(), completed_at: params.conclusion === void 0 ? null : iso() };
634
+ rows(data, "/check-runs").push(run3);
635
+ return created("/check-runs", structuredClone(run3), run3);
607
636
  }
608
637
  if (resource === "issues") {
609
638
  const inRepo = rows(data, "/issues").filter((r) => r.repo === repo);
@@ -980,7 +1009,7 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
980
1009
  if (method === "POST") {
981
1010
  if (Object.keys(params).some((k) => !["title", "text", "tags", "priority", "alert_type", "source"].includes(k))) return void 0;
982
1011
  if (typeof params.title !== "string" || !params.title || typeof params.text !== "string" || !params.text) return badRequest("/events", { errors: ["The value provided for parameter 'title' or 'text' is invalid"] });
983
- const event = { id: sequence, title: params.title, text: params.text, tags: Array.isArray(params.tags) ? structuredClone(params.tags) : [], priority: params.priority === void 0 ? "normal" : params.priority, alert_type: str(params.alert_type) ?? "info", source: str(params.source) ?? "agenttwin", date_happened: EPOCH, device_name: null, host: null, resource: `/api/v1/events/${sequence}`, url: null, status: "ok" };
1012
+ const event = { id: sequence, title: params.title, text: params.text, tags: Array.isArray(params.tags) ? structuredClone(params.tags) : [], priority: params.priority === void 0 ? "normal" : params.priority, alert_type: str(params.alert_type) ?? "info", source: str(params.source) ?? "agenttwin", date_happened: twinNowSeconds(EPOCH), device_name: null, host: null, resource: `/api/v1/events/${sequence}`, url: null, status: "ok" };
984
1013
  rows(data, "/events").push(event);
985
1014
  return { status: 200, body: { status: "ok", event: structuredClone(event) }, collection: "/events", record: structuredClone(event), operation: "write" };
986
1015
  }
@@ -1032,7 +1061,7 @@ function gmailOperation(method, path, params, _headers, data, sequence) {
1032
1061
  const mime = raw ? parseGmailRaw(raw) : void 0;
1033
1062
  if (mime && "error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
1034
1063
  const body = mime?.text ?? text ?? "";
1035
- const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body.slice(0, 100), payload: { mimeType: "text/plain", headers: mime?.headers ?? [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: mime?.encodedBody ?? body } }, sizeEstimate: mime?.bytes ?? body.length, internalDate: "1700000000000", historyId: String(17e8 + sequence) };
1064
+ const message = { id: `gmail_at_${sequence}`, threadId: str(params.threadId) ?? `gmail_at_${sequence}`, labelIds: ["SENT"], snippet: body.slice(0, 100), payload: { mimeType: "text/plain", headers: mime?.headers ?? [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: mime?.encodedBody ?? body } }, sizeEstimate: mime?.bytes ?? body.length, internalDate: String(twinNowMs(17e11)), historyId: String(17e8 + sequence) };
1036
1065
  rowsIn(data, MESSAGES).push(message);
1037
1066
  return write(200, MESSAGES, structuredClone(message), message);
1038
1067
  }
@@ -1097,7 +1126,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
1097
1126
  if (timed && events.some((row) => !isObject(row.start) || !isObject(row.end) || !Number.isFinite(timestamp(row.start.dateTime)) || !Number.isFinite(timestamp(row.end.dateTime)))) return void 0;
1098
1127
  if (timed) events = events.filter((row) => timestamp(row.end.dateTime) > lower && timestamp(row.start.dateTime) < upper);
1099
1128
  if (params.orderBy === "startTime") events = [...events].sort((a, b) => timestamp(a.start.dateTime) - timestamp(b.start.dateTime));
1100
- const query = Object.fromEntries(Object.entries(params).filter(([key]) => key !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
1129
+ const query = Object.fromEntries(Object.entries(params).filter(([key2]) => key2 !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
1101
1130
  const fingerprint = sha(JSON.stringify({ query, events })).slice(0, 20);
1102
1131
  let offset = 0;
1103
1132
  if (params.pageToken !== void 0) {
@@ -1391,12 +1420,13 @@ var EPOCH, iso, sha, detUuid, rows, notFound, badRequest, ok, created, write, is
1391
1420
  var init_rest_adapters = __esm({
1392
1421
  "src/runtime/rest-adapters.ts"() {
1393
1422
  "use strict";
1423
+ init_twin_clock();
1394
1424
  init_llm_adapter();
1395
1425
  init_composio_twin();
1396
1426
  init_google_oauth_twin();
1397
1427
  init_gmail_mime();
1398
1428
  EPOCH = 17e8;
1399
- iso = (epoch = EPOCH) => new Date(epoch * 1e3).toISOString();
1429
+ iso = (epoch = EPOCH) => new Date(twinNowMs(epoch * 1e3)).toISOString();
1400
1430
  sha = (value) => createHash2("sha256").update(value).digest("hex");
1401
1431
  detUuid = (seed) => {
1402
1432
  const hex = sha(seed).slice(0, 32).split("");
@@ -1418,9 +1448,9 @@ var init_rest_adapters = __esm({
1418
1448
  const limit = params.limit === void 0 ? limitDefault : Number(params.limit);
1419
1449
  return { limit };
1420
1450
  };
1421
- uniqueId = (existing, base, key = "id") => {
1451
+ uniqueId = (existing, base, key2 = "id") => {
1422
1452
  let candidate = base;
1423
- while (existing.some((r) => r[key] === String(candidate))) candidate++;
1453
+ while (existing.some((r) => r[key2] === String(candidate))) candidate++;
1424
1454
  return String(candidate);
1425
1455
  };
1426
1456
  boundedInt = (value, min, max) => {
@@ -1636,9 +1666,9 @@ function fakeValue(schema, name, stream, depth = 0, sequence = 0) {
1636
1666
  if (type === "object") {
1637
1667
  if (depth > 3 || schema["x-recursive"]) return {};
1638
1668
  const out = {};
1639
- for (const [key, child] of Object.entries(schema.properties ?? {})) {
1640
- const v = fakeValue(child, key, stream, depth + 1, sequence);
1641
- if (v !== void 0) out[key] = v;
1669
+ for (const [key2, child] of Object.entries(schema.properties ?? {})) {
1670
+ const v = fakeValue(child, key2, stream, depth + 1, sequence);
1671
+ if (v !== void 0) out[key2] = v;
1642
1672
  }
1643
1673
  return out;
1644
1674
  }
@@ -1682,13 +1712,14 @@ var tierLabel, FIRST, LAST, COMPANY, WORDS, twinClock, streamFor, normName, sing
1682
1712
  var init_model = __esm({
1683
1713
  "src/runtime/compiler/model.ts"() {
1684
1714
  "use strict";
1715
+ init_twin_clock();
1685
1716
  init_seed();
1686
1717
  tierLabel = (twin) => `${twin.tier} (${twin.fidelity}: ${twin.source.kind}${twin.source.license ? `, ${twin.source.license}` : ""})`;
1687
1718
  FIRST = ["Avery", "Jordan", "Riley", "Morgan", "Casey", "Quinn", "Harper", "Rowan", "Emerson", "Sage"];
1688
1719
  LAST = ["Chen", "Patel", "Okafor", "Silva", "Novak", "Haddad", "Larsen", "Moreau", "Kim", "Rossi"];
1689
1720
  COMPANY = ["Northwind", "Globex", "Initech", "Umbrella Labs", "Acme Freight", "Vandelay", "Hooli", "Soylent", "Stark Supply", "Wayne Analytics"];
1690
1721
  WORDS = ["renewal", "onboarding", "enterprise plan", "pilot", "expansion", "support", "quarterly review", "migration", "integration", "upgrade"];
1691
- twinClock = (sequence) => new Date(Date.UTC(2026, 0, 5, 9, 0, 0) + sequence * 6e4);
1722
+ twinClock = (sequence) => new Date(twinNowMs(Date.UTC(2026, 0, 5, 9, 0, 0) + sequence * 6e4));
1692
1723
  streamFor = (seed, purpose) => new SeedStream(normalizeSeed(seed ?? "42"), purpose);
1693
1724
  normName = (s) => s.toLowerCase().replace(/[^a-z0-9]/g, "");
1694
1725
  singular = (s) => s.replace(/ies$/, "y").replace(/(sses|xes|ches|shes)$/, (m) => m.slice(0, -2)).replace(/([^s])s$/, "$1");
@@ -1728,13 +1759,13 @@ function materialize(schema, mode, stream, sequence, name = "", depth = 0) {
1728
1759
  function overlay(target, input, schema, merge) {
1729
1760
  const props = schema?.properties ?? {};
1730
1761
  for (const [k, v] of Object.entries(input)) {
1731
- const key = Object.hasOwn(props, k) ? k : Object.keys(props).find((p) => normName(p) === normName(k)) ?? k;
1732
- const child = props[key];
1733
- if (isObj(v) && isObj(target[key]) && merge) {
1734
- const next = structuredClone(target[key]);
1762
+ const key2 = Object.hasOwn(props, k) ? k : Object.keys(props).find((p) => normName(p) === normName(k)) ?? k;
1763
+ const child = props[key2];
1764
+ if (isObj(v) && isObj(target[key2]) && merge) {
1765
+ const next = structuredClone(target[key2]);
1735
1766
  overlay(next, v, child, true);
1736
- target[key] = next;
1737
- } else target[key] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
1767
+ target[key2] = next;
1768
+ } else target[key2] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
1738
1769
  }
1739
1770
  }
1740
1771
  function newId(resource, rows2, stream) {
@@ -2124,10 +2155,10 @@ var init_packs = __esm({
2124
2155
 
2125
2156
  // src/runtime/enterprise-twins.ts
2126
2157
  import { createHash as createHash4 } from "crypto";
2127
- function eqFilter(expression, quote) {
2158
+ function eqFilter(expression, quote2) {
2128
2159
  const parts = expression.split(/\s+and\s+/i), tests = [];
2129
2160
  for (const part of parts) {
2130
- const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote}([^${quote}]*)${quote}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
2161
+ const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote2}([^${quote2}]*)${quote2}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
2131
2162
  if (!m) return null;
2132
2163
  const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
2133
2164
  tests.push((r) => {
@@ -2147,7 +2178,7 @@ function soql(q) {
2147
2178
  const value = c[3] !== void 0 ? c[3].replace(/\\(.)/g, "$1") : c[4].toLowerCase() === "null" ? null : /^(true|false)$/i.test(c[4]) ? c[4].toLowerCase() === "true" : Number(c[4]);
2148
2179
  const field = c[1].toLowerCase();
2149
2180
  tests.push((r) => {
2150
- const k = Object.keys(r).find((key) => key.toLowerCase() === field);
2181
+ const k = Object.keys(r).find((key2) => key2.toLowerCase() === field);
2151
2182
  const equal = (k ? r[k] : null) === value;
2152
2183
  return c[2] === "=" ? equal : !equal;
2153
2184
  });
@@ -2175,10 +2206,11 @@ var ENTERPRISE_ADAPTERS, isEnterpriseAdapter, EPOCH2, iso2, hash, isObject2, sca
2175
2206
  var init_enterprise_twins = __esm({
2176
2207
  "src/runtime/enterprise-twins.ts"() {
2177
2208
  "use strict";
2209
+ init_twin_clock();
2178
2210
  ENTERPRISE_ADAPTERS = ["salesforce", "servicenow", "workday", "sap", "microsoft-teams", "outlook", "entra-id", "okta", "confluence", "sharepoint", "snowflake", "netsuite", "pagerduty"];
2179
2211
  isEnterpriseAdapter = (name) => ENTERPRISE_ADAPTERS.includes(name);
2180
2212
  EPOCH2 = 17e8;
2181
- iso2 = (sequence) => new Date((EPOCH2 + sequence) * 1e3).toISOString();
2213
+ iso2 = (sequence) => new Date(twinNowMs((EPOCH2 + sequence) * 1e3)).toISOString();
2182
2214
  hash = (seed) => createHash4("sha256").update(seed).digest("hex");
2183
2215
  isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
2184
2216
  scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
@@ -2191,7 +2223,7 @@ var init_enterprise_twins = __esm({
2191
2223
  const n = Number(value);
2192
2224
  return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
2193
2225
  };
2194
- nextNumber = (rows2, key, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
2226
+ nextNumber = (rows2, key2, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key2] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
2195
2227
  header2 = (headers, name) => {
2196
2228
  const v = headers[name];
2197
2229
  return Array.isArray(v) ? v[0] : v;
@@ -2345,11 +2377,11 @@ var init_enterprise_twins = __esm({
2345
2377
  sap = (method, path, body, query, headers, data, sequence) => {
2346
2378
  const m = /^\/sap\/opu\/odata\/sap\/(API_BUSINESS_PARTNER|API_SALES_ORDER_SRV)\/(A_BusinessPartner|A_SalesOrder)(?:\('([^']{1,20})'\))?$/.exec(path);
2347
2379
  if (!m || SAP_SETS[m[2]].service !== m[1]) return;
2348
- const [, , set, key] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
2380
+ const [, , set, key2] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
2349
2381
  if (method === "GET") {
2350
2382
  const issued = header2(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
2351
- if (key) {
2352
- const record3 = rows2.find((r) => r[SAP_SETS[set].key] === key);
2383
+ if (key2) {
2384
+ const record3 = rows2.find((r) => r[SAP_SETS[set].key] === key2);
2353
2385
  return record3 ? read(collection, { d: sapView(set, record3) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
2354
2386
  }
2355
2387
  const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
@@ -2358,10 +2390,10 @@ var init_enterprise_twins = __esm({
2358
2390
  return read(collection, { d: { results: rows2.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
2359
2391
  }
2360
2392
  if (header2(headers, "x-csrf-token") !== csrf) return { ...sapError(403, "403", "CSRF token validation failed", { "x-csrf-token": "Required" }), collection };
2361
- if (method === "POST" && !key) {
2393
+ if (method === "POST" && !key2) {
2362
2394
  if (set === "A_BusinessPartner") {
2363
2395
  if (!flat(body) || !["1", "2"].includes(String(body.BusinessPartnerCategory))) return { ...sapError(400, "R11/005", "Enter a valid business partner category (1 = person, 2 = organization)"), collection };
2364
- const record4 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`, BusinessPartnerIsBlocked: false };
2396
+ const record4 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
2365
2397
  rows2.push(record4);
2366
2398
  return write2(collection, record4, { d: sapView(set, record4) }, 201);
2367
2399
  }
@@ -2376,14 +2408,14 @@ var init_enterprise_twins = __esm({
2376
2408
  TransactionCurrency: body.TransactionCurrency ?? "USD",
2377
2409
  TotalNetAmount: total.toFixed(2),
2378
2410
  OverallSDProcessStatus: "A",
2379
- CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`,
2411
+ CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`,
2380
2412
  to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
2381
2413
  };
2382
2414
  rows2.push(record3);
2383
2415
  return write2(collection, record3, { d: sapView(set, record3) }, 201);
2384
2416
  }
2385
- const record2 = key ? rows2.find((r) => r[SAP_SETS[set].key] === key) : void 0;
2386
- if (!record2) return key ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
2417
+ const record2 = key2 ? rows2.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
2418
+ if (!record2) return key2 ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
2387
2419
  if (method === "PATCH" || method === "MERGE") {
2388
2420
  if (!flat(body) || SAP_SETS[set].key in body) return;
2389
2421
  Object.assign(record2, body);
@@ -2419,7 +2451,7 @@ var init_enterprise_twins = __esm({
2419
2451
  if (body.body.contentType !== void 0 && !["text", "html"].includes(body.body.contentType)) return;
2420
2452
  if (parentId && !messages.some((r) => scope(r) && r.id === parentId)) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
2421
2453
  const record2 = {
2422
- id: String((EPOCH2 + sequence) * 1e3 + messages.length),
2454
+ id: String(twinNowMs((EPOCH2 + sequence) * 1e3) + messages.length),
2423
2455
  replyToId: parentId ?? null,
2424
2456
  messageType: "message",
2425
2457
  createdDateTime: iso2(sequence),
@@ -2489,8 +2521,8 @@ var init_enterprise_twins = __esm({
2489
2521
  const m = /^\/v1\.0\/(users|groups)(?:\/([^/]+))?(?:\/members(?:\/([\w-]+))?(\/\$ref)?)?$/.exec(path);
2490
2522
  if (!m) return;
2491
2523
  const [, kind, rawKey, memberId, ref] = m, users = table(data, "/users"), groups2 = table(data, "/groups"), members = table(data, "/groupMembers");
2492
- const key = rawKey && decodeURIComponent(rawKey), membersRoute = path.includes("/members");
2493
- if (kind === "users" && !key) {
2524
+ const key2 = rawKey && decodeURIComponent(rawKey), membersRoute = path.includes("/members");
2525
+ if (kind === "users" && !key2) {
2494
2526
  if (method === "GET") {
2495
2527
  const page = graphPage(users, query);
2496
2528
  return page ? read("/users", { value: page }) : void 0;
@@ -2506,13 +2538,13 @@ var init_enterprise_twins = __esm({
2506
2538
  users.push(record2);
2507
2539
  return write2("/users", record2, record2, 201);
2508
2540
  }
2509
- if (kind === "groups" && !key && method === "GET") {
2541
+ if (kind === "groups" && !key2 && method === "GET") {
2510
2542
  const page = graphPage(groups2, query);
2511
2543
  return page ? read("/groups", { value: page }) : void 0;
2512
2544
  }
2513
2545
  if (kind === "users") {
2514
- const user = users.find((u) => u.id === key || String(u.userPrincipalName).toLowerCase() === String(key).toLowerCase());
2515
- if (!user) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${key}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/users" };
2546
+ const user = users.find((u) => u.id === key2 || String(u.userPrincipalName).toLowerCase() === String(key2).toLowerCase());
2547
+ if (!user) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${key2}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/users" };
2516
2548
  if (membersRoute) return;
2517
2549
  if (method === "GET") return read("/users", user);
2518
2550
  if (method === "PATCH") {
@@ -2527,8 +2559,8 @@ var init_enterprise_twins = __esm({
2527
2559
  }
2528
2560
  return;
2529
2561
  }
2530
- const group = groups2.find((g) => g.id === key);
2531
- if (!group) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${key}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/groups" };
2562
+ const group = groups2.find((g) => g.id === key2);
2563
+ if (!group) return { ...graphError(404, "Request_ResourceNotFound", `Resource '${key2}' does not exist or one of its queried reference-property objects are not present.`, sequence), collection: "/groups" };
2532
2564
  if (!membersRoute) return method === "GET" ? read("/groups", group) : void 0;
2533
2565
  if (method === "GET" && !memberId && !ref) return read("/groupMembers", { value: members.filter((l) => l.groupId === group.id).map((l) => users.find((u) => u.id === l.userId)).filter(Boolean).map((u) => ({ "@odata.type": "#microsoft.graph.user", ...u })) });
2534
2566
  if (method === "POST" && !memberId && ref) {
@@ -2552,9 +2584,9 @@ var init_enterprise_twins = __esm({
2552
2584
  const m = /^\/api\/v1\/(users|groups)(?:\/([^/]+))?(?:\/(users)(?:\/([\w]+))?|\/lifecycle\/(activate|deactivate|suspend|unsuspend))?$/.exec(path);
2553
2585
  if (!m) return;
2554
2586
  const [, kind, rawKey, groupUsers, memberId, lifecycle] = m, users = table(data, "/users"), groups2 = table(data, "/groups"), memberships = table(data, "/groupMemberships");
2555
- const key = rawKey && decodeURIComponent(rawKey);
2587
+ const key2 = rawKey && decodeURIComponent(rawKey);
2556
2588
  const notFound2 = (what, type) => ({ ...oktaError(404, "E0000007", `Not found: Resource not found: ${what} (${type})`), collection: `/${kind}` });
2557
- if (kind === "users" && !key) {
2589
+ if (kind === "users" && !key2) {
2558
2590
  if (method === "GET") {
2559
2591
  const limit = limitOf(query.limit, 200, 200);
2560
2592
  if (limit === null) return;
@@ -2581,13 +2613,13 @@ var init_enterprise_twins = __esm({
2581
2613
  users.push(record2);
2582
2614
  return write2("/users", record2, record2);
2583
2615
  }
2584
- if (kind === "groups" && !key && method === "GET") {
2616
+ if (kind === "groups" && !key2 && method === "GET") {
2585
2617
  const q = query.q?.toLowerCase();
2586
2618
  return read("/groups", groups2.filter((g) => !q || String(g.profile?.name ?? "").toLowerCase().startsWith(q)));
2587
2619
  }
2588
2620
  if (kind === "users") {
2589
- const user = users.find((u) => u.id === key || String(u.profile?.login).toLowerCase() === String(key).toLowerCase());
2590
- if (!user) return notFound2(String(key), "User");
2621
+ const user = users.find((u) => u.id === key2 || String(u.profile?.login).toLowerCase() === String(key2).toLowerCase());
2622
+ if (!user) return notFound2(String(key2), "User");
2591
2623
  if (lifecycle && method === "POST") {
2592
2624
  const from = user.status;
2593
2625
  const to = lifecycle === "activate" ? ["STAGED", "PROVISIONED", "DEPROVISIONED"].includes(from) ? "ACTIVE" : null : lifecycle === "deactivate" ? from !== "DEPROVISIONED" ? "DEPROVISIONED" : null : lifecycle === "suspend" ? from === "ACTIVE" ? "SUSPENDED" : null : from === "SUSPENDED" ? "ACTIVE" : null;
@@ -2614,8 +2646,8 @@ var init_enterprise_twins = __esm({
2614
2646
  }
2615
2647
  return;
2616
2648
  }
2617
- const group = groups2.find((g) => g.id === key);
2618
- if (!group) return notFound2(String(key), "UserGroup");
2649
+ const group = groups2.find((g) => g.id === key2);
2650
+ if (!group) return notFound2(String(key2), "UserGroup");
2619
2651
  if (!groupUsers) return method === "GET" && !lifecycle ? read("/groups", group) : void 0;
2620
2652
  if (!memberId && method === "GET") return read("/groupMemberships", memberships.filter((l) => l.groupId === group.id).map((l) => users.find((u) => u.id === l.userId)).filter(Boolean));
2621
2653
  if (!memberId) return;
@@ -2772,7 +2804,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
2772
2804
  sqlState: "00000",
2773
2805
  statementHandle: handle,
2774
2806
  message: "Statement executed successfully.",
2775
- createdOn: (EPOCH2 + sequence) * 1e3
2807
+ createdOn: twinNowMs((EPOCH2 + sequence) * 1e3)
2776
2808
  });
2777
2809
  const remember = (collection, res, operation, record2) => {
2778
2810
  log.push({ statementHandle: handle, statement, result: res, createdOn: iso2(sequence) });
@@ -2888,8 +2920,8 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
2888
2920
  pdId = (seed) => "P" + hash(seed).replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 6);
2889
2921
  pagerduty = (method, path, body, query, headers, data, sequence) => {
2890
2922
  const services = table(data, "/services"), incidents = table(data, "/incidents"), notes = table(data, "/notes"), events = table(data, "/events");
2891
- const open = (serviceId, key) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key && i.status !== "resolved");
2892
- const create = (service, title, urgency, key, details) => {
2923
+ const open = (serviceId, key2) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key2 && i.status !== "resolved");
2924
+ const create = (service, title, urgency, key2, details) => {
2893
2925
  const id2 = pdId(`pd:incident:${sequence}:${incidents.length}`);
2894
2926
  const record2 = {
2895
2927
  id: id2,
@@ -2901,7 +2933,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
2901
2933
  urgency,
2902
2934
  created_at: iso2(sequence),
2903
2935
  updated_at: iso2(sequence),
2904
- incident_key: key,
2936
+ incident_key: key2,
2905
2937
  service: { id: service.id, type: "service_reference", summary: service.name },
2906
2938
  html_url: `https://contoso.pagerduty.test/incidents/${id2}`,
2907
2939
  ...details === void 0 ? {} : { body: { type: "incident_body", details } }
@@ -2917,13 +2949,13 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
2917
2949
  if (action === "trigger" && !(isObject2(payload) && payload.summary && payload.source && ["critical", "error", "warning", "info"].includes(payload.severity)))
2918
2950
  return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'payload.summary', 'payload.source' and 'payload.severity' are required"] } };
2919
2951
  if (action !== "trigger" && !body.dedup_key) return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'dedup_key' is required for acknowledge and resolve"] } };
2920
- const key = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
2921
- const existing = open(service.id, key);
2922
- if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key, payload.custom_details);
2952
+ const key2 = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
2953
+ const existing = open(service.id, key2);
2954
+ if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key2, payload.custom_details);
2923
2955
  if (action !== "trigger" && existing) Object.assign(existing, { status: action === "acknowledge" ? "acknowledged" : "resolved", updated_at: iso2(sequence) });
2924
- const event = { id: hash(`pd:event:${sequence}:${events.length}`).slice(0, 24), service: service.id, event_action: action, dedup_key: key, grouped: action === "trigger" && !!existing, summary: isObject2(payload) ? payload.summary ?? null : null, received_at: iso2(sequence) };
2956
+ const event = { id: hash(`pd:event:${sequence}:${events.length}`).slice(0, 24), service: service.id, event_action: action, dedup_key: key2, grouped: action === "trigger" && !!existing, summary: isObject2(payload) ? payload.summary ?? null : null, received_at: iso2(sequence) };
2925
2957
  events.push(event);
2926
- return write2("/events", event, { status: "success", message: "Event processed", dedup_key: key }, 202);
2958
+ return write2("/events", event, { status: "success", message: "Event processed", dedup_key: key2 }, 202);
2927
2959
  }
2928
2960
  const m = /^\/(incidents|services)(?:\/(\w+))?(?:\/(notes))?$/.exec(path);
2929
2961
  if (!m) return;
@@ -3113,6 +3145,7 @@ function parseWorld(value) {
3113
3145
  if (!Number.isInteger(v.timeoutSeconds) || Number(v.timeoutSeconds) < 1 || Number(v.timeoutSeconds) > 300) invalid("timeoutSeconds must be 1\u2013300");
3114
3146
  if (v.workflowId !== void 0 && (typeof v.workflowId !== "string" || !v.workflowId)) invalid("workflowId must be a nonempty string");
3115
3147
  if (v.sourceBuild !== void 0 && (typeof v.sourceBuild !== "string" || !/^[a-f0-9]{64}$/.test(v.sourceBuild))) invalid("sourceBuild must be a SHA-256 build-record digest");
3148
+ if (v.twinClock !== void 0 && !validTwinClock(v.twinClock)) invalid("twinClock requires only now as a canonical UTC timestamp with milliseconds");
3116
3149
  if (v.applicationClock !== void 0 && !validApplicationClock(v.applicationClock)) invalid("applicationClock requires only now as a canonical UTC timestamp with milliseconds");
3117
3150
  if (!Array.isArray(v.services) || !v.services.length || v.services.length > 10) invalid("services must contain 1\u201310 HTTP services");
3118
3151
  const services = /* @__PURE__ */ new Map();
@@ -3266,7 +3299,7 @@ function parseWorld(value) {
3266
3299
  origins.add(mapping.origin);
3267
3300
  }
3268
3301
  }
3269
- const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "files", "command", "timeoutSeconds", "browser", "background", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
3302
+ const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "twinClock", "files", "command", "timeoutSeconds", "browser", "background", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
3270
3303
  if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
3271
3304
  return v;
3272
3305
  }
@@ -3274,6 +3307,7 @@ var RUNTIMES, ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PR
3274
3307
  var init_spec = __esm({
3275
3308
  "src/runtime/spec.ts"() {
3276
3309
  "use strict";
3310
+ init_twin_clock();
3277
3311
  init_postgres_clock();
3278
3312
  init_adapters();
3279
3313
  init_packs();
@@ -3392,7 +3426,7 @@ var init_pack_log = __esm({
3392
3426
  import { createServer } from "http";
3393
3427
  import { isDeepStrictEqual } from "util";
3394
3428
  import { createHash as createHash5 } from "crypto";
3395
- import { AsyncLocalStorage } from "async_hooks";
3429
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
3396
3430
  import { mkdir, mkdtemp as mkdtemp2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
3397
3431
  import { tmpdir as tmpdir2 } from "os";
3398
3432
  import { join as join4 } from "path";
@@ -3400,6 +3434,7 @@ var idempotencyKeyDigest, HttpWorld;
3400
3434
  var init_http_world = __esm({
3401
3435
  "src/runtime/http-world.ts"() {
3402
3436
  "use strict";
3437
+ init_twin_clock();
3403
3438
  init_request_source();
3404
3439
  init_stripe_adapter();
3405
3440
  init_rest_adapters();
@@ -3409,13 +3444,14 @@ var init_http_world = __esm({
3409
3444
  init_adapters();
3410
3445
  init_packs();
3411
3446
  init_pack_log();
3412
- idempotencyKeyDigest = (key) => typeof key === "string" && key ? `sha256:${createHash5("sha256").update(key).digest("hex").slice(0, 16)}` : void 0;
3447
+ idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash5("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
3413
3448
  HttpWorld = class {
3414
3449
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
3415
3450
  constructor(spec, seed, options = {}) {
3416
3451
  this.spec = spec;
3417
3452
  this.options = options;
3418
3453
  this.seed = normalizeSeed(seed);
3454
+ this.twinClock = spec.twinClock ? Object.freeze({ ...spec.twinClock }) : void 0;
3419
3455
  }
3420
3456
  spec;
3421
3457
  options;
@@ -3425,6 +3461,7 @@ var init_http_world = __esm({
3425
3461
  unsupported = [];
3426
3462
  /** The run seed that governed every seeded twin-side decision in this world instance. */
3427
3463
  seed;
3464
+ twinClock;
3428
3465
  servers = [];
3429
3466
  timers = /* @__PURE__ */ new Set();
3430
3467
  fired = false;
@@ -3432,15 +3469,15 @@ var init_http_world = __esm({
3432
3469
  candidateCounts = /* @__PURE__ */ new Map();
3433
3470
  epoch = 0;
3434
3471
  replayKeys = /* @__PURE__ */ new Map();
3435
- sourceContext = new AsyncLocalStorage();
3472
+ sourceContext = new AsyncLocalStorage2();
3436
3473
  record(service, operation, path, detail, record2) {
3437
3474
  if (this.events.length >= 5e4) return;
3438
3475
  const source = this.sourceContext.getStore();
3439
3476
  this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record2 ? { record: structuredClone(record2) } : {}, ...source ? { source } : {} });
3440
3477
  }
3441
3478
  /** Tags the event just recorded with the request's idempotency key digest. */
3442
- keyed(key) {
3443
- const digest2 = idempotencyKeyDigest(key), last = this.events[this.events.length - 1];
3479
+ keyed(key2) {
3480
+ const digest2 = idempotencyKeyDigest(key2), last = this.events[this.events.length - 1];
3444
3481
  if (digest2 && last) last.idempotencyKey = digest2;
3445
3482
  }
3446
3483
  rejectUnsupported(service, method, path, detail) {
@@ -3448,12 +3485,23 @@ var init_http_world = __esm({
3448
3485
  this.record(service, "unsupported", path, detail);
3449
3486
  }
3450
3487
  /** Seeded fault scheduling: the k-th matched request of the fault's scope is faulted iff the seeded draw picked ordinal k. */
3451
- candidateIndex(key) {
3452
- const next = this.candidateCounts.get(key) ?? 0;
3453
- this.candidateCounts.set(key, next + 1);
3488
+ candidateIndex(key2) {
3489
+ const next = this.candidateCounts.get(key2) ?? 0;
3490
+ this.candidateCounts.set(key2, next + 1);
3454
3491
  return next;
3455
3492
  }
3456
- async start() {
3493
+ start() {
3494
+ if (this.servers.length) return Promise.reject(new Error("World is already started"));
3495
+ return withTwinClock(this.twinClock, async () => {
3496
+ try {
3497
+ return await this.startWithClock();
3498
+ } catch (error) {
3499
+ await this.close();
3500
+ throw error;
3501
+ }
3502
+ });
3503
+ }
3504
+ async startWithClock() {
3457
3505
  if (this.servers.length) throw new Error("World is already started");
3458
3506
  const fault = this.spec.fault;
3459
3507
  for (const service of this.spec.services) {
@@ -3479,7 +3527,7 @@ var init_http_world = __esm({
3479
3527
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
3480
3528
  continue;
3481
3529
  }
3482
- const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3530
+ const server = createServer((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3483
3531
  const epoch = this.epoch;
3484
3532
  const send = (code, body, headers = {}) => {
3485
3533
  if (!res.destroyed) {
@@ -3577,7 +3625,7 @@ var init_http_world = __esm({
3577
3625
  }
3578
3626
  const url = new URL(req.url ?? "/", "http://localhost");
3579
3627
  let path = url.pathname;
3580
- if (service.adapter === "composio" && [...url.searchParams.keys()].some((key2) => url.searchParams.getAll(key2).length !== 1)) {
3628
+ if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
3581
3629
  this.rejectUnsupported(service.name, req.method ?? "", path, "Repeated query parameters are unsupported");
3582
3630
  respond(501, restUnsupportedBody("composio"));
3583
3631
  return;
@@ -3608,9 +3656,9 @@ var init_http_world = __esm({
3608
3656
  else if (mode === "form") {
3609
3657
  const form = new URLSearchParams(text);
3610
3658
  parsed = {};
3611
- for (const key2 of new Set(form.keys())) {
3612
- const all = form.getAll(key2);
3613
- parsed[key2] = all.length > 1 ? all : all[0];
3659
+ for (const key3 of new Set(form.keys())) {
3660
+ const all = form.getAll(key3);
3661
+ parsed[key3] = all.length > 1 ? all : all[0];
3614
3662
  }
3615
3663
  } else if (mode === "raw") {
3616
3664
  rawBody = text;
@@ -3621,7 +3669,7 @@ var init_http_world = __esm({
3621
3669
  return;
3622
3670
  }
3623
3671
  const form = new URLSearchParams(text);
3624
- if ([...form.keys()].some((key2) => form.getAll(key2).length !== 1)) {
3672
+ if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
3625
3673
  respond(400, { error: "invalid_request" });
3626
3674
  return;
3627
3675
  }
@@ -3646,9 +3694,9 @@ var init_http_world = __esm({
3646
3694
  if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
3647
3695
  const params = payload ?? Object.fromEntries(url.searchParams);
3648
3696
  const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
3649
- const key2 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
3697
+ const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
3650
3698
  const signature2 = JSON.stringify(params);
3651
- const previous2 = key2 ? keys.get(key2) : void 0;
3699
+ const previous2 = key3 ? keys.get(key3) : void 0;
3652
3700
  if (previous2) {
3653
3701
  if (previous2.body !== signature2) {
3654
3702
  respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
@@ -3672,8 +3720,8 @@ var init_http_world = __esm({
3672
3720
  this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
3673
3721
  this.keyed(keyHeader2);
3674
3722
  }
3675
- if (key2 && (result.status === 200 || result.status === 201 || enterprise && (result.status === 202 || result.status === 204))) keys.set(key2, { body: signature2, record: structuredClone(result.body), status: result.status, ...headers(result) ? { headers: headers(result) } : {} });
3676
- const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key2 && matchesFault(result.collection);
3723
+ if (key3 && (result.status === 200 || result.status === 201 || enterprise && (result.status === 202 || result.status === 204))) keys.set(key3, { body: signature2, record: structuredClone(result.body), status: result.status, ...headers(result) ? { headers: headers(result) } : {} });
3724
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key3 && matchesFault(result.collection);
3677
3725
  const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
3678
3726
  if (duplicate2) {
3679
3727
  const second = invoke(this.events.length + 1);
@@ -3749,9 +3797,9 @@ var init_http_world = __esm({
3749
3797
  return;
3750
3798
  }
3751
3799
  const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
3752
- const key = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
3800
+ const key2 = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
3753
3801
  const signature = JSON.stringify(body);
3754
- const previous = key ? keys.get(key) : void 0;
3802
+ const previous = key2 ? keys.get(key2) : void 0;
3755
3803
  if (previous) {
3756
3804
  if (previous.body !== signature) {
3757
3805
  respond(409, { error: "idempotency_conflict" });
@@ -3762,7 +3810,7 @@ var init_http_world = __esm({
3762
3810
  respondSlowly(path, "replay", 200, previous.record);
3763
3811
  return;
3764
3812
  }
3765
- const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
3813
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
3766
3814
  if (duplicate) this.faultActions++;
3767
3815
  let index = data[path].length + 1;
3768
3816
  while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
@@ -3770,7 +3818,7 @@ var init_http_world = __esm({
3770
3818
  if (slack) row.ts = `${index}.000001`;
3771
3819
  const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
3772
3820
  data[path].push(row);
3773
- if (key) keys.set(key, { body: signature, record: row });
3821
+ if (key2) keys.set(key2, { body: signature, record: row });
3774
3822
  this.record(service.name, "write", path, String(row.id), row);
3775
3823
  this.keyed(keyHeader);
3776
3824
  if (duplicate) {
@@ -3797,7 +3845,7 @@ var init_http_world = __esm({
3797
3845
  } catch {
3798
3846
  respond(500, { error: "world_request_error" });
3799
3847
  }
3800
- }));
3848
+ })));
3801
3849
  server.requestTimeout = 1e4;
3802
3850
  await new Promise((resolve7, reject) => {
3803
3851
  server.once("error", reject);
@@ -3818,9 +3866,10 @@ var init_http_world = __esm({
3818
3866
  */
3819
3867
  async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
3820
3868
  const name = service.adapter.slice(PACK_PREFIX.length), meta = packRecord(name);
3869
+ if (this.twinClock && packCatalog()?.engine[meta.generation]?.clockSupport !== "async-context-v1") throw new Error("Twin packs need rebuilding for per-run clock support");
3821
3870
  const root = await mkdtemp2(join4(tmpdir2(), `agenttwin-pack-${name}-`));
3822
3871
  this.packRoots.push(root);
3823
- const worldSeed = meta.logService ? JSON.stringify({ id: `twin:${meta.logService}:world_seed.record:seed:agenttwin`, service: meta.logService, op: "set", operation: "world_seed.record", subject: { type: "_world_seed", id: "seed" }, occurredAt: (/* @__PURE__ */ new Date()).toISOString(), actor: { kind: "system" }, fields: { value: new SeedStream(this.seed, `pack-world:${service.name}`).nextHex(64) } }) + "\n" : "";
3872
+ const worldSeed = meta.logService ? JSON.stringify({ id: `twin:${meta.logService}:world_seed.record:seed:agenttwin`, service: meta.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" : "";
3824
3873
  const writeSeedLog = async (dir, text) => {
3825
3874
  if (!text) return;
3826
3875
  await mkdir(join4(dir, ".volter/world", meta.logService), { recursive: true });
@@ -3841,7 +3890,7 @@ var init_http_world = __esm({
3841
3890
  }
3842
3891
  }
3843
3892
  const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
3844
- const seeded = meta.logService ? worldSeed + account + seedActions(meta.logService, service.collections, (/* @__PURE__ */ new Date()).toISOString(), tenant) : "";
3893
+ const seeded = meta.logService ? worldSeed + account + seedActions(meta.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
3845
3894
  await writeSeedLog(root, seeded);
3846
3895
  const twin = await (await loadPack(name))({ root });
3847
3896
  const baseHost = meta.hosts[0]?.host ?? `${name}.twin.test`;
@@ -3898,11 +3947,11 @@ var init_http_world = __esm({
3898
3947
  for (const collection of service.collections) data[collection.path] ??= [];
3899
3948
  let chain = Promise.resolve();
3900
3949
  const serialized = (fn) => {
3901
- const run2 = chain.then(fn, fn);
3902
- chain = run2.then(() => void 0, () => void 0);
3903
- return run2;
3950
+ const run3 = chain.then(fn, fn);
3951
+ chain = run3.then(() => void 0, () => void 0);
3952
+ return run3;
3904
3953
  };
3905
- const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3954
+ const server = createServer((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3906
3955
  const epoch = this.epoch;
3907
3956
  const send = (status, headers, body) => {
3908
3957
  if (!res.destroyed) {
@@ -4036,7 +4085,7 @@ var init_http_world = __esm({
4036
4085
  } catch {
4037
4086
  json(500, { error: "world_request_error" });
4038
4087
  }
4039
- }));
4088
+ })));
4040
4089
  server.requestTimeout = 1e4;
4041
4090
  await new Promise((resolve7, reject) => {
4042
4091
  server.once("error", reject);
@@ -4091,71 +4140,497 @@ var init_http_world = __esm({
4091
4140
  }
4092
4141
  });
4093
4142
 
4143
+ // src/runtime/application-process.ts
4144
+ import { execFile } from "child_process";
4145
+ import { promisify } from "util";
4146
+ import { win32 } from "path";
4147
+ async function processes() {
4148
+ if (process.platform === "win32") {
4149
+ const shell = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
4150
+ const script = "$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -gt 1 -and $_.CreationDate } | ForEach-Object { @{pid=[int]$_.ProcessId;parent=[int]$_.ParentProcessId;born=$_.CreationDate.ToUniversalTime().ToString('o');state='running'} }) | ConvertTo-Json -Compress";
4151
+ const { stdout: stdout2 } = await exec(shell, ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 1e3, windowsHide: true, maxBuffer: 4 * 1024 * 1024 });
4152
+ const data = JSON.parse(stdout2.trim() || "[]");
4153
+ const rows2 = Array.isArray(data) ? data : [data];
4154
+ if (!rows2.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
4155
+ return rows2;
4156
+ }
4157
+ const { stdout } = await exec("ps", ["-axo", "pid=,ppid=,stat=,lstart="], { timeout: 1e3, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } });
4158
+ return stdout.trim().split("\n").filter(Boolean).map((line) => {
4159
+ const [pid, parent, state, ...born] = line.trim().split(/\s+/);
4160
+ return { pid: Number(pid), parent: Number(parent), state, born: born.join(" ") };
4161
+ });
4162
+ }
4163
+ function manageApplication(child) {
4164
+ const known2 = /* @__PURE__ */ new Map();
4165
+ let scan = Promise.resolve();
4166
+ let scanError;
4167
+ let stopPromise;
4168
+ const exited = new Promise((resolve7, reject) => {
4169
+ child.once("exit", resolve7);
4170
+ child.once("error", reject);
4171
+ });
4172
+ void exited.catch(() => {
4173
+ });
4174
+ const closed = new Promise((resolve7) => {
4175
+ child.once("close", () => resolve7());
4176
+ child.once("error", () => resolve7());
4177
+ });
4178
+ async function capture() {
4179
+ const rows2 = await processes();
4180
+ for (const [pid, born] of known2) if (!rows2.some((r) => r.pid === pid && r.born === born)) known2.delete(pid);
4181
+ const root = rows2.find((r) => r.pid === child.pid);
4182
+ if (root && child.exitCode === null && child.signalCode === null) known2.set(root.pid, root.born);
4183
+ let changed = true;
4184
+ while (changed) {
4185
+ changed = false;
4186
+ for (const row of rows2) {
4187
+ if (row.pid > 1 && known2.has(row.parent) && !known2.has(row.pid)) {
4188
+ known2.set(row.pid, row.born);
4189
+ changed = true;
4190
+ }
4191
+ }
4192
+ }
4193
+ return rows2.filter((r) => known2.get(r.pid) === r.born && !r.state.startsWith("Z"));
4194
+ }
4195
+ let scanning = false;
4196
+ const tick = () => {
4197
+ if (scanning) return;
4198
+ scanning = true;
4199
+ scan = capture().then(() => {
4200
+ }, (e) => {
4201
+ scanError = e;
4202
+ }).finally(() => {
4203
+ scanning = false;
4204
+ });
4205
+ };
4206
+ tick();
4207
+ const monitor = setInterval(tick, 100);
4208
+ monitor.unref();
4209
+ function killRoot() {
4210
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
4211
+ try {
4212
+ process.platform === "win32" ? child.kill("SIGKILL") : process.kill(-child.pid, "SIGKILL");
4213
+ } catch {
4214
+ }
4215
+ }
4216
+ }
4217
+ async function terminate() {
4218
+ await scan;
4219
+ try {
4220
+ const targets = await capture();
4221
+ if (process.platform === "win32" && targets.length) {
4222
+ const exe = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "taskkill.exe");
4223
+ try {
4224
+ await exec(exe, [...targets.flatMap((t) => ["/PID", String(t.pid)]), "/T", "/F"], { timeout: 1e3, windowsHide: true });
4225
+ } catch {
4226
+ }
4227
+ } else {
4228
+ for (const target of targets.reverse()) try {
4229
+ process.kill(target.pid, "SIGKILL");
4230
+ } catch (e) {
4231
+ if (e.code !== "ESRCH") throw e;
4232
+ }
4233
+ }
4234
+ killRoot();
4235
+ const until = Date.now() + 2e3;
4236
+ while ((await capture()).length) {
4237
+ if (Date.now() >= until) throw Error("Application processes remain after termination");
4238
+ await new Promise((r) => setTimeout(r, 25));
4239
+ }
4240
+ if (scanError) throw scanError;
4241
+ } finally {
4242
+ killRoot();
4243
+ }
4244
+ }
4245
+ function stop() {
4246
+ if (!stopPromise) {
4247
+ clearInterval(monitor);
4248
+ stopPromise = terminate();
4249
+ void stopPromise.catch(() => {
4250
+ });
4251
+ }
4252
+ return stopPromise;
4253
+ }
4254
+ return { exited, stop, async finish() {
4255
+ let timer;
4256
+ try {
4257
+ await Promise.race([(async () => {
4258
+ await stop();
4259
+ await closed;
4260
+ })(), new Promise((_, reject) => {
4261
+ timer = setTimeout(() => reject(Error("Application cleanup deadline exceeded")), CLEANUP_MS);
4262
+ })]);
4263
+ } finally {
4264
+ clearInterval(monitor);
4265
+ if (timer) clearTimeout(timer);
4266
+ for (const stream of child.stdio) if (stream && "destroy" in stream) stream.destroy();
4267
+ child.unref();
4268
+ }
4269
+ } };
4270
+ }
4271
+ var exec, CLEANUP_MS;
4272
+ var init_application_process = __esm({
4273
+ "src/runtime/application-process.ts"() {
4274
+ "use strict";
4275
+ exec = promisify(execFile);
4276
+ CLEANUP_MS = 5e3;
4277
+ }
4278
+ });
4279
+
4280
+ // src/runtime/browser-process-windows.ts
4281
+ import { randomUUID } from "crypto";
4282
+ import { execFile as execFile2 } from "child_process";
4283
+ import { promisify as promisify2 } from "util";
4284
+ import { win32 as win322 } from "path";
4285
+ function windowsBrowserProcess(executable, commands = run) {
4286
+ const marker = "--agenttwin-browser-owner=" + randomUUID();
4287
+ const system = process.env.SystemRoot || process.env.SYSTEMROOT || "C:\\Windows";
4288
+ const powershell = win322.join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
4289
+ const taskkill = win322.join(system, "System32", "taskkill.exe");
4290
+ const known2 = /* @__PURE__ */ new Map();
4291
+ const script = "$ErrorActionPreference='Stop'; @(Get-CimInstance Win32_Process | Where-Object { $_.ProcessId -gt 1 -and $_.CreationDate } | ForEach-Object { @{pid=[int]$_.ProcessId; parent=[int]$_.ParentProcessId; created=$_.CreationDate.ToUniversalTime().ToString('o'); command=[string]$_.CommandLine} }) | ConvertTo-Json -Compress";
4292
+ async function snapshot() {
4293
+ const { stdout } = await commands(powershell, ["-NoProfile", "-NonInteractive", "-Command", script]);
4294
+ const parsed = JSON.parse(stdout.trim() || "[]");
4295
+ const rows2 = Array.isArray(parsed) ? parsed : [parsed];
4296
+ if (!rows2.every((r) => r && Number.isSafeInteger(r.pid) && r.pid >= 0 && Number.isSafeInteger(r.parent) && typeof r.created === "string" && r.created.length > 0 && typeof r.command === "string")) throw Error("Invalid Windows process evidence");
4297
+ return rows2;
4298
+ }
4299
+ async function owned() {
4300
+ const rows2 = await snapshot();
4301
+ for (const [pid, created2] of known2) if (!rows2.some((r) => r.pid === pid && r.created === created2)) known2.delete(pid);
4302
+ for (const row of rows2) if (row.parent === process.pid && row.command.split(/[\s"]+/).includes(marker)) known2.set(row.pid, row.created);
4303
+ let changed = true;
4304
+ while (changed) {
4305
+ changed = false;
4306
+ for (const row of rows2) {
4307
+ const parent = known2.get(row.parent);
4308
+ if (row.pid > 1 && parent && row.created >= parent && !known2.has(row.pid)) {
4309
+ known2.set(row.pid, row.created);
4310
+ changed = true;
4311
+ }
4312
+ }
4313
+ }
4314
+ return rows2.filter((r) => known2.get(r.pid) === r.created);
4315
+ }
4316
+ return {
4317
+ launcher: executable,
4318
+ args: [marker],
4319
+ async alive() {
4320
+ return (await owned()).map((r) => r.pid);
4321
+ },
4322
+ async kill() {
4323
+ const targets = await owned();
4324
+ if (!targets.length) return;
4325
+ const current = await snapshot();
4326
+ const live = targets.filter((t) => current.some((r) => r.pid === t.pid && r.created === t.created));
4327
+ if (!live.length) return;
4328
+ try {
4329
+ await commands(taskkill, [...live.flatMap((t) => ["/PID", String(t.pid)]), "/T", "/F"]);
4330
+ } catch (error) {
4331
+ if ((await snapshot()).some((r) => live.some((t) => r.pid === t.pid && r.created === t.created))) throw error;
4332
+ }
4333
+ }
4334
+ };
4335
+ }
4336
+ var exec2, run;
4337
+ var init_browser_process_windows = __esm({
4338
+ "src/runtime/browser-process-windows.ts"() {
4339
+ "use strict";
4340
+ exec2 = promisify2(execFile2);
4341
+ run = (file, args) => exec2(file, args, { windowsHide: true, timeout: 2e3, maxBuffer: 4 * 1024 * 1024 });
4342
+ }
4343
+ });
4344
+
4345
+ // src/runtime/browser-process.ts
4346
+ import { mkdtemp as mkdtemp3, writeFile as writeFile3, readFile as readFile2, rm as rm3 } from "fs/promises";
4347
+ import { tmpdir as tmpdir3 } from "os";
4348
+ import { join as join5 } from "path";
4349
+ import { execFile as execFile3 } from "child_process";
4350
+ import { promisify as promisify3 } from "util";
4351
+ async function ownBrowserProcess(executable) {
4352
+ if (process.platform === "win32") return withCleanup(windowsBrowserProcess(executable), async () => {
4353
+ });
4354
+ const root = await mkdtemp3(join5(tmpdir3(), "agenttwin-browser-owner-"));
4355
+ const pidFile = join5(root, "pid"), launcher = join5(root, "launch");
4356
+ await writeFile3(launcher, `#!/bin/sh
4357
+ echo $$ > ${quote(pidFile)}
4358
+ exec ${quote(executable)} "$@"
4359
+ `, { mode: 448 });
4360
+ let group;
4361
+ async function processes2() {
4362
+ const { stdout } = await exec3("ps", ["-axo", "pid=,pgid=,stat="], { timeout: 2e3, maxBuffer: 4 * 1024 * 1024 });
4363
+ return stdout.trim().split("\n").map((line) => {
4364
+ const [pid, pgid, state] = line.trim().split(/\s+/);
4365
+ return { pid: Number(pid), pgid: Number(pgid), state };
4366
+ });
4367
+ }
4368
+ async function discover() {
4369
+ if (group) return group;
4370
+ let pid;
4371
+ try {
4372
+ pid = Number((await readFile2(pidFile, "utf8")).trim());
4373
+ } catch (e) {
4374
+ if (e.code === "ENOENT") return;
4375
+ throw e;
4376
+ }
4377
+ if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error("Invalid browser process identity");
4378
+ const rows2 = await processes2(), leader = rows2.find((p) => p.pid === pid);
4379
+ if (leader && leader.pgid !== pid) throw new Error("Browser launcher does not own its process group");
4380
+ group = pid;
4381
+ return group;
4382
+ }
4383
+ async function alive() {
4384
+ const id = await discover();
4385
+ return id ? (await processes2()).filter((p) => p.pgid === id && !p.state?.startsWith("Z")).map((p) => p.pid) : [];
4386
+ }
4387
+ async function kill() {
4388
+ const id = await discover();
4389
+ if (id) {
4390
+ try {
4391
+ process.kill(-id, "SIGKILL");
4392
+ } catch (e) {
4393
+ if (e.code !== "ESRCH") throw e;
4394
+ }
4395
+ }
4396
+ }
4397
+ return withCleanup({ launcher, args: [], alive, kill }, () => rm3(root, { recursive: true, force: true }));
4398
+ }
4399
+ function withCleanup(owner, dispose) {
4400
+ const { alive, kill } = owner;
4401
+ return { ...owner, async finish(close) {
4402
+ let timer, forced = false;
4403
+ let inspectionError;
4404
+ try {
4405
+ try {
4406
+ await alive();
4407
+ } catch (error) {
4408
+ inspectionError = error;
4409
+ }
4410
+ const closed = Promise.resolve().then(close).then(() => true, () => false);
4411
+ const graceful = await Promise.race([closed, new Promise((resolve7) => {
4412
+ timer = setTimeout(() => resolve7(false), BROWSER_CLEANUP_MS);
4413
+ })]);
4414
+ if (inspectionError) {
4415
+ if (!graceful) {
4416
+ forced = true;
4417
+ try {
4418
+ await kill();
4419
+ } catch {
4420
+ }
4421
+ }
4422
+ throw inspectionError;
4423
+ }
4424
+ if (!graceful || (await alive()).length) {
4425
+ forced = true;
4426
+ await kill();
4427
+ }
4428
+ const until = Date.now() + 2e3;
4429
+ while ((await alive()).length) {
4430
+ if (Date.now() > until) throw new Error("Browser cleanup could not confirm process exit");
4431
+ await kill();
4432
+ await pause(25);
4433
+ }
4434
+ return { forced, remainingProcesses: 0 };
4435
+ } finally {
4436
+ if (timer) clearTimeout(timer);
4437
+ await dispose();
4438
+ }
4439
+ } };
4440
+ }
4441
+ var exec3, BROWSER_STARTUP_MS, BROWSER_CLEANUP_MS, quote, pause;
4442
+ var init_browser_process = __esm({
4443
+ "src/runtime/browser-process.ts"() {
4444
+ "use strict";
4445
+ init_browser_process_windows();
4446
+ exec3 = promisify3(execFile3);
4447
+ BROWSER_STARTUP_MS = 2e4;
4448
+ BROWSER_CLEANUP_MS = 3e3;
4449
+ quote = (s) => "'" + s.replaceAll("'", `'"'"'`) + "'";
4450
+ pause = (ms) => new Promise((r) => setTimeout(r, ms));
4451
+ }
4452
+ });
4453
+
4454
+ // src/runtime/browser-directories.ts
4455
+ import { mkdtemp as mkdtemp4, mkdir as mkdir2, chown, chmod, rm as rm4 } from "fs/promises";
4456
+ import { tmpdir as tmpdir4 } from "os";
4457
+ import { join as join6 } from "path";
4458
+ async function createBrowserDirectories(identity) {
4459
+ if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
4460
+ const root = await mkdtemp4(join6(tmpdir4(), "agenttwin-browser-"));
4461
+ const profile = join6(root, "profile"), artifacts = join6(root, "artifacts");
4462
+ const close = () => rm4(root, { recursive: true, force: true });
4463
+ try {
4464
+ await mkdir2(profile, { mode: 448 });
4465
+ await mkdir2(artifacts, { mode: 448 });
4466
+ for (const directory2 of [profile, artifacts, root]) {
4467
+ await chmod(directory2, 448);
4468
+ if (identity.uid !== process.getuid?.() || identity.gid !== process.getgid?.()) await chown(directory2, identity.uid, identity.gid);
4469
+ }
4470
+ return { root, profile, artifacts, close };
4471
+ } catch (error) {
4472
+ await close();
4473
+ throw error;
4474
+ }
4475
+ }
4476
+ var init_browser_directories = __esm({
4477
+ "src/runtime/browser-directories.ts"() {
4478
+ "use strict";
4479
+ }
4480
+ });
4481
+
4094
4482
  // src/runtime/browser-execution.ts
4095
4483
  import { chromium } from "playwright";
4096
4484
  import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
4097
- async function browserExecution(spec, world, signal) {
4485
+ async function browserExecution(spec, world, signal, identity, onReady = () => {
4486
+ }) {
4098
4487
  signal?.throwIfAborted();
4099
- const recipe = spec.browser;
4100
- const browser = await chromium.launch({ headless: true, timeout: spec.timeoutSeconds * 1e3, ...process.env.AGENTTWIN_CHROMIUM_EXECUTABLE_PATH ? { executablePath: process.env.AGENTTWIN_CHROMIUM_EXECUTABLE_PATH } : {} });
4101
- const abort = () => {
4102
- void browser.close().catch(() => {
4488
+ const recipe = spec.browser, result = { engine: "playwright-chromium", steps: [], passed: false, blockedOrigins: [], timedOut: false, timings: [] };
4489
+ let browser, context2;
4490
+ let directories;
4491
+ let owner;
4492
+ const deadlineAborted = () => signal?.aborted && signal.reason instanceof Error && signal.reason.message === "Test deadline exceeded";
4493
+ let stage = "Browser startup", stageStart = performance.now(), expired = false;
4494
+ const mark = (next) => {
4495
+ result.timings.push({ stage, durationMs: Math.round(performance.now() - stageStart) });
4496
+ stage = next;
4497
+ stageStart = performance.now();
4498
+ };
4499
+ const close = async () => {
4500
+ if (browser) await browser.close();
4501
+ else if (context2) await context2.close();
4502
+ };
4503
+ let killFailure;
4504
+ let stopping = Promise.resolve();
4505
+ const stop = () => {
4506
+ stopping = stopping.then(async () => {
4507
+ try {
4508
+ await owner?.kill();
4509
+ } catch (e) {
4510
+ killFailure = e;
4511
+ }
4103
4512
  });
4104
4513
  };
4514
+ const abort = () => {
4515
+ stop();
4516
+ };
4105
4517
  signal?.addEventListener("abort", abort, { once: true });
4106
- try {
4518
+ const startupDeadline = Date.now() + BROWSER_STARTUP_MS;
4519
+ const startupTimer = setTimeout(() => {
4520
+ expired = true;
4521
+ stop();
4522
+ }, BROWSER_STARTUP_MS);
4523
+ const check = () => {
4524
+ if (expired) throw new Error(stage + " timed out");
4107
4525
  signal?.throwIfAborted();
4108
- const context = await browser.newContext({ serviceWorkers: "block", viewport: { width: 1280, height: 720 } });
4526
+ };
4527
+ let failure;
4528
+ let testTimer;
4529
+ try {
4530
+ owner = await ownBrowserProcess(process.env.AGENTTWIN_CHROMIUM_EXECUTABLE_PATH || chromium.executablePath());
4531
+ if (identity) directories = await createBrowserDirectories(identity);
4532
+ check();
4533
+ const windowsEnv = {};
4534
+ if (process.platform === "win32") for (const [key2, value] of Object.entries(process.env)) {
4535
+ if (value && ["systemroot", "windir", "temp", "tmp", "userprofile", "localappdata"].includes(key2.toLowerCase())) windowsEnv[key2] = value;
4536
+ }
4537
+ const options = { headless: true, executablePath: owner.launcher, args: owner.args, env: { ...windowsEnv, PATH: process.env.PATH ?? "", HOME: directories?.root ?? process.env.HOME ?? "/tmp", TMPDIR: directories?.root ?? process.env.TMPDIR ?? "/tmp" }, timeout: Math.max(1, startupDeadline - Date.now()) };
4538
+ if (directories) context2 = await chromium.launchPersistentContext(directories.profile, { ...options, artifactsDir: directories.artifacts, serviceWorkers: "block", viewport: { width: 1280, height: 720 } });
4539
+ else {
4540
+ browser = await chromium.launch(options);
4541
+ check();
4542
+ context2 = await browser.newContext({ serviceWorkers: "block", viewport: { width: 1280, height: 720 } });
4543
+ }
4544
+ check();
4545
+ mark("Application readiness");
4109
4546
  const origins = /* @__PURE__ */ new Set([new URL(recipe.baseUrl).origin, ...Object.values(world.credentials).map((c) => new URL(c.endpoint).origin)]);
4110
4547
  const blocked = /* @__PURE__ */ new Set();
4111
- await context.route("**/*", (route) => {
4548
+ await context2.route("**/*", (route) => {
4112
4549
  const origin = new URL(route.request().url()).origin;
4113
4550
  if (origins.has(origin)) return route.continue();
4114
4551
  if (blocked.size < 100) blocked.add(origin);
4115
4552
  return route.abort("blockedbyclient");
4116
4553
  });
4117
- const page = await context.newPage();
4554
+ if (spec.applicationClock) await context2.addInitScript({ content: applicationClockHook(spec.applicationClock) });
4555
+ const page = await context2.newPage();
4118
4556
  page.setDefaultTimeout(Math.min(spec.timeoutSeconds * 500, 1e4));
4119
- const deadline = Date.now() + Math.min(spec.timeoutSeconds * 1e3, 1e4);
4120
4557
  while (true) {
4121
- signal?.throwIfAborted();
4558
+ check();
4122
4559
  try {
4123
4560
  const r = await fetch(recipe.baseUrl, { signal: AbortSignal.timeout(300) });
4124
4561
  if (r.ok) break;
4125
4562
  } catch {
4126
4563
  }
4127
- if (Date.now() > deadline) throw new Error("Application browser readiness timed out");
4564
+ if (Date.now() >= startupDeadline) {
4565
+ expired = true;
4566
+ check();
4567
+ }
4128
4568
  await new Promise((r) => setTimeout(r, 50));
4129
4569
  }
4130
- const steps = [];
4131
- let error;
4570
+ clearTimeout(startupTimer);
4571
+ onReady();
4572
+ testTimer = setTimeout(() => {
4573
+ expired = true;
4574
+ stop();
4575
+ }, spec.timeoutSeconds * 1e3);
4132
4576
  for (const step of recipe.steps) {
4133
- signal?.throwIfAborted();
4577
+ mark(step.action + " step");
4578
+ check();
4134
4579
  try {
4135
4580
  if (step.action === "goto") await page.goto(new URL(step.path, recipe.baseUrl).href);
4136
4581
  else if (step.action === "click") await page.locator(step.selector).click();
4137
4582
  else if (step.action === "fill") await page.locator(step.selector).fill(step.value);
4138
4583
  else await page.locator(step.selector).filter({ hasText: step.text }).waitFor({ state: "visible" });
4139
- steps.push({ action: step.action, passed: true });
4584
+ result.steps.push({ action: step.action, passed: true });
4140
4585
  } catch (cause) {
4141
- error = cause instanceof Error ? cause.message : String(cause);
4142
- for (const s of recipe.steps) if (s.action === "fill" && s.value) error = error.split(s.value).join("[input]");
4143
- steps.push({ action: step.action, passed: false });
4586
+ result.timedOut = expired || !!deadlineAborted() || cause instanceof Error && cause.name === "TimeoutError";
4587
+ result.error = stage + (result.timedOut ? " timed out" : " failed");
4588
+ result.steps.push({ action: step.action, passed: false });
4144
4589
  break;
4145
4590
  }
4146
4591
  }
4147
- let screenshot;
4148
- try {
4149
- const bytes = await page.screenshot({ type: "jpeg", quality: 65 });
4150
- if (bytes.length <= 768 * 1024) screenshot = { mimeType: "image/jpeg", base64: bytes.toString("base64") };
4151
- } catch {
4592
+ mark("Screenshot");
4593
+ if (!signal?.aborted && !expired) {
4594
+ try {
4595
+ const bytes = await page.screenshot({ type: "jpeg", quality: 65, timeout: 1e3 });
4596
+ if (bytes.length <= 768 * 1024) result.screenshot = { mimeType: "image/jpeg", base64: bytes.toString("base64") };
4597
+ } catch {
4598
+ }
4152
4599
  }
4600
+ result.blockedOrigins = [...blocked];
4153
4601
  for (const origin of blocked) world.unsupported.push(`browser: blocked unmodeled request origin ${origin}`);
4154
- return { engine: "playwright-chromium", steps, passed: !error, error, blockedOrigins: [...blocked], screenshot };
4602
+ if (!result.error) check();
4603
+ result.passed = !result.error;
4604
+ } catch (error) {
4605
+ failure = error;
4606
+ result.timedOut = expired || error instanceof Error && error.name === "TimeoutError" || !!deadlineAborted();
4607
+ result.error = result.timedOut ? stage + " timed out" : error instanceof Error ? error.message : String(error);
4155
4608
  } finally {
4609
+ clearTimeout(startupTimer);
4610
+ if (testTimer) clearTimeout(testTimer);
4156
4611
  signal?.removeEventListener("abort", abort);
4157
- await browser.close();
4612
+ mark("Browser cleanup");
4613
+ try {
4614
+ await stopping;
4615
+ result.cleanup = owner ? await owner.finish(close) : { forced: false, remainingProcesses: 0 };
4616
+ if (killFailure) throw killFailure;
4617
+ } catch (error) {
4618
+ failure = error;
4619
+ result.error = "Browser cleanup failed";
4620
+ result.passed = false;
4621
+ } finally {
4622
+ try {
4623
+ await directories?.close();
4624
+ } catch (error) {
4625
+ failure = error;
4626
+ result.error = "Browser directory cleanup failed";
4627
+ result.passed = false;
4628
+ }
4629
+ result.timings.push({ stage, durationMs: Math.round(performance.now() - stageStart) });
4630
+ }
4158
4631
  }
4632
+ if (failure) throw new BrowserExecutionError(result.error, result);
4633
+ return result;
4159
4634
  }
4160
4635
  async function waitBackground(spec, world, signal) {
4161
4636
  const check = spec.background, deadline = Date.now() + check.timeoutMs;
@@ -4167,9 +4642,20 @@ async function waitBackground(spec, world, signal) {
4167
4642
  await new Promise((r) => setTimeout(r, 25));
4168
4643
  }
4169
4644
  }
4645
+ var BrowserExecutionError;
4170
4646
  var init_browser_execution = __esm({
4171
4647
  "src/runtime/browser-execution.ts"() {
4172
4648
  "use strict";
4649
+ init_application_clock();
4650
+ init_browser_directories();
4651
+ init_browser_process();
4652
+ BrowserExecutionError = class extends Error {
4653
+ constructor(message, evidence) {
4654
+ super(message);
4655
+ this.evidence = evidence;
4656
+ }
4657
+ evidence;
4658
+ };
4173
4659
  }
4174
4660
  });
4175
4661
 
@@ -4240,8 +4726,8 @@ function evaluateProperty(policy, final, events) {
4240
4726
  const keyed = /* @__PURE__ */ new Map();
4241
4727
  for (const row of rows2) {
4242
4728
  if (row[field] === void 0) continue;
4243
- const key = JSON.stringify(canonical(row[field]));
4244
- keyed.set(key, [...keyed.get(key) ?? [], row.id ?? row]);
4729
+ const key2 = JSON.stringify(canonical(row[field]));
4730
+ keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
4245
4731
  }
4246
4732
  const duplicates = [...keyed.entries()].filter(([, list2]) => list2.length > 1);
4247
4733
  return {
@@ -4249,7 +4735,7 @@ function evaluateProperty(policy, final, events) {
4249
4735
  passed: duplicates.length === 0,
4250
4736
  expected: 0,
4251
4737
  actual: duplicates.length,
4252
- evidence: { field, duplicates: duplicates.map(([key, ids]) => ({ value: short(key), ids: ids.map(String) })), eventSequences: eventsFor("write").filter((e) => e.record !== void 0 && e.record[field] !== void 0 && duplicates.some(([key]) => key === JSON.stringify(canonical(e.record[field])))).map((e) => e.sequence) }
4738
+ evidence: { field, duplicates: duplicates.map(([key2, ids]) => ({ value: short(key2), ids: ids.map(String) })), eventSequences: eventsFor("write").filter((e) => e.record !== void 0 && e.record[field] !== void 0 && duplicates.some(([key2]) => key2 === JSON.stringify(canonical(e.record[field])))).map((e) => e.sequence) }
4253
4739
  };
4254
4740
  }
4255
4741
  if (policy.kind === "no-loss") {
@@ -4287,7 +4773,7 @@ var init_evaluation = __esm({
4287
4773
  "src/runtime/evaluation.ts"() {
4288
4774
  "use strict";
4289
4775
  matches = (row, where) => !where || Object.entries(where).every(([k, v]) => isDeepStrictEqual3(row[k], v));
4290
- canonical = (value) => Array.isArray(value) ? value.map(canonical) : typeof value === "object" && value !== null ? Object.fromEntries(Object.keys(value).sort().map((key) => [key, canonical(value[key])])) : value;
4776
+ canonical = (value) => Array.isArray(value) ? value.map(canonical) : typeof value === "object" && value !== null ? Object.fromEntries(Object.keys(value).sort().map((key2) => [key2, canonical(value[key2])])) : value;
4291
4777
  short = (value, limit = 120) => value.length <= limit ? value : `${value.slice(0, limit)}\u2026`;
4292
4778
  escape = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
4293
4779
  }
@@ -4568,8 +5054,8 @@ var init_contracts = __esm({
4568
5054
  });
4569
5055
 
4570
5056
  // src/runtime/cost-model.ts
4571
- import { readFile as readFile2, writeFile as writeFile3 } from "fs/promises";
4572
- import { join as join5 } from "path";
5057
+ import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
5058
+ import { join as join7 } from "path";
4573
5059
  var init_cost_model = __esm({
4574
5060
  "src/runtime/cost-model.ts"() {
4575
5061
  "use strict";
@@ -4623,7 +5109,7 @@ function normalizeCall(raw) {
4623
5109
  const method = raw.method.toUpperCase(), path = raw.path.split("?")[0] || "/", { resourcePath, resourceId } = resourceOf2(method, path);
4624
5110
  const graphqlRead = /graphql/i.test(path) && typeof raw.body?.query === "string" && !/^\s*mutation\b/.test(raw.body.query);
4625
5111
  const isWrite = WRITE_METHODS.has(method) && !READ_LIKE.test(path) && !MODEL_HOST.test(raw.host) && !String(raw.service ?? "").startsWith("model:") && !graphqlRead;
4626
- const outcome = raw.outcome ?? outcomeOf(raw.status), key = keyFrom(raw.headers, raw.body), source = parseSource(raw.source);
5112
+ const outcome = raw.outcome ?? outcomeOf(raw.status), key2 = keyFrom(raw.headers, raw.body), source = parseSource(raw.source);
4627
5113
  return {
4628
5114
  sequence: raw.sequence,
4629
5115
  service: raw.service ?? raw.host,
@@ -4633,7 +5119,7 @@ function normalizeCall(raw) {
4633
5119
  resourcePath,
4634
5120
  ...method === "POST" && raw.createdId ? { resourceId: raw.createdId } : resourceId ? { resourceId } : {},
4635
5121
  isWrite,
4636
- ...key ? { idempotencyKey: key } : {},
5122
+ ...key2 ? { idempotencyKey: key2 } : {},
4637
5123
  ...raw.body !== void 0 ? { requestDigest: digest(stable(raw.body)), body: raw.body } : {},
4638
5124
  ...raw.response !== void 0 ? { responseDigest: digest(stable(raw.response)) } : {},
4639
5125
  outcome,
@@ -4650,9 +5136,9 @@ function callsFromWorldEvents(events, tierOf = () => void 0) {
4650
5136
  const calls = [], seen = /* @__PURE__ */ new Set();
4651
5137
  const last = (service) => [...calls].reverse().find((c) => c.service === service && c.isWrite);
4652
5138
  for (const e of events) {
4653
- const tier = tierOf(e.service), key = e.idempotencyKey;
5139
+ const tier = tierOf(e.service), key2 = e.idempotencyKey;
4654
5140
  const base = (method, path, extra) => normalizeCall({ sequence: e.sequence, host: e.service, service: e.service, method, path, ...tier ? { tier } : {}, ...e.source ? { source: e.source } : {}, ...extra });
4655
- const withKey = (c) => key ? { ...c, idempotencyKey: key } : c;
5141
+ const withKey = (c) => key2 ? { ...c, idempotencyKey: key2 } : c;
4656
5142
  if (e.operation === "write") {
4657
5143
  const id = e.record?.id === void 0 ? void 0 : String(e.record.id), path = e.path, recordKey = `${e.service}${path}:${id}`;
4658
5144
  const method = /^(POST|PUT|PATCH|DELETE)\b/.exec(e.detail)?.[1] ?? (id && seen.has(recordKey) ? "PATCH" : "POST");
@@ -4932,18 +5418,18 @@ function addedRows(initial, final) {
4932
5418
  for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
4933
5419
  return rows2(final).filter((r) => {
4934
5420
  if (r.id !== void 0 && r.id !== null) return !ids.has(r.id);
4935
- const key = canonical3(r), left = seen.get(key) ?? 0;
5421
+ const key2 = canonical3(r), left = seen.get(key2) ?? 0;
4936
5422
  if (left > 0) {
4937
- seen.set(key, left - 1);
5423
+ seen.set(key2, left - 1);
4938
5424
  return false;
4939
5425
  }
4940
5426
  return true;
4941
5427
  });
4942
5428
  }
4943
- function groups(items, key) {
5429
+ function groups(items, key2) {
4944
5430
  const out = /* @__PURE__ */ new Map();
4945
5431
  for (const item of items) {
4946
- const k = key(item);
5432
+ const k = key2(item);
4947
5433
  if (k !== void 0) out.set(k, [...out.get(k) ?? [], item]);
4948
5434
  }
4949
5435
  return [...out.values()].filter((g) => g.length > 1);
@@ -5048,7 +5534,7 @@ var init_default_checks = __esm({
5048
5534
  };
5049
5535
  rowsOf = (state, service, path) => (state?.[service]?.[path] ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
5050
5536
  VOLATILE2 = /* @__PURE__ */ new Set(["id", "ts", "created", "created_at", "updated_at", "inserted_at", "createdAt", "updatedAt", "internalDate", "historyId", "threadId", "number", "iid", "latest_charge", "object", "sequence", "uuid"]);
5051
- volatileKey = (key) => VOLATILE2.has(key) || /_at$|At$/.test(key);
5537
+ volatileKey = (key2) => VOLATILE2.has(key2) || /_at$|At$/.test(key2);
5052
5538
  canonical3 = (value) => Array.isArray(value) ? `[${value.map(canonical3).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical3(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
5053
5539
  contentSignature = (row) => canonical3(Object.fromEntries(Object.entries(row).filter(([k]) => !volatileKey(k))));
5054
5540
  writeSequences = (ctx, service, ids) => ctx.events.filter((e) => e.service === service && e.operation === "write" && ids.includes(e.record?.id)).map((e) => e.sequence);
@@ -5241,13 +5727,13 @@ var init_default_checks = __esm({
5241
5727
  });
5242
5728
 
5243
5729
  // src/runtime/twin-proxy.ts
5244
- import { execFile } from "child_process";
5245
- import { mkdtemp as mkdtemp3, readFile as readFile3, rm as rm3, writeFile as writeFile4 } from "fs/promises";
5730
+ import { execFile as execFile4 } from "child_process";
5731
+ import { mkdtemp as mkdtemp5, readFile as readFile4, rm as rm5, writeFile as writeFile5 } from "fs/promises";
5246
5732
  import { createServer as createServer2, request as httpRequest } from "http";
5247
- import { tmpdir as tmpdir3 } from "os";
5248
- import { join as join6 } from "path";
5733
+ import { tmpdir as tmpdir5 } from "os";
5734
+ import { join as join8 } from "path";
5249
5735
  import { createSecureContext, TLSSocket } from "tls";
5250
- import { promisify } from "util";
5736
+ import { promisify as promisify4 } from "util";
5251
5737
  function matchRoute(routes2, host, pathname) {
5252
5738
  host = host.toLowerCase().replace(/\.$/, "");
5253
5739
  let best;
@@ -5270,8 +5756,8 @@ function rewrite(r, p) {
5270
5756
  return p;
5271
5757
  }
5272
5758
  async function runAuthority(dir) {
5273
- const ca = { key: join6(dir, "ca.key"), cert: join6(dir, "ca.pem") };
5274
- await run("openssl", [
5759
+ const ca = { key: join8(dir, "ca.key"), cert: join8(dir, "ca.pem") };
5760
+ await run2("openssl", [
5275
5761
  "req",
5276
5762
  "-x509",
5277
5763
  "-newkey",
@@ -5301,17 +5787,17 @@ async function runAuthority(dir) {
5301
5787
  let ctx = contexts.get(host);
5302
5788
  if (!ctx) {
5303
5789
  ctx = (async () => {
5304
- const base = join6(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
5305
- await writeFile4(base + ".ext", `basicConstraints=critical,CA:FALSE
5790
+ const base = join8(dir, host.replace(/[^a-z0-9.-]/gi, "_"));
5791
+ await writeFile5(base + ".ext", `basicConstraints=critical,CA:FALSE
5306
5792
  keyUsage=critical,digitalSignature
5307
5793
  extendedKeyUsage=serverAuth
5308
5794
  subjectAltName=DNS:${host}
5309
5795
  subjectKeyIdentifier=hash
5310
5796
  authorityKeyIdentifier=keyid,issuer
5311
5797
  `);
5312
- await run("openssl", ["req", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", base + ".key", "-out", base + ".csr", "-subj", `/CN=${host}`]);
5313
- await run("openssl", ["x509", "-req", "-in", base + ".csr", "-CA", ca.cert, "-CAkey", ca.key, "-set_serial", "0x" + Buffer.from(host).toString("hex").slice(0, 30).padEnd(16, "1"), "-days", "2", "-out", base + ".pem", "-extfile", base + ".ext"]);
5314
- return createSecureContext({ key: await readFile3(base + ".key"), cert: await readFile3(base + ".pem") });
5798
+ await run2("openssl", ["req", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1", "-nodes", "-keyout", base + ".key", "-out", base + ".csr", "-subj", `/CN=${host}`]);
5799
+ await run2("openssl", ["x509", "-req", "-in", base + ".csr", "-CA", ca.cert, "-CAkey", ca.key, "-set_serial", "0x" + Buffer.from(host).toString("hex").slice(0, 30).padEnd(16, "1"), "-days", "2", "-out", base + ".pem", "-extfile", base + ".ext"]);
5800
+ return createSecureContext({ key: await readFile4(base + ".key"), cert: await readFile4(base + ".pem") });
5315
5801
  })();
5316
5802
  contexts.set(host, ctx);
5317
5803
  }
@@ -5320,7 +5806,7 @@ authorityKeyIdentifier=keyid,issuer
5320
5806
  };
5321
5807
  }
5322
5808
  async function startTwinProxy(routes2) {
5323
- const dir = await mkdtemp3(join6(tmpdir3(), "agenttwin-proxy-"));
5809
+ const dir = await mkdtemp5(join8(tmpdir5(), "agenttwin-proxy-"));
5324
5810
  const authority = await runAuthority(dir).catch((error) => {
5325
5811
  throw new Error(`The twin proxy needs the openssl command to make this run's certificate authority: ${error instanceof Error ? error.message : error}`);
5326
5812
  });
@@ -5415,15 +5901,15 @@ async function startTwinProxy(routes2) {
5415
5901
  server.closeAllConnections();
5416
5902
  });
5417
5903
  inner.closeAllConnections();
5418
- await rm3(dir, { recursive: true, force: true });
5904
+ await rm5(dir, { recursive: true, force: true });
5419
5905
  }
5420
5906
  };
5421
5907
  }
5422
- var run, SECRET, hostRouted;
5908
+ var run2, SECRET, hostRouted;
5423
5909
  var init_twin_proxy = __esm({
5424
5910
  "src/runtime/twin-proxy.ts"() {
5425
5911
  "use strict";
5426
- run = promisify(execFile);
5912
+ run2 = promisify4(execFile4);
5427
5913
  SECRET = ["authorization", "x-api-key", "cookie", "proxy-authorization", "host", "proxy-connection"];
5428
5914
  hostRouted = (routes2, host) => routes2.some((r) => r.hostPattern ? (() => {
5429
5915
  try {
@@ -5436,9 +5922,9 @@ var init_twin_proxy = __esm({
5436
5922
  });
5437
5923
 
5438
5924
  // src/runtime/twin-routing.ts
5439
- import { mkdtemp as mkdtemp4, readFile as readFile4, rm as rm4, writeFile as writeFile5 } from "fs/promises";
5440
- import { tmpdir as tmpdir4 } from "os";
5441
- import { join as join7 } from "path";
5925
+ import { mkdtemp as mkdtemp6, readFile as readFile5, rm as rm6, writeFile as writeFile6 } from "fs/promises";
5926
+ import { tmpdir as tmpdir6 } from "os";
5927
+ import { join as join9 } from "path";
5442
5928
  function twinRoutes(services, world, models) {
5443
5929
  const routes2 = [];
5444
5930
  for (const service of services) {
@@ -5610,7 +6096,7 @@ require('node:module').syncBuiltinESMExports();
5610
6096
  // src/runtime/local.ts
5611
6097
  import { spawn } from "child_process";
5612
6098
  async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {}) {
5613
- if (spec.applicationClock) throw new Error("applicationClock requires the Docker runner; no application was executed.");
6099
+ if (spec.applicationClock && !/(^|\/)node(\.exe)?$/.test(spec.command[0])) throw new Error("applicationClock requires a Node application");
5614
6100
  if (spec.postgres || spec.redis) throw new Error("This world needs PostgreSQL or Redis. Use --runtime hosted or --runtime e2b, or prepare a workflow using HTTP twins only. No local containers are started.");
5615
6101
  signal?.throwIfAborted();
5616
6102
  const world = existingWorld ?? new HttpWorld(spec, seed), started = Date.now();
@@ -5639,13 +6125,10 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
5639
6125
  child.stderr.on("data", (b) => {
5640
6126
  stderr = (stderr + b.toString()).slice(-65536);
5641
6127
  });
6128
+ const managed = manageApplication(child);
5642
6129
  const kill = () => {
5643
- if (child.pid) {
5644
- try {
5645
- process.platform === "win32" ? child.kill("SIGKILL") : process.kill(-child.pid, "SIGKILL");
5646
- } catch {
5647
- }
5648
- }
6130
+ void managed.stop().catch(() => {
6131
+ });
5649
6132
  };
5650
6133
  const executionAbort = new AbortController();
5651
6134
  const abort = () => {
@@ -5653,28 +6136,39 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
5653
6136
  kill();
5654
6137
  };
5655
6138
  signal?.addEventListener("abort", abort, { once: true });
5656
- const timer = setTimeout(() => {
6139
+ const expire = () => {
5657
6140
  timedOut = true;
5658
- executionAbort.abort();
6141
+ executionAbort.abort(new Error("Test deadline exceeded"));
5659
6142
  kill();
5660
- }, spec.timeoutSeconds * 1e3);
5661
- const completion = new Promise((resolve7, reject) => {
5662
- child.once("error", reject);
5663
- child.once("close", resolve7);
5664
- });
6143
+ };
6144
+ let timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + (spec.browser ? BROWSER_STARTUP_MS + BROWSER_CLEANUP_MS : 0));
6145
+ const browserReady = () => {
6146
+ clearTimeout(timer);
6147
+ timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + BROWSER_CLEANUP_MS);
6148
+ };
6149
+ let work;
6150
+ const completion = managed.exited;
5665
6151
  let browser, background, executionError;
5666
6152
  let exitCode;
5667
6153
  let blockedFetches = [];
5668
6154
  try {
5669
6155
  if (spec.browser || spec.background) {
5670
- const work = (async () => {
5671
- if (spec.browser) browser = await browserExecution(spec, world, executionAbort.signal);
6156
+ work = (async () => {
6157
+ if (spec.browser) {
6158
+ try {
6159
+ browser = await browserExecution(spec, world, executionAbort.signal, void 0, browserReady);
6160
+ } catch (e) {
6161
+ if (e instanceof BrowserExecutionError) browser = e.evidence;
6162
+ throw e;
6163
+ }
6164
+ if (!browser.passed) return 1;
6165
+ }
5672
6166
  if (spec.background) background = await waitBackground(spec, world, executionAbort.signal);
5673
6167
  return 0;
5674
6168
  })();
5675
6169
  exitCode = await Promise.race([work, completion.then((code) => {
5676
6170
  if (!spec.browser && code === 0) return work;
5677
- throw new Error(`Application exited before browser/background completion (${code})`);
6171
+ throw new Error(timedOut ? "Test deadline exceeded" : `Application exited before browser/background completion (${code})`);
5678
6172
  })]);
5679
6173
  } else exitCode = await completion;
5680
6174
  } catch (error) {
@@ -5685,8 +6179,18 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
5685
6179
  clearTimeout(timer);
5686
6180
  signal?.removeEventListener("abort", abort);
5687
6181
  kill();
5688
- await completion.catch(() => {
6182
+ await work?.catch(() => {
5689
6183
  });
6184
+ if (browser?.timedOut) {
6185
+ timedOut = true;
6186
+ executionError = browser.error;
6187
+ }
6188
+ try {
6189
+ await managed.finish();
6190
+ } catch {
6191
+ executionError = "Application cleanup failed";
6192
+ exitCode = 1;
6193
+ }
5690
6194
  try {
5691
6195
  blockedFetches = await hook.readViolations();
5692
6196
  } finally {
@@ -5708,7 +6212,7 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
5708
6212
  const evaluation = evaluateState(spec, initialState, world.state, world.events);
5709
6213
  const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null });
5710
6214
  const status = blockedFetches.length || world.unsupported.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || exitCode !== 0 ? "error" : background?.passed === false || browser?.passed === false ? "failed" : evaluation.outcome === "passed" && defaultChecks.every((c) => c.passed) ? "passed" : "failed";
5711
- return { schema: "agenttwin/run-v1", name: spec.name, workflowId: spec.workflowId, status, browser, background, executionError, application: { command: spec.command, exitCode, timedOut, stdout, stderr }, assertions, evaluation, defaultChecks, contracts: operationMatrix(spec), scenario: spec.scenario, infrastructureAssertions: [], fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, seed: world.seed, reproducibility: "Seed " + world.seed + " deterministically drives twin-side fault scheduling, latency jitter and test credentials. The seed does not control the application's own randomness, wall-clock behavior or threading; compare runs only over twin events and final state.", initialState, finalState: world.snapshot(), events: structuredClone(world.events), blockedFetches, unsupported: [...world.unsupported], durationMs: Date.now() - started, coverage: "CLI Node execution with fresh in-process HTTP collections and advertised provider subsets. Optional Chromium browser steps and bounded collection-state background completion. Not a VM or network/filesystem isolation boundary. No production environment variables inherited; reviewed code can still access the host filesystem and network.", isolation: { kind: "process", productionCredentialsInherited: false, network: "host network; not isolated", rootFilesystem: "host-accessible; explicit files staged in temporary directory" } };
6215
+ return { schema: "agenttwin/run-v1", name: spec.name, workflowId: spec.workflowId, status, applicationClock: applicationClockEvidence(spec.applicationClock), twinClock: twinClockEvidence(world.twinClock), browser, background, executionError, application: { command: spec.command, exitCode, timedOut, stdout, stderr }, assertions, evaluation, defaultChecks, contracts: operationMatrix(spec), scenario: spec.scenario, infrastructureAssertions: [], fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, seed: world.seed, reproducibility: spec.applicationClock ? "Explicit Date clock fixed; timers, performance clocks and scheduling remain real. Twin randomness uses the recorded seed." : "Seed " + world.seed + " deterministically drives twin-side fault scheduling, latency jitter and test credentials. The seed does not control the application's own randomness, wall-clock behavior or threading; compare runs only over twin events and final state.", initialState, finalState: world.snapshot(), events: structuredClone(world.events), blockedFetches, unsupported: [...world.unsupported], durationMs: Date.now() - started, coverage: "CLI Node execution with fresh in-process HTTP collections and advertised provider subsets. Optional Chromium browser steps and bounded collection-state background completion. Not a VM or network/filesystem isolation boundary. No production environment variables inherited; reviewed code can still access the host filesystem and network.", isolation: { kind: "process", productionCredentialsInherited: false, network: "host network; not isolated", rootFilesystem: "host-accessible; explicit files staged in temporary directory" } };
5712
6216
  } finally {
5713
6217
  if (existingWorld) world.quiesce();
5714
6218
  else await world.close();
@@ -5717,6 +6221,10 @@ async function executeLocal(app, spec, signal, existingWorld, seed, extraEnv = {
5717
6221
  var init_local = __esm({
5718
6222
  "src/runtime/local.ts"() {
5719
6223
  "use strict";
6224
+ init_application_process();
6225
+ init_browser_process();
6226
+ init_twin_clock();
6227
+ init_application_clock();
5720
6228
  init_browser_execution();
5721
6229
  init_request_source();
5722
6230
  init_http_world();
@@ -5730,8 +6238,8 @@ var init_local = __esm({
5730
6238
 
5731
6239
  // src/runtime/scenarios.ts
5732
6240
  import { createHash as createHash7 } from "crypto";
5733
- import { mkdir as mkdir2, readFile as readFile5, readdir, writeFile as writeFile6 } from "fs/promises";
5734
- import { join as join8 } from "path";
6241
+ import { mkdir as mkdir3, readFile as readFile6, readdir, writeFile as writeFile7 } from "fs/promises";
6242
+ import { join as join10 } from "path";
5735
6243
  import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
5736
6244
  function parseScenario(value) {
5737
6245
  const fail = (detail) => {
@@ -5770,8 +6278,8 @@ function reference(ref) {
5770
6278
  }
5771
6279
  async function loadScenario(cwd, ref) {
5772
6280
  const { id, version } = reference(ref);
5773
- const path = join8(cwd, ".agenttwin/scenarios", id, `${version}.json`);
5774
- const bytes = await readFile5(path);
6281
+ const path = join10(cwd, ".agenttwin/scenarios", id, `${version}.json`);
6282
+ const bytes = await readFile6(path);
5775
6283
  if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
5776
6284
  const scenario = parseScenario(JSON.parse(bytes.toString()));
5777
6285
  if (scenario.id !== id || scenario.version !== version) throw new Error("Scenario identity does not match its stored version");
@@ -5794,23 +6302,6 @@ var init_scenarios = __esm({
5794
6302
  }
5795
6303
  });
5796
6304
 
5797
- // src/lib/offline.ts
5798
- var init_offline = __esm({
5799
- "src/lib/offline.ts"() {
5800
- "use strict";
5801
- }
5802
- });
5803
-
5804
- // src/runtime/credentials.ts
5805
- import { homedir } from "os";
5806
- import { join as join9 } from "path";
5807
- import { readFile as readFile6, mkdir as mkdir3, writeFile as writeFile7, chmod, rm as rm5 } from "fs/promises";
5808
- var init_credentials = __esm({
5809
- "src/runtime/credentials.ts"() {
5810
- "use strict";
5811
- }
5812
- });
5813
-
5814
6305
  // src/lib/exit.ts
5815
6306
  var EXIT, CliError;
5816
6307
  var init_exit = __esm({
@@ -5837,9 +6328,37 @@ var init_exit = __esm({
5837
6328
  }
5838
6329
  });
5839
6330
 
6331
+ // src/runtime/stage-worker.ts
6332
+ import { copyFile, rm as rm7 } from "fs/promises";
6333
+ import { basename, dirname as dirname2, join as join11 } from "path";
6334
+ import { fileURLToPath as fileURLToPath2 } from "url";
6335
+ var init_stage_worker = __esm({
6336
+ "src/runtime/stage-worker.ts"() {
6337
+ "use strict";
6338
+ init_exit();
6339
+ }
6340
+ });
6341
+
6342
+ // src/lib/offline.ts
6343
+ var init_offline = __esm({
6344
+ "src/lib/offline.ts"() {
6345
+ "use strict";
6346
+ }
6347
+ });
6348
+
6349
+ // src/runtime/credentials.ts
6350
+ import { homedir } from "os";
6351
+ import { join as join12 } from "path";
6352
+ import { readFile as readFile7, mkdir as mkdir4, writeFile as writeFile8, chmod as chmod2, rm as rm8 } from "fs/promises";
6353
+ var init_credentials = __esm({
6354
+ "src/runtime/credentials.ts"() {
6355
+ "use strict";
6356
+ }
6357
+ });
6358
+
5840
6359
  // src/runtime/remote.ts
5841
- import { readFile as readFile7 } from "fs/promises";
5842
- import { join as join10 } from "path";
6360
+ import { readFile as readFile8 } from "fs/promises";
6361
+ import { join as join13 } from "path";
5843
6362
  var init_remote = __esm({
5844
6363
  "src/runtime/remote.ts"() {
5845
6364
  "use strict";
@@ -5850,29 +6369,29 @@ var init_remote = __esm({
5850
6369
  });
5851
6370
 
5852
6371
  // src/runtime/docker-engine.ts
5853
- import { execFile as execFile2 } from "child_process";
5854
- import { promisify as promisify2 } from "util";
5855
- var exec;
6372
+ import { execFile as execFile5 } from "child_process";
6373
+ import { promisify as promisify5 } from "util";
6374
+ var exec4;
5856
6375
  var init_docker_engine = __esm({
5857
6376
  "src/runtime/docker-engine.ts"() {
5858
6377
  "use strict";
5859
- exec = promisify2(execFile2);
6378
+ exec4 = promisify5(execFile5);
5860
6379
  }
5861
6380
  });
5862
6381
 
5863
6382
  // src/runtime/docker-postgres.ts
5864
6383
  import postgres from "postgres";
5865
- import { execFile as execFile3, spawn as spawn2 } from "child_process";
5866
- import { promisify as promisify3, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
5867
- import { randomBytes as randomBytes2, randomUUID } from "crypto";
6384
+ import { execFile as execFile6, spawn as spawn2 } from "child_process";
6385
+ import { promisify as promisify6, isDeepStrictEqual as isDeepStrictEqual5 } from "util";
6386
+ import { randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
5868
6387
  import { Duplex } from "stream";
5869
- var exec2;
6388
+ var exec5;
5870
6389
  var init_docker_postgres = __esm({
5871
6390
  "src/runtime/docker-postgres.ts"() {
5872
6391
  "use strict";
5873
6392
  init_docker_engine();
5874
6393
  init_postgres_clock();
5875
- exec2 = promisify3(execFile3);
6394
+ exec5 = promisify6(execFile6);
5876
6395
  }
5877
6396
  });
5878
6397
 
@@ -5886,16 +6405,17 @@ var init_stdio_fetch = __esm({
5886
6405
  });
5887
6406
 
5888
6407
  // src/runtime/docker.ts
5889
- import { execFile as execFile4, spawn as spawn3 } from "child_process";
5890
- import { promisify as promisify4 } from "util";
5891
- import { chmod as chmod2, copyFile, mkdir as mkdir4, mkdtemp as mkdtemp5, readFile as readFile8, rm as rm6, writeFile as writeFile8 } from "fs/promises";
5892
- import { tmpdir as tmpdir5 } from "os";
5893
- import { join as join11 } from "path";
5894
- import { randomUUID as randomUUID2 } from "crypto";
5895
- var exec3;
6408
+ import { execFile as execFile7, spawn as spawn3 } from "child_process";
6409
+ import { promisify as promisify7 } from "util";
6410
+ import { chmod as chmod3, copyFile as copyFile2, mkdir as mkdir5, mkdtemp as mkdtemp7, readFile as readFile9, rm as rm9, writeFile as writeFile9 } from "fs/promises";
6411
+ import { tmpdir as tmpdir7 } from "os";
6412
+ import { join as join14 } from "path";
6413
+ import { randomUUID as randomUUID3 } from "crypto";
6414
+ var exec6;
5896
6415
  var init_docker = __esm({
5897
6416
  "src/runtime/docker.ts"() {
5898
6417
  "use strict";
6418
+ init_twin_clock();
5899
6419
  init_http_world();
5900
6420
  init_evaluation();
5901
6421
  init_contracts();
@@ -5906,16 +6426,16 @@ var init_docker = __esm({
5906
6426
  init_application_clock();
5907
6427
  init_docker_engine();
5908
6428
  init_docker_engine();
5909
- exec3 = promisify4(execFile4);
6429
+ exec6 = promisify7(execFile7);
5910
6430
  }
5911
6431
  });
5912
6432
 
5913
6433
  // src/runtime/git.ts
5914
- import { execFile as execFile5 } from "child_process";
5915
- import { promisify as promisify5 } from "util";
6434
+ import { execFile as execFile8 } from "child_process";
6435
+ import { promisify as promisify8 } from "util";
5916
6436
  async function captureGit(cwd, previousHead) {
5917
- const exec4 = promisify5(execFile5);
5918
- const git = async (...args) => (await exec4("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
6437
+ const exec7 = promisify8(execFile8);
6438
+ const git = async (...args) => (await exec7("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
5919
6439
  try {
5920
6440
  const head = await git("rev-parse", "HEAD");
5921
6441
  const [branch, total, status, history] = await Promise.all([git("branch", "--show-current"), git("rev-list", "--count", "HEAD"), git("status", "--porcelain", "--untracked-files=no"), git("log", "--since=14 days ago", "-100", "--format=%H %cI")]);
@@ -5941,22 +6461,36 @@ var init_git = __esm({
5941
6461
  }
5942
6462
  });
5943
6463
 
6464
+ // src/runtime/hosted-packs.ts
6465
+ import { readFile as readFile10, readdir as readdir2 } from "fs/promises";
6466
+ import { join as join15 } from "path";
6467
+ var init_hosted_packs = __esm({
6468
+ "src/runtime/hosted-packs.ts"() {
6469
+ "use strict";
6470
+ init_packs();
6471
+ }
6472
+ });
6473
+
5944
6474
  // src/runtime/e2b.ts
5945
- import { readFile as readFile9 } from "fs/promises";
6475
+ import { createRequire } from "module";
6476
+ import { readFile as readFile11 } from "fs/promises";
5946
6477
  import { randomBytes as randomBytes3 } from "crypto";
5947
6478
  import { homedir as homedir2 } from "os";
5948
- import { join as join12 } from "path";
6479
+ import { join as join16 } from "path";
5949
6480
  var init_e2b = __esm({
5950
6481
  "src/runtime/e2b.ts"() {
5951
6482
  "use strict";
6483
+ init_browser_process();
6484
+ init_hosted_packs();
6485
+ init_postgres_clock();
5952
6486
  init_exit();
5953
6487
  }
5954
6488
  });
5955
6489
 
5956
6490
  // src/runtime/matrix.ts
5957
6491
  import { createHash as createHash8 } from "crypto";
5958
- import { mkdir as mkdir5, readFile as readFile10, writeFile as writeFile9 } from "fs/promises";
5959
- import { join as join13, relative, resolve as resolve3 } from "path";
6492
+ import { mkdir as mkdir6, readFile as readFile12, writeFile as writeFile10 } from "fs/promises";
6493
+ import { join as join17, relative, resolve as resolve3 } from "path";
5960
6494
  var init_matrix = __esm({
5961
6495
  "src/runtime/matrix.ts"() {
5962
6496
  "use strict";
@@ -5968,8 +6502,8 @@ var init_matrix = __esm({
5968
6502
 
5969
6503
  // src/runtime/source-build.ts
5970
6504
  import { createHash as createHash9 } from "crypto";
5971
- import { lstat, readFile as readFile11, realpath as realpath2 } from "fs/promises";
5972
- import { isAbsolute, join as join14, relative as relative2, resolve as resolve4, sep } from "path";
6505
+ import { lstat, readFile as readFile13, realpath as realpath2 } from "fs/promises";
6506
+ import { isAbsolute, join as join18, relative as relative2, resolve as resolve4, sep } from "path";
5973
6507
  import { isDeepStrictEqual as isDeepStrictEqual6 } from "util";
5974
6508
  var init_source_build = __esm({
5975
6509
  "src/runtime/source-build.ts"() {
@@ -5979,11 +6513,10 @@ var init_source_build = __esm({
5979
6513
  });
5980
6514
 
5981
6515
  // src/commands/run.ts
5982
- import { mkdtemp as mkdtemp6, mkdir as mkdir6, readFile as readFile12, writeFile as writeFile10, realpath as realpath3, lstat as lstat2, rm as rm7, copyFile as copyFile2 } from "fs/promises";
5983
- import { tmpdir as tmpdir6 } from "os";
5984
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join15, relative as relative3, resolve as resolve5, sep as sep2 } from "path";
5985
- import { fileURLToPath as fileURLToPath2 } from "url";
5986
- import { createHash as createHash10, randomUUID as randomUUID3 } from "crypto";
6516
+ import { mkdtemp as mkdtemp8, mkdir as mkdir7, readFile as readFile14, writeFile as writeFile11, realpath as realpath3, lstat as lstat2, rm as rm10 } from "fs/promises";
6517
+ import { tmpdir as tmpdir8 } from "os";
6518
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute2, join as join19, relative as relative3, resolve as resolve5, sep as sep2 } from "path";
6519
+ import { createHash as createHash10, randomUUID as randomUUID4 } from "crypto";
5987
6520
  async function stageApplication(root, files, destination) {
5988
6521
  const canonicalRoot = await realpath3(root);
5989
6522
  const digests = {};
@@ -5993,12 +6526,12 @@ async function stageApplication(root, files, destination) {
5993
6526
  const source = await realpath3(resolve5(canonicalRoot, file));
5994
6527
  const rel = relative3(canonicalRoot, source);
5995
6528
  if (rel.startsWith(`..${sep2}`) || rel === ".." || isAbsolute2(rel) || source !== resolve5(canonicalRoot, file) || !(await lstat2(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
5996
- const contents = await readFile12(source);
6529
+ const contents = await readFile14(source);
5997
6530
  bytes += contents.length;
5998
6531
  if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
5999
- const target = join15(destination, file);
6000
- await mkdir6(dirname2(target), { recursive: true });
6001
- await writeFile10(target, contents, { mode: 420 });
6532
+ const target = join19(destination, file);
6533
+ await mkdir7(dirname3(target), { recursive: true });
6534
+ await writeFile11(target, contents, { mode: 420 });
6002
6535
  digests[file] = createHash10("sha256").update(contents).digest("hex");
6003
6536
  }
6004
6537
  return digests;
@@ -6006,6 +6539,7 @@ async function stageApplication(root, files, destination) {
6006
6539
  var init_run = __esm({
6007
6540
  "src/commands/run.ts"() {
6008
6541
  "use strict";
6542
+ init_stage_worker();
6009
6543
  init_run_summary();
6010
6544
  init_cost_model();
6011
6545
  init_remote();
@@ -6031,10 +6565,10 @@ init_contracts();
6031
6565
  init_run();
6032
6566
  init_git();
6033
6567
  import { createServer as createServer3 } from "http";
6034
- import { randomBytes as randomBytes4, randomUUID as randomUUID4, createHash as createHash11 } from "crypto";
6035
- import { mkdir as mkdir7, mkdtemp as mkdtemp7, readFile as readFile13, readdir as readdir2, rename, rm as rm8, writeFile as writeFile11 } from "fs/promises";
6036
- import { dirname as dirname3, join as join16, resolve as resolve6, relative as relative4, sep as sep3 } from "path";
6037
- import { tmpdir as tmpdir7 } from "os";
6568
+ import { randomBytes as randomBytes4, randomUUID as randomUUID5, createHash as createHash11 } from "crypto";
6569
+ import { mkdir as mkdir8, mkdtemp as mkdtemp9, readFile as readFile15, readdir as readdir3, rename, rm as rm11, writeFile as writeFile12 } from "fs/promises";
6570
+ import { dirname as dirname4, join as join20, resolve as resolve6, relative as relative4, sep as sep3 } from "path";
6571
+ import { tmpdir as tmpdir9 } from "os";
6038
6572
  import { fileURLToPath as fileURLToPath3 } from "url";
6039
6573
  import { spawn as spawn4 } from "child_process";
6040
6574
  var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
@@ -6044,15 +6578,15 @@ function duration(value) {
6044
6578
  return value;
6045
6579
  }
6046
6580
  async function persist(directory2, session) {
6047
- const temporary = join16(directory2, `${randomUUID4()}.tmp`);
6048
- await writeFile11(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
6049
- await rename(temporary, join16(directory2, "session.json"));
6581
+ const temporary = join20(directory2, `${randomUUID5()}.tmp`);
6582
+ await writeFile12(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
6583
+ await rename(temporary, join20(directory2, "session.json"));
6050
6584
  }
6051
6585
  var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
6052
6586
  async function serveWorldSession(directory2) {
6053
- const session = JSON.parse(await readFile13(join16(directory2, "session.json"), "utf8"));
6587
+ const session = JSON.parse(await readFile15(join20(directory2, "session.json"), "utf8"));
6054
6588
  if (session.status !== "provisioning" || !uuid.test(session.id)) throw new Error("Session is not awaiting provisioning");
6055
- const spec = parseWorld(JSON.parse(await readFile13(join16(directory2, "world.json"), "utf8")));
6589
+ const spec = parseWorld(JSON.parse(await readFile15(join20(directory2, "world.json"), "utf8")));
6056
6590
  const world = new HttpWorld(spec);
6057
6591
  let control;
6058
6592
  let timer;
@@ -6152,10 +6686,10 @@ async function serveWorldSession(directory2) {
6152
6686
  reply(200, { ...view(session), state: world.snapshot() });
6153
6687
  return;
6154
6688
  }
6155
- let current = parseWorld(JSON.parse(await readFile13(session.file, "utf8")));
6689
+ let current = parseWorld(JSON.parse(await readFile15(session.file, "utf8")));
6156
6690
  if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
6157
6691
  if (hash2(current) !== hash2(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
6158
- const stage = await mkdtemp7(join16(tmpdir7(), "agenttwin-session-run-"));
6692
+ const stage = await mkdtemp9(join20(tmpdir9(), "agenttwin-session-run-"));
6159
6693
  active = new AbortController();
6160
6694
  let result;
6161
6695
  try {
@@ -6163,28 +6697,28 @@ async function serveWorldSession(directory2) {
6163
6697
  session.status = "running";
6164
6698
  await save();
6165
6699
  active.signal.throwIfAborted();
6166
- const sourceDigests = await stageApplication(dirname3(session.file), spec.files, stage);
6700
+ const sourceDigests = await stageApplication(dirname4(session.file), spec.files, stage);
6167
6701
  active.signal.throwIfAborted();
6168
6702
  world.reset();
6169
6703
  const report = await executeLocal(stage, spec, active.signal, world);
6170
6704
  if (stopping) throw new Error("World expired during execution");
6171
- const runId = randomUUID4();
6705
+ const runId = randomUUID5();
6172
6706
  let project = "local-workspace";
6173
6707
  try {
6174
- project = JSON.parse(await readFile13(join16(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
6708
+ project = JSON.parse(await readFile15(join20(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
6175
6709
  } catch {
6176
6710
  }
6177
- const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname3(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
6178
- const out = join16(session.cwd, ".agenttwin/runs", runId);
6179
- await mkdir7(out, { recursive: true, mode: 448 });
6180
- const evidencePath = join16(out, "run.json");
6181
- await writeFile11(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
6182
- await writeFile11(join16(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
6711
+ const receipt = { ...report, sourceDirectory: relative4(session.cwd, dirname4(session.file)).split(sep3).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash2(spec), provenance: "CLI-reported execution; not independently attested" };
6712
+ const out = join20(session.cwd, ".agenttwin/runs", runId);
6713
+ await mkdir8(out, { recursive: true, mode: 448 });
6714
+ const evidencePath = join20(out, "run.json");
6715
+ await writeFile12(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
6716
+ await writeFile12(join20(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
6183
6717
  session.lastRunId = runId;
6184
6718
  result = { ...receipt, evidencePath };
6185
6719
  } finally {
6186
6720
  active = void 0;
6187
- await rm8(stage, { recursive: true, force: true });
6721
+ await rm11(stage, { recursive: true, force: true });
6188
6722
  if (!stopping) {
6189
6723
  session.status = "ready";
6190
6724
  await save();
@@ -6202,7 +6736,7 @@ async function serveWorldSession(directory2) {
6202
6736
  control.once("error", reject);
6203
6737
  control.listen(0, "127.0.0.1", resolve7);
6204
6738
  });
6205
- const latest = JSON.parse(await readFile13(join16(directory2, "session.json"), "utf8"));
6739
+ const latest = JSON.parse(await readFile15(join20(directory2, "session.json"), "utf8"));
6206
6740
  if (latest.status !== "provisioning") throw new Error("Provisioning was abandoned");
6207
6741
  session.controlUrl = `http://127.0.0.1:${control.address().port}`;
6208
6742
  if (stopping) throw new Error("World expired during provisioning");