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
package/dist/worker.js CHANGED
@@ -1,21 +1,301 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- // src/runtime/worker.ts
4
- import { readFile as readFile2 } from "fs/promises";
5
- import { promisify } from "util";
3
+ // src/runtime/application-process.ts
6
4
  import { execFile } from "child_process";
7
- import { spawn } from "child_process";
8
-
9
- // src/runtime/http-world.ts
10
- import { createServer } from "http";
11
- import { isDeepStrictEqual } from "util";
12
- import { createHash as createHash5 } from "crypto";
13
- import { AsyncLocalStorage } from "async_hooks";
5
+ import { promisify } from "util";
6
+ import { win32 } from "path";
7
+ var exec = promisify(execFile);
8
+ var CLEANUP_MS = 5e3;
9
+ async function processes() {
10
+ if (process.platform === "win32") {
11
+ const shell = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
12
+ 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";
13
+ const { stdout: stdout2 } = await exec(shell, ["-NoProfile", "-NonInteractive", "-Command", script], { timeout: 1e3, windowsHide: true, maxBuffer: 4 * 1024 * 1024 });
14
+ const data = JSON.parse(stdout2.trim() || "[]");
15
+ const rows2 = Array.isArray(data) ? data : [data];
16
+ if (!rows2.every((r) => Number.isSafeInteger(r.pid) && Number.isSafeInteger(r.parent) && typeof r.born === "string")) throw Error("Invalid process evidence");
17
+ return rows2;
18
+ }
19
+ const { stdout } = await exec("ps", ["-axo", "pid=,ppid=,stat=,lstart="], { timeout: 1e3, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } });
20
+ return stdout.trim().split("\n").filter(Boolean).map((line) => {
21
+ const [pid, parent, state, ...born] = line.trim().split(/\s+/);
22
+ return { pid: Number(pid), parent: Number(parent), state, born: born.join(" ") };
23
+ });
24
+ }
25
+ function manageApplication(child) {
26
+ const known2 = /* @__PURE__ */ new Map();
27
+ let scan = Promise.resolve();
28
+ let scanError;
29
+ let stopPromise;
30
+ const exited = new Promise((resolve3, reject) => {
31
+ child.once("exit", resolve3);
32
+ child.once("error", reject);
33
+ });
34
+ void exited.catch(() => {
35
+ });
36
+ const closed = new Promise((resolve3) => {
37
+ child.once("close", () => resolve3());
38
+ child.once("error", () => resolve3());
39
+ });
40
+ async function capture() {
41
+ const rows2 = await processes();
42
+ for (const [pid, born] of known2) if (!rows2.some((r) => r.pid === pid && r.born === born)) known2.delete(pid);
43
+ const root = rows2.find((r) => r.pid === child.pid);
44
+ if (root && child.exitCode === null && child.signalCode === null) known2.set(root.pid, root.born);
45
+ let changed = true;
46
+ while (changed) {
47
+ changed = false;
48
+ for (const row of rows2) {
49
+ if (row.pid > 1 && known2.has(row.parent) && !known2.has(row.pid)) {
50
+ known2.set(row.pid, row.born);
51
+ changed = true;
52
+ }
53
+ }
54
+ }
55
+ return rows2.filter((r) => known2.get(r.pid) === r.born && !r.state.startsWith("Z"));
56
+ }
57
+ let scanning = false;
58
+ const tick = () => {
59
+ if (scanning) return;
60
+ scanning = true;
61
+ scan = capture().then(() => {
62
+ }, (e) => {
63
+ scanError = e;
64
+ }).finally(() => {
65
+ scanning = false;
66
+ });
67
+ };
68
+ tick();
69
+ const monitor = setInterval(tick, 100);
70
+ monitor.unref();
71
+ function killRoot() {
72
+ if (child.pid && child.exitCode === null && child.signalCode === null) {
73
+ try {
74
+ process.platform === "win32" ? child.kill("SIGKILL") : process.kill(-child.pid, "SIGKILL");
75
+ } catch {
76
+ }
77
+ }
78
+ }
79
+ async function terminate() {
80
+ await scan;
81
+ try {
82
+ const targets = await capture();
83
+ if (process.platform === "win32" && targets.length) {
84
+ const exe = win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "taskkill.exe");
85
+ try {
86
+ await exec(exe, [...targets.flatMap((t) => ["/PID", String(t.pid)]), "/T", "/F"], { timeout: 1e3, windowsHide: true });
87
+ } catch {
88
+ }
89
+ } else {
90
+ for (const target of targets.reverse()) try {
91
+ process.kill(target.pid, "SIGKILL");
92
+ } catch (e) {
93
+ if (e.code !== "ESRCH") throw e;
94
+ }
95
+ }
96
+ killRoot();
97
+ const until = Date.now() + 2e3;
98
+ while ((await capture()).length) {
99
+ if (Date.now() >= until) throw Error("Application processes remain after termination");
100
+ await new Promise((r) => setTimeout(r, 25));
101
+ }
102
+ if (scanError) throw scanError;
103
+ } finally {
104
+ killRoot();
105
+ }
106
+ }
107
+ function stop() {
108
+ if (!stopPromise) {
109
+ clearInterval(monitor);
110
+ stopPromise = terminate();
111
+ void stopPromise.catch(() => {
112
+ });
113
+ }
114
+ return stopPromise;
115
+ }
116
+ return { exited, stop, async finish() {
117
+ let timer;
118
+ try {
119
+ await Promise.race([(async () => {
120
+ await stop();
121
+ await closed;
122
+ })(), new Promise((_, reject) => {
123
+ timer = setTimeout(() => reject(Error("Application cleanup deadline exceeded")), CLEANUP_MS);
124
+ })]);
125
+ } finally {
126
+ clearInterval(monitor);
127
+ if (timer) clearTimeout(timer);
128
+ for (const stream of child.stdio) if (stream && "destroy" in stream) stream.destroy();
129
+ child.unref();
130
+ }
131
+ } };
132
+ }
14
133
 
15
- // src/runtime/request-source.ts
16
- import { mkdtemp, writeFile, readFile, rm, realpath } from "fs/promises";
134
+ // src/runtime/browser-process.ts
135
+ import { mkdtemp, writeFile, readFile, rm } from "fs/promises";
17
136
  import { tmpdir } from "os";
18
- import { join, resolve } from "path";
137
+ import { join } from "path";
138
+ import { execFile as execFile3 } from "child_process";
139
+ import { promisify as promisify3 } from "util";
140
+
141
+ // src/runtime/browser-process-windows.ts
142
+ import { randomUUID } from "crypto";
143
+ import { execFile as execFile2 } from "child_process";
144
+ import { promisify as promisify2 } from "util";
145
+ import { win32 as win322 } from "path";
146
+ var exec2 = promisify2(execFile2);
147
+ var run = (file, args) => exec2(file, args, { windowsHide: true, timeout: 2e3, maxBuffer: 4 * 1024 * 1024 });
148
+ function windowsBrowserProcess(executable, commands = run) {
149
+ const marker = "--agenttwin-browser-owner=" + randomUUID();
150
+ const system = process.env.SystemRoot || process.env.SYSTEMROOT || "C:\\Windows";
151
+ const powershell = win322.join(system, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
152
+ const taskkill = win322.join(system, "System32", "taskkill.exe");
153
+ const known2 = /* @__PURE__ */ new Map();
154
+ 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";
155
+ async function snapshot() {
156
+ const { stdout } = await commands(powershell, ["-NoProfile", "-NonInteractive", "-Command", script]);
157
+ const parsed = JSON.parse(stdout.trim() || "[]");
158
+ const rows2 = Array.isArray(parsed) ? parsed : [parsed];
159
+ 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");
160
+ return rows2;
161
+ }
162
+ async function owned() {
163
+ const rows2 = await snapshot();
164
+ for (const [pid, created2] of known2) if (!rows2.some((r) => r.pid === pid && r.created === created2)) known2.delete(pid);
165
+ for (const row of rows2) if (row.parent === process.pid && row.command.split(/[\s"]+/).includes(marker)) known2.set(row.pid, row.created);
166
+ let changed = true;
167
+ while (changed) {
168
+ changed = false;
169
+ for (const row of rows2) {
170
+ const parent = known2.get(row.parent);
171
+ if (row.pid > 1 && parent && row.created >= parent && !known2.has(row.pid)) {
172
+ known2.set(row.pid, row.created);
173
+ changed = true;
174
+ }
175
+ }
176
+ }
177
+ return rows2.filter((r) => known2.get(r.pid) === r.created);
178
+ }
179
+ return {
180
+ launcher: executable,
181
+ args: [marker],
182
+ async alive() {
183
+ return (await owned()).map((r) => r.pid);
184
+ },
185
+ async kill() {
186
+ const targets = await owned();
187
+ if (!targets.length) return;
188
+ const current = await snapshot();
189
+ const live = targets.filter((t) => current.some((r) => r.pid === t.pid && r.created === t.created));
190
+ if (!live.length) return;
191
+ try {
192
+ await commands(taskkill, [...live.flatMap((t) => ["/PID", String(t.pid)]), "/T", "/F"]);
193
+ } catch (error) {
194
+ if ((await snapshot()).some((r) => live.some((t) => r.pid === t.pid && r.created === t.created))) throw error;
195
+ }
196
+ }
197
+ };
198
+ }
199
+
200
+ // src/runtime/browser-process.ts
201
+ var exec3 = promisify3(execFile3);
202
+ var BROWSER_STARTUP_MS = 2e4;
203
+ var BROWSER_CLEANUP_MS = 3e3;
204
+ var quote = (s) => "'" + s.replaceAll("'", `'"'"'`) + "'";
205
+ var pause = (ms) => new Promise((r) => setTimeout(r, ms));
206
+ async function ownBrowserProcess(executable) {
207
+ if (process.platform === "win32") return withCleanup(windowsBrowserProcess(executable), async () => {
208
+ });
209
+ const root = await mkdtemp(join(tmpdir(), "agenttwin-browser-owner-"));
210
+ const pidFile = join(root, "pid"), launcher = join(root, "launch");
211
+ await writeFile(launcher, `#!/bin/sh
212
+ echo $$ > ${quote(pidFile)}
213
+ exec ${quote(executable)} "$@"
214
+ `, { mode: 448 });
215
+ let group;
216
+ async function processes2() {
217
+ const { stdout } = await exec3("ps", ["-axo", "pid=,pgid=,stat="], { timeout: 2e3, maxBuffer: 4 * 1024 * 1024 });
218
+ return stdout.trim().split("\n").map((line) => {
219
+ const [pid, pgid, state] = line.trim().split(/\s+/);
220
+ return { pid: Number(pid), pgid: Number(pgid), state };
221
+ });
222
+ }
223
+ async function discover() {
224
+ if (group) return group;
225
+ let pid;
226
+ try {
227
+ pid = Number((await readFile(pidFile, "utf8")).trim());
228
+ } catch (e) {
229
+ if (e.code === "ENOENT") return;
230
+ throw e;
231
+ }
232
+ if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error("Invalid browser process identity");
233
+ const rows2 = await processes2(), leader = rows2.find((p) => p.pid === pid);
234
+ if (leader && leader.pgid !== pid) throw new Error("Browser launcher does not own its process group");
235
+ group = pid;
236
+ return group;
237
+ }
238
+ async function alive() {
239
+ const id = await discover();
240
+ return id ? (await processes2()).filter((p) => p.pgid === id && !p.state?.startsWith("Z")).map((p) => p.pid) : [];
241
+ }
242
+ async function kill() {
243
+ const id = await discover();
244
+ if (id) {
245
+ try {
246
+ process.kill(-id, "SIGKILL");
247
+ } catch (e) {
248
+ if (e.code !== "ESRCH") throw e;
249
+ }
250
+ }
251
+ }
252
+ return withCleanup({ launcher, args: [], alive, kill }, () => rm(root, { recursive: true, force: true }));
253
+ }
254
+ function withCleanup(owner, dispose) {
255
+ const { alive, kill } = owner;
256
+ return { ...owner, async finish(close) {
257
+ let timer, forced = false;
258
+ let inspectionError;
259
+ try {
260
+ try {
261
+ await alive();
262
+ } catch (error) {
263
+ inspectionError = error;
264
+ }
265
+ const closed = Promise.resolve().then(close).then(() => true, () => false);
266
+ const graceful = await Promise.race([closed, new Promise((resolve3) => {
267
+ timer = setTimeout(() => resolve3(false), BROWSER_CLEANUP_MS);
268
+ })]);
269
+ if (inspectionError) {
270
+ if (!graceful) {
271
+ forced = true;
272
+ try {
273
+ await kill();
274
+ } catch {
275
+ }
276
+ }
277
+ throw inspectionError;
278
+ }
279
+ if (!graceful || (await alive()).length) {
280
+ forced = true;
281
+ await kill();
282
+ }
283
+ const until = Date.now() + 2e3;
284
+ while ((await alive()).length) {
285
+ if (Date.now() > until) throw new Error("Browser cleanup could not confirm process exit");
286
+ await kill();
287
+ await pause(25);
288
+ }
289
+ return { forced, remainingProcesses: 0 };
290
+ } finally {
291
+ if (timer) clearTimeout(timer);
292
+ await dispose();
293
+ }
294
+ } };
295
+ }
296
+
297
+ // src/runtime/twin-clock.ts
298
+ import { AsyncLocalStorage } from "async_hooks";
19
299
 
20
300
  // src/runtime/application-clock.ts
21
301
  function validApplicationClock(value) {
@@ -23,8 +303,59 @@ function validApplicationClock(value) {
23
303
  const now = value.now;
24
304
  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;
25
305
  }
306
+ function applicationClockEvidence(clock) {
307
+ return clock ? { now: clock.now, scope: "date-wall-clock" } : void 0;
308
+ }
309
+ function applicationClockHook(clock) {
310
+ if (!clock) return "";
311
+ if (!validApplicationClock(clock)) throw new Error("Invalid applicationClock");
312
+ return `{
313
+ const NativeDate=globalThis.Date,epoch=${Date.parse(clock.now)};
314
+ const fixedNow=()=>epoch;
315
+ const ClockDate=new Proxy(NativeDate,{
316
+ apply(){return new NativeDate(epoch).toString();},
317
+ construct(target,args,newTarget){return Reflect.construct(target,args.length?args:[epoch],newTarget);}
318
+ });
319
+ Object.defineProperty(NativeDate,'now',{value:fixedNow,writable:true,configurable:true});
320
+ Object.defineProperty(NativeDate.prototype,'constructor',{value:ClockDate,writable:true,configurable:true});
321
+ globalThis.Date=ClockDate;
322
+ }
323
+ `;
324
+ }
325
+
326
+ // src/runtime/twin-clock.ts
327
+ var validTwinClock = validApplicationClock;
328
+ var key = /* @__PURE__ */ Symbol.for("agenttwin.twinClock.v1");
329
+ var registry = globalThis;
330
+ var context = registry[key] ?? new AsyncLocalStorage();
331
+ if (!registry[key]) Object.defineProperty(registry, key, { value: context });
332
+ function withTwinClock(clock, action) {
333
+ if (clock !== void 0 && !validTwinClock(clock)) throw new Error("Invalid twin clock");
334
+ return context.run(clock?.now, action);
335
+ }
336
+ function twinNowMs(fallback) {
337
+ const now = context.getStore();
338
+ return now === void 0 ? fallback : Date.parse(now);
339
+ }
340
+ var twinNowSeconds = (fallback) => Math.floor(twinNowMs(fallback * 1e3) / 1e3);
341
+ var twinClockEvidence = (clock) => clock ? { now: clock.now, scope: "twin-wall-clock" } : void 0;
342
+
343
+ // src/runtime/hosted-worker.ts
344
+ import { readFile as readFile4, chmod as chmod2, realpath as realpath2 } from "fs/promises";
345
+ import { promisify as promisify4 } from "util";
346
+ import { execFile as execFile4 } from "child_process";
347
+ import { spawn } from "child_process";
348
+
349
+ // src/runtime/http-world.ts
350
+ import { createServer } from "http";
351
+ import { isDeepStrictEqual } from "util";
352
+ import { createHash as createHash5 } from "crypto";
353
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "async_hooks";
26
354
 
27
355
  // src/runtime/request-source.ts
356
+ import { mkdtemp as mkdtemp2, writeFile as writeFile2, readFile as readFile2, rm as rm2, realpath } from "fs/promises";
357
+ import { tmpdir as tmpdir2 } from "os";
358
+ import { join as join2, resolve } from "path";
28
359
  function parseRequestSource(raw, spec) {
29
360
  if (typeof raw !== "string" || raw.length > 1024) return;
30
361
  try {
@@ -35,6 +366,69 @@ function parseRequestSource(raw, spec) {
35
366
  return;
36
367
  }
37
368
  }
369
+ async function createRequestSourceHook(app, spec, credentials, runtime) {
370
+ const dir = await mkdtemp2(join2(tmpdir2(), "agenttwin-source-hook-"));
371
+ const path = join2(dir, "hook.cjs");
372
+ const violationsPath = join2(dir, "blocked.jsonl");
373
+ 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 };
374
+ const hook = applicationClockHook(spec.applicationClock) + `const config=${JSON.stringify(config)};
375
+ ` + String.raw`
376
+ const http=require('node:http'),https=require('node:https'),path=require('node:path'),{fileURLToPath}=require('node:url');
377
+ const origins=new Set(config.origins),files=new Set(config.files);
378
+ function source(){for(const frame of new Error().stack.split('\n').slice(2)){const match=frame.match(/(?:\(|\s)(file:\/\/[^\s)]+|\/[^\s)]+):(\d+):(\d+)\)?$/);if(!match)continue;let file;try{file=match[1].startsWith('file:')?fileURLToPath(match[1]):match[1];}catch{continue;}file=path.relative(config.root,file);if(files.has(file))return JSON.stringify({file,line:Number(match[2]),column:Number(match[3])});}}
379
+ const blockedOrigins=new Set();
380
+ const originalFetch=globalThis.fetch;
381
+ if(originalFetch)globalThis.fetch=async function(input,init){
382
+ 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');}
383
+ const route=Object.hasOwn(config.routes,url.origin)?config.routes[url.origin]:undefined;
384
+ if(config.routing&&!route&&!origins.has(url.origin)){
385
+ 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');}
386
+ throw new Error('AgentTwin blocked fetch to an unmapped origin: '+url.origin);
387
+ }
388
+ if(!route&&!origins.has(url.origin))return originalFetch(input,init);
389
+ if(!config.routing){const location=source();if(!location)return originalFetch(input,init);const headers=new Headers(init?.headers??input?.headers);headers.set('x-agenttwin-source',location);return originalFetch(input,{...init,headers});}
390
+ const request=new Request(input,init);
391
+ const headers=new Headers(request.headers);
392
+ if(route){headers.delete('cookie');headers.delete('proxy-authorization');headers.set('authorization','Bearer '+route.token);}
393
+ const location=source();if(location)headers.set('x-agenttwin-source',location);
394
+ const target=route?route.endpoint+url.pathname+url.search:url.href;
395
+ return originalFetch(new Request(target,request),{headers,redirect:'error'});
396
+ };
397
+ const plainHttp={request:http.request,get:http.get};
398
+ const loopback=host=>['127.0.0.1','localhost','::1','[::1]'].includes(host);
399
+ 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);}
400
+ // SDKs on node:http/https (Stripe, Slack via axios) reach mapped vendor origins only through their twin.
401
+ function routeNode(method,route,url,options,index,args){
402
+ const target=new URL(route.endpoint),headers={};
403
+ const raw=Array.isArray(options.headers)?Object.fromEntries(options.headers.reduce((pairs,item,i,all)=>i%2?pairs:[...pairs,[item,all[i+1]]],[])):options.headers||{};
404
+ for(const [key,value] of Object.entries(raw))if(!['authorization','cookie','proxy-authorization','host'].includes(key.toLowerCase()))headers[key]=value;
405
+ headers.authorization='Bearer '+route.token;headers.host=target.host;
406
+ const location=source();if(location)headers['x-agenttwin-source']=location;
407
+ const path=index===1?url.pathname+url.search:(options.path||'/');
408
+ const {agent:_agent,servername:_servername,createConnection:_connection,...rest}=options;
409
+ const updated={...rest,protocol:'http:',hostname:target.hostname,host:target.hostname,port:target.port,path,headers};
410
+ const tail=index===1?args.slice(args[1]&&typeof args[1]==='object'?2:1):args.slice(1);
411
+ const req=plainHttp[method].call(http,updated,...tail);
412
+ // Plain-HTTP twin: clients that write only after 'secureConnect' (stripe-node) need the handshake signal.
413
+ if(url.protocol==='https:')req.once('socket',socket=>{if(socket.connecting)socket.once('connect',()=>socket.emit('secureConnect'));else socket.emit('secureConnect');});
414
+ return req;
415
+ }
416
+ for(const mod of [http,https])for(const method of ['request','get']){const original=mod[method];mod[method]=function(...args){let options,url,index;try{if(typeof args[0]==='string'||args[0] instanceof URL){url=new URL(args[0]);index=1;options=args[1]&&typeof args[1]==='object'?args[1]:{};}else{index=0;options=args[0]||{};url=new URL((options.protocol||(mod===https?'https:':'http:'))+'//'+(options.hostname||options.host||'localhost')+(options.port?':'+options.port:''));}}catch{return original.apply(this,args);}
417
+ if(config.routing&&Object.hasOwn(config.routes,url.origin))return routeNode(method,config.routes[url.origin],url,options,index,args);
418
+ if(config.routing&&!origins.has(url.origin)&&!loopback(url.hostname))blockNode(url.origin);
419
+ if(!origins.has(url.origin))return original.apply(this,args);const location=source();if(!location)return original.apply(this,args);const headers=Array.isArray(options.headers)?[...options.headers,'x-agenttwin-source',location]:{...options.headers,'x-agenttwin-source':location};const updated={...options,headers};if(index===1&&typeof args[1]==='function')args.splice(1,0,updated);else args[index]=updated;return original.apply(this,args);};}
420
+ require('node:module').syncBuiltinESMExports();
421
+ `;
422
+ await writeFile2(path, hook, { mode: 384 });
423
+ return { path, violationsPath, readViolations: async () => {
424
+ try {
425
+ return (await readFile2(violationsPath, "utf8")).trim().split("\n").filter(Boolean).map((line) => JSON.parse(line));
426
+ } catch (error) {
427
+ if (error.code === "ENOENT") return [];
428
+ throw error;
429
+ }
430
+ }, close: () => rm2(dir, { recursive: true, force: true }) };
431
+ }
38
432
 
39
433
  // src/runtime/stripe-adapter.ts
40
434
  var stripeError = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
@@ -46,14 +440,14 @@ function nextId(rows2, prefix, sequence) {
46
440
  function chargeFor(intent, data, sequence) {
47
441
  const charges = data["/v1/charges"];
48
442
  if (!charges || intent.latest_charge) return;
49
- 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 };
443
+ 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 };
50
444
  charges.push(charge);
51
445
  intent.latest_charge = charge.id;
52
446
  }
53
447
  function metadataOf(params) {
54
- const entries = Object.entries(params).filter(([key]) => /^metadata\[[^\]]+\]$/.test(key));
448
+ const entries = Object.entries(params).filter(([key2]) => /^metadata\[[^\]]+\]$/.test(key2));
55
449
  if (params.metadata && typeof params.metadata === "object" && !Array.isArray(params.metadata)) return params.metadata;
56
- return Object.fromEntries(entries.map(([key, value]) => [key.slice(9, -1), String(value)]));
450
+ return Object.fromEntries(entries.map(([key2, value]) => [key2.slice(9, -1), String(value)]));
57
451
  }
58
452
  function refundOperation(method, id, params, data, sequence) {
59
453
  const collection = "/v1/refunds", refunds = data[collection], charges = data["/v1/charges"];
@@ -91,12 +485,12 @@ function refundOperation(method, id, params, data, sequence) {
91
485
  if (amount > remaining) return { ...stripeError(400, "amount_too_large", `Refund amount (${amount}) is greater than unrefunded amount on charge (${remaining})`, "amount"), collection };
92
486
  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 };
93
487
  if (refunds.length >= 1e4) return { ...stripeError(429, "world_capacity", "World record capacity reached"), collection };
94
- 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 };
488
+ 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) };
95
489
  refunds.push(refund);
96
490
  charge.amount_refunded = Number(charge.amount_refunded ?? 0) + amount;
97
491
  charge.refunded = charge.amount_refunded === charge.amount;
98
492
  const events = data["/v1/events"];
99
- if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: 17e8, livemode: false, data: { object: structuredClone(charge) } });
493
+ if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: twinNowSeconds(17e8), livemode: false, data: { object: structuredClone(charge) } });
100
494
  return { status: 200, body: refund, collection, record: structuredClone(refund), operation: "write" };
101
495
  }
102
496
  function readOnlyOperation(method, resource, id, params, data) {
@@ -146,10 +540,10 @@ function stripeOperation(method, path, params, data, sequence) {
146
540
  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" };
147
541
  }
148
542
  const form = Object.fromEntries(Object.entries(params).map(([k, v]) => [k, v])), nested = {};
149
- for (const [key, value] of Object.entries(form)) {
150
- const m = /^([^[]+)((?:\[[^\]]*\])+)$/.exec(key);
543
+ for (const [key2, value] of Object.entries(form)) {
544
+ const m = /^([^[]+)((?:\[[^\]]*\])+)$/.exec(key2);
151
545
  if (!m) {
152
- nested[key] = value;
546
+ nested[key2] = value;
153
547
  continue;
154
548
  }
155
549
  const path2 = [m[1], ...[...m[2].matchAll(/\[([^\]]*)\]/g)].map((x) => x[1])];
@@ -163,7 +557,7 @@ function stripeOperation(method, path, params, data, sequence) {
163
557
  const prefix = resource === "customers" ? "cus" : "pi";
164
558
  let suffix = sequence;
165
559
  while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
166
- const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: 17e8, livemode: false };
560
+ const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: twinNowSeconds(17e8), livemode: false };
167
561
  if (resource === "customers") {
168
562
  if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
169
563
  Object.assign(created2, { email: null, name: null, description: null, metadata: {}, ...nested });
@@ -180,7 +574,7 @@ function stripeOperation(method, path, params, data, sequence) {
180
574
  }
181
575
  if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
182
576
  if (resource === "payment_intents") {
183
- for (const key of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key] !== void 0) created2[key] = nested[key];
577
+ for (const key2 of ["description", "receipt_email", "statement_descriptor", "capture_method"]) if (nested[key2] !== void 0) created2[key2] = nested[key2];
184
578
  }
185
579
  if (resource === "payment_intents") created2.metadata = typeof nested.metadata === "object" && nested.metadata ? nested.metadata : {};
186
580
  rows2.push(created2);
@@ -374,7 +768,7 @@ function anthropicOperation(method, path, params, _headers, data, sequence) {
374
768
  // src/runtime/composio-twin.ts
375
769
  var SEND = ["GMAIL_SEND_EMAIL", "GMAIL_SEND_MESSAGE"];
376
770
  var object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
377
- var known = (v, keys) => Object.keys(v).every((key) => keys.includes(key));
771
+ var known = (v, keys) => Object.keys(v).every((key2) => keys.includes(key2));
378
772
  var list = (v) => v === void 0 ? void 0 : typeof v === "string" && v.length <= 4096 ? v.split(",") : null;
379
773
  var composioOperation = (method, path, params, _headers, data, sequence) => {
380
774
  const match = /^\/api\/v3(?:\.1)?\/(.+)$/.exec(path);
@@ -430,7 +824,7 @@ import { createHash as createHash2 } from "crypto";
430
824
  // src/runtime/google-oauth-twin.ts
431
825
  import { createHash } from "crypto";
432
826
  var googleOAuthOperation = (method, path, params, headers, data, sequence) => {
433
- if (method !== "POST" || path !== "/token" || Object.keys(params).some((key) => !["client_id", "client_secret", "grant_type", "refresh_token"].includes(key)) || headers.dpop) return;
827
+ if (method !== "POST" || path !== "/token" || Object.keys(params).some((key2) => !["client_id", "client_secret", "grant_type", "refresh_token"].includes(key2)) || headers.dpop) return;
434
828
  const error = (status, code) => ({ status, collection: "/tokens", body: { error: code } });
435
829
  if (params.grant_type !== "refresh_token") return;
436
830
  if (typeof params.client_id !== "string" || typeof params.refresh_token !== "string" || !params.client_id || !params.refresh_token) return error(400, "invalid_request");
@@ -475,7 +869,7 @@ function parseGmailRaw(raw) {
475
869
 
476
870
  // src/runtime/rest-adapters.ts
477
871
  var EPOCH = 17e8;
478
- var iso = (epoch = EPOCH) => new Date(epoch * 1e3).toISOString();
872
+ var iso = (epoch = EPOCH) => new Date(twinNowMs(epoch * 1e3)).toISOString();
479
873
  var sha = (value) => createHash2("sha256").update(value).digest("hex");
480
874
  var detUuid = (seed) => {
481
875
  const hex = sha(seed).slice(0, 32).split("");
@@ -497,9 +891,9 @@ var pagination = (params, limitDefault, limitMax) => {
497
891
  const limit = params.limit === void 0 ? limitDefault : Number(params.limit);
498
892
  return { limit };
499
893
  };
500
- var uniqueId = (existing, base, key = "id") => {
894
+ var uniqueId = (existing, base, key2 = "id") => {
501
895
  let candidate = base;
502
- while (existing.some((r) => r[key] === String(candidate))) candidate++;
896
+ while (existing.some((r) => r[key2] === String(candidate))) candidate++;
503
897
  return String(candidate);
504
898
  };
505
899
  var boundedInt = (value, min, max) => {
@@ -527,9 +921,9 @@ function githubOperation(method, path, params, _headers, data, sequence) {
527
921
  if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
528
922
  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" }] });
529
923
  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" }] });
530
- const run = { 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() };
531
- rows(data, "/check-runs").push(run);
532
- return created("/check-runs", structuredClone(run), run);
924
+ 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() };
925
+ rows(data, "/check-runs").push(run2);
926
+ return created("/check-runs", structuredClone(run2), run2);
533
927
  }
534
928
  if (resource === "issues") {
535
929
  const inRepo = rows(data, "/issues").filter((r) => r.repo === repo);
@@ -919,7 +1313,7 @@ function datadogOperation(method, path, params, _headers, data, sequence) {
919
1313
  if (method === "POST") {
920
1314
  if (Object.keys(params).some((k) => !["title", "text", "tags", "priority", "alert_type", "source"].includes(k))) return void 0;
921
1315
  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"] });
922
- 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" };
1316
+ 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" };
923
1317
  rows(data, "/events").push(event);
924
1318
  return { status: 200, body: { status: "ok", event: structuredClone(event) }, collection: "/events", record: structuredClone(event), operation: "write" };
925
1319
  }
@@ -973,7 +1367,7 @@ function gmailOperation(method, path, params, _headers, data, sequence) {
973
1367
  const mime = raw ? parseGmailRaw(raw) : void 0;
974
1368
  if (mime && "error" in mime) return mime.unsupported ? void 0 : fail(400, mime.error);
975
1369
  const body = mime?.text ?? text ?? "";
976
- 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) };
1370
+ 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) };
977
1371
  rowsIn(data, MESSAGES).push(message);
978
1372
  return write(200, MESSAGES, structuredClone(message), message);
979
1373
  }
@@ -1038,7 +1432,7 @@ function googleCalendarOperation(method, path, params, _headers, data, sequence)
1038
1432
  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;
1039
1433
  if (timed) events = events.filter((row) => timestamp(row.end.dateTime) > lower && timestamp(row.start.dateTime) < upper);
1040
1434
  if (params.orderBy === "startTime") events = [...events].sort((a, b) => timestamp(a.start.dateTime) - timestamp(b.start.dateTime));
1041
- const query = Object.fromEntries(Object.entries(params).filter(([key]) => key !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
1435
+ const query = Object.fromEntries(Object.entries(params).filter(([key2]) => key2 !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
1042
1436
  const fingerprint = sha(JSON.stringify({ query, events })).slice(0, 20);
1043
1437
  let offset = 0;
1044
1438
  if (params.pageToken !== void 0) {
@@ -1504,7 +1898,7 @@ var FIRST = ["Avery", "Jordan", "Riley", "Morgan", "Casey", "Quinn", "Harper", "
1504
1898
  var LAST = ["Chen", "Patel", "Okafor", "Silva", "Novak", "Haddad", "Larsen", "Moreau", "Kim", "Rossi"];
1505
1899
  var COMPANY = ["Northwind", "Globex", "Initech", "Umbrella Labs", "Acme Freight", "Vandelay", "Hooli", "Soylent", "Stark Supply", "Wayne Analytics"];
1506
1900
  var WORDS = ["renewal", "onboarding", "enterprise plan", "pilot", "expansion", "support", "quarterly review", "migration", "integration", "upgrade"];
1507
- var twinClock = (sequence) => new Date(Date.UTC(2026, 0, 5, 9, 0, 0) + sequence * 6e4);
1901
+ var twinClock = (sequence) => new Date(twinNowMs(Date.UTC(2026, 0, 5, 9, 0, 0) + sequence * 6e4));
1508
1902
  function fakeValue(schema, name, stream, depth = 0, sequence = 0) {
1509
1903
  if (!schema) return void 0;
1510
1904
  if (schema.example !== void 0 && depth > 0 && typeof schema.example !== "object") return schema.example;
@@ -1514,9 +1908,9 @@ function fakeValue(schema, name, stream, depth = 0, sequence = 0) {
1514
1908
  if (type === "object") {
1515
1909
  if (depth > 3 || schema["x-recursive"]) return {};
1516
1910
  const out = {};
1517
- for (const [key, child] of Object.entries(schema.properties ?? {})) {
1518
- const v = fakeValue(child, key, stream, depth + 1, sequence);
1519
- if (v !== void 0) out[key] = v;
1911
+ for (const [key2, child] of Object.entries(schema.properties ?? {})) {
1912
+ const v = fakeValue(child, key2, stream, depth + 1, sequence);
1913
+ if (v !== void 0) out[key2] = v;
1520
1914
  }
1521
1915
  return out;
1522
1916
  }
@@ -1617,13 +2011,13 @@ var coerce = (value, schema) => {
1617
2011
  function overlay(target, input, schema, merge) {
1618
2012
  const props = schema?.properties ?? {};
1619
2013
  for (const [k, v] of Object.entries(input)) {
1620
- const key = Object.hasOwn(props, k) ? k : Object.keys(props).find((p) => normName(p) === normName(k)) ?? k;
1621
- const child = props[key];
1622
- if (isObj(v) && isObj(target[key]) && merge) {
1623
- const next = structuredClone(target[key]);
2014
+ const key2 = Object.hasOwn(props, k) ? k : Object.keys(props).find((p) => normName(p) === normName(k)) ?? k;
2015
+ const child = props[key2];
2016
+ if (isObj(v) && isObj(target[key2]) && merge) {
2017
+ const next = structuredClone(target[key2]);
1624
2018
  overlay(next, v, child, true);
1625
- target[key] = next;
1626
- } else target[key] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
2019
+ target[key2] = next;
2020
+ } else target[key2] = isObj(v) || Array.isArray(v) ? structuredClone(v) : coerce(v, child);
1627
2021
  }
1628
2022
  }
1629
2023
  function newId(resource, rows2, stream) {
@@ -1931,18 +2325,18 @@ function generatedAdapter(adapter) {
1931
2325
 
1932
2326
  // src/runtime/packs.ts
1933
2327
  import { existsSync, readFileSync } from "fs";
1934
- import { dirname, join as join2, resolve as resolve2 } from "path";
2328
+ import { dirname, join as join3, resolve as resolve2 } from "path";
1935
2329
  import { fileURLToPath, pathToFileURL } from "url";
1936
2330
  function packsDir() {
1937
2331
  const here = dirname(fileURLToPath(import.meta.url));
1938
- const candidates = [process.env.AGENTTWIN_TWINS_DIR, join2(here, "twins"), join2(here, "../twins"), resolve2(here, "../../../twins/dist")];
1939
- return candidates.find((dir) => !!dir && existsSync(join2(dir, "catalog.json")));
2332
+ const candidates = [process.env.AGENTTWIN_TWINS_DIR, join3(here, "twins"), join3(here, "../twins"), resolve2(here, "../../../twins/dist")];
2333
+ return candidates.find((dir) => !!dir && existsSync(join3(dir, "catalog.json")));
1940
2334
  }
1941
2335
  var cached;
1942
2336
  function packCatalog() {
1943
2337
  if (cached !== void 0) return cached;
1944
2338
  const dir = packsDir();
1945
- cached = dir ? JSON.parse(readFileSync(join2(dir, "catalog.json"), "utf8")) : null;
2339
+ cached = dir ? JSON.parse(readFileSync(join3(dir, "catalog.json"), "utf8")) : null;
1946
2340
  return cached;
1947
2341
  }
1948
2342
  var PACK_PREFIX = "pack:";
@@ -1957,7 +2351,7 @@ function loadPack(name) {
1957
2351
  if (!record2) throw new Error(`No twin pack named ${name}`);
1958
2352
  let factory = loaded.get(name);
1959
2353
  if (!factory) {
1960
- const file = join2(packsDir(), "packs", name, "index.mjs");
2354
+ const file = join3(packsDir(), "packs", name, "index.mjs");
1961
2355
  factory = import(pathToFileURL(file).href).then((mod) => {
1962
2356
  if (typeof mod.createTwinFetch !== "function") throw new Error(`Twin pack ${name} exports no createTwinFetch`);
1963
2357
  return mod.createTwinFetch;
@@ -1972,7 +2366,7 @@ import { createHash as createHash4 } from "crypto";
1972
2366
  var ENTERPRISE_ADAPTERS = ["salesforce", "servicenow", "workday", "sap", "microsoft-teams", "outlook", "entra-id", "okta", "confluence", "sharepoint", "snowflake", "netsuite", "pagerduty"];
1973
2367
  var isEnterpriseAdapter = (name) => ENTERPRISE_ADAPTERS.includes(name);
1974
2368
  var EPOCH2 = 17e8;
1975
- var iso2 = (sequence) => new Date((EPOCH2 + sequence) * 1e3).toISOString();
2369
+ var iso2 = (sequence) => new Date(twinNowMs((EPOCH2 + sequence) * 1e3)).toISOString();
1976
2370
  var hash = (seed) => createHash4("sha256").update(seed).digest("hex");
1977
2371
  var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1978
2372
  var scalar = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
@@ -1985,15 +2379,15 @@ var limitOf = (value, fallback, max) => {
1985
2379
  const n = Number(value);
1986
2380
  return Number.isInteger(n) && n >= 1 && n <= max ? n : null;
1987
2381
  };
1988
- var nextNumber = (rows2, key, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
2382
+ var nextNumber = (rows2, key2, start) => rows2.reduce((max, r) => Math.max(max, Number(String(r[key2] ?? "").replace(/\D/g, "")) || 0), start - 1) + 1;
1989
2383
  var header2 = (headers, name) => {
1990
2384
  const v = headers[name];
1991
2385
  return Array.isArray(v) ? v[0] : v;
1992
2386
  };
1993
- function eqFilter(expression, quote) {
2387
+ function eqFilter(expression, quote2) {
1994
2388
  const parts = expression.split(/\s+and\s+/i), tests = [];
1995
2389
  for (const part of parts) {
1996
- const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote}([^${quote}]*)${quote}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
2390
+ const m = new RegExp(`^\\s*([\\w.]+)\\s+eq\\s+(?:${quote2}([^${quote2}]*)${quote2}|(true|false|-?\\d+(?:\\.\\d+)?|null))\\s*$`, "i").exec(part);
1997
2391
  if (!m) return null;
1998
2392
  const value = m[2] !== void 0 ? m[2] : m[3] === "null" ? null : m[3] === "true" ? true : m[3] === "false" ? false : Number(m[3]);
1999
2393
  tests.push((r) => {
@@ -2025,7 +2419,7 @@ function soql(q) {
2025
2419
  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]);
2026
2420
  const field = c[1].toLowerCase();
2027
2421
  tests.push((r) => {
2028
- const k = Object.keys(r).find((key) => key.toLowerCase() === field);
2422
+ const k = Object.keys(r).find((key2) => key2.toLowerCase() === field);
2029
2423
  const equal = (k ? r[k] : null) === value;
2030
2424
  return c[2] === "=" ? equal : !equal;
2031
2425
  });
@@ -2169,11 +2563,11 @@ var sapView = (set, r) => ({ __metadata: { id: `/sap/opu/odata/sap/${SAP_SETS[se
2169
2563
  var sap = (method, path, body, query, headers, data, sequence) => {
2170
2564
  const m = /^\/sap\/opu\/odata\/sap\/(API_BUSINESS_PARTNER|API_SALES_ORDER_SRV)\/(A_BusinessPartner|A_SalesOrder)(?:\('([^']{1,20})'\))?$/.exec(path);
2171
2565
  if (!m || SAP_SETS[m[2]].service !== m[1]) return;
2172
- const [, , set, key] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
2566
+ const [, , set, key2] = m, collection = `/${set}`, rows2 = table(data, collection), csrf = hash("sap:csrf").slice(0, 24);
2173
2567
  if (method === "GET") {
2174
2568
  const issued = header2(headers, "x-csrf-token")?.toLowerCase() === "fetch" ? { "x-csrf-token": csrf } : void 0;
2175
- if (key) {
2176
- const record3 = rows2.find((r) => r[SAP_SETS[set].key] === key);
2569
+ if (key2) {
2570
+ const record3 = rows2.find((r) => r[SAP_SETS[set].key] === key2);
2177
2571
  return record3 ? read(collection, { d: sapView(set, record3) }, 200, issued) : { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection };
2178
2572
  }
2179
2573
  const where = query.$filter ? eqFilter(query.$filter, "'") : () => true;
@@ -2182,10 +2576,10 @@ var sap = (method, path, body, query, headers, data, sequence) => {
2182
2576
  return read(collection, { d: { results: rows2.filter(where).slice(skip, skip + top).map((r) => sapView(set, r)) } }, 200, issued);
2183
2577
  }
2184
2578
  if (header2(headers, "x-csrf-token") !== csrf) return { ...sapError(403, "403", "CSRF token validation failed", { "x-csrf-token": "Required" }), collection };
2185
- if (method === "POST" && !key) {
2579
+ if (method === "POST" && !key2) {
2186
2580
  if (set === "A_BusinessPartner") {
2187
2581
  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 };
2188
- const record4 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`, BusinessPartnerIsBlocked: false };
2582
+ const record4 = { BusinessPartner: String(nextNumber(rows2, "BusinessPartner", 10000001)), ...body, CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`, BusinessPartnerIsBlocked: false };
2189
2583
  rows2.push(record4);
2190
2584
  return write2(collection, record4, { d: sapView(set, record4) }, 201);
2191
2585
  }
@@ -2200,14 +2594,14 @@ var sap = (method, path, body, query, headers, data, sequence) => {
2200
2594
  TransactionCurrency: body.TransactionCurrency ?? "USD",
2201
2595
  TotalNetAmount: total.toFixed(2),
2202
2596
  OverallSDProcessStatus: "A",
2203
- CreationDate: `/Date(${(EPOCH2 + sequence) * 1e3})/`,
2597
+ CreationDate: `/Date(${twinNowMs((EPOCH2 + sequence) * 1e3)})/`,
2204
2598
  to_Item: { results: items.map((i, n) => ({ SalesOrderItem: String((n + 1) * 10), ...i })) }
2205
2599
  };
2206
2600
  rows2.push(record3);
2207
2601
  return write2(collection, record3, { d: sapView(set, record3) }, 201);
2208
2602
  }
2209
- const record2 = key ? rows2.find((r) => r[SAP_SETS[set].key] === key) : void 0;
2210
- if (!record2) return key ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
2603
+ const record2 = key2 ? rows2.find((r) => r[SAP_SETS[set].key] === key2) : void 0;
2604
+ if (!record2) return key2 ? { ...sapError(404, "/IWBEP/CM_MGW_RT/020", `Resource not found for segment '${set}'`), collection } : void 0;
2211
2605
  if (method === "PATCH" || method === "MERGE") {
2212
2606
  if (!flat(body) || SAP_SETS[set].key in body) return;
2213
2607
  Object.assign(record2, body);
@@ -2243,7 +2637,7 @@ var teams = (method, path, body, query, _headers, data, sequence) => {
2243
2637
  if (body.body.contentType !== void 0 && !["text", "html"].includes(body.body.contentType)) return;
2244
2638
  if (parentId && !messages.some((r) => scope(r) && r.id === parentId)) return { ...graphError(404, "NotFound", "Resource not found", sequence), collection: "/messages" };
2245
2639
  const record2 = {
2246
- id: String((EPOCH2 + sequence) * 1e3 + messages.length),
2640
+ id: String(twinNowMs((EPOCH2 + sequence) * 1e3) + messages.length),
2247
2641
  replyToId: parentId ?? null,
2248
2642
  messageType: "message",
2249
2643
  createdDateTime: iso2(sequence),
@@ -2312,9 +2706,9 @@ var outlook = (method, path, body, query, _headers, data, sequence) => {
2312
2706
  var entra = (method, path, body, query, _headers, data, sequence) => {
2313
2707
  const m = /^\/v1\.0\/(users|groups)(?:\/([^/]+))?(?:\/members(?:\/([\w-]+))?(\/\$ref)?)?$/.exec(path);
2314
2708
  if (!m) return;
2315
- const [, kind, rawKey, memberId, ref] = m, users = table(data, "/users"), groups = table(data, "/groups"), members = table(data, "/groupMembers");
2316
- const key = rawKey && decodeURIComponent(rawKey), membersRoute = path.includes("/members");
2317
- if (kind === "users" && !key) {
2709
+ const [, kind, rawKey, memberId, ref] = m, users = table(data, "/users"), groups2 = table(data, "/groups"), members = table(data, "/groupMembers");
2710
+ const key2 = rawKey && decodeURIComponent(rawKey), membersRoute = path.includes("/members");
2711
+ if (kind === "users" && !key2) {
2318
2712
  if (method === "GET") {
2319
2713
  const page = graphPage(users, query);
2320
2714
  return page ? read("/users", { value: page }) : void 0;
@@ -2330,13 +2724,13 @@ var entra = (method, path, body, query, _headers, data, sequence) => {
2330
2724
  users.push(record2);
2331
2725
  return write2("/users", record2, record2, 201);
2332
2726
  }
2333
- if (kind === "groups" && !key && method === "GET") {
2334
- const page = graphPage(groups, query);
2727
+ if (kind === "groups" && !key2 && method === "GET") {
2728
+ const page = graphPage(groups2, query);
2335
2729
  return page ? read("/groups", { value: page }) : void 0;
2336
2730
  }
2337
2731
  if (kind === "users") {
2338
- const user = users.find((u) => u.id === key || String(u.userPrincipalName).toLowerCase() === String(key).toLowerCase());
2339
- 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" };
2732
+ const user = users.find((u) => u.id === key2 || String(u.userPrincipalName).toLowerCase() === String(key2).toLowerCase());
2733
+ 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" };
2340
2734
  if (membersRoute) return;
2341
2735
  if (method === "GET") return read("/users", user);
2342
2736
  if (method === "PATCH") {
@@ -2351,8 +2745,8 @@ var entra = (method, path, body, query, _headers, data, sequence) => {
2351
2745
  }
2352
2746
  return;
2353
2747
  }
2354
- const group = groups.find((g) => g.id === key);
2355
- 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" };
2748
+ const group = groups2.find((g) => g.id === key2);
2749
+ 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" };
2356
2750
  if (!membersRoute) return method === "GET" ? read("/groups", group) : void 0;
2357
2751
  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 })) });
2358
2752
  if (method === "POST" && !memberId && ref) {
@@ -2375,10 +2769,10 @@ var oktaId = (prefix, seed) => prefix + Buffer.from(hash(seed)).toString("base64
2375
2769
  var okta = (method, path, body, query, _headers, data, sequence) => {
2376
2770
  const m = /^\/api\/v1\/(users|groups)(?:\/([^/]+))?(?:\/(users)(?:\/([\w]+))?|\/lifecycle\/(activate|deactivate|suspend|unsuspend))?$/.exec(path);
2377
2771
  if (!m) return;
2378
- const [, kind, rawKey, groupUsers, memberId, lifecycle] = m, users = table(data, "/users"), groups = table(data, "/groups"), memberships = table(data, "/groupMemberships");
2379
- const key = rawKey && decodeURIComponent(rawKey);
2772
+ const [, kind, rawKey, groupUsers, memberId, lifecycle] = m, users = table(data, "/users"), groups2 = table(data, "/groups"), memberships = table(data, "/groupMemberships");
2773
+ const key2 = rawKey && decodeURIComponent(rawKey);
2380
2774
  const notFound2 = (what, type) => ({ ...oktaError(404, "E0000007", `Not found: Resource not found: ${what} (${type})`), collection: `/${kind}` });
2381
- if (kind === "users" && !key) {
2775
+ if (kind === "users" && !key2) {
2382
2776
  if (method === "GET") {
2383
2777
  const limit = limitOf(query.limit, 200, 200);
2384
2778
  if (limit === null) return;
@@ -2405,13 +2799,13 @@ var okta = (method, path, body, query, _headers, data, sequence) => {
2405
2799
  users.push(record2);
2406
2800
  return write2("/users", record2, record2);
2407
2801
  }
2408
- if (kind === "groups" && !key && method === "GET") {
2802
+ if (kind === "groups" && !key2 && method === "GET") {
2409
2803
  const q = query.q?.toLowerCase();
2410
- return read("/groups", groups.filter((g) => !q || String(g.profile?.name ?? "").toLowerCase().startsWith(q)));
2804
+ return read("/groups", groups2.filter((g) => !q || String(g.profile?.name ?? "").toLowerCase().startsWith(q)));
2411
2805
  }
2412
2806
  if (kind === "users") {
2413
- const user = users.find((u) => u.id === key || String(u.profile?.login).toLowerCase() === String(key).toLowerCase());
2414
- if (!user) return notFound2(String(key), "User");
2807
+ const user = users.find((u) => u.id === key2 || String(u.profile?.login).toLowerCase() === String(key2).toLowerCase());
2808
+ if (!user) return notFound2(String(key2), "User");
2415
2809
  if (lifecycle && method === "POST") {
2416
2810
  const from = user.status;
2417
2811
  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;
@@ -2438,8 +2832,8 @@ var okta = (method, path, body, query, _headers, data, sequence) => {
2438
2832
  }
2439
2833
  return;
2440
2834
  }
2441
- const group = groups.find((g) => g.id === key);
2442
- if (!group) return notFound2(String(key), "UserGroup");
2835
+ const group = groups2.find((g) => g.id === key2);
2836
+ if (!group) return notFound2(String(key2), "UserGroup");
2443
2837
  if (!groupUsers) return method === "GET" && !lifecycle ? read("/groups", group) : void 0;
2444
2838
  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));
2445
2839
  if (!memberId) return;
@@ -2608,7 +3002,7 @@ Object '${[body.database, body.schema, name].filter(Boolean).join(".").toUpperCa
2608
3002
  sqlState: "00000",
2609
3003
  statementHandle: handle,
2610
3004
  message: "Statement executed successfully.",
2611
- createdOn: (EPOCH2 + sequence) * 1e3
3005
+ createdOn: twinNowMs((EPOCH2 + sequence) * 1e3)
2612
3006
  });
2613
3007
  const remember = (collection, res, operation, record2) => {
2614
3008
  log.push({ statementHandle: handle, statement, result: res, createdOn: iso2(sequence) });
@@ -2724,8 +3118,8 @@ var pdError = (status, message, code, errors = []) => ({ status, body: { error:
2724
3118
  var pdId = (seed) => "P" + hash(seed).replace(/[^A-Z0-9]/gi, "").toUpperCase().slice(0, 6);
2725
3119
  var pagerduty = (method, path, body, query, headers, data, sequence) => {
2726
3120
  const services = table(data, "/services"), incidents = table(data, "/incidents"), notes = table(data, "/notes"), events = table(data, "/events");
2727
- const open = (serviceId, key) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key && i.status !== "resolved");
2728
- const create = (service, title, urgency, key, details) => {
3121
+ const open = (serviceId, key2) => incidents.find((i) => i.service.id === serviceId && i.incident_key === key2 && i.status !== "resolved");
3122
+ const create = (service, title, urgency, key2, details) => {
2729
3123
  const id2 = pdId(`pd:incident:${sequence}:${incidents.length}`);
2730
3124
  const record2 = {
2731
3125
  id: id2,
@@ -2737,7 +3131,7 @@ var pagerduty = (method, path, body, query, headers, data, sequence) => {
2737
3131
  urgency,
2738
3132
  created_at: iso2(sequence),
2739
3133
  updated_at: iso2(sequence),
2740
- incident_key: key,
3134
+ incident_key: key2,
2741
3135
  service: { id: service.id, type: "service_reference", summary: service.name },
2742
3136
  html_url: `https://contoso.pagerduty.test/incidents/${id2}`,
2743
3137
  ...details === void 0 ? {} : { body: { type: "incident_body", details } }
@@ -2753,13 +3147,13 @@ var pagerduty = (method, path, body, query, headers, data, sequence) => {
2753
3147
  if (action === "trigger" && !(isObject2(payload) && payload.summary && payload.source && ["critical", "error", "warning", "info"].includes(payload.severity)))
2754
3148
  return { status: 400, collection: "/events", body: { status: "invalid event", message: "Event object is invalid", errors: ["'payload.summary', 'payload.source' and 'payload.severity' are required"] } };
2755
3149
  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"] } };
2756
- const key = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
2757
- const existing = open(service.id, key);
2758
- if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key, payload.custom_details);
3150
+ const key2 = String(body.dedup_key ?? hash(`pd:dedup:${sequence}`).slice(0, 32));
3151
+ const existing = open(service.id, key2);
3152
+ if (action === "trigger" && !existing) create(service, payload.summary, payload.severity === "critical" || payload.severity === "error" ? "high" : "low", key2, payload.custom_details);
2759
3153
  if (action !== "trigger" && existing) Object.assign(existing, { status: action === "acknowledge" ? "acknowledged" : "resolved", updated_at: iso2(sequence) });
2760
- 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) };
3154
+ 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) };
2761
3155
  events.push(event);
2762
- return write2("/events", event, { status: "success", message: "Event processed", dedup_key: key }, 202);
3156
+ return write2("/events", event, { status: "success", message: "Event processed", dedup_key: key2 }, 202);
2763
3157
  }
2764
3158
  const m = /^\/(incidents|services)(?:\/(\w+))?(?:\/(notes))?$/.exec(path);
2765
3159
  if (!m) return;
@@ -2985,6 +3379,7 @@ function parseWorld(value) {
2985
3379
  if (!Number.isInteger(v.timeoutSeconds) || Number(v.timeoutSeconds) < 1 || Number(v.timeoutSeconds) > 300) invalid("timeoutSeconds must be 1\u2013300");
2986
3380
  if (v.workflowId !== void 0 && (typeof v.workflowId !== "string" || !v.workflowId)) invalid("workflowId must be a nonempty string");
2987
3381
  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");
3382
+ if (v.twinClock !== void 0 && !validTwinClock(v.twinClock)) invalid("twinClock requires only now as a canonical UTC timestamp with milliseconds");
2988
3383
  if (v.applicationClock !== void 0 && !validApplicationClock(v.applicationClock)) invalid("applicationClock requires only now as a canonical UTC timestamp with milliseconds");
2989
3384
  if (!Array.isArray(v.services) || !v.services.length || v.services.length > 10) invalid("services must contain 1\u201310 HTTP services");
2990
3385
  const services = /* @__PURE__ */ new Map();
@@ -3138,14 +3533,14 @@ function parseWorld(value) {
3138
3533
  origins.add(mapping.origin);
3139
3534
  }
3140
3535
  }
3141
- const keys = ["schema", "name", "workflowId", "sourceBuild", "applicationClock", "files", "command", "timeoutSeconds", "browser", "background", "services", "fetchRoutes", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
3536
+ 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"];
3142
3537
  if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
3143
3538
  return v;
3144
3539
  }
3145
3540
 
3146
3541
  // src/runtime/pack-log.ts
3147
3542
  import { closeSync, existsSync as existsSync2, openSync, readdirSync, readSync, statSync } from "fs";
3148
- import { join as join3 } from "path";
3543
+ import { join as join4 } from "path";
3149
3544
  var PackActionTail = class {
3150
3545
  constructor(root) {
3151
3546
  this.root = root;
@@ -3155,7 +3550,7 @@ var PackActionTail = class {
3155
3550
  partial = /* @__PURE__ */ new Map();
3156
3551
  files() {
3157
3552
  if (!existsSync2(this.root)) return [];
3158
- return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join3(this.root, f)).sort();
3553
+ return readdirSync(this.root, { recursive: true, encoding: "utf8" }).filter((f) => f.endsWith("actions.jsonl")).map((f) => join4(this.root, f)).sort();
3159
3554
  }
3160
3555
  drain() {
3161
3556
  const out = [];
@@ -3211,16 +3606,17 @@ function seedActions(service, collections, at, tenant = {}) {
3211
3606
  }
3212
3607
 
3213
3608
  // src/runtime/http-world.ts
3214
- import { mkdir, mkdtemp as mkdtemp2, rm as rm2, writeFile as writeFile2 } from "fs/promises";
3215
- import { tmpdir as tmpdir2 } from "os";
3216
- import { join as join4 } from "path";
3217
- var idempotencyKeyDigest = (key) => typeof key === "string" && key ? `sha256:${createHash5("sha256").update(key).digest("hex").slice(0, 16)}` : void 0;
3609
+ import { mkdir, mkdtemp as mkdtemp3, rm as rm3, writeFile as writeFile3 } from "fs/promises";
3610
+ import { tmpdir as tmpdir3 } from "os";
3611
+ import { join as join5 } from "path";
3612
+ var idempotencyKeyDigest = (key2) => typeof key2 === "string" && key2 ? `sha256:${createHash5("sha256").update(key2).digest("hex").slice(0, 16)}` : void 0;
3218
3613
  var HttpWorld = class {
3219
3614
  /** The one-command flow runs apps that hard-code their own model key: the model twins then accept any credential. */
3220
3615
  constructor(spec, seed, options = {}) {
3221
3616
  this.spec = spec;
3222
3617
  this.options = options;
3223
3618
  this.seed = normalizeSeed(seed);
3619
+ this.twinClock = spec.twinClock ? Object.freeze({ ...spec.twinClock }) : void 0;
3224
3620
  }
3225
3621
  spec;
3226
3622
  options;
@@ -3230,6 +3626,7 @@ var HttpWorld = class {
3230
3626
  unsupported = [];
3231
3627
  /** The run seed that governed every seeded twin-side decision in this world instance. */
3232
3628
  seed;
3629
+ twinClock;
3233
3630
  servers = [];
3234
3631
  timers = /* @__PURE__ */ new Set();
3235
3632
  fired = false;
@@ -3237,28 +3634,39 @@ var HttpWorld = class {
3237
3634
  candidateCounts = /* @__PURE__ */ new Map();
3238
3635
  epoch = 0;
3239
3636
  replayKeys = /* @__PURE__ */ new Map();
3240
- sourceContext = new AsyncLocalStorage();
3637
+ sourceContext = new AsyncLocalStorage2();
3241
3638
  record(service, operation, path, detail, record2) {
3242
3639
  if (this.events.length >= 5e4) return;
3243
3640
  const source = this.sourceContext.getStore();
3244
3641
  this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record2 ? { record: structuredClone(record2) } : {}, ...source ? { source } : {} });
3245
3642
  }
3246
3643
  /** Tags the event just recorded with the request's idempotency key digest. */
3247
- keyed(key) {
3248
- const digest = idempotencyKeyDigest(key), last = this.events[this.events.length - 1];
3249
- if (digest && last) last.idempotencyKey = digest;
3644
+ keyed(key2) {
3645
+ const digest2 = idempotencyKeyDigest(key2), last = this.events[this.events.length - 1];
3646
+ if (digest2 && last) last.idempotencyKey = digest2;
3250
3647
  }
3251
3648
  rejectUnsupported(service, method, path, detail) {
3252
3649
  this.unsupported.push(`${service}: ${method} ${path}: ${detail}`);
3253
3650
  this.record(service, "unsupported", path, detail);
3254
3651
  }
3255
3652
  /** Seeded fault scheduling: the k-th matched request of the fault's scope is faulted iff the seeded draw picked ordinal k. */
3256
- candidateIndex(key) {
3257
- const next = this.candidateCounts.get(key) ?? 0;
3258
- this.candidateCounts.set(key, next + 1);
3653
+ candidateIndex(key2) {
3654
+ const next = this.candidateCounts.get(key2) ?? 0;
3655
+ this.candidateCounts.set(key2, next + 1);
3259
3656
  return next;
3260
3657
  }
3261
- async start() {
3658
+ start() {
3659
+ if (this.servers.length) return Promise.reject(new Error("World is already started"));
3660
+ return withTwinClock(this.twinClock, async () => {
3661
+ try {
3662
+ return await this.startWithClock();
3663
+ } catch (error) {
3664
+ await this.close();
3665
+ throw error;
3666
+ }
3667
+ });
3668
+ }
3669
+ async startWithClock() {
3262
3670
  if (this.servers.length) throw new Error("World is already started");
3263
3671
  const fault = this.spec.fault;
3264
3672
  for (const service of this.spec.services) {
@@ -3284,7 +3692,7 @@ var HttpWorld = class {
3284
3692
  this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server2.address().port}`, token };
3285
3693
  continue;
3286
3694
  }
3287
- const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3695
+ const server = createServer((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3288
3696
  const epoch = this.epoch;
3289
3697
  const send = (code, body, headers = {}) => {
3290
3698
  if (!res.destroyed) {
@@ -3382,7 +3790,7 @@ var HttpWorld = class {
3382
3790
  }
3383
3791
  const url = new URL(req.url ?? "/", "http://localhost");
3384
3792
  let path = url.pathname;
3385
- if (service.adapter === "composio" && [...url.searchParams.keys()].some((key2) => url.searchParams.getAll(key2).length !== 1)) {
3793
+ if (service.adapter === "composio" && [...url.searchParams.keys()].some((key3) => url.searchParams.getAll(key3).length !== 1)) {
3386
3794
  this.rejectUnsupported(service.name, req.method ?? "", path, "Repeated query parameters are unsupported");
3387
3795
  respond(501, restUnsupportedBody("composio"));
3388
3796
  return;
@@ -3413,9 +3821,9 @@ var HttpWorld = class {
3413
3821
  else if (mode === "form") {
3414
3822
  const form = new URLSearchParams(text);
3415
3823
  parsed = {};
3416
- for (const key2 of new Set(form.keys())) {
3417
- const all = form.getAll(key2);
3418
- parsed[key2] = all.length > 1 ? all : all[0];
3824
+ for (const key3 of new Set(form.keys())) {
3825
+ const all = form.getAll(key3);
3826
+ parsed[key3] = all.length > 1 ? all : all[0];
3419
3827
  }
3420
3828
  } else if (mode === "raw") {
3421
3829
  rawBody = text;
@@ -3426,7 +3834,7 @@ var HttpWorld = class {
3426
3834
  return;
3427
3835
  }
3428
3836
  const form = new URLSearchParams(text);
3429
- if ([...form.keys()].some((key2) => form.getAll(key2).length !== 1)) {
3837
+ if ([...form.keys()].some((key3) => form.getAll(key3).length !== 1)) {
3430
3838
  respond(400, { error: "invalid_request" });
3431
3839
  return;
3432
3840
  }
@@ -3451,9 +3859,9 @@ var HttpWorld = class {
3451
3859
  if (service.adapter === "stripe" || restAdapter || enterprise || generated) {
3452
3860
  const params = payload ?? Object.fromEntries(url.searchParams);
3453
3861
  const keyHeader2 = req.headers["idempotency-key"] ?? (enterprise === "netsuite" ? req.headers["x-netsuite-idempotency-key"] : void 0);
3454
- const key2 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
3862
+ const key3 = !["google-oauth", "composio"].includes(service.adapter ?? "") && req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
3455
3863
  const signature2 = JSON.stringify(params);
3456
- const previous2 = key2 ? keys.get(key2) : void 0;
3864
+ const previous2 = key3 ? keys.get(key3) : void 0;
3457
3865
  if (previous2) {
3458
3866
  if (previous2.body !== signature2) {
3459
3867
  respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
@@ -3477,8 +3885,8 @@ var HttpWorld = class {
3477
3885
  this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
3478
3886
  this.keyed(keyHeader2);
3479
3887
  }
3480
- 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) } : {} });
3481
- const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key2 && matchesFault(result.collection);
3888
+ 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) } : {} });
3889
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key3 && matchesFault(result.collection);
3482
3890
  const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
3483
3891
  if (duplicate2) {
3484
3892
  const second = invoke(this.events.length + 1);
@@ -3554,9 +3962,9 @@ var HttpWorld = class {
3554
3962
  return;
3555
3963
  }
3556
3964
  const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
3557
- const key = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
3965
+ const key2 = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
3558
3966
  const signature = JSON.stringify(body);
3559
- const previous = key ? keys.get(key) : void 0;
3967
+ const previous = key2 ? keys.get(key2) : void 0;
3560
3968
  if (previous) {
3561
3969
  if (previous.body !== signature) {
3562
3970
  respond(409, { error: "idempotency_conflict" });
@@ -3567,7 +3975,7 @@ var HttpWorld = class {
3567
3975
  respondSlowly(path, "replay", 200, previous.record);
3568
3976
  return;
3569
3977
  }
3570
- const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
3978
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key2 && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
3571
3979
  if (duplicate) this.faultActions++;
3572
3980
  let index = data[path].length + 1;
3573
3981
  while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
@@ -3575,7 +3983,7 @@ var HttpWorld = class {
3575
3983
  if (slack) row.ts = `${index}.000001`;
3576
3984
  const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
3577
3985
  data[path].push(row);
3578
- if (key) keys.set(key, { body: signature, record: row });
3986
+ if (key2) keys.set(key2, { body: signature, record: row });
3579
3987
  this.record(service.name, "write", path, String(row.id), row);
3580
3988
  this.keyed(keyHeader);
3581
3989
  if (duplicate) {
@@ -3602,7 +4010,7 @@ var HttpWorld = class {
3602
4010
  } catch {
3603
4011
  respond(500, { error: "world_request_error" });
3604
4012
  }
3605
- }));
4013
+ })));
3606
4014
  server.requestTimeout = 1e4;
3607
4015
  await new Promise((resolve3, reject) => {
3608
4016
  server.once("error", reject);
@@ -3623,34 +4031,35 @@ var HttpWorld = class {
3623
4031
  */
3624
4032
  async startPack(service, token, faultOrdinalsFor, faultKey, data, latencyMs) {
3625
4033
  const name = service.adapter.slice(PACK_PREFIX.length), meta = packRecord(name);
3626
- const root = await mkdtemp2(join4(tmpdir2(), `agenttwin-pack-${name}-`));
4034
+ if (this.twinClock && packCatalog()?.engine[meta.generation]?.clockSupport !== "async-context-v1") throw new Error("Twin packs need rebuilding for per-run clock support");
4035
+ const root = await mkdtemp3(join5(tmpdir3(), `agenttwin-pack-${name}-`));
3627
4036
  this.packRoots.push(root);
3628
- 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" : "";
4037
+ 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" : "";
3629
4038
  const writeSeedLog = async (dir, text) => {
3630
4039
  if (!text) return;
3631
- await mkdir(join4(dir, ".volter/world", meta.logService), { recursive: true });
3632
- await writeFile2(join4(dir, ".volter/world", meta.logService, "actions.jsonl"), text);
4040
+ await mkdir(join5(dir, ".volter/world", meta.logService), { recursive: true });
4041
+ await writeFile3(join5(dir, ".volter/world", meta.logService, "actions.jsonl"), text);
3633
4042
  };
3634
4043
  let tenant = {}, credential;
3635
4044
  if (meta.logService && meta.credentialDoor && (service.collections.some((c) => c.seed.length) || service.account)) {
3636
- const probe = await mkdtemp2(join4(tmpdir2(), `agenttwin-pack-${name}-probe-`));
4045
+ const probe = await mkdtemp3(join5(tmpdir3(), `agenttwin-pack-${name}-probe-`));
3637
4046
  try {
3638
4047
  await writeSeedLog(probe, worldSeed);
3639
4048
  const scratch = await (await loadPack(name))({ root: probe });
3640
4049
  await (await scratch(new Request(`https://${meta.hosts[0]?.host ?? `${name}.twin.test`}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }))).arrayBuffer();
3641
- const probed = new PackActionTail(join4(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
4050
+ const probed = new PackActionTail(join5(probe, ".volter")).drain().filter((a) => a.subject?.type !== "_world_seed");
3642
4051
  tenant = tenantFields(probed);
3643
4052
  credential = credentialAction(probed);
3644
4053
  } finally {
3645
- await rm2(probe, { recursive: true, force: true });
4054
+ await rm3(probe, { recursive: true, force: true });
3646
4055
  }
3647
4056
  }
3648
4057
  const account = credential && service.account ? JSON.stringify({ ...credential, id: `${credential.id ?? "credential"}:preset`, fields: { ...credential.fields, ...service.account } }) + "\n" : "";
3649
- const seeded = meta.logService ? worldSeed + account + seedActions(meta.logService, service.collections, (/* @__PURE__ */ new Date()).toISOString(), tenant) : "";
4058
+ const seeded = meta.logService ? worldSeed + account + seedActions(meta.logService, service.collections, new Date(twinNowMs(Date.now())).toISOString(), tenant) : "";
3650
4059
  await writeSeedLog(root, seeded);
3651
4060
  const twin = await (await loadPack(name))({ root });
3652
4061
  const baseHost = meta.hosts[0]?.host ?? `${name}.twin.test`;
3653
- const log = new PackActionTail(join4(root, ".volter"));
4062
+ const log = new PackActionTail(join5(root, ".volter"));
3654
4063
  let issued = {};
3655
4064
  if (meta.credentialDoor) {
3656
4065
  const r = await twin(new Request(`https://${baseHost}${meta.credentialDoor.path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(meta.credentialDoor.body ?? {}) }));
@@ -3703,11 +4112,11 @@ var HttpWorld = class {
3703
4112
  for (const collection of service.collections) data[collection.path] ??= [];
3704
4113
  let chain = Promise.resolve();
3705
4114
  const serialized = (fn) => {
3706
- const run = chain.then(fn, fn);
3707
- chain = run.then(() => void 0, () => void 0);
3708
- return run;
4115
+ const run2 = chain.then(fn, fn);
4116
+ chain = run2.then(() => void 0, () => void 0);
4117
+ return run2;
3709
4118
  };
3710
- const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
4119
+ const server = createServer((req, res) => withTwinClock(this.twinClock, () => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
3711
4120
  const epoch = this.epoch;
3712
4121
  const send = (status, headers, body) => {
3713
4122
  if (!res.destroyed) {
@@ -3841,7 +4250,7 @@ var HttpWorld = class {
3841
4250
  } catch {
3842
4251
  json(500, { error: "world_request_error" });
3843
4252
  }
3844
- }));
4253
+ })));
3845
4254
  server.requestTimeout = 1e4;
3846
4255
  await new Promise((resolve3, reject) => {
3847
4256
  server.once("error", reject);
@@ -3890,7 +4299,7 @@ var HttpWorld = class {
3890
4299
  server.closeAllConnections();
3891
4300
  })));
3892
4301
  this.servers.length = 0;
3893
- await Promise.all(this.packRoots.splice(0).map((root) => rm2(root, { recursive: true, force: true })));
4302
+ await Promise.all(this.packRoots.splice(0).map((root) => rm3(root, { recursive: true, force: true })));
3894
4303
  }
3895
4304
  };
3896
4305
 
@@ -3952,7 +4361,7 @@ function evaluateState(spec, initial, final, events) {
3952
4361
  const safe = [...forbidden, ...preserved, ...properties].every((c) => c.passed);
3953
4362
  return { schema: "agenttwin/evaluation-v1", outcome: !safe ? "unsafe" : taskPassed ? "passed" : "failed", taskPassed, safe, checks: [...checks, ...forbidden, ...preserved, ...properties] };
3954
4363
  }
3955
- var 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;
4364
+ var 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;
3956
4365
  var short = (value, limit = 120) => value.length <= limit ? value : `${value.slice(0, limit)}\u2026`;
3957
4366
  function evaluateProperty(policy, final, events) {
3958
4367
  const base = { id: policy.id, kind: "property", propertyKind: policy.kind, service: policy.service, path: policy.path, passed: false };
@@ -3964,8 +4373,8 @@ function evaluateProperty(policy, final, events) {
3964
4373
  const keyed = /* @__PURE__ */ new Map();
3965
4374
  for (const row of rows2) {
3966
4375
  if (row[field] === void 0) continue;
3967
- const key = JSON.stringify(canonical(row[field]));
3968
- keyed.set(key, [...keyed.get(key) ?? [], row.id ?? row]);
4376
+ const key2 = JSON.stringify(canonical(row[field]));
4377
+ keyed.set(key2, [...keyed.get(key2) ?? [], row.id ?? row]);
3969
4378
  }
3970
4379
  const duplicates = [...keyed.entries()].filter(([, list2]) => list2.length > 1);
3971
4380
  return {
@@ -3973,7 +4382,7 @@ function evaluateProperty(policy, final, events) {
3973
4382
  passed: duplicates.length === 0,
3974
4383
  expected: 0,
3975
4384
  actual: duplicates.length,
3976
- 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) }
4385
+ 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) }
3977
4386
  };
3978
4387
  }
3979
4388
  if (policy.kind === "no-loss") {
@@ -4275,113 +4684,1042 @@ function packContract(name, adapter) {
4275
4684
  return { name, adapter, version: "twin-pack", operations: [], pack: adapter.slice("pack:".length) };
4276
4685
  }
4277
4686
 
4278
- // src/runtime/worker.ts
4279
- var secrets = [];
4280
- async function main() {
4281
- const spec = parseWorld(JSON.parse(await readFile2("/input/world.json", "utf8")));
4282
- if (spec.applicationClock) throw new Error("applicationClock requires the Docker runner; this worker does not implement that clock contract.");
4283
- if (spec.postgres?.clock) throw new Error("postgres.clock requires the Docker runner; this worker does not implement that clock contract.");
4284
- if (spec.fetchRoutes) throw new Error("fetchRoutes currently requires the local runtime; hosted routing is unsupported.");
4285
- if (spec.browser || spec.background) throw new Error("Browser and background execution require the local runtime; this hosted worker does not provision Chromium.");
4687
+ // src/runtime/browser-directories.ts
4688
+ import { mkdtemp as mkdtemp4, mkdir as mkdir2, chown, chmod, rm as rm4 } from "fs/promises";
4689
+ import { tmpdir as tmpdir4 } from "os";
4690
+ import { join as join6 } from "path";
4691
+ async function createBrowserDirectories(identity) {
4692
+ if (!Number.isSafeInteger(identity.uid) || identity.uid < 0 || !Number.isSafeInteger(identity.gid) || identity.gid < 0) throw new Error("Invalid browser identity");
4693
+ const root = await mkdtemp4(join6(tmpdir4(), "agenttwin-browser-"));
4694
+ const profile = join6(root, "profile"), artifacts = join6(root, "artifacts");
4695
+ const close = () => rm4(root, { recursive: true, force: true });
4696
+ try {
4697
+ await mkdir2(profile, { mode: 448 });
4698
+ await mkdir2(artifacts, { mode: 448 });
4699
+ for (const directory of [profile, artifacts, root]) {
4700
+ await chmod(directory, 448);
4701
+ if (identity.uid !== process.getuid?.() || identity.gid !== process.getgid?.()) await chown(directory, identity.uid, identity.gid);
4702
+ }
4703
+ return { root, profile, artifacts, close };
4704
+ } catch (error) {
4705
+ await close();
4706
+ throw error;
4707
+ }
4708
+ }
4709
+
4710
+ // src/runtime/browser-execution.ts
4711
+ import { chromium } from "playwright";
4712
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
4713
+ var BrowserExecutionError = class extends Error {
4714
+ constructor(message, evidence) {
4715
+ super(message);
4716
+ this.evidence = evidence;
4717
+ }
4718
+ evidence;
4719
+ };
4720
+ async function browserExecution(spec, world, signal, identity, onReady = () => {
4721
+ }) {
4722
+ signal?.throwIfAborted();
4723
+ const recipe = spec.browser, result = { engine: "playwright-chromium", steps: [], passed: false, blockedOrigins: [], timedOut: false, timings: [] };
4724
+ let browser, context2;
4725
+ let directories;
4726
+ let owner;
4727
+ const deadlineAborted = () => signal?.aborted && signal.reason instanceof Error && signal.reason.message === "Test deadline exceeded";
4728
+ let stage = "Browser startup", stageStart = performance.now(), expired = false;
4729
+ const mark = (next) => {
4730
+ result.timings.push({ stage, durationMs: Math.round(performance.now() - stageStart) });
4731
+ stage = next;
4732
+ stageStart = performance.now();
4733
+ };
4734
+ const close = async () => {
4735
+ if (browser) await browser.close();
4736
+ else if (context2) await context2.close();
4737
+ };
4738
+ let killFailure;
4739
+ let stopping = Promise.resolve();
4740
+ const stop = () => {
4741
+ stopping = stopping.then(async () => {
4742
+ try {
4743
+ await owner?.kill();
4744
+ } catch (e) {
4745
+ killFailure = e;
4746
+ }
4747
+ });
4748
+ };
4749
+ const abort = () => {
4750
+ stop();
4751
+ };
4752
+ signal?.addEventListener("abort", abort, { once: true });
4753
+ const startupDeadline = Date.now() + BROWSER_STARTUP_MS;
4754
+ const startupTimer = setTimeout(() => {
4755
+ expired = true;
4756
+ stop();
4757
+ }, BROWSER_STARTUP_MS);
4758
+ const check = () => {
4759
+ if (expired) throw new Error(stage + " timed out");
4760
+ signal?.throwIfAborted();
4761
+ };
4762
+ let failure;
4763
+ let testTimer;
4764
+ try {
4765
+ owner = await ownBrowserProcess(process.env.AGENTTWIN_CHROMIUM_EXECUTABLE_PATH || chromium.executablePath());
4766
+ if (identity) directories = await createBrowserDirectories(identity);
4767
+ check();
4768
+ const windowsEnv = {};
4769
+ if (process.platform === "win32") for (const [key2, value] of Object.entries(process.env)) {
4770
+ if (value && ["systemroot", "windir", "temp", "tmp", "userprofile", "localappdata"].includes(key2.toLowerCase())) windowsEnv[key2] = value;
4771
+ }
4772
+ 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()) };
4773
+ if (directories) context2 = await chromium.launchPersistentContext(directories.profile, { ...options, artifactsDir: directories.artifacts, serviceWorkers: "block", viewport: { width: 1280, height: 720 } });
4774
+ else {
4775
+ browser = await chromium.launch(options);
4776
+ check();
4777
+ context2 = await browser.newContext({ serviceWorkers: "block", viewport: { width: 1280, height: 720 } });
4778
+ }
4779
+ check();
4780
+ mark("Application readiness");
4781
+ const origins = /* @__PURE__ */ new Set([new URL(recipe.baseUrl).origin, ...Object.values(world.credentials).map((c) => new URL(c.endpoint).origin)]);
4782
+ const blocked = /* @__PURE__ */ new Set();
4783
+ await context2.route("**/*", (route) => {
4784
+ const origin = new URL(route.request().url()).origin;
4785
+ if (origins.has(origin)) return route.continue();
4786
+ if (blocked.size < 100) blocked.add(origin);
4787
+ return route.abort("blockedbyclient");
4788
+ });
4789
+ if (spec.applicationClock) await context2.addInitScript({ content: applicationClockHook(spec.applicationClock) });
4790
+ const page = await context2.newPage();
4791
+ page.setDefaultTimeout(Math.min(spec.timeoutSeconds * 500, 1e4));
4792
+ while (true) {
4793
+ check();
4794
+ try {
4795
+ const r = await fetch(recipe.baseUrl, { signal: AbortSignal.timeout(300) });
4796
+ if (r.ok) break;
4797
+ } catch {
4798
+ }
4799
+ if (Date.now() >= startupDeadline) {
4800
+ expired = true;
4801
+ check();
4802
+ }
4803
+ await new Promise((r) => setTimeout(r, 50));
4804
+ }
4805
+ clearTimeout(startupTimer);
4806
+ onReady();
4807
+ testTimer = setTimeout(() => {
4808
+ expired = true;
4809
+ stop();
4810
+ }, spec.timeoutSeconds * 1e3);
4811
+ for (const step of recipe.steps) {
4812
+ mark(step.action + " step");
4813
+ check();
4814
+ try {
4815
+ if (step.action === "goto") await page.goto(new URL(step.path, recipe.baseUrl).href);
4816
+ else if (step.action === "click") await page.locator(step.selector).click();
4817
+ else if (step.action === "fill") await page.locator(step.selector).fill(step.value);
4818
+ else await page.locator(step.selector).filter({ hasText: step.text }).waitFor({ state: "visible" });
4819
+ result.steps.push({ action: step.action, passed: true });
4820
+ } catch (cause) {
4821
+ result.timedOut = expired || !!deadlineAborted() || cause instanceof Error && cause.name === "TimeoutError";
4822
+ result.error = stage + (result.timedOut ? " timed out" : " failed");
4823
+ result.steps.push({ action: step.action, passed: false });
4824
+ break;
4825
+ }
4826
+ }
4827
+ mark("Screenshot");
4828
+ if (!signal?.aborted && !expired) {
4829
+ try {
4830
+ const bytes = await page.screenshot({ type: "jpeg", quality: 65, timeout: 1e3 });
4831
+ if (bytes.length <= 768 * 1024) result.screenshot = { mimeType: "image/jpeg", base64: bytes.toString("base64") };
4832
+ } catch {
4833
+ }
4834
+ }
4835
+ result.blockedOrigins = [...blocked];
4836
+ for (const origin of blocked) world.unsupported.push(`browser: blocked unmodeled request origin ${origin}`);
4837
+ if (!result.error) check();
4838
+ result.passed = !result.error;
4839
+ } catch (error) {
4840
+ failure = error;
4841
+ result.timedOut = expired || error instanceof Error && error.name === "TimeoutError" || !!deadlineAborted();
4842
+ result.error = result.timedOut ? stage + " timed out" : error instanceof Error ? error.message : String(error);
4843
+ } finally {
4844
+ clearTimeout(startupTimer);
4845
+ if (testTimer) clearTimeout(testTimer);
4846
+ signal?.removeEventListener("abort", abort);
4847
+ mark("Browser cleanup");
4848
+ try {
4849
+ await stopping;
4850
+ result.cleanup = owner ? await owner.finish(close) : { forced: false, remainingProcesses: 0 };
4851
+ if (killFailure) throw killFailure;
4852
+ } catch (error) {
4853
+ failure = error;
4854
+ result.error = "Browser cleanup failed";
4855
+ result.passed = false;
4856
+ } finally {
4857
+ try {
4858
+ await directories?.close();
4859
+ } catch (error) {
4860
+ failure = error;
4861
+ result.error = "Browser directory cleanup failed";
4862
+ result.passed = false;
4863
+ }
4864
+ result.timings.push({ stage, durationMs: Math.round(performance.now() - stageStart) });
4865
+ }
4866
+ }
4867
+ if (failure) throw new BrowserExecutionError(result.error, result);
4868
+ return result;
4869
+ }
4870
+ async function waitBackground(spec, world, signal) {
4871
+ const check = spec.background, deadline = Date.now() + check.timeoutMs;
4872
+ while (true) {
4873
+ signal?.throwIfAborted();
4874
+ const actual = world.state[check.service][check.path].filter((row) => !check.where || Object.entries(check.where).every(([k, v]) => isDeepStrictEqual3(row[k], v))).length;
4875
+ if (actual === check.count) return { ...check, actual, passed: true };
4876
+ if (Date.now() >= deadline) return { ...check, actual, passed: false };
4877
+ await new Promise((r) => setTimeout(r, 25));
4878
+ }
4879
+ }
4880
+
4881
+ // src/runtime/cost-model.ts
4882
+ import { readFile as readFile3, writeFile as writeFile4 } from "fs/promises";
4883
+ import { join as join7 } from "path";
4884
+
4885
+ // src/runtime/run-summary.ts
4886
+ var formatMoney = (m) => new Intl.NumberFormat("en-US", { style: "currency", currency: m.currency.length === 3 ? m.currency : "USD" }).format(m.amount);
4887
+
4888
+ // src/runtime/generic-calls.ts
4889
+ import { createHash as createHash6 } from "crypto";
4890
+ var WRITE_METHODS = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
4891
+ var READ_LIKE = /\/(search|query|lookup|count|batch\/read|completions|embeddings|responses|count_tokens|graphql\/query)$/i;
4892
+ var MODEL_HOST = /(^|\.)(openai\.com|anthropic\.com|generativelanguage\.googleapis\.com|mistral\.ai|groq\.com|cohere\.ai)$/i;
4893
+ var VOLATILE = /^(id|ts|created|created_at|updated_at|createdAt|updatedAt|timestamp|request_id|requestId|nonce|uuid|sequence|object|livemode)$|_at$/;
4894
+ var KEY_HEADERS = ["idempotency-key", "x-idempotency-key", "x-request-id", "x-amz-client-token"];
4895
+ var KEY_FIELDS = /^(idempotency_?key|ClientToken|ClientRequestToken|MessageDeduplicationId|client_token|request_id)$/i;
4896
+ var digest = (value) => `sha256:${createHash6("sha256").update(typeof value === "string" ? value : canonical2(value)).digest("hex").slice(0, 16)}`;
4897
+ function canonical2(value) {
4898
+ return Array.isArray(value) ? `[${value.map(canonical2).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonical2(value[k])}`).join(",")}}` : JSON.stringify(value ?? null);
4899
+ }
4900
+ var stable = (value) => Array.isArray(value) ? value.map(stable) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).filter(([k]) => !VOLATILE.test(k) && !KEY_FIELDS.test(k)).map(([k, v]) => [k, stable(v)])) : value;
4901
+ var idLike = (segment) => /^\d+$/.test(segment) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) || segment.length >= 3 && /\d/.test(segment) && /^[A-Za-z0-9_\-:.]+$/.test(segment) && !/^v\d+(\.\d+)*$/i.test(segment) && !/^\d{4}-\d{2}-\d{2}$/.test(segment) && !/^[A-Za-z]+\.(json|xml)$/.test(segment);
4902
+ function resourceOf2(method, path) {
4903
+ const segments = path.split("?")[0].split("/").filter(Boolean).map((s) => {
4904
+ try {
4905
+ return decodeURIComponent(s);
4906
+ } catch {
4907
+ return s;
4908
+ }
4909
+ });
4910
+ let resourceId;
4911
+ const template = segments.map((s, i) => {
4912
+ const last = i === segments.length - 1, byMethod = last && ["PUT", "PATCH", "DELETE"].includes(method) && segments.length > 1;
4913
+ if (idLike(s) || byMethod) {
4914
+ if (last || !resourceId || idLike(s)) resourceId = s;
4915
+ return "{id}";
4916
+ }
4917
+ return s;
4918
+ });
4919
+ return { resourcePath: "/" + template.join("/"), ...resourceId ? { resourceId } : {} };
4920
+ }
4921
+ var outcomeOf = (status) => status === void 0 ? "ok" : status === 401 || status === 403 ? "unauthorized" : status === 429 ? "rate-limited" : status >= 500 ? "server-error" : status >= 400 ? "client-error" : "ok";
4922
+ function keyFrom(headers, body) {
4923
+ for (const name of KEY_HEADERS) {
4924
+ const v = headers?.[name];
4925
+ if (typeof v === "string" && v) return digest(v);
4926
+ }
4927
+ if (body && typeof body === "object") {
4928
+ for (const [k, v] of Object.entries(body)) if (KEY_FIELDS.test(k) && typeof v === "string" && v) return digest(v);
4929
+ }
4930
+ }
4931
+ var parseSource = (s) => {
4932
+ if (!s) return;
4933
+ if (typeof s !== "string") return s;
4934
+ try {
4935
+ const v = JSON.parse(s);
4936
+ return typeof v?.file === "string" ? v : void 0;
4937
+ } catch {
4938
+ return;
4939
+ }
4940
+ };
4941
+ function normalizeCall(raw) {
4942
+ const method = raw.method.toUpperCase(), path = raw.path.split("?")[0] || "/", { resourcePath, resourceId } = resourceOf2(method, path);
4943
+ const graphqlRead = /graphql/i.test(path) && typeof raw.body?.query === "string" && !/^\s*mutation\b/.test(raw.body.query);
4944
+ const isWrite = WRITE_METHODS.has(method) && !READ_LIKE.test(path) && !MODEL_HOST.test(raw.host) && !String(raw.service ?? "").startsWith("model:") && !graphqlRead;
4945
+ const outcome = raw.outcome ?? outcomeOf(raw.status), key2 = keyFrom(raw.headers, raw.body), source = parseSource(raw.source);
4946
+ return {
4947
+ sequence: raw.sequence,
4948
+ service: raw.service ?? raw.host,
4949
+ host: raw.host,
4950
+ method,
4951
+ path,
4952
+ resourcePath,
4953
+ ...method === "POST" && raw.createdId ? { resourceId: raw.createdId } : resourceId ? { resourceId } : {},
4954
+ isWrite,
4955
+ ...key2 ? { idempotencyKey: key2 } : {},
4956
+ ...raw.body !== void 0 ? { requestDigest: digest(stable(raw.body)), body: raw.body } : {},
4957
+ ...raw.response !== void 0 ? { responseDigest: digest(stable(raw.response)) } : {},
4958
+ outcome,
4959
+ ...raw.status !== void 0 ? { status: raw.status } : {},
4960
+ committed: raw.committed ?? (isWrite ? outcome === "ok" : void 0),
4961
+ ...raw.duplicated ? { duplicated: true } : {},
4962
+ ...raw.retryAfterMs !== void 0 ? { retryAfterMs: raw.retryAfterMs } : {},
4963
+ ...raw.at !== void 0 ? { at: raw.at } : {},
4964
+ ...source ? { source } : {},
4965
+ ...raw.tier ? { tier: raw.tier } : {}
4966
+ };
4967
+ }
4968
+ function callsFromWorldEvents(events, tierOf = () => void 0) {
4969
+ const calls = [], seen = /* @__PURE__ */ new Set();
4970
+ const last = (service) => [...calls].reverse().find((c) => c.service === service && c.isWrite);
4971
+ for (const e of events) {
4972
+ const tier = tierOf(e.service), key2 = e.idempotencyKey;
4973
+ 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 });
4974
+ const withKey = (c) => key2 ? { ...c, idempotencyKey: key2 } : c;
4975
+ if (e.operation === "write") {
4976
+ const id = e.record?.id === void 0 ? void 0 : String(e.record.id), path = e.path, recordKey = `${e.service}${path}:${id}`;
4977
+ const method = /^(POST|PUT|PATCH|DELETE)\b/.exec(e.detail)?.[1] ?? (id && seen.has(recordKey) ? "PATCH" : "POST");
4978
+ if (id) seen.add(recordKey);
4979
+ const c = base(method, method === "POST" ? path : `${path}/${id ?? ""}`, { body: e.record, committed: true, ...id ? { createdId: id } : {} });
4980
+ calls.push(withKey({ ...c, resourcePath: resourceOf2("GET", path).resourcePath, ...id ? { resourceId: id } : {} }));
4981
+ } else if (e.operation === "replay") calls.push(withKey(base("POST", e.path, { outcome: "replayed", committed: false })));
4982
+ else if (e.operation === "auth-denied") calls.push(base("POST", e.path.split("?")[0], { outcome: "unauthorized", committed: false }));
4983
+ else if (e.operation === "fault") {
4984
+ const prior = last(e.service), method = /\((POST|PUT|PATCH|DELETE|GET)\)\s*$/.exec(e.detail)?.[1];
4985
+ if (/^write committed|^slow-response: write/.test(e.detail) && prior) {
4986
+ prior.outcome = "timeout";
4987
+ prior.committed = true;
4988
+ } else if (/^duplicate-write: (one write committed as two|a single write was delivered twice)/.test(e.detail) && prior) prior.duplicated = true;
4989
+ else if (/^server-error/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "server-error", committed: false })));
4990
+ else if (/^blackhole/.test(e.detail)) calls.push(withKey(base(method ?? "POST", e.path, { outcome: "timeout", committed: false })));
4991
+ }
4992
+ }
4993
+ return calls;
4994
+ }
4995
+ var SUCCESS = /\b(done|complete[d]?|success(ful(ly)?)?|refunded|closed|created|updated|sent|processed|confirmed|welcome|paid|invoiced|won|approved|resolved|scheduled|saved|booked|cancell?ed|shipped|delivered)\b/i;
4996
+ var FAILURE = /\b(fail(ed|ure)?|error|unable|could ?n[o']t|cannot|can't|did ?n[o']t|not (?:been )?(?:\w+ed)|retry(ing)?|escalat\w*|pending|try again|sorry)\b/i;
4997
+ var TEXT_FIELDS = /^(text|body|message|content|subject|summary|description|Body|Message|html|markdown|note|comment)$/;
4998
+ var MESSAGING = /(message|messages|sms|mail|email|emails|notification|notifications|notify|send|postMessage|comments?|reply|replies)(\.json)?$/i;
4999
+ var polarityOf = (text) => FAILURE.test(text) ? "failure" : SUCCESS.test(text) ? "success" : "neutral";
5000
+ function textOf(body, depth = 0) {
5001
+ if (!body || typeof body !== "object" || depth > 3) return "";
5002
+ return Object.entries(body).map(([k, v]) => typeof v === "string" && TEXT_FIELDS.test(k) ? v : v && typeof v === "object" ? textOf(v, depth + 1) : "").filter(Boolean).join(" ").trim();
5003
+ }
5004
+ var RECIPIENT = /^(to|recipient|recipients|email|phone|phone_number|channel|cc|bcc|To|chat_id|user_id)$/;
5005
+ function recipientsOf(body, depth = 0) {
5006
+ if (!body || typeof body !== "object" || depth > 3) return [];
5007
+ return Object.entries(body).flatMap(([k, v]) => RECIPIENT.test(k) ? (Array.isArray(v) ? v : [v]).filter((x) => typeof x === "string" && !!x) : v && typeof v === "object" ? recipientsOf(v, depth + 1) : []);
5008
+ }
5009
+ var isAnnouncement = (c) => c.isWrite && !!textOf(c.body) && (MESSAGING.test(c.path) || recipientsOf(c.body).length > 0);
5010
+ function claimsOf(calls, output = []) {
5011
+ const claims = calls.filter(isAnnouncement).map((c) => {
5012
+ const text = textOf(c.body);
5013
+ return { sequence: c.sequence, text, polarity: polarityOf(text), via: c.sequence, ...c.source ? { source: c.source } : {} };
5014
+ });
5015
+ const end = Math.max(0, ...calls.map((c) => c.sequence)) + 1;
5016
+ output.map((t) => t.trim()).filter(Boolean).slice(0, 50).forEach((text, i) => claims.push({ sequence: end + i, text: text.slice(0, 500), polarity: polarityOf(text) }));
5017
+ return claims;
5018
+ }
5019
+ var AMOUNT = /^(amount|total|price|unit_amount|amount_total|grand_total|subtotal|value|amount_cents|amount_minor|total_cents|price_cents)$/i;
5020
+ function moneyOf(body, depth = 0) {
5021
+ if (!body || typeof body !== "object" || depth > 3) return;
5022
+ const row = body, currency = Object.entries(row).find(([k, v]) => /^currency(_code)?$/i.test(k) && typeof v === "string" && /^[a-z]{3}$/i.test(v))?.[1];
5023
+ for (const [k, v] of Object.entries(row)) {
5024
+ const n = typeof v === "number" ? v : typeof v === "string" && /^\d+(\.\d+)?$/.test(v) ? Number(v) : NaN;
5025
+ if (AMOUNT.test(k) && Number.isFinite(n) && n > 0 && currency) return { amount: /cents|minor/i.test(k) ? n / 100 : n, currency: currency.toUpperCase() };
5026
+ }
5027
+ for (const v of Object.values(row)) {
5028
+ const nested = v && typeof v === "object" ? moneyOf(v, depth + 1) : void 0;
5029
+ if (nested) return nested;
5030
+ }
5031
+ }
5032
+ function impactOf(calls, extra, fallback, hint) {
5033
+ const money2 = calls.map((c) => moneyOf(c.body)).find(Boolean), recipients = [...new Set(calls.flatMap((c) => recipientsOf(c.body)))];
5034
+ if (money2 && extra > 0) return { kind: "money", amount: money2.amount * extra, currency: money2.currency, count: extra, summary: `${formatMoney({ amount: money2.amount * extra, currency: money2.currency })} moved more than intended (${formatMoney(money2)} each)` };
5035
+ const messaging = calls.some((c) => MESSAGING.test(c.path.split("?")[0]));
5036
+ if (recipients.length && extra > 0 && !messaging) {
5037
+ const noun = (calls[0]?.path.split("?")[0].split("/").filter(Boolean).pop() ?? "record").replace(/\.json$/, "").replace(/ies$/, "y").replace(/s$/, "");
5038
+ return { kind: "data-integrity", recipients, count: extra, summary: `${extra + 1} ${noun} records would exist for ${recipients[0]} instead of 1` };
5039
+ }
5040
+ if (recipients.length && (extra > 0 && messaging || fallback === "customer-facing")) return { kind: "customer-facing", recipients, count: Math.max(1, extra), summary: `${recipients.slice(0, 3).join(", ")} ${extra > 0 ? `would have received ${extra + 1} copies` : "would have been told something untrue"}` };
5041
+ return { kind: fallback, count: Math.max(1, extra), summary: hint };
5042
+ }
5043
+ var times = (n) => n === 2 ? "twice" : `${n} times`;
5044
+ var FAILED = ["server-error", "lost-response", "timeout", "client-error", "unauthorized", "rate-limited"];
5045
+ var AMBIGUOUS = ["server-error", "lost-response", "timeout"];
5046
+ var label = (c) => `${c.method} ${c.path} on ${c.service}`;
5047
+ var sameRequest = (a, b) => a.service === b.service && a.method === b.method && a.resourcePath === b.resourcePath && (a.method === "POST" || a.resourceId === b.resourceId) && (!a.requestDigest || !b.requestDigest || a.requestDigest === b.requestDigest);
5048
+ var succeeded = (c) => c.outcome === "ok" || c.outcome === "replayed";
5049
+ var effects = (c) => c.committed === false || c.outcome === "replayed" || c.outcome === "blocked" ? 0 : (c.committed || c.outcome === "ok" ? 1 : 0) * (c.duplicated ? 2 : 1);
5050
+ var sites = (calls) => [...new Map(calls.filter((c) => c.source).map((c) => [`${c.source.file}:${c.source.line}`, c.source])).values()];
5051
+ function faultWords(c) {
5052
+ const who = c.service;
5053
+ return c.outcome === "lost-response" ? `${who} saved the write but the reply was lost` : c.outcome === "timeout" ? `${who} ${c.committed ? "saved the write but answered after the client timeout" : "never answered"}` : c.outcome === "server-error" ? `${who} returned ${c.status ?? 500}` : c.outcome === "rate-limited" ? `${who} rate-limited the call (429)` : c.outcome === "unauthorized" ? `${who} rejected the credential (${c.status ?? 401})` : c.outcome === "client-error" ? `${who} rejected the request (${c.status ?? 400})` : `${who} failed`;
5054
+ }
5055
+ var groupsOf = (writes) => {
5056
+ const groups2 = [];
5057
+ for (const c of writes) {
5058
+ const g = groups2.find((g2) => sameRequest(g2[0], c));
5059
+ if (g) g.push(c);
5060
+ else groups2.push([c]);
5061
+ }
5062
+ return groups2;
5063
+ };
5064
+ function genericChecks(calls, opts = {}) {
5065
+ const out = [], covered = opts.covered ?? (() => false);
5066
+ const ordered = [...calls].sort((a, b) => a.sequence - b.sequence), writes = ordered.filter((c) => c.isWrite && c.outcome !== "blocked");
5067
+ const claims = opts.claims ?? claimsOf(ordered, opts.output);
5068
+ const announcementSeqs = new Set(claims.map((c) => c.via).filter((v) => v !== void 0));
5069
+ for (const group of groupsOf(writes)) {
5070
+ if (group.length < 2 && !group[0].duplicated) continue;
5071
+ const first = group[0], made = group.reduce((n, c) => n + effects(c), 0), keys = new Set(group.map((c) => c.idempotencyKey));
5072
+ const fault = group.find((c, i) => AMBIGUOUS.includes(c.outcome) && i < group.length - 1);
5073
+ const keyed = keys.size === 1 && !keys.has(void 0);
5074
+ const announce = announcementSeqs.has(first.sequence) || isAnnouncement(first);
5075
+ const when = fault ? ` after ${faultWords(fault)}` : opts.duplicateDelivery ? " when the trigger was delivered twice" : first.duplicated ? ` when ${first.service} received the request twice` : "";
5076
+ if (made >= 2 && (first.method === "POST" || first.method === "DELETE" || announce) && !covered(first.service, "duplicate-write")) {
5077
+ const noun = first.method === "POST" ? "saved" : "applied";
5078
+ out.push({
5079
+ check: "duplicate-write",
5080
+ service: first.service,
5081
+ resource: `${first.method} ${first.path}`,
5082
+ calls: group.map((c) => c.sequence),
5083
+ finding: `${label(first)} was ${group.length > 1 ? `sent ${times(group.length)}` : "sent once"} and ${noun} ${times(made)}${when}${keyed ? " (the key was not honored)" : group.some((c) => c.idempotencyKey) ? " with different idempotency keys" : " without an idempotency key"}`,
5084
+ impact: impactOf(group, made - 1, "data-integrity", `the same ${first.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} exists ${times(made)} downstream`),
5085
+ ...group[group.length - 1].source ? { source: group[group.length - 1].source } : {},
5086
+ writeSites: sites(group),
5087
+ fix: announce ? "check-before-resend" : "idempotency-key"
5088
+ });
5089
+ continue;
5090
+ }
5091
+ if (fault && !keyed && made >= 2 && !covered(first.service, "retry-without-key")) {
5092
+ const retry = group.find((c) => c.sequence > fault.sequence);
5093
+ out.push({
5094
+ check: "retry-without-key",
5095
+ service: first.service,
5096
+ resource: `${first.method} ${first.path}`,
5097
+ calls: group.map((c) => c.sequence),
5098
+ finding: `${label(first)} was sent ${times(group.length)}${when}, ${retry.idempotencyKey ? "with a new idempotency key" : "without an idempotency key"}`,
5099
+ impact: made >= 2 ? impactOf(group, made - 1, "data-integrity", "the write was applied more than once") : { kind: "reliability", count: 1, summary: `a retry without a stable key can apply ${first.method} ${first.resourcePath} twice when the first attempt was saved` },
5100
+ ...retry.source ? { source: retry.source } : {},
5101
+ writeSites: sites(group),
5102
+ fix: announce ? "check-before-resend" : "idempotency-key"
5103
+ });
5104
+ }
5105
+ }
5106
+ for (const limited of ordered.filter((c) => c.outcome === "rate-limited" && c.retryAfterMs && c.at !== void 0)) {
5107
+ const next = ordered.find((c) => c.sequence > limited.sequence && c.service === limited.service && c.at !== void 0 && sameRequest(limited, c));
5108
+ if (next && next.at - limited.at < limited.retryAfterMs * 0.9 && !covered(limited.service, "retry-after-ignored"))
5109
+ out.push({
5110
+ check: "retry-after-ignored",
5111
+ service: limited.service,
5112
+ resource: `${limited.method} ${limited.path}`,
5113
+ calls: [limited.sequence, next.sequence],
5114
+ finding: `${label(limited)} was retried after ${next.at - limited.at}ms although ${limited.service} asked to wait ${Math.round(limited.retryAfterMs / 1e3)}s (Retry-After)`,
5115
+ impact: { kind: "reliability", count: 1, summary: "ignoring Retry-After prolongs rate limiting and can get the credential throttled or banned" },
5116
+ ...next.source ? { source: next.source } : {},
5117
+ fix: "respect-retry-after"
5118
+ });
5119
+ }
5120
+ const unrecoveredBefore = (seq) => writes.filter((w) => w.sequence < seq && !announcementSeqs.has(w.sequence) && FAILED.includes(w.outcome) && w.outcome !== "lost-response" && !(w.outcome === "timeout" && w.committed) && !writes.some((r) => r.sequence > w.sequence && r.sequence < seq && sameRequest(w, r) && succeeded(r)));
5121
+ for (const claim of claims.filter((c) => c.polarity === "success")) {
5122
+ const failed = unrecoveredBefore(claim.sequence)[0], via = claim.via !== void 0 ? ordered.find((c) => c.sequence === claim.via) : void 0;
5123
+ if (!failed || covered(via?.service ?? failed.service, "announce-after-failed-write")) continue;
5124
+ out.push({
5125
+ check: "announce-after-failed-write",
5126
+ service: via?.service ?? failed.service,
5127
+ resource: via ? `${via.method} ${via.path}` : "agent output",
5128
+ calls: [failed.sequence, ...via ? [via.sequence] : []],
5129
+ finding: `Your agent said "${claim.text.slice(0, 80)}"${via ? ` (${label(via)})` : ""} after ${label(failed)} failed (${faultWords(failed)}) and never succeeded`,
5130
+ impact: impactOf(via ? [via] : [], 0, "customer-facing", "the agent reports work that never happened"),
5131
+ ...claim.source ?? via?.source ? { source: claim.source ?? via?.source } : {},
5132
+ fix: "confirm-before-announce"
5133
+ });
5134
+ break;
5135
+ }
5136
+ for (const claim of claims.filter((c) => c.polarity === "failure")) {
5137
+ const later = writes.find((w) => w.sequence > claim.sequence && !announcementSeqs.has(w.sequence) && effects(w) > 0);
5138
+ if (!later || covered(later.service, "write-after-reported-failure")) continue;
5139
+ out.push({
5140
+ check: "write-after-reported-failure",
5141
+ service: later.service,
5142
+ resource: `${later.method} ${later.path}`,
5143
+ calls: [...claim.via ? [claim.via] : [], later.sequence],
5144
+ finding: `Your agent reported "${claim.text.slice(0, 80)}" and then still sent ${label(later)}`,
5145
+ impact: impactOf([later], 0, "data-integrity", "the system changed after the agent told someone it had not"),
5146
+ ...later.source ? { source: later.source } : {}
5147
+ });
5148
+ break;
5149
+ }
5150
+ if (opts.readBack) for (const claim of claims.filter((c) => c.polarity === "success")) {
5151
+ for (const w of writes.filter((w2) => w2.sequence < claim.sequence && w2.resourceId && w2.method !== "POST" && new RegExp(`(^|[^\\w-])${w2.resourceId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}([^\\w-]|$)`).test(claim.text))) {
5152
+ const rb = opts.readBack(w);
5153
+ if (!rb || covered(w.service, "claimed-change-unchanged")) continue;
5154
+ const unchanged = w.method === "DELETE" ? rb.after !== void 0 : canonical2(stable(rb.before)) === canonical2(stable(rb.after));
5155
+ if (!unchanged) continue;
5156
+ out.push({
5157
+ check: "claimed-change-unchanged",
5158
+ service: w.service,
5159
+ resource: `${w.method} ${w.path}`,
5160
+ calls: [w.sequence, ...claim.via ? [claim.via] : []],
5161
+ finding: `Your agent said "${claim.text.slice(0, 80)}", but ${w.service} ${w.path} is unchanged at read-back`,
5162
+ impact: { kind: "data-integrity", count: 1, summary: `${w.resourcePath.split("/").filter((s) => s !== "{id}").pop() ?? "record"} ${w.resourceId} was reported changed but is not` },
5163
+ ...claim.source ?? w.source ? { source: claim.source ?? w.source } : {},
5164
+ fix: "confirm-before-announce"
5165
+ });
5166
+ break;
5167
+ }
5168
+ }
5169
+ for (const failed of writes.filter((w) => FAILED.includes(w.outcome) && !(w.outcome === "timeout" && w.committed) && w.outcome !== "lost-response")) {
5170
+ if (writes.some((r) => r.sequence > failed.sequence && sameRequest(failed, r) && succeeded(r))) continue;
5171
+ const committed = writes.find((a) => a.sequence < failed.sequence && a.service !== failed.service && effects(a) > 0 && !announcementSeqs.has(a.sequence) && !isAnnouncement(a) && !writes.some((x) => x.sequence > failed.sequence && x.service === a.service && (x.resourceId ? x.resourceId === a.resourceId : x.resourcePath === a.resourcePath) && effects(x) > 0));
5172
+ if (!committed || covered(committed.service, "partial-commit")) continue;
5173
+ out.push({
5174
+ check: "partial-commit",
5175
+ service: committed.service,
5176
+ resource: `${committed.method} ${committed.path}`,
5177
+ calls: [committed.sequence, failed.sequence],
5178
+ finding: `${label(committed)} was saved, then ${label(failed)} failed (${faultWords(failed)}) and nothing undid the first write`,
5179
+ impact: impactOf([committed], 0, "data-integrity", `${committed.service} and ${failed.service} disagree: one recorded the change, the other did not`),
5180
+ ...failed.source ? { source: failed.source } : {}
5181
+ });
5182
+ break;
5183
+ }
5184
+ return out;
5185
+ }
5186
+ function worldReadBack(ctx) {
5187
+ return (c) => {
5188
+ const find = (state) => (state?.[c.service]?.[c.resourcePath.replace(/\/\{id\}$/, "")] ?? []).find((r) => r && typeof r === "object" && String(r.id) === c.resourceId);
5189
+ return { before: find(ctx.initialState), after: find(ctx.finalState) };
5190
+ };
5191
+ }
5192
+ var GENERIC_TITLES = {
5193
+ "duplicate-write": ["World-changing calls take effect once", "each create, charge or send is applied once, even under retries and redelivery"],
5194
+ "retry-without-key": ["Retries after a fault reuse the idempotency key", "a write retried after an ambiguous failure carries the same idempotency key"],
5195
+ "retry-after-ignored": ["Rate-limited calls wait for Retry-After", "a 429 is retried no sooner than its Retry-After"],
5196
+ "announce-after-failed-write": ["Success is announced only after the write succeeded", "the agent claims success only when every write it depends on succeeded"],
5197
+ "write-after-reported-failure": ["No writes after the agent reported failure", "after the agent reports a failure it changes nothing else"],
5198
+ "claimed-change-unchanged": ["Claimed changes are visible at read-back", "every resource the agent says it changed is changed when read back"],
5199
+ "partial-commit": ["Multi-service writes commit together or compensate", "when a later write fails, earlier writes in other services are undone"]
5200
+ };
5201
+ function genericWorldChecks(covers) {
5202
+ const rules = ["retry-without-key", "announce-after-failed-write", "write-after-reported-failure", "claimed-change-unchanged", "partial-commit"];
5203
+ return rules.map((rule) => ({
5204
+ id: `generic.${rule}`,
5205
+ title: GENERIC_TITLES[rule][0],
5206
+ expected: GENERIC_TITLES[rule][1],
5207
+ path: "/",
5208
+ impact: rule === "announce-after-failed-write" ? "customer-facing" : rule === "retry-without-key" ? "reliability" : "data-integrity",
5209
+ impactHint: GENERIC_TITLES[rule][1],
5210
+ run(ctx) {
5211
+ if (["openai", "anthropic", "google-oauth", "postgres"].includes(ctx.service.adapter ?? "")) return [];
5212
+ const adapterOf = (name) => ctx.services.find((s) => s.name === name)?.adapter;
5213
+ const calls = callsFromWorldEvents(ctx.events).filter((c) => !["openai", "anthropic", "google-oauth"].includes(adapterOf(c.service) ?? ""));
5214
+ return genericChecks(calls, { readBack: worldReadBack(ctx), duplicateDelivery: ctx.duplicateDelivery, covered: (service, check) => check !== rule || covers(adapterOf(service), check) }).filter((v) => v.check === rule && v.service === ctx.service.name).map((v) => ({ path: v.resource.split(" ")[1] ?? "/", actual: { resource: v.resource, calls: v.calls }, finding: v.finding, impact: { kind: v.impact.kind, count: v.impact.count, ...v.impact.amount ? { amount: Math.round(v.impact.amount * 100), currency: v.impact.currency } : {} }, evidence: v.calls }));
5215
+ }
5216
+ }));
5217
+ }
5218
+
5219
+ // src/runtime/default-checks.ts
5220
+ var PROVIDER = { stripe: "Stripe", slack: "Slack", gmail: "Gmail", postgres: "Postgres" };
5221
+ var displayName = (services, name) => {
5222
+ const s = services.find((x) => x.name === name);
5223
+ return PROVIDER[s?.adapter ?? name] ?? name;
5224
+ };
5225
+ var rowsOf = (state, service, path) => (state?.[service]?.[path] ?? []).filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
5226
+ var 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"]);
5227
+ var volatileKey = (key2) => VOLATILE2.has(key2) || /_at$|At$/.test(key2);
5228
+ var 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);
5229
+ var contentSignature = (row) => canonical3(Object.fromEntries(Object.entries(row).filter(([k]) => !volatileKey(k))));
5230
+ function addedRows(initial, final) {
5231
+ const rows2 = (list2) => list2.filter((r) => !!r && typeof r === "object" && !Array.isArray(r));
5232
+ const ids = new Set(rows2(initial).map((r) => r.id).filter((id) => id !== void 0 && id !== null));
5233
+ const seen = /* @__PURE__ */ new Map();
5234
+ for (const r of rows2(initial)) if (r.id === void 0) seen.set(canonical3(r), (seen.get(canonical3(r)) ?? 0) + 1);
5235
+ return rows2(final).filter((r) => {
5236
+ if (r.id !== void 0 && r.id !== null) return !ids.has(r.id);
5237
+ const key2 = canonical3(r), left = seen.get(key2) ?? 0;
5238
+ if (left > 0) {
5239
+ seen.set(key2, left - 1);
5240
+ return false;
5241
+ }
5242
+ return true;
5243
+ });
5244
+ }
5245
+ function groups(items, key2) {
5246
+ const out = /* @__PURE__ */ new Map();
5247
+ for (const item of items) {
5248
+ const k = key2(item);
5249
+ if (k !== void 0) out.set(k, [...out.get(k) ?? [], item]);
5250
+ }
5251
+ return [...out.values()].filter((g) => g.length > 1);
5252
+ }
5253
+ var writeSequences = (ctx, service, ids) => ctx.events.filter((e) => e.service === service && e.operation === "write" && ids.includes(e.record?.id)).map((e) => e.sequence);
5254
+ var times2 = (n) => n === 2 ? "twice" : `${n} times`;
5255
+ function faultPhrase(ctx) {
5256
+ if (ctx.duplicateDelivery) return " when the triggering webhook was delivered twice";
5257
+ const f = ctx.fault;
5258
+ if (!f || f.triggered === false || !ctx.events.some((e) => e.operation === "fault")) return "";
5259
+ const who = displayName(ctx.services, f.service);
5260
+ return f.type === "timeout-after-write" ? ` when ${who} timed out after saving the write` : f.type === "server-error" ? ` when ${who} returned a 500` : f.type === "slow-response" ? ` when ${who} answered slower than your client timeout` : f.type === "blackhole" ? ` when ${who} dropped a request` : f.type === "duplicate-write" ? ` when ${who} received the same request twice` : ` when ${who} failed`;
5261
+ }
5262
+ var money = (amount, currency) => formatMoney({ amount: amount / 100, currency: currency.toUpperCase() });
5263
+ var stripeRefundOnce = {
5264
+ id: "stripe.refund-once",
5265
+ title: "Each charge refunded at most once per request",
5266
+ path: "/v1/refunds",
5267
+ coversDuplicates: true,
5268
+ expected: "each charge refunded at most once for the same amount and reason; refund total \u2264 charge amount",
5269
+ impact: "money",
5270
+ impactHint: "duplicated refund amount is money paid out twice",
5271
+ run(ctx) {
5272
+ const s = ctx.service.name, out = [];
5273
+ const refunds = addedRows(rowsOf(ctx.initialState, s, "/v1/refunds"), rowsOf(ctx.finalState, s, "/v1/refunds"));
5274
+ for (const group of groups(refunds, (r) => typeof r.charge === "string" ? canonical3({ charge: r.charge, amount: r.amount, reason: r.reason ?? null, metadata: r.metadata ?? {} }) : void 0)) {
5275
+ const amount = Number(group[0].amount), currency = String(group[0].currency ?? "usd"), extra = amount * (group.length - 1);
5276
+ out.push({
5277
+ path: "/v1/refunds",
5278
+ actual: { charge: group[0].charge, refunds: group.map((r) => r.id), amount, currency },
5279
+ finding: `Your agent refunded ${String(group[0].charge)} ${times2(group.length)} (${money(amount, currency)} each)${faultPhrase(ctx)}`,
5280
+ impact: { amount: extra, currency, count: group.length - 1 },
5281
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
5282
+ });
5283
+ }
5284
+ const all = rowsOf(ctx.finalState, s, "/v1/refunds");
5285
+ for (const charge of rowsOf(ctx.finalState, s, "/v1/charges")) {
5286
+ const total = all.filter((r) => r.charge === charge.id && r.status !== "failed" && r.status !== "canceled").reduce((sum, r) => sum + Number(r.amount ?? 0), 0);
5287
+ if (typeof charge.amount === "number" && total > charge.amount) out.push({
5288
+ path: "/v1/refunds",
5289
+ actual: { charge: charge.id, refunded: total, amount: charge.amount },
5290
+ finding: `Your agent refunded ${money(total, String(charge.currency ?? "usd"))} on ${String(charge.id)}, more than its ${money(charge.amount, String(charge.currency ?? "usd"))} charge`,
5291
+ impact: { amount: total - charge.amount, currency: String(charge.currency ?? "usd") }
5292
+ });
5293
+ }
5294
+ return out;
5295
+ }
5296
+ };
5297
+ var stripeNoDuplicatePayment = {
5298
+ id: "stripe.no-duplicate-payment",
5299
+ title: "No duplicate charges or customers for one request",
5300
+ path: "/v1/payment_intents",
5301
+ coversDuplicates: true,
5302
+ expected: "one payment intent per amount/currency/customer/payment method and one customer per email",
5303
+ impact: "money",
5304
+ impactHint: "a duplicated succeeded payment charges the customer twice",
5305
+ run(ctx) {
5306
+ const s = ctx.service.name, out = [];
5307
+ const intents = addedRows(rowsOf(ctx.initialState, s, "/v1/payment_intents"), rowsOf(ctx.finalState, s, "/v1/payment_intents"));
5308
+ for (const group of groups(intents, (r) => canonical3({ amount: r.amount, currency: r.currency, customer: r.customer ?? null, payment_method: r.payment_method ?? null }))) {
5309
+ const succeeded2 = group.filter((r) => r.status === "succeeded"), currency = String(group[0].currency ?? "usd"), amount = Number(group[0].amount);
5310
+ out.push({
5311
+ path: "/v1/payment_intents",
5312
+ actual: { paymentIntents: group.map((r) => r.id), amount, currency, succeeded: succeeded2.length },
5313
+ finding: `Your agent created ${times2(group.length)} the same ${money(amount, currency)} payment${group[0].customer ? ` for ${String(group[0].customer)}` : ""}${faultPhrase(ctx)}`,
5314
+ impact: { amount: amount * Math.max(0, succeeded2.length - 1), currency, count: group.length - 1 },
5315
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
5316
+ });
5317
+ }
5318
+ const customers = addedRows(rowsOf(ctx.initialState, s, "/v1/customers"), rowsOf(ctx.finalState, s, "/v1/customers"));
5319
+ for (const group of groups(customers, (r) => typeof r.email === "string" && r.email ? r.email.toLowerCase() : void 0))
5320
+ out.push({
5321
+ path: "/v1/customers",
5322
+ actual: { customers: group.map((r) => r.id), email: group[0].email },
5323
+ finding: `Your agent created ${times2(group.length)} the Stripe customer ${String(group[0].email)}${faultPhrase(ctx)}`,
5324
+ impact: { kind: "data-integrity", count: group.length - 1 },
5325
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
5326
+ });
5327
+ return out;
5328
+ }
5329
+ };
5330
+ var stripeIdempotentRetries = {
5331
+ id: "stripe.idempotent-retries",
5332
+ title: "Retried POSTs reuse the idempotency key",
5333
+ path: "/v1",
5334
+ expected: "a POST retried after a fault carries the same Idempotency-Key as the attempt that failed",
5335
+ impact: "reliability",
5336
+ impactHint: "retries without a stable key can duplicate money movement",
5337
+ run(ctx) {
5338
+ const s = ctx.service.name, out = [], events = ctx.events.filter((e) => e.service === s);
5339
+ const writeFault = (e) => e.operation === "fault" && (e.detail.startsWith("write committed") || e.detail.startsWith("slow-response: write") || /^(server-error|blackhole)\b.*\((POST|PUT|PATCH|DELETE)\)$/.test(e.detail));
5340
+ for (const fault of events.filter(writeFault)) {
5341
+ const retry = events.find((e) => e.sequence > fault.sequence && (e.operation === "write" || e.operation === "replay") && (e.path === fault.path || e.path.startsWith(`${fault.path}/`)));
5342
+ if (!retry || retry.operation === "replay") continue;
5343
+ const committed = fault.detail.startsWith("write committed") ? events.filter((e) => e.sequence < fault.sequence && e.operation === "write" && e.path === fault.path).pop() : void 0;
5344
+ const original = committed ? committed.idempotencyKey : fault.idempotencyKey;
5345
+ if (retry.idempotencyKey && retry.idempotencyKey === original) continue;
5346
+ out.push({
5347
+ path: fault.path,
5348
+ actual: { faultEvent: fault.sequence, retryEvent: retry.sequence, retryKey: retry.idempotencyKey ?? null, originalKey: original ?? null },
5349
+ finding: `Your agent retried POST ${fault.path} ${retry.idempotencyKey ? "with a new" : "without an"} idempotency key${faultPhrase(ctx)}`,
5350
+ evidence: [fault.sequence, retry.sequence]
5351
+ });
5352
+ }
5353
+ return out;
5354
+ }
5355
+ };
5356
+ var NEGATIVE = /\b(fail|failed|failure|error|unable|could ?n[o']t|cannot|can't|retry|retrying|escalat\w*|pending|not (?:been )?(?:refunded|created|processed|completed))\b/i;
5357
+ var gmailText = (r) => {
5358
+ const headers = r.payload?.headers ?? [];
5359
+ const header3 = (name) => headers.find((h) => h.name?.toLowerCase() === name)?.value ?? "";
5360
+ return { to: header3("to"), subject: header3("subject"), body: String(r.payload?.body?.data ?? r.snippet ?? "") };
5361
+ };
5362
+ function messageChecks(adapter, path) {
5363
+ const noun = adapter === "slack" ? "Slack message" : "email", name = PROVIDER[adapter];
5364
+ const signature = (r) => adapter === "slack" ? typeof r.text === "string" ? canonical3({ channel: r.channel, text: r.text }) : void 0 : Array.isArray(r.labelIds) && !r.labelIds.includes("SENT") ? void 0 : canonical3(gmailText(r));
5365
+ const text = (r) => adapter === "slack" ? String(r.text ?? "") : `${gmailText(r).subject} ${gmailText(r).body}`;
5366
+ const target = (r) => adapter === "slack" ? String(r.channel ?? "the channel") : gmailText(r).to || "the recipient";
5367
+ return [{
5368
+ id: `${adapter}.no-duplicate-message`,
5369
+ title: `No duplicate ${noun} for one action`,
5370
+ path,
5371
+ coversDuplicates: true,
5372
+ expected: `each ${noun} sent once per logical action`,
5373
+ impact: "customer-facing",
5374
+ impactHint: `duplicate ${noun}s are visible to ${adapter === "slack" ? "your team or customers" : "customers"}`,
5375
+ run(ctx) {
5376
+ const s = ctx.service.name;
5377
+ return groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), signature).map((group) => ({
5378
+ path,
5379
+ actual: { messages: group.map((r) => r.id), to: target(group[0]), text: text(group[0]).slice(0, 200) },
5380
+ finding: `Your agent sent the same ${noun} to ${target(group[0])} ${times2(group.length)}${faultPhrase(ctx)}`,
5381
+ impact: { count: group.length - 1 },
5382
+ evidence: writeSequences(ctx, s, group.map((r) => r.id))
5383
+ }));
5384
+ }
5385
+ }, {
5386
+ id: `${adapter}.announce-after-success`,
5387
+ title: `${name} announces only actions that succeeded`,
5388
+ path,
5389
+ expected: `a ${noun} is sent only after the action it announces succeeded`,
5390
+ impact: "customer-facing",
5391
+ impactHint: `the ${noun} reports work that never happened`,
5392
+ run(ctx) {
5393
+ const s = ctx.service.name, out = [];
5394
+ const sent = ctx.events.filter((e) => e.service === s && e.operation === "write" && e.path === path && e.record);
5395
+ const failed = ctx.events.filter((e) => e.service !== s && e.operation === "fault" && /^(server-error|blackhole)\b.*\((POST|PUT|PATCH|DELETE)\)$/.test(e.detail));
5396
+ for (const message of sent) {
5397
+ const words = text(message.record);
5398
+ if (NEGATIVE.test(words)) continue;
5399
+ const unrecovered = failed.find((f) => f.sequence < message.sequence && !ctx.events.some((e) => e.service === f.service && e.sequence > f.sequence && e.sequence < message.sequence && (e.operation === "write" || e.operation === "replay") && (e.path === f.path || e.path.startsWith(`${f.path}/`))));
5400
+ if (!unrecovered) continue;
5401
+ const who = displayName(ctx.services, unrecovered.service);
5402
+ out.push({
5403
+ path,
5404
+ actual: { message: message.record.id, text: words.slice(0, 200), failedService: unrecovered.service, failedPath: unrecovered.path },
5405
+ finding: `Your agent sent "${words.slice(0, 80)}" to ${target(message.record)} after ${who} ${unrecovered.path} failed and was never retried`,
5406
+ impact: { count: 1 },
5407
+ evidence: [unrecovered.sequence, message.sequence]
5408
+ });
5409
+ }
5410
+ return out;
5411
+ }
5412
+ }];
5413
+ }
5414
+ var postgresUpdateApplied = {
5415
+ id: "postgres.update-applied",
5416
+ title: "Updates the agent ran actually changed rows",
5417
+ path: "/",
5418
+ expected: "every UPDATE/DELETE the agent ran matched at least one row",
5419
+ impact: "data-integrity",
5420
+ impactHint: "the agent believes a record changed when it did not",
5421
+ run(ctx) {
5422
+ return (ctx.database?.statements ?? []).filter((st) => /^(UPDATE|DELETE)$/i.test(st.command ?? "") && st.count === 0).map((st) => {
5423
+ const table2 = /^\s*(?:update|delete\s+from)\s+(?:only\s+)?"?([\w.]+)"?/i.exec(st.text)?.[1] ?? "a table";
5424
+ return {
5425
+ path: `/${table2}`,
5426
+ actual: { statement: st.text.slice(0, 200), rowsAffected: 0 },
5427
+ finding: `Your agent ran ${String(st.command).toUpperCase()} on ${table2} but it matched 0 rows, so nothing changed`,
5428
+ impact: { count: 1 }
5429
+ };
5430
+ });
5431
+ }
5432
+ };
5433
+ var postgresNoDuplicateInsert = {
5434
+ id: "postgres.no-duplicate-insert",
5435
+ title: "No duplicate rows for one action",
5436
+ path: "/",
5437
+ coversDuplicates: true,
5438
+ expected: "no two rows added by the run are identical apart from ids and timestamps",
5439
+ impact: "data-integrity",
5440
+ impactHint: "duplicate rows double-count orders, refunds or audit entries",
5441
+ run(ctx) {
5442
+ const out = [];
5443
+ if (!ctx.database?.final) return out;
5444
+ for (const table2 of ctx.database.final.tables) {
5445
+ const before = ctx.database.initial.tables.find((t) => t.name === table2.name)?.rows ?? [];
5446
+ for (const group of groups(addedRows(before, table2.rows), contentSignature))
5447
+ out.push({
5448
+ path: `/${table2.name}`,
5449
+ actual: { table: table2.name, rows: group.length, row: group[0] },
5450
+ finding: `Your agent inserted the same ${table2.name} row ${times2(group.length)}${faultPhrase(ctx)}`,
5451
+ impact: { count: group.length - 1 }
5452
+ });
5453
+ }
5454
+ return out;
5455
+ }
5456
+ };
5457
+ var NOT_EFFECTS = /* @__PURE__ */ new Set(["openai", "anthropic", "google-oauth"]);
5458
+ var genericRepeat = {
5459
+ id: "generic.no-repeat-after-fault",
5460
+ title: "Writes are not repeated after a fault",
5461
+ path: "/",
5462
+ expected: "a write is applied once even when the service faults and the agent retries",
5463
+ impact: "data-integrity",
5464
+ impactHint: "the same record exists twice downstream",
5465
+ run(ctx) {
5466
+ const s = ctx.service.name, out = [];
5467
+ if (NOT_EFFECTS.has(ctx.service.adapter ?? "") || registryFor(ctx.service.adapter).some((c) => c.coversDuplicates)) return out;
5468
+ const faults = ctx.events.filter((e) => e.operation === "fault").map((e) => e.sequence);
5469
+ if (!faults.length && !ctx.duplicateDelivery) return out;
5470
+ for (const path of Object.keys(ctx.finalState?.[s] ?? {})) {
5471
+ for (const group of groups(addedRows(rowsOf(ctx.initialState, s, path), rowsOf(ctx.finalState, s, path)), contentSignature)) {
5472
+ const seq = writeSequences(ctx, s, group.map((r) => r.id));
5473
+ if (!ctx.duplicateDelivery && seq.length && !faults.some((f) => f < Math.max(...seq))) continue;
5474
+ const label2 = path.split("/").filter(Boolean).pop() ?? "record";
5475
+ out.push({
5476
+ path,
5477
+ actual: { records: group.map((r) => r.id ?? null), count: group.length },
5478
+ finding: `Your agent created the same ${s} ${label2.replace(/s$/, "")} ${times2(group.length)}${faultPhrase(ctx)}`,
5479
+ impact: { count: group.length - 1 },
5480
+ evidence: seq
5481
+ });
5482
+ }
5483
+ }
5484
+ return out;
5485
+ }
5486
+ };
5487
+ var DEFAULT_CHECKS = {
5488
+ stripe: [stripeRefundOnce, stripeNoDuplicatePayment, stripeIdempotentRetries],
5489
+ slack: messageChecks("slack", "/messages"),
5490
+ gmail: messageChecks("gmail", "/gmail/v1/users/me/messages"),
5491
+ postgres: [postgresUpdateApplied, postgresNoDuplicateInsert],
5492
+ "*": [genericRepeat]
5493
+ };
5494
+ var VENDOR_COVERS = { "retry-without-key": /\.idempotent-retries$/, "announce-after-failed-write": /\.announce-after-success$/ };
5495
+ DEFAULT_CHECKS["*"].push(...genericWorldChecks((adapter, rule) => !!VENDOR_COVERS[rule] && registryFor(adapter).some((c) => VENDOR_COVERS[rule].test(c.id))));
5496
+ var registryFor = (adapter) => DEFAULT_CHECKS[adapter ?? "json-collection"] ?? [];
5497
+ var refOf = (s) => typeof s === "string" ? { name: s, adapter: s } : s;
5498
+ function defaultChecksFor(services, opts = {}) {
5499
+ const refs = services.map(refOf);
5500
+ if (opts.postgres && !refs.some((r) => r.adapter === "postgres")) refs.push({ name: "postgres", adapter: "postgres" });
5501
+ return refs.flatMap((service) => [...registryFor(service.adapter), ...service.adapter === "postgres" ? [] : DEFAULT_CHECKS["*"]].map((check) => ({ service, check })));
5502
+ }
5503
+ function runDefaultChecks(input) {
5504
+ const services = input.spec.services.map((s) => ({ name: s.name, adapter: s.adapter ?? "json-collection", collections: s.collections }));
5505
+ return defaultChecksFor(services, { postgres: !!input.database && !!input.spec.postgres }).map(({ service, check }) => {
5506
+ const violations = check.run({ service, services, initialState: input.initialState, finalState: input.finalState, events: input.events, fault: input.fault, database: input.database, duplicateDelivery: input.duplicateDelivery });
5507
+ const base = { id: `default.${check.id}.${service.name}`, kind: "default", check: check.id, title: check.title, service: service.name, expected: check.expected };
5508
+ if (!violations.length) return { ...base, path: check.path, passed: true, actual: "no violations" };
5509
+ const amounts = violations.filter((v) => typeof v.impact?.amount === "number" && v.impact.amount > 0);
5510
+ const currency = amounts[0]?.impact?.currency;
5511
+ const amount = amounts.filter((v) => v.impact?.currency === currency).reduce((sum, v) => sum + v.impact.amount, 0);
5512
+ const count = violations.reduce((sum, v) => sum + (v.impact?.count ?? 1), 0);
5513
+ const kind = violations.find((v) => v.impact?.kind)?.impact?.kind ?? check.impact;
5514
+ const summary = kind === "money" && amount && currency ? `${money(amount, currency)} paid out more than intended` : `${count} occurrence${count === 1 ? "" : "s"}: ${check.impactHint}`;
5515
+ return {
5516
+ ...base,
5517
+ path: violations[0].path,
5518
+ passed: false,
5519
+ actual: violations.length === 1 ? violations[0].actual : violations.map((v) => v.actual),
5520
+ finding: violations[0].finding + (violations.length > 1 ? ` (+${violations.length - 1} more)` : ""),
5521
+ impact: { kind, summary, count, ...amount && currency ? { amount, currency } : {} },
5522
+ evidence: violations.flatMap((v) => v.evidence ?? [])
5523
+ };
5524
+ });
5525
+ }
5526
+
5527
+ // src/runtime/hosted-worker.ts
5528
+ import { join as join8, dirname as dirname2 } from "path";
5529
+ async function executeHostedWorker(input = "/input", identity = { uid: 1e3, gid: 1e3 }) {
5530
+ input = await realpath2(input);
5531
+ const secrets = [];
5532
+ const spec = parseWorld(JSON.parse(await readFile4(join8(input, "world.json"), "utf8")));
4286
5533
  let suppliedSeed;
4287
5534
  try {
4288
- suppliedSeed = normalizeSeed(JSON.parse(await readFile2("/input/seed.json", "utf8")).seed);
5535
+ suppliedSeed = normalizeSeed(JSON.parse(await readFile4(join8(input, "seed.json"), "utf8")).seed);
4289
5536
  } catch {
4290
5537
  }
4291
5538
  const world = new HttpWorld(spec, suppliedSeed);
4292
5539
  const started = Date.now();
5540
+ let hook;
4293
5541
  try {
4294
5542
  const credentials = await world.start();
4295
5543
  secrets.push(...Object.values(credentials).map((c) => c.token));
4296
- const runtimeEnv = JSON.parse(await readFile2("/input/runtime.json", "utf8"));
5544
+ const initialState = world.snapshot();
5545
+ const runtimeEnv = JSON.parse(await readFile4(join8(input, "runtime.json"), "utf8"));
4297
5546
  secrets.push(...Object.values(runtimeEnv));
4298
- const env = { PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/tmp", TMPDIR: "/tmp", NODE_ENV: "test", ...runtimeEnv };
5547
+ const packEnv = Object.assign({}, ...Object.values(world.packEnv));
5548
+ secrets.push(...Object.values(packEnv));
5549
+ const env = { ...packEnv, PATH: "/usr/local/bin:/usr/bin:/bin", HOME: "/tmp", TMPDIR: "/tmp", NODE_ENV: "test", ...runtimeEnv };
4299
5550
  for (const [name, credential] of Object.entries(credentials)) {
4300
5551
  env[`AGENTTWIN_${name.toUpperCase()}_URL`] = credential.endpoint;
4301
5552
  env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = credential.token;
4302
5553
  }
4303
5554
  if (spec.command[0] !== "node") throw new Error(`The isolated runner runs Node applications; run ${spec.command[0]} workflows locally with npx agenttwin (they use the twin proxy).`);
5555
+ hook = await createRequestSourceHook(join8(input, "app"), spec, credentials, { root: join8(input, "app"), violationsPath: "", violationsFd: 3 });
5556
+ await chmod2(dirname2(hook.path), 493);
5557
+ await chmod2(hook.path, 420);
5558
+ const blockedFetches = [];
5559
+ let violationBuffer = "";
4304
5560
  let stdout = "", stderr = "", timedOut = false;
4305
- const child = spawn(spec.command[0], spec.command.slice(1), { cwd: "/input/app", env, stdio: ["ignore", "pipe", "pipe"], detached: true, uid: 1e3, gid: 1e3 });
5561
+ const child = spawn(process.execPath, ["--require", hook.path, ...spec.command.slice(1)], { cwd: join8(input, "app"), env, stdio: ["ignore", "pipe", "pipe", "pipe"], detached: true, ...identity });
4306
5562
  child.stdout.on("data", (b) => {
4307
5563
  stdout = (stdout + b.toString()).slice(-65536);
4308
5564
  });
4309
5565
  child.stderr.on("data", (b) => {
4310
5566
  stderr = (stderr + b.toString()).slice(-65536);
4311
5567
  });
4312
- const kill = () => {
4313
- if (child.pid) {
5568
+ const violations = child.stdio[3];
5569
+ violations.on("data", (b) => {
5570
+ violationBuffer += b.toString();
5571
+ let end;
5572
+ while ((end = violationBuffer.indexOf("\n")) >= 0) {
5573
+ const line = violationBuffer.slice(0, end);
5574
+ violationBuffer = violationBuffer.slice(end + 1);
5575
+ if (blockedFetches.length >= 100) continue;
4314
5576
  try {
4315
- process.kill(-child.pid, "SIGKILL");
5577
+ const entry = JSON.parse(line);
5578
+ if (typeof entry.origin !== "string" || entry.origin.length > 2048 || !["unmapped-fetch-origin", "unmapped-http-origin"].includes(entry.reason)) throw new Error("Invalid routing evidence");
5579
+ blockedFetches.push(entry);
4316
5580
  } catch {
5581
+ blockedFetches.push({ origin: "unknown", reason: "unmapped-fetch-origin" });
4317
5582
  }
4318
5583
  }
5584
+ if (violationBuffer.length > 8192) {
5585
+ violationBuffer = "";
5586
+ if (blockedFetches.length < 100) blockedFetches.push({ origin: "unknown", reason: "unmapped-fetch-origin" });
5587
+ }
5588
+ });
5589
+ const managed = manageApplication(child);
5590
+ const kill = () => {
5591
+ void managed.stop().catch(() => {
5592
+ });
4319
5593
  };
4320
- const timer = setTimeout(() => {
5594
+ const executionAbort = new AbortController();
5595
+ const expire = () => {
4321
5596
  timedOut = true;
5597
+ executionAbort.abort(new Error("Test deadline exceeded"));
4322
5598
  kill();
4323
- }, spec.timeoutSeconds * 1e3);
4324
- const exitCode = await new Promise((resolve3, reject) => {
4325
- child.once("error", reject);
4326
- child.once("exit", resolve3);
4327
- }).finally(() => {
5599
+ };
5600
+ let timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + (spec.browser ? BROWSER_STARTUP_MS + BROWSER_CLEANUP_MS : 0));
5601
+ const browserReady = () => {
5602
+ clearTimeout(timer);
5603
+ timer = setTimeout(expire, spec.timeoutSeconds * 1e3 + BROWSER_CLEANUP_MS);
5604
+ };
5605
+ let work;
5606
+ const completion = managed.exited;
5607
+ let browser;
5608
+ let background;
5609
+ let executionError, exitCode;
5610
+ try {
5611
+ if (spec.browser || spec.background) {
5612
+ work = (async () => {
5613
+ if (spec.browser) {
5614
+ try {
5615
+ browser = await browserExecution(spec, world, executionAbort.signal, identity, browserReady);
5616
+ } catch (e) {
5617
+ if (e instanceof BrowserExecutionError) browser = e.evidence;
5618
+ throw e;
5619
+ }
5620
+ if (!browser.passed) return 1;
5621
+ }
5622
+ if (spec.background) background = await waitBackground(spec, world, executionAbort.signal);
5623
+ return 0;
5624
+ })();
5625
+ exitCode = await Promise.race([work, completion.then((code) => {
5626
+ if (!spec.browser && code === 0) return work;
5627
+ throw new Error(timedOut ? "Test deadline exceeded" : `Application exited before browser/background completion (${code})`);
5628
+ })]);
5629
+ } else exitCode = await completion;
5630
+ } catch (error) {
5631
+ executionError = String(error);
5632
+ exitCode = 1;
5633
+ } finally {
5634
+ executionAbort.abort();
4328
5635
  clearTimeout(timer);
4329
5636
  kill();
4330
- });
5637
+ await work?.catch(() => {
5638
+ });
5639
+ if (browser?.timedOut) {
5640
+ timedOut = true;
5641
+ executionError = browser.error;
5642
+ }
5643
+ try {
5644
+ await managed.finish();
5645
+ } catch {
5646
+ executionError = "Application cleanup failed";
5647
+ exitCode = 1;
5648
+ }
5649
+ }
5650
+ if (violationBuffer && blockedFetches.length < 100) blockedFetches.push({ origin: "unknown", reason: "unmapped-fetch-origin" });
4331
5651
  await world.close();
4332
5652
  const assertions = world.assertions();
4333
5653
  const infrastructureAssertions = [];
4334
5654
  for (const assertion of spec.postgres?.assertions ?? []) {
4335
- const { stdout: output } = await promisify(execFile)("psql", [runtimeEnv.DATABASE_URL, "-qAt", "-v", "ON_ERROR_STOP=1", "-c", "BEGIN READ ONLY", "-c", `SELECT COALESCE(json_agg(t), '[]'::json) FROM (${assertion.query}) t`, "-c", "COMMIT"], { env: { ...env, PGOPTIONS: "-c statement_timeout=5000" }, timeout: 7e3 });
5655
+ const { stdout: output } = await promisify4(execFile4)("psql", [runtimeEnv.DATABASE_URL, "-qAt", "-v", "ON_ERROR_STOP=1", "-c", "BEGIN READ ONLY", "-c", `SELECT COALESCE(json_agg(t), '[]'::json) FROM (${assertion.query}) t`, "-c", "COMMIT"], { env: { ...env, PGOPTIONS: "-c statement_timeout=5000" }, timeout: 7e3 });
4336
5656
  const actual = JSON.parse(output.trim());
4337
5657
  infrastructureAssertions.push({ service: "postgres", query: assertion.query, expected: assertion.equals, actual, passed: JSON.stringify(actual) === JSON.stringify(assertion.equals) });
4338
5658
  }
4339
5659
  for (const assertion of spec.redis?.assertions ?? []) {
4340
- const { stdout: exists } = await promisify(execFile)("redis-cli", ["--raw", "EXISTS", assertion.key], { env, timeout: 5e3 });
4341
- const { stdout: output } = await promisify(execFile)("redis-cli", ["--raw", "GET", assertion.key], { env, timeout: 5e3 });
5660
+ const { stdout: exists } = await promisify4(execFile4)("redis-cli", ["--raw", "EXISTS", assertion.key], { env, timeout: 5e3 });
5661
+ const { stdout: output } = await promisify4(execFile4)("redis-cli", ["--raw", "GET", assertion.key], { env, timeout: 5e3 });
4342
5662
  const actual = exists.trim() === "0" ? null : output.replace(/\n$/, "");
4343
5663
  infrastructureAssertions.push({ service: "redis", key: assertion.key, expected: assertion.equals, actual, passed: actual === assertion.equals });
4344
5664
  }
4345
- const initialState = Object.fromEntries(spec.services.map((s) => [s.name, Object.fromEntries(s.collections.map((c) => [c.path, c.seed]))]));
4346
5665
  const evaluation = evaluateState(spec, initialState, world.state, world.events);
4347
- const status = world.unsupported.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || exitCode !== 0 ? "error" : evaluation.outcome === "passed" && infrastructureAssertions.every((a) => a.passed) ? "passed" : "failed";
5666
+ const defaultChecks = runDefaultChecks({ spec, initialState, finalState: world.state, events: world.events, fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null });
5667
+ const status = blockedFetches.length || world.unsupported.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || exitCode !== 0 ? "error" : browser?.passed === false || background?.passed === false ? "failed" : evaluation.outcome === "passed" && defaultChecks.every((c) => c.passed) && infrastructureAssertions.every((a) => a.passed) ? "passed" : "failed";
4348
5668
  for (const c of Object.values(credentials)) {
4349
5669
  stdout = stdout.split(c.token).join("[test-token]");
4350
5670
  stderr = stderr.split(c.token).join("[test-token]");
4351
5671
  }
4352
- for (const secret of Object.values(runtimeEnv)) {
5672
+ for (const secret of [...Object.values(runtimeEnv), ...Object.values(packEnv)]) {
4353
5673
  stdout = stdout.split(secret).join("[test-credential]");
4354
5674
  stderr = stderr.split(secret).join("[test-credential]");
4355
5675
  }
4356
- process.stdout.write(JSON.stringify({
5676
+ return {
4357
5677
  schema: "agenttwin/run-v1",
4358
5678
  name: spec.name,
4359
5679
  workflowId: spec.workflowId,
4360
5680
  status,
5681
+ browser,
5682
+ background,
5683
+ executionError,
5684
+ applicationClock: applicationClockEvidence(spec.applicationClock),
5685
+ twinClock: twinClockEvidence(world.twinClock),
5686
+ ...spec.postgres?.clock ? { database: { clock: { ...spec.postgres.clock, scope: "unqualified-now-function" } } } : {},
4361
5687
  application: { command: spec.command, exitCode, timedOut, stdout, stderr },
4362
5688
  assertions,
4363
5689
  infrastructureAssertions,
4364
5690
  evaluation,
5691
+ defaultChecks,
5692
+ blockedFetches,
4365
5693
  contracts: operationMatrix(spec),
4366
5694
  scenario: spec.scenario,
4367
5695
  fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null,
4368
5696
  seed: world.seed,
4369
- 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.",
4370
- initialState: Object.fromEntries(spec.services.map((s) => [s.name, Object.fromEntries(s.collections.map((c) => [c.path, c.seed]))])),
4371
- finalState: world.state,
4372
- events: world.events,
4373
- unsupported: world.unsupported,
5697
+ 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.",
5698
+ initialState,
5699
+ finalState: world.snapshot(),
5700
+ events: structuredClone(world.events),
5701
+ unsupported: [...world.unsupported],
4374
5702
  durationMs: Date.now() - started,
4375
- coverage: "JSON collections: GET/list, POST/create, idempotency replay. Slack subset (JSON/form): chat.postMessage, conversations.list/history (no OAuth, pagination or provider parity claim). Optional real PostgreSQL 15 / Redis with explicit final-state checks."
4376
- }) + "\n");
5703
+ coverage: "JSON collections: GET/list, POST/create, idempotency replay. Slack subset (JSON/form): chat.postMessage, conversations.list/history (no OAuth, pagination or provider parity claim). Optional Chromium recipes, bounded background checks, explicit Date clock and real PostgreSQL 15 / Redis final-state checks. Unsupported traffic that bypasses the helper is not comprehensively attributed."
5704
+ };
5705
+ } catch (error) {
5706
+ let message = String(error);
5707
+ for (const secret of secrets) message = message.split(secret).join("[test-credential]");
5708
+ throw new Error(message);
4377
5709
  } finally {
4378
- await world.close();
5710
+ try {
5711
+ await hook?.close();
5712
+ } finally {
5713
+ await world.close();
5714
+ }
4379
5715
  }
4380
5716
  }
4381
- main().catch((error) => {
4382
- let message = String(error);
4383
- for (const secret of secrets) message = message.split(secret).join("[test-credential]");
4384
- process.stderr.write(`World runtime failed: ${message}
5717
+
5718
+ // src/runtime/worker.ts
5719
+ executeHostedWorker().then((receipt) => {
5720
+ process.stdout.write(JSON.stringify(receipt) + "\n");
5721
+ }).catch((error) => {
5722
+ process.stderr.write(`World runtime failed: ${String(error)}
4385
5723
  `);
4386
5724
  process.exitCode = 1;
4387
5725
  });