agenttwin 0.3.6 → 0.3.8

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 (79) hide show
  1. package/README.md +17 -6
  2. package/dist/api.js +3363 -313
  3. package/dist/cli.js +5851 -798
  4. package/dist/dashboard/assets/dashboard/agent-home.css +130 -0
  5. package/dist/dashboard/assets/dashboard/golden-gate-portrait.png +0 -0
  6. package/dist/dashboard/assets/next/static/2g265p4WMG_nO2mZLqMm6/_buildManifest.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/{4bd1b696-c023c6e3521b1417.js → 08ffc717-8762425cc415d63e.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/{772-85561381eedc95da.js → 432-c62d9b48a7d6ccab.js} +2 -2
  9. package/dist/dashboard/assets/next/static/chunks/49-1030db7fbea7040f.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/569-40122b1284f67d6a.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/763-591b8154b93c62c9.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-b98766fc366ca9f1.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/account/password/page-233a9ebc76252642.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-61b8b3be0e794aac.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-00f7cd91ede8c855.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/demo/page-8aa153465b6db0ff.js +1 -0
  17. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-4fa9f4e9dd4f6dad.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-d7050946aac756a5.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/layout-6e927a2292a84bf6.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/login/page-e6294a5f57d54f5b.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-5ec79ea6cfd7cd2d.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/page-ca3b8f68fccf45b1.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-586a8fca800d528e.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/signup/page-e6294a5f57d54f5b.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-a1876335f52de3bc.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-dd08f4b1d4f23f97.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-5afc46f2b00b2680.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-c87340f4ff137c46.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-6907e7e63a858618.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/page-12bc7303ea36169c.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/v2/page-0e2e02a3fde43e92.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-6907e7e63a858618.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/framework-9306c712dbc33cd6.js +1 -0
  34. package/dist/dashboard/assets/next/static/chunks/main-54d795e329dc7419.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/main-app-1b876317815c7f42.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/pages/_app-d27c16deeb41f43e.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/pages/_error-e7f3ba1f3701e7a7.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/webpack-a79d1eff6c08383c.js +1 -0
  39. package/dist/dashboard/assets/next/static/css/138b575a572b2958.css +1 -0
  40. package/dist/dashboard/assets/next/static/css/1f0bd0855bbd1a14.css +1 -0
  41. package/dist/dashboard/assets/next/static/css/311920319a51fc90.css +1 -0
  42. package/dist/dashboard/assets/next/static/css/32d869ddee6d2dc1.css +1 -0
  43. package/dist/dashboard/assets/next/static/css/3f003235629d65a0.css +1 -0
  44. package/dist/dashboard/assets/next/static/css/4af3c8ca0da0f48b.css +1 -0
  45. package/dist/dashboard/assets/next/static/css/4fa51ab33fbc7e1b.css +1 -0
  46. package/dist/dashboard/assets/next/static/css/556c40e9d291ee02.css +1 -0
  47. package/dist/dashboard/assets/next/static/css/807e07644631d8e2.css +1 -0
  48. package/dist/dashboard/assets/next/static/css/97d686ac80c4018f.css +1 -0
  49. package/dist/dashboard/assets/next/static/css/c1117da59daa6ba9.css +1 -0
  50. package/dist/dashboard/assets/next/static/css/d99eecb7633d1200.css +1 -0
  51. package/dist/dashboard/assets/next/static/css/ec9722ff890f136c.css +1 -0
  52. package/dist/dashboard/assets/next/static/css/f9c2780fff15fd22.css +1 -0
  53. package/dist/dashboard/assets/next/static/media/golden-gate-portrait.7941528f.png +0 -0
  54. package/dist/dashboard/index.html +16 -1
  55. package/dist/gateway.js +3405 -306
  56. package/dist/worker.js +1701 -53
  57. package/dist/world-host.js +2442 -0
  58. package/package.json +6 -1
  59. package/dist/dashboard/assets/next/static/HZwGKKvvx_oO6caYggjFh/_buildManifest.js +0 -1
  60. package/dist/dashboard/assets/next/static/chunks/255-09fb0d129bb12f51.js +0 -1
  61. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-5dc6a60918e8652d.js +0 -1
  62. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-74603c2c8eaf0760.js +0 -1
  63. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-b79ed135f6bac5f7.js +0 -1
  64. package/dist/dashboard/assets/next/static/chunks/app/demo/page-760a47a5e4dee43f.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-80a0c2c82d5b4efd.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/layout-1a40c59e535513d4.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/page-de4735052adab906.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-7703fc31d6dff0f7.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-ef5a216a578eb7a8.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/framework-292291387d6b2e39.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/main-aea6e71289384293.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/main-app-99295a8cc37e8a47.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/pages/_app-7d307437aca18ad4.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/pages/_error-cb2a52f75f2162e2.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/webpack-f3b6dd27998e84ce.js +0 -1
  76. package/dist/dashboard/assets/next/static/css/1323d7da89b3fa5e.css +0 -1
  77. package/dist/dashboard/assets/next/static/css/9282330a2fd1ab73.css +0 -1
  78. package/dist/dashboard/assets/next/static/css/96e4f356a1159071.css +0 -1
  79. /package/dist/dashboard/assets/next/static/{HZwGKKvvx_oO6caYggjFh → 2g265p4WMG_nO2mZLqMm6}/_ssgManifest.js +0 -0
@@ -0,0 +1,2442 @@
1
+ #!/usr/bin/env node
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+
7
+ // src/runtime/contracts.ts
8
+ function operationMatrix(spec) {
9
+ return {
10
+ schema: "agenttwin/contracts-v1",
11
+ unsupported: { status: 501, marker: "X-AgentTwin-Unsupported", coverage: "incomplete", forwardedToProduction: false },
12
+ adapters: CONTRACTS,
13
+ services: spec?.services.map((s) => ({
14
+ name: s.name,
15
+ adapter: s.adapter ?? "json-collection",
16
+ version: CONTRACTS[s.adapter ?? "json-collection"].version,
17
+ operations: s.adapter === "slack" ? CONTRACTS.slack.operations : s.adapter === "stripe" ? CONTRACTS.stripe.operations : s.adapter && s.adapter !== "json-collection" ? CONTRACTS[s.adapter].operations : s.collections.flatMap((c) => CONTRACTS["json-collection"].operations.map((op) => ({ ...op, endpoint: c.path })))
18
+ })) ?? []
19
+ };
20
+ }
21
+ var CONTRACTS;
22
+ var init_contracts = __esm({
23
+ "src/runtime/contracts.ts"() {
24
+ "use strict";
25
+ CONTRACTS = {
26
+ "json-collection": {
27
+ version: "1.0.0",
28
+ authentication: "Bearer run-scoped test token",
29
+ operations: [
30
+ { method: "GET", endpoint: "<collection path>", effect: "read", response: "{data: records}", errors: ["401 invalid_test_credential", "429 world_capacity"] },
31
+ { method: "POST", endpoint: "<collection path>", effect: "append", response: "201 record; 200 idempotency replay", errors: ["400 expected_json_object", "409 idempotency_conflict", "413 body_too_large", "429 world_capacity"] }
32
+ ],
33
+ limitations: ["Custom API contract, not a vendor replica", "No update/delete, pagination, OAuth, webhooks or schema validation", "Idempotency compares the exact parsed JSON serialization"]
34
+ },
35
+ stripe: {
36
+ version: "1.0.0",
37
+ authentication: "Bearer run-scoped test token; official Stripe SDK configured with test endpoint",
38
+ operations: [
39
+ { method: "POST", endpoint: "/v1/customers", effect: "append customer", parameters: ["email", "name", "description"], errors: ["400 invalid parameters"] },
40
+ { method: "GET", endpoint: "/v1/customers[/<id>]", effect: "retrieve or list customers", parameters: ["limit", "starting_after"], errors: ["404 resource_missing", "400 invalid pagination"] },
41
+ { method: "POST", endpoint: "/v1/payment_intents", effect: "create test payment intent", parameters: ["amount", "currency", "customer", "payment_method", "confirm"], errors: ["400 invalid parameters", "400 resource_missing", "402 card_declined"] },
42
+ { method: "GET", endpoint: "/v1/payment_intents/<id>", effect: "retrieve intent", parameters: [], errors: ["404 resource_missing"] },
43
+ { method: "POST", endpoint: "/v1/payment_intents/<id>/confirm", effect: "test success or decline", parameters: ["payment_method"], errors: ["404 resource_missing", "400 unsupported test method", "402 card_declined"] }
44
+ ],
45
+ limitations: ["Bounded subset, not full Stripe parity; minimal object fields only; no real money", "Only pm_card_visa and pm_card_chargeDeclined test methods", "No webhooks, refunds, subscriptions, payment-method APIs, metadata, updates or deletes", "Customers list supports limit/starting_after; payment intent listing unsupported", "POST idempotency supported; reset clears records and keys; unsupported operations/parameters return 501 and make coverage incomplete"]
46
+ },
47
+ slack: {
48
+ version: "1.0.0",
49
+ authentication: "Bearer run-scoped test token; no Slack OAuth",
50
+ operations: [
51
+ { method: "POST", endpoint: "/api/chat.postMessage", effect: "append /messages", parameters: ["channel", "text"], errors: ["channel_not_found", "no_text"] },
52
+ { method: "GET|POST", endpoint: "/api/conversations.history", effect: "read /messages", parameters: ["channel"], errors: ["channel_not_found"] },
53
+ { method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
54
+ ],
55
+ limitations: ["JSON and form bodies only", "No OAuth, scopes, pagination, threads, edits, deletes, attachments or webhooks", "Errors channel_not_found/no_text use HTTP 200 with ok:false", "Unmodeled parameters and operations return HTTP 501 and make coverage incomplete"]
56
+ },
57
+ github: {
58
+ version: "1.0.0",
59
+ authentication: "Bearer run-scoped test token; GitHub-style Authorization header",
60
+ operations: [
61
+ { method: "GET", endpoint: "/repos", effect: "list repositories", parameters: [], errors: [] },
62
+ { method: "GET", endpoint: "/repos/<repo>", effect: "retrieve repository by name or full_name", parameters: [], errors: ["404 Not Found"] },
63
+ { method: "GET", endpoint: "/repos/<repo>/issues", effect: "list issues", parameters: ["state", "page", "per_page"], errors: ["404 Not Found", "422 validation"] },
64
+ { method: "POST", endpoint: "/repos/<repo>/issues", effect: "create issue", parameters: ["title", "body", "labels"], errors: ["404 Not Found", "422 validation"] },
65
+ { method: "GET", endpoint: "/repos/<repo>/issues/<number>", effect: "retrieve issue", parameters: [], errors: ["404 Not Found"] },
66
+ { method: "PATCH", endpoint: "/repos/<repo>/issues/<number>", effect: "update title/body or close", parameters: ["state", "title", "body"], errors: ["404 Not Found", "422 validation"] },
67
+ { method: "POST", endpoint: "/repos/<repo>/issues/<number>/comments", effect: "create comment", parameters: ["body"], errors: ["404 Not Found", "422 validation"] },
68
+ { method: "GET", endpoint: "/repos/<repo>/issues/<number>/comments", effect: "list comments", parameters: [], errors: ["404 Not Found"] },
69
+ { method: "GET", endpoint: "/repos/<repo>/pulls", effect: "list pull requests", parameters: ["state"], errors: ["404 Not Found", "422 validation"] },
70
+ { method: "GET", endpoint: "/repos/<repo>/pulls/<number>", effect: "retrieve pull request", parameters: [], errors: ["404 Not Found"] },
71
+ { method: "PUT", endpoint: "/repos/<repo>/pulls/<number>/merge", effect: "merge pull request", parameters: ["merge_method"], errors: ["404 Not Found", "405 not mergeable/already merged", "422 validation"] },
72
+ { method: "POST", endpoint: "/repos/<repo>/check-runs", effect: "create check run", parameters: ["name", "head_sha", "status", "conclusion"], errors: ["404 Not Found", "422 validation"] }
73
+ ],
74
+ limitations: ["Bounded REST v3-shaped subset; minimal object fields only", "Ids, numbers and timestamps are deterministic synthetic values", "No auth beyond the run token, no reactions, labels mutation, reviews, branches, contents, releases or webhooks", "Unknown query parameters and operations return 501 and make coverage incomplete"]
75
+ },
76
+ linear: {
77
+ version: "1.0.0",
78
+ authentication: "Bearer run-scoped test token; GraphQL endpoint shape",
79
+ operations: [
80
+ { method: "POST", endpoint: "/graphql query viewer", effect: "read first seeded user as viewer", parameters: [], errors: [] },
81
+ { method: "POST", endpoint: "/graphql query issues", effect: "list issues", parameters: [], errors: [] },
82
+ { method: "POST", endpoint: "/graphql query issue(id:)", effect: "retrieve issue", parameters: ["id"], errors: ["data:null with Entity not found error"] },
83
+ { method: "POST", endpoint: "/graphql query projects", effect: "list projects", parameters: [], errors: [] },
84
+ { method: "POST", endpoint: "/graphql query project(id:)", effect: "retrieve project", parameters: ["id"], errors: ["data:null with Entity not found error"] },
85
+ { method: "POST", endpoint: "/graphql mutation issueCreate", effect: "create issue", parameters: ["input:title,description,state,assigneeId,projectId,priority"], errors: ["Issue title required"] },
86
+ { method: "POST", endpoint: "/graphql mutation issueUpdate", effect: "update issue", parameters: ["id", "input:title,description,state,assigneeId,projectId,priority"], errors: ["data:null with Entity not found error"] },
87
+ { method: "POST", endpoint: "/graphql mutation commentCreate", effect: "create issue comment", parameters: ["input:issueId,body"], errors: ["data:null with Entity not found error", "Comment body required"] }
88
+ ],
89
+ limitations: ["GraphQL-shaped approximation of Linear\u2019s API, not the real schema: a bounded root-field whitelist over the same POST /graphql surface", "Structured inputs must be sent as GraphQL variables; inline object arguments are rejected", "Responses use full bounded node shapes regardless of selection set; no pagination, filters, teams, workflows, attachments or subscriptions", "Known failures (missing entity, validation) use HTTP 200 GraphQL errors; unsupported root fields return 501 and make coverage incomplete"]
90
+ },
91
+ notion: {
92
+ version: "1.0.0",
93
+ authentication: "Bearer run-scoped test token; requires Notion-Version header",
94
+ operations: [
95
+ { method: "GET", endpoint: "/v1/pages/<id>", effect: "retrieve page", parameters: [], errors: ["404 object_not_found"] },
96
+ { method: "POST", endpoint: "/v1/pages", effect: "create page in a seeded database", parameters: ["parent.database_id", "properties"], errors: ["400 validation_error", "404 object_not_found"] },
97
+ { method: "PATCH", endpoint: "/v1/pages/<id>", effect: "update properties or archive", parameters: ["properties", "archived"], errors: ["404 object_not_found", "400 validation_error"] },
98
+ { method: "GET", endpoint: "/v1/databases/<id>", effect: "retrieve database", parameters: [], errors: ["404 object_not_found"] },
99
+ { method: "POST", endpoint: "/v1/databases/<id>/query", effect: "query pages in database", parameters: ["filter(property + equals on title/rich_text/number/select/status/checkbox)", "page_size"], errors: ["404 object_not_found", "400 validation_error"] },
100
+ { method: "PATCH", endpoint: "/v1/blocks/<id>/children", effect: "append child blocks", parameters: ["children (1-100)"], errors: ["404 object_not_found", "400 validation_error"] }
101
+ ],
102
+ limitations: ["Bounded envelope subset: pages must use a seeded database parent", "Ids are deterministic synthetic UUIDs; no url, users, comments, searches or nested rich text parsing", "Databases and blocks are returned as created; schema changes and page_size cursoring are not modeled", "Unsupported filters and operations return 501 and make coverage incomplete"]
103
+ },
104
+ hubspot: {
105
+ version: "1.0.0",
106
+ authentication: "Bearer run-scoped test token; HubSpot-style Bearer private token",
107
+ operations: [
108
+ { method: "GET", endpoint: "/crm/v3/objects/<contacts|companies|deals|tickets>", effect: "list objects", parameters: ["limit", "after"], errors: ["400 validation"] },
109
+ { method: "POST", endpoint: "/crm/v3/objects/<contacts|companies|deals|tickets>", effect: "create object", parameters: ["properties"], errors: ["400 validation"] },
110
+ { method: "GET", endpoint: "/crm/v3/objects/<object>/<id>", effect: "retrieve object", parameters: [], errors: ["404 OBJECT_NOT_FOUND"] },
111
+ { method: "PATCH", endpoint: "/crm/v3/objects/<object>/<id>", effect: "update properties", parameters: ["properties"], errors: ["404 OBJECT_NOT_FOUND", "400 validation"] },
112
+ { method: "POST", endpoint: "/crm/v3/objects/<object>/search", effect: "search objects", parameters: ["query", "filterGroups(EQ only, max 3 filters)", "limit", "after"], errors: ["400 validation"] }
113
+ ],
114
+ limitations: ["Bounded CRM v3 subset: scalar properties only, no associations, batches, pipelines, owners or dedupe", "Ids and timestamps are deterministic synthetic values", "properties/sorts query parameters and filter operators beyond EQ are unsupported", "Unknown objects, parameters and operations return 501 and make coverage incomplete"]
115
+ },
116
+ shopify: {
117
+ version: "1.0.0",
118
+ authentication: "Bearer run-scoped test token; also accepts X-Shopify-Access-Token",
119
+ operations: [
120
+ { method: "GET", endpoint: "/admin/api/2024-01/products.json", effect: "list products", parameters: ["limit", "since_id"], errors: ["400 validation"] },
121
+ { method: "POST", endpoint: "/admin/api/2024-01/products.json", effect: "create product", parameters: ["product:title,body_html,vendor,product_type,status,tags,variants,options"], errors: ["422 title blank"] },
122
+ { method: "GET|PUT", endpoint: "/admin/api/2024-01/products/<id>.json", effect: "retrieve or update product", parameters: ["product"], errors: ["404 Not Found"] },
123
+ { method: "GET", endpoint: "/admin/api/2024-01/orders.json", effect: "list orders", parameters: ["limit", "since_id"], errors: ["400 validation"] },
124
+ { method: "POST", endpoint: "/admin/api/2024-01/orders.json", effect: "create order with line_items", parameters: ["order:email,phone,line_items,financial_status,fulfillment_status,note,total_price,currency"], errors: ["422 line_items blank"] },
125
+ { method: "GET|PUT", endpoint: "/admin/api/2024-01/orders/<id>.json", effect: "retrieve or update order", parameters: ["order"], errors: ["404 Not Found"] },
126
+ { method: "GET", endpoint: "/admin/api/2024-01/customers.json", effect: "list customers", parameters: ["limit", "since_id"], errors: ["400 validation"] },
127
+ { method: "POST", endpoint: "/admin/api/2024-01/customers.json", effect: "create customer", parameters: ["customer:first_name,last_name,email,phone,note,tags"], errors: [] },
128
+ { method: "GET|PUT", endpoint: "/admin/api/2024-01/customers/<id>.json", effect: "retrieve or update customer", parameters: ["customer"], errors: ["404 Not Found"] }
129
+ ],
130
+ limitations: ["REST Admin API pinned to version 2024-01; .json endpoints only", "No metafields, variants mutation, fulfillment, transactions, webhooks, GraphQL or counts endpoints", "Ids and timestamps are deterministic synthetic values", "Unknown parameters and operations return 501 and make coverage incomplete"]
131
+ },
132
+ datadog: {
133
+ version: "1.0.0",
134
+ authentication: "Bearer run-scoped test token; also accepts DD-API-KEY and DD-APPLICATION-KEY headers",
135
+ operations: [
136
+ { method: "GET", endpoint: "/api/v1/monitors", effect: "list monitors", parameters: ["name"], errors: [] },
137
+ { method: "POST", endpoint: "/api/v1/monitors", effect: "create monitor", parameters: ["name", "type", "query", "message", "tags", "options", "priority"], errors: ["400 invalid name/type/query"] },
138
+ { method: "GET", endpoint: "/api/v1/monitor/<id>", effect: "retrieve monitor", parameters: [], errors: ["404 Monitor not found"] },
139
+ { method: "POST", endpoint: "/api/v1/monitor/<id>/mute", effect: "mute monitor", parameters: ["scope", "end"], errors: ["404 Monitor not found"] },
140
+ { method: "POST", endpoint: "/api/v1/events", effect: "post event", parameters: ["title", "text", "tags", "priority", "alert_type", "source"], errors: ["400 invalid title/text"] },
141
+ { method: "GET", endpoint: "/api/v1/events", effect: "list events in window", parameters: ["start", "end", "priority", "tags"], errors: ["400 start/end required"] },
142
+ { method: "GET", endpoint: "/api/v1/query", effect: "query seeded metric series", parameters: ["from", "to", "query (avg/min/max/sum:metric{scope})"], errors: ["400 malformed query"] }
143
+ ],
144
+ limitations: ["Bounded v1 subset: no dashboards, logs, SLOs, downtimes, unmute or v2 endpoints", "Overall state is always OK; monitor unmute and event deletion are unsupported", "Metric queries return seeded /metrics points clipped to the window; unknown metrics return empty series", "Unknown parameters and operations return 501 and make coverage incomplete"]
145
+ },
146
+ gmail: {
147
+ version: "1.0.0",
148
+ authentication: "Bearer run-scoped test token; Google-style OAuth2 Bearer header",
149
+ operations: [
150
+ { method: "POST", endpoint: "/gmail/v1/users/me/messages/send", effect: "append a sent message", parameters: ["text", "raw", "to", "subject", "threadId"], errors: ["400 body required", "400 invalid field type"] },
151
+ { method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
152
+ { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
153
+ { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] }
154
+ ],
155
+ limitations: ["Bounded Gmail v1 subset: send, list, get and labels only", "Sent messages carry a bounded Message envelope; MIME bodies are not parsed and attachments are not modeled", "No drafts, threads, history, modify, trash or watch endpoints", "Unknown fields and operations return 501 and make coverage incomplete"]
156
+ },
157
+ "google-calendar": {
158
+ version: "1.1.0",
159
+ authentication: "Bearer run-scoped test token; Google-style OAuth2 Bearer header",
160
+ operations: [
161
+ { method: "GET", endpoint: "/calendar/v3/users/me/calendarList", effect: "list seeded calendars", parameters: [], errors: [] },
162
+ { method: "GET", endpoint: "/calendar/v3/calendars/primary/events", effect: "filter and paginate nonrecurring timed primary-calendar events", parameters: ["timeMin", "timeMax", "maxResults", "pageToken", "singleEvents", "orderBy=startTime", "conferenceDataVersion=1"], errors: ["400 invalid range, page size, ordering or stale page token"] },
163
+ { method: "POST", endpoint: "/calendar/v3/calendars/primary/events", effect: "create event", parameters: ["summary", "description", "location", "start", "end", "attendees", "status"], errors: ["400 summary required", "400 invalid field type", "404 unknown calendar"] },
164
+ { method: "GET", endpoint: "/calendar/v3/calendars/primary/events/<id>", effect: "retrieve event", parameters: [], errors: ["404 NOT_FOUND"] },
165
+ { method: "PATCH", endpoint: "/calendar/v3/calendars/primary/events/<id>", effect: "update event fields", parameters: ["summary", "description", "location", "start", "end", "attendees", "status"], errors: ["404 NOT_FOUND", "400 invalid field type"] },
166
+ { method: "DELETE", endpoint: "/calendar/v3/calendars/primary/events/<id>", effect: "delete event (responds 200 with an empty object; production returns 204)", parameters: [], errors: ["404 NOT_FOUND"] }
167
+ ],
168
+ limitations: ["Bounded Calendar v3 subset: events on the primary seeded calendar only; requests to any other calendar id return 404", "Recurring-event expansion, all-day timezone filtering, reminders, conference data and sendUpdates are not modeled; these queries return 501", "Pagination tokens are synthetic and expire when query or event state changes; calendar queries follow documented end > timeMin and start < timeMax semantics", "Unknown fields and operations return 501 and make coverage incomplete"]
169
+ },
170
+ gitlab: {
171
+ version: "1.0.0",
172
+ authentication: "Bearer run-scoped test token; GitLab-style Bearer/OAuth token",
173
+ operations: [
174
+ { method: "GET", endpoint: "/api/v4/projects", effect: "list projects", parameters: [], errors: [] },
175
+ { method: "POST", endpoint: "/api/v4/projects", effect: "create project", parameters: ["name", "description", "visibility"], errors: ["400 name missing"] },
176
+ { method: "GET", endpoint: "/api/v4/projects/<id>", effect: "retrieve project", parameters: [], errors: ["404 Not Found"] },
177
+ { method: "GET", endpoint: "/api/v4/issues", effect: "list issues", parameters: [], errors: [] },
178
+ { method: "POST", endpoint: "/api/v4/issues", effect: "create issue in a seeded project", parameters: ["title", "project_id", "description", "labels", "assignee_ids"], errors: ["400 missing title/project_id", "404 Project Not Found"] },
179
+ { method: "GET", endpoint: "/api/v4/issues/<id>", effect: "retrieve issue", parameters: [], errors: ["404 Not Found"] },
180
+ { method: "GET", endpoint: "/api/v4/merge_requests", effect: "list merge requests", parameters: [], errors: [] },
181
+ { method: "POST", endpoint: "/api/v4/merge_requests", effect: "create merge request in a seeded project", parameters: ["title", "project_id", "source_branch", "target_branch", "description"], errors: ["400 missing fields", "404 Project Not Found"] },
182
+ { method: "GET", endpoint: "/api/v4/merge_requests/<iid>", effect: "retrieve merge request", parameters: [], errors: ["404 Not Found"] },
183
+ { method: "GET", endpoint: "/api/v4/merge_requests/<iid>/notes", effect: "list merge request notes", parameters: [], errors: ["404 Merge Request Not Found"] },
184
+ { method: "POST", endpoint: "/api/v4/merge_requests/<iid>/notes", effect: "create merge request note", parameters: ["body"], errors: ["404 Merge Request Not Found", "400 body required"] }
185
+ ],
186
+ limitations: ["Bounded v4 subset: groups, branches, pipelines, environments, tags workflows and uploads are not modeled", "Ids, iids and timestamps are deterministic synthetic values", "List endpoints take no query parameters; unsupported filters return 501", "Unknown operations return 501 and make coverage incomplete"]
187
+ },
188
+ jira: {
189
+ version: "1.0.0",
190
+ authentication: "Bearer run-scoped test token; Atlassian PAT Bearer header",
191
+ operations: [
192
+ { method: "POST", endpoint: "/rest/api/3/issue", effect: "create issue", parameters: ["fields:project.key,issuetype.name,summary,description,priority,labels,assignee"], errors: ["400 missing fields", "400 unknown project"] },
193
+ { method: "GET", endpoint: "/rest/api/3/issue/<keyOrId>", effect: "retrieve issue", parameters: [], errors: ["404 Issue does not exist"] },
194
+ { method: "POST", endpoint: "/rest/api/3/search", effect: "search issues with bounded JQL (project = KEY only)", parameters: ["jql", "maxResults", "fields"], errors: ["400 jql required", "501 JQL clauses beyond project ="] },
195
+ { method: "POST", endpoint: "/rest/api/3/issue/<key>/comment", effect: "create issue comment (ADF doc or plain string)", parameters: ["body"], errors: ["404 Issue does not exist", "400 body format"] },
196
+ { method: "POST", endpoint: "/rest/api/3/issue/<key>/transitions", effect: "apply a bounded transition (11 To Do, 21 In Progress, 31 Done)", parameters: ["transition.id"], errors: ["404 Issue does not exist", "400 unknown transition id"] },
197
+ { method: "GET", endpoint: "/rest/api/3/project", effect: "list seeded projects", parameters: [], errors: [] },
198
+ { method: "GET", endpoint: "/rest/api/3/project/<key>", effect: "retrieve project", parameters: [], errors: ["404 No project could be found"] }
199
+ ],
200
+ limitations: ["Bounded /rest/api/3 subset", "JQL supports only the project = KEY clause; unsupported clauses return 501", "Transitions are the fixed ids 11/21/31 and respond 200 with an empty object", "Comment bodies accept ADF doc objects or plain strings; no rich-text validation", "No attachments, watchers, boards, bulk operations or user endpoints", "Unknown fields and operations return 501 and make coverage incomplete"]
201
+ },
202
+ discord: {
203
+ version: "1.0.0",
204
+ authentication: "Bearer run-scoped test token; also accepts the Discord-idiomatic Authorization: Bot header",
205
+ operations: [
206
+ { method: "GET", endpoint: "/api/channels/<id>", effect: "retrieve seeded channel", parameters: [], errors: ["404 Unknown Channel"] },
207
+ { method: "GET", endpoint: "/api/channels/<id>/messages", effect: "list channel messages (newest first)", parameters: [], errors: ["404 Unknown Channel"] },
208
+ { method: "POST", endpoint: "/api/channels/<id>/messages", effect: "create channel message", parameters: ["content", "tts"], errors: ["404 Unknown Channel", "400 content empty", "400 invalid field type"] },
209
+ { method: "GET", endpoint: "/api/guilds/<id>", effect: "retrieve seeded guild", parameters: [], errors: ["404 Unknown Guild"] },
210
+ { method: "GET", endpoint: "/api/guilds/<id>/members", effect: "list guild members", parameters: ["limit"], errors: ["404 Unknown Guild", "400 invalid limit"] }
211
+ ],
212
+ limitations: ["Bounded subset: channels and guilds exist only as seeded reference state", "Message edit/delete, reactions, roles, threads and guild creation are unsupported", "Member results are seeded records; no gateway presence or intents"]
213
+ },
214
+ twilio: {
215
+ version: "1.0.0",
216
+ authentication: "Bearer run-scoped test token; production Twilio HTTP Basic auth is not required by this twin",
217
+ operations: [
218
+ { method: "POST", endpoint: "/2010-04-01/Accounts/<sid>/Messages.json", effect: "create outbound message (status queued)", parameters: ["To", "From", "Body"], errors: ["400 missing parameters"] },
219
+ { method: "GET", endpoint: "/2010-04-01/Accounts/<sid>/Messages.json", effect: "list messages", parameters: ["To", "From"], errors: ["400 validation"] },
220
+ { method: "POST", endpoint: "/2010-04-01/Accounts/<sid>/Calls.json", effect: "create outbound call (status queued)", parameters: ["To", "From", "Url"], errors: ["400 missing parameters"] },
221
+ { method: "GET", endpoint: "/2010-04-01/Accounts/<sid>/Calls.json", effect: "list calls", parameters: ["To", "From"], errors: ["400 validation"] }
222
+ ],
223
+ limitations: ["JSON bodies accepted in place of Twilio\u2019s form encoding; the .json suffix is optional", "Messages and Calls only; statuses stay queued and never progress in-flight", "No call updates, lookups, queues, recordings, SMS status callbacks or rate limits", "Deterministic synthetic sids; any account sid is accepted", "Unknown parameters and operations return 501 and make coverage incomplete"]
224
+ },
225
+ zendesk: {
226
+ version: "1.0.0",
227
+ authentication: "Bearer run-scoped test token; production Zendesk Basic auth is not required by this twin",
228
+ operations: [
229
+ { method: "GET", endpoint: "/api/v2/tickets.json", effect: "list tickets", parameters: [], errors: [] },
230
+ { method: "POST", endpoint: "/api/v2/tickets.json", effect: "create ticket", parameters: ["ticket:subject,comment.body,requester,status,priority,tags,description,type"], errors: ["400 RecordInvalid subject/comment required", "400 InvalidStatus"] },
231
+ { method: "GET", endpoint: "/api/v2/tickets/<id>.json", effect: "retrieve ticket", parameters: [], errors: ["404 RecordNotFound"] },
232
+ { method: "PUT", endpoint: "/api/v2/tickets/<id>.json", effect: "update ticket fields", parameters: ["ticket:subject,status,priority,tags"], errors: ["404 RecordNotFound", "400 InvalidStatus"] },
233
+ { method: "GET", endpoint: "/api/v2/users.json", effect: "list seeded users", parameters: [], errors: [] },
234
+ { method: "GET", endpoint: "/api/v2/organizations.json", effect: "list seeded organizations", parameters: [], errors: [] }
235
+ ],
236
+ limitations: ["Bounded Support API v2 subset: ticket create/list/get/update plus users and organizations lists", "No macros, views, triggers, audits, attachments, bulk updates or deletes", "Users and organizations are seed-only records; their updates are unsupported", "Unknown fields and operations return 501 and make coverage incomplete"]
237
+ }
238
+ };
239
+ }
240
+ });
241
+
242
+ // src/runtime/git.ts
243
+ import { execFile } from "child_process";
244
+ import { promisify } from "util";
245
+ async function captureGit(cwd, previousHead) {
246
+ const exec = promisify(execFile);
247
+ const git = async (...args) => (await exec("git", args, { cwd, timeout: 5e3, maxBuffer: 1024 * 1024 })).stdout.trim();
248
+ try {
249
+ const head = await git("rev-parse", "HEAD");
250
+ const [branch, total, status, history] = await Promise.all([git("branch", "--show-current"), git("rev-list", "--count", "HEAD"), git("status", "--porcelain", "--untracked-files=no"), git("log", "--since=14 days ago", "-100", "--format=%H %cI")]);
251
+ let changed = await git("diff", "--name-only", "HEAD");
252
+ if (previousHead && /^[a-f0-9]{40,64}$/.test(previousHead) && previousHead !== head) {
253
+ try {
254
+ changed += "\n" + await git("diff", "--name-only", previousHead, head);
255
+ } catch {
256
+ previousHead = void 0;
257
+ }
258
+ }
259
+ return { head, branch: branch || "detached HEAD", totalCommits: Number(total), dirty: !!status, capturedAt: (/* @__PURE__ */ new Date()).toISOString(), commits: history ? history.split("\n").map((line) => {
260
+ const [sha2, date] = line.split(" ");
261
+ return { sha: sha2, date };
262
+ }) : [], changedFiles: [...new Set(changed.split("\n").filter(Boolean))].slice(0, 1e3), ...previousHead ? { previousHead } : {} };
263
+ } catch {
264
+ return void 0;
265
+ }
266
+ }
267
+ var init_git = __esm({
268
+ "src/runtime/git.ts"() {
269
+ "use strict";
270
+ }
271
+ });
272
+
273
+ // src/runtime/world-session.ts
274
+ import { createServer as createServer2 } from "http";
275
+ import { randomBytes as randomBytes3, randomUUID as randomUUID2, createHash as createHash6 } from "crypto";
276
+ import { mkdir as mkdir5, mkdtemp as mkdtemp3, readFile as readFile7, readdir as readdir2, rename, rm as rm4, writeFile as writeFile6 } from "fs/promises";
277
+ import { dirname as dirname2, join as join8, resolve as resolve4, relative as relative3, sep as sep2 } from "path";
278
+ import { tmpdir as tmpdir3 } from "os";
279
+ import { fileURLToPath as fileURLToPath2 } from "url";
280
+ import { spawn as spawn2 } from "child_process";
281
+
282
+ // src/runtime/http-world.ts
283
+ import { createServer } from "http";
284
+ import { isDeepStrictEqual } from "util";
285
+ import { AsyncLocalStorage } from "async_hooks";
286
+
287
+ // src/runtime/request-source.ts
288
+ import { mkdtemp, writeFile, rm, realpath } from "fs/promises";
289
+ import { tmpdir } from "os";
290
+ import { join, resolve } from "path";
291
+ function parseRequestSource(raw, spec) {
292
+ if (typeof raw !== "string" || raw.length > 1024) return;
293
+ try {
294
+ const source = JSON.parse(raw);
295
+ if (!source || typeof source.file !== "string" || !spec.files.includes(source.file) || !Number.isSafeInteger(source.line) || source.line < 1 || source.line > 1e6 || !Number.isSafeInteger(source.column) || source.column < 1 || source.column > 1e6) return;
296
+ return { file: source.file, line: source.line, column: source.column, provenance: "application-reported" };
297
+ } catch {
298
+ return;
299
+ }
300
+ }
301
+ async function createRequestSourceHook(app, spec, credentials) {
302
+ const dir = await mkdtemp(join(tmpdir(), "agenttwin-source-hook-"));
303
+ const path = join(dir, "hook.cjs");
304
+ const config = { root: await realpath(resolve(app)), files: spec.files, origins: Object.values(credentials).map((c) => new URL(c.endpoint).origin) };
305
+ const hook = `const config=${JSON.stringify(config)};
306
+ ` + String.raw`
307
+ const http=require('node:http'),https=require('node:https'),path=require('node:path'),{fileURLToPath}=require('node:url');
308
+ const origins=new Set(config.origins),files=new Set(config.files);
309
+ 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])});}}
310
+ const originalFetch=globalThis.fetch;
311
+ if(originalFetch)globalThis.fetch=function(input,init){let url;try{url=new URL(typeof input==='string'||input instanceof URL?input:input.url);}catch{return originalFetch(input,init);}if(!origins.has(url.origin))return originalFetch(input,init);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});};
312
+ 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);}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);};}
313
+ require('node:module').syncBuiltinESMExports();
314
+ `;
315
+ await writeFile(path, hook, { mode: 384 });
316
+ return { path, close: () => rm(dir, { recursive: true, force: true }) };
317
+ }
318
+
319
+ // src/runtime/stripe-adapter.ts
320
+ function stripeOperation(method, path, params, data, sequence) {
321
+ const error = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
322
+ const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
323
+ if (!match || !["GET", "POST"].includes(method)) return void 0;
324
+ const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
325
+ const allowed = method === "GET" ? id ? [] : ["limit", "starting_after"] : resource === "customers" && !id ? ["email", "name", "description"] : resource === "payment_intents" && !id ? ["amount", "currency", "customer", "payment_method", "confirm"] : action === "confirm" ? ["payment_method"] : void 0;
326
+ if (!allowed || resource === "customers" && action || resource === "payment_intents" && method === "GET" && !id) return void 0;
327
+ if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
328
+ if (method === "GET" && !id) {
329
+ const limit = params.limit === void 0 ? 10 : Number(params.limit);
330
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...error(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
331
+ const ordered = [...rows2].reverse();
332
+ const index = params.starting_after === void 0 ? -1 : ordered.findIndex((r) => r.id === params.starting_after);
333
+ if (params.starting_after !== void 0 && index === -1) return { ...error(400, "resource_missing", "No such starting_after customer", "starting_after"), collection };
334
+ const page = ordered.slice(index + 1, index + 1 + limit);
335
+ return { status: 200, body: { object: "list", data: page, has_more: ordered.length > index + 1 + limit, url: collection }, collection, operation: "read" };
336
+ }
337
+ const row = id ? rows2.find((r) => r.id === id) : void 0;
338
+ if (id && !row) return { ...error(404, "resource_missing", `No such ${resource}: '${id}'`), collection };
339
+ if (method === "GET") return { status: 200, body: row, collection, operation: "read" };
340
+ if (action === "confirm") {
341
+ if (row.status === "succeeded") return { status: 200, body: row, collection, operation: "replay" };
342
+ const payment = params.payment_method ?? row.payment_method;
343
+ if (payment !== "pm_card_visa" && payment !== "pm_card_chargeDeclined") return { ...error(400, "parameter_invalid", "Only pm_card_visa and pm_card_chargeDeclined are supported", "payment_method"), collection };
344
+ row.payment_method = payment;
345
+ row.status = payment === "pm_card_visa" ? "succeeded" : "requires_payment_method";
346
+ row.last_payment_error = payment === "pm_card_chargeDeclined" ? { code: "card_declined", decline_code: "generic_decline", message: "Your card was declined." } : null;
347
+ 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" };
348
+ }
349
+ const prefix = resource === "customers" ? "cus" : "pi";
350
+ let suffix = sequence;
351
+ while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
352
+ const created2 = { id: `${prefix}_at_${suffix}`, object: resource === "customers" ? "customer" : "payment_intent", created: 17e8, livemode: false };
353
+ if (resource === "customers") {
354
+ if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
355
+ Object.assign(created2, { email: null, name: null, description: null, ...params });
356
+ } else {
357
+ const amount = Number(params.amount);
358
+ if (!Number.isSafeInteger(amount) || amount < 1) return { ...error(400, "parameter_invalid_integer", "amount must be a positive integer", "amount"), collection };
359
+ if (typeof params.currency !== "string" || !/^[a-z]{3}$/.test(params.currency)) return { ...error(400, "parameter_invalid", "currency must be a lowercase three-letter code", "currency"), collection };
360
+ if (params.customer && !data["/v1/customers"].some((r) => r.id === params.customer)) return { ...error(400, "resource_missing", "No such customer", "customer"), collection };
361
+ if (params.payment_method !== void 0 && !["pm_card_visa", "pm_card_chargeDeclined"].includes(String(params.payment_method))) return { ...error(400, "parameter_invalid", "Unsupported test payment method", "payment_method"), collection };
362
+ if (params.confirm !== void 0 && !["true", "false", true, false].includes(params.confirm)) return { ...error(400, "parameter_invalid", "confirm must be boolean", "confirm"), collection };
363
+ const confirm = params.confirm === "true" || params.confirm === true;
364
+ if (confirm && !params.payment_method) return { ...error(400, "parameter_missing", "Missing payment_method", "payment_method"), collection };
365
+ Object.assign(created2, { amount, currency: params.currency, customer: params.customer ?? null, payment_method: params.payment_method ?? null, status: confirm && params.payment_method === "pm_card_visa" ? "succeeded" : !confirm && params.payment_method ? "requires_confirmation" : "requires_payment_method", last_payment_error: confirm && params.payment_method === "pm_card_chargeDeclined" ? { code: "card_declined", message: "Your card was declined." } : null });
366
+ }
367
+ if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
368
+ rows2.push(created2);
369
+ const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
370
+ return { status: declined ? 402 : 200, body: declined ? { error: { type: "card_error", code: "card_declined", decline_code: "generic_decline", message: "Your card was declined.", payment_intent: structuredClone(created2) } } : created2, collection, record: structuredClone(created2), operation: "write" };
371
+ }
372
+
373
+ // src/runtime/rest-adapters.ts
374
+ import { createHash } from "crypto";
375
+ var EPOCH = 17e8;
376
+ var iso = (epoch = EPOCH) => new Date(epoch * 1e3).toISOString();
377
+ var sha = (value) => createHash("sha256").update(value).digest("hex");
378
+ var detUuid = (seed) => {
379
+ const hex = sha(seed).slice(0, 32).split("");
380
+ hex[12] = "4";
381
+ hex[16] = "8";
382
+ const s = hex.join("");
383
+ return `${s.slice(0, 8)}-${s.slice(8, 12)}-${s.slice(12, 16)}-${s.slice(16, 20)}-${s.slice(20)}`;
384
+ };
385
+ var rows = (data, collection) => data[collection];
386
+ var notFound = (collection, body) => ({ status: 404, body, collection });
387
+ var badRequest = (collection, body) => ({ status: 400, body, collection });
388
+ var ok = (collection, body, operation = "read") => ({ status: 200, body, collection, operation });
389
+ var created = (collection, body, record) => ({ status: 201, body, collection, record: structuredClone(record), operation: "write" });
390
+ var write = (status, collection, body, record) => ({ status, body, collection, record: structuredClone(record), operation: "write" });
391
+ var isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
392
+ var str = (v) => typeof v === "string" ? v : void 0;
393
+ var pagination = (params, limitDefault, limitMax) => {
394
+ if (params.limit !== void 0 && (!Number.isInteger(Number(params.limit)) || Number(params.limit) < 1 || Number(params.limit) > limitMax)) return void 0;
395
+ const limit = params.limit === void 0 ? limitDefault : Number(params.limit);
396
+ return { limit };
397
+ };
398
+ var uniqueId = (existing, base, key = "id") => {
399
+ let candidate = base;
400
+ while (existing.some((r) => r[key] === String(candidate))) candidate++;
401
+ return String(candidate);
402
+ };
403
+ var boundedInt = (value, min, max) => {
404
+ if (value === void 0) return void 0;
405
+ const n = typeof value === "number" ? value : typeof value === "string" && /^-?\d+$/.test(value) ? Number(value) : NaN;
406
+ return Number.isInteger(n) && n >= min && n <= max ? n : null;
407
+ };
408
+ function githubOperation(method, path, params, _headers, data, sequence) {
409
+ const errors = (status, message, extra) => ({ status, body: { message, documentation_url: "https://docs.github.com/rest", ...extra ?? {} }, collection: "/repos" });
410
+ if (path === "/repos") return method === "GET" ? ok("/repos", rows(data, "/repos").map((row) => structuredClone(row))) : void 0;
411
+ const match = /^\/repos\/([^/]+)\/([^/]+)(?:\/(issues|pulls|check-runs)(?:\/(\d+))?(?:\/(comments|merge))?)?$/.exec(path);
412
+ if (!match) return void 0;
413
+ const [, owner, name, resource, id, sub] = match;
414
+ const repo = `${owner}/${name}`;
415
+ if (!rows(data, "/repos").some((r) => r.name === repo || r.full_name === repo)) return notFound("/repos", { message: "Not Found", documentation_url: "https://docs.github.com/rest" });
416
+ if (!resource) {
417
+ if (method !== "GET") return void 0;
418
+ const repository = rows(data, "/repos").find((r) => r.name === repo || r.full_name === repo);
419
+ return ok("/repos", structuredClone(repository));
420
+ }
421
+ if (resource === "check-runs") {
422
+ if (method !== "POST" || id) return void 0;
423
+ if (typeof params.name !== "string" || !params.name || typeof params.head_sha !== "string" || !params.head_sha) return errors(422, "Validation Failed", { errors: [{ resource: "CheckRun", field: "name", code: "missing_field" }] });
424
+ const allowed = ["name", "head_sha", "status", "conclusion"];
425
+ if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
426
+ 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" }] });
427
+ 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" }] });
428
+ 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() };
429
+ rows(data, "/check-runs").push(run);
430
+ return created("/check-runs", structuredClone(run), run);
431
+ }
432
+ if (resource === "issues") {
433
+ const inRepo = rows(data, "/issues").filter((r) => r.repo === repo);
434
+ if (method === "GET" && !id && !sub) {
435
+ if (Object.keys(params).some((k) => !["state", "page", "per_page"].includes(k))) return void 0;
436
+ const page = pagination(params, 30, 100);
437
+ if (!page) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "per_page", code: "invalid" }] });
438
+ const state = str(params.state) ?? "open";
439
+ if (!["open", "closed", "all"].includes(state)) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "state", code: "invalid" }] });
440
+ const filtered = inRepo.filter((r) => state === "all" || r.state === state);
441
+ const pageNumber = params.page === void 0 ? 1 : Number(params.page);
442
+ if (!Number.isInteger(pageNumber) || pageNumber < 1) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "page", code: "invalid" }] });
443
+ return ok("/issues", filtered.slice((pageNumber - 1) * page.limit, pageNumber * page.limit).map((row) => structuredClone(row)));
444
+ }
445
+ if (method === "POST" && !id && !sub) {
446
+ if (Object.keys(params).some((k) => !["title", "body", "labels"].includes(k))) return void 0;
447
+ if (typeof params.title !== "string" || !params.title) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "title", code: "missing_field" }] });
448
+ if (params.labels !== void 0 && (!Array.isArray(params.labels) || !params.labels.every((l) => typeof l === "string"))) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "labels", code: "invalid" }] });
449
+ const issue2 = { id: `github_at_${sequence}`, number: inRepo.reduce((max, r) => Math.max(max, Number(r.number) || 0), 0) + 1, repo, title: params.title, body: str(params.body) ?? null, state: "open", user: { login: "agenttwin-test" }, labels: Array.isArray(params.labels) ? structuredClone(params.labels) : [], comments: 0, created_at: iso(), updated_at: iso(), closed_at: null };
450
+ rows(data, "/issues").push(issue2);
451
+ return created("/issues", structuredClone(issue2), issue2);
452
+ }
453
+ const issue = id ? inRepo.find((r) => String(r.number) === id) : void 0;
454
+ if (!issue) return notFound("/issues", { message: "Not Found", documentation_url: "https://docs.github.com/rest" });
455
+ if (method === "GET" && !sub) return ok("/issues", structuredClone(issue));
456
+ if (method === "PATCH" && !sub) {
457
+ const allowed = ["state", "title", "body"];
458
+ if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
459
+ if (params.state !== void 0 && !["open", "closed"].includes(String(params.state))) return errors(422, "Validation Failed", { errors: [{ resource: "Issue", field: "state", code: "invalid" }] });
460
+ if (params.title !== void 0 && typeof params.title !== "string") return void 0;
461
+ if (params.body !== void 0 && typeof params.body !== "string") return void 0;
462
+ if (params.title !== void 0) issue.title = params.title;
463
+ if (params.body !== void 0) issue.body = params.body;
464
+ if (params.state !== void 0) {
465
+ issue.state = params.state;
466
+ issue.closed_at = params.state === "closed" ? iso() : null;
467
+ }
468
+ issue.updated_at = iso();
469
+ return write(200, "/issues", structuredClone(issue), issue);
470
+ }
471
+ if (method === "POST" && sub === "comments") {
472
+ if (typeof params.body !== "string" || !params.body) return errors(422, "Validation Failed", { errors: [{ resource: "IssueComment", field: "body", code: "missing_field" }] });
473
+ if (Object.keys(params).some((k) => k !== "body")) return void 0;
474
+ const comment = { id: `github_at_${sequence}`, repo, issue_number: issue.number, body: params.body, user: { login: "agenttwin-test" }, created_at: iso(), updated_at: iso() };
475
+ rows(data, "/comments").push(comment);
476
+ return created("/comments", structuredClone(comment), comment);
477
+ }
478
+ if (method === "GET" && sub === "comments") return ok("/comments", rows(data, "/comments").filter((c) => c.repo === repo && c.issue_number === issue.number).map((row) => structuredClone(row)));
479
+ return void 0;
480
+ }
481
+ if (resource === "pulls") {
482
+ const inRepo = rows(data, "/pulls").filter((r) => r.repo === repo);
483
+ const pull = id ? inRepo.find((r) => String(r.number) === id) : void 0;
484
+ if (method === "GET" && !id && !sub) {
485
+ if (Object.keys(params).some((k) => k !== "state")) return void 0;
486
+ const state = str(params.state) ?? "open";
487
+ if (!["open", "closed", "all"].includes(state)) return errors(422, "Validation Failed", { errors: [{ resource: "PullRequest", field: "state", code: "invalid" }] });
488
+ return ok("/pulls", inRepo.filter((r) => state === "all" || r.state === state).map((row) => structuredClone(row)));
489
+ }
490
+ if (!pull) return id ? notFound("/pulls", { message: "Not Found", documentation_url: "https://docs.github.com/rest" }) : void 0;
491
+ if (method === "GET" && id && !sub) return ok("/pulls", structuredClone(pull));
492
+ if (method === "PUT" && sub === "merge") {
493
+ if (Object.keys(params).some((k) => k !== "merge_method")) return void 0;
494
+ if (params.merge_method !== void 0 && !["merge", "squash", "rebase"].includes(String(params.merge_method))) return errors(422, "Validation Failed", { errors: [{ resource: "PullRequest", field: "merge_method", code: "invalid" }] });
495
+ if (pull.merged) return errors(405, "Pull Request was already merged");
496
+ if (pull.state !== "open") return errors(405, "Pull Request is not mergeable");
497
+ pull.merged = true;
498
+ pull.merged_at = iso();
499
+ pull.state = "closed";
500
+ pull.merge_commit_sha = sha(`${repo}:${pull.number}:${sequence}`).slice(0, 40);
501
+ return write(200, "/pulls", { sha: pull.merge_commit_sha, merged: true, message: "Pull Request successfully merged" }, pull);
502
+ }
503
+ return void 0;
504
+ }
505
+ return void 0;
506
+ }
507
+ function linearOperation(method, path, params, _headers, data, sequence) {
508
+ const notFoundNode = (name) => ({ status: 200, body: { data: null, errors: [{ message: `Entity not found: ${name}` }] }, collection: "/issues", operation: "read" });
509
+ if (method !== "POST" || path !== "/graphql") return void 0;
510
+ const query = str(params.query);
511
+ if (!query) return void 0;
512
+ if (!/^\s*(query|mutation)\b/m.test(query)) return void 0;
513
+ const isMutation = /\bmutation\b/.test(query.slice(0, query.indexOf("{") + 1));
514
+ const root = new RegExp(isMutation ? "\\bmutation\\b[^{]*\\{\\s*(\\w+)" : "\\bquery\\b[^{]*\\{\\s*(\\w+)").exec(query);
515
+ if (!root) return void 0;
516
+ const variables = isObject(params.variables) ? params.variables : {};
517
+ const arg = (name) => variables[name] ?? (new RegExp(`\\b${name}\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(query)?.[1] !== void 0 ? JSON.parse(`"${new RegExp(`\\b${name}\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`).exec(query)[1]}"`) : void 0);
518
+ const input = variables.input ?? void 0;
519
+ if (!isMutation) {
520
+ if (root[1] === "viewer") {
521
+ if (Object.keys(variables).length) return void 0;
522
+ return ok("/users", { data: { viewer: rows(data, "/users")[0] ?? { id: "linear_at_viewer", name: "Test User", email: "user@example.test", displayName: "Test User" } } });
523
+ }
524
+ if (root[1] === "issues") {
525
+ if (Object.keys(variables).length) return void 0;
526
+ return ok("/issues", { data: { issues: { nodes: rows(data, "/issues").map((row) => structuredClone(row)) } } });
527
+ }
528
+ if (root[1] === "projects") {
529
+ if (Object.keys(variables).length) return void 0;
530
+ return ok("/projects", { data: { projects: { nodes: rows(data, "/projects").map((row) => structuredClone(row)) } } });
531
+ }
532
+ if (root[1] === "issue") {
533
+ const issue = rows(data, "/issues").find((r) => r.id === arg("id"));
534
+ if (Object.keys(variables).some((k) => k !== "id") || arg("id") === void 0) return void 0;
535
+ return issue ? ok("/issues", { data: { issue: structuredClone(issue) } }) : notFoundNode("Issue");
536
+ }
537
+ if (root[1] === "project") {
538
+ const project = rows(data, "/projects").find((r) => r.id === arg("id"));
539
+ if (Object.keys(variables).some((k) => k !== "id") || arg("id") === void 0) return void 0;
540
+ return project ? ok("/projects", { data: { project: structuredClone(project) } }) : notFoundNode("Project");
541
+ }
542
+ return void 0;
543
+ }
544
+ if (root[1] === "issueCreate") {
545
+ if (!isObject(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
546
+ if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
547
+ if (typeof input.title !== "string" || !input.title) return { status: 200, body: { data: null, errors: [{ message: "Issue title required" }] }, collection: "/issues" };
548
+ const issue = { id: `linear_at_${sequence}`, title: input.title, description: str(input.description) ?? null, state: str(input.state) ?? "todo", assigneeId: str(input.assigneeId) ?? null, projectId: str(input.projectId) ?? null, priority: input.priority === void 0 ? 0 : input.priority, createdAt: iso(), updatedAt: iso() };
549
+ rows(data, "/issues").push(issue);
550
+ return write(200, "/issues", { data: { issueCreate: { success: true, issue: structuredClone(issue) } } }, issue);
551
+ }
552
+ if (root[1] === "issueUpdate") {
553
+ if (!isObject(input) || arg("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
554
+ const issue = rows(data, "/issues").find((r) => r.id === arg("id"));
555
+ if (!issue) return notFoundNode("Issue");
556
+ if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
557
+ for (const [k, v] of Object.entries(input)) if (["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k)) issue[k] = v;
558
+ issue.updatedAt = iso();
559
+ return write(200, "/issues", { data: { issueUpdate: { success: true, issue: structuredClone(issue) } } }, issue);
560
+ }
561
+ if (root[1] === "commentCreate") {
562
+ if (!isObject(input) || Object.keys(variables).some((k) => k !== "input")) return void 0;
563
+ if (Object.keys(input).some((k) => !["issueId", "body"].includes(k))) return void 0;
564
+ const issue = rows(data, "/issues").find((r) => r.id === input.issueId);
565
+ if (!issue) return notFoundNode("Issue");
566
+ if (typeof input.body !== "string" || !input.body) return { status: 200, body: { data: null, errors: [{ message: "Comment body required" }] }, collection: "/comments" };
567
+ const comment = { id: `linear_at_${sequence}`, issueId: input.issueId, body: input.body, userId: rows(data, "/users")[0]?.id ?? "linear_at_viewer", createdAt: iso() };
568
+ rows(data, "/comments").push(comment);
569
+ return write(200, "/comments", { data: { commentCreate: { success: true, comment: structuredClone(comment) } } }, comment);
570
+ }
571
+ return void 0;
572
+ }
573
+ var notionPropValue = (property) => {
574
+ if (!isObject(property)) return property;
575
+ if (property.title !== void 0) return Array.isArray(property.title) ? property.title.map((t) => t?.plain_text ?? t?.text?.content ?? "").join("") : property.title;
576
+ if (property.rich_text !== void 0) return Array.isArray(property.rich_text) ? property.rich_text.map((t) => t?.plain_text ?? t?.text?.content ?? "").join("") : property.rich_text;
577
+ if (property.select !== void 0) return isObject(property.select) ? property.select.name : property.select;
578
+ if (property.status !== void 0) return isObject(property.status) ? property.status.name : property.status;
579
+ return property.number ?? property.checkbox ?? property.url ?? property.email ?? property.phone_number ?? null;
580
+ };
581
+ var notionPage = (id, parent, properties, archived = false) => ({ object: "page", id, created_time: iso(), last_edited_time: iso(), created_by: null, last_edited_by: null, cover: null, icon: null, parent, archived, properties, url: null });
582
+ var notionError = (collection, status, code, message) => ({ status, body: { object: "error", status, code, message }, collection });
583
+ function notionOperation(method, path, params, headers, data, sequence) {
584
+ if (!/^\/v1\/(pages|databases|blocks)/.test(path)) return void 0;
585
+ const version = headers["notion-version"];
586
+ if (typeof version !== "string" || !version) return notionError("/pages", 400, "invalid_request", "Notion-Version header failed validation: Notion-Version header should be defined, instead was `undefined`.");
587
+ if (path === "/v1/pages") {
588
+ if (method !== "POST") return void 0;
589
+ if (Object.keys(params).some((k) => !["parent", "properties"].includes(k))) return void 0;
590
+ const parent = isObject(params.parent) ? params.parent : void 0;
591
+ if (!parent || str(parent.database_id) === void 0 || Object.keys(parent).some((k) => k !== "database_id")) return notionError("/pages", 400, "validation_error", "Bounded Notion twin supports database parents only: provide parent.database_id.");
592
+ const database = rows(data, "/databases").find((d) => d.id === parent.database_id);
593
+ if (!database) return notionError("/pages", 404, "object_not_found", "Could not find database with ID.");
594
+ if (!isObject(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be defined.");
595
+ const page = notionPage(detUuid(`page:${sequence}`), { type: "database_id", database_id: database.id }, structuredClone(params.properties));
596
+ rows(data, "/pages").push(page);
597
+ return { status: 200, body: structuredClone(page), collection: "/pages", record: structuredClone(page), operation: "write" };
598
+ }
599
+ const pageMatch = /^\/v1\/pages\/([^/]+)$/.exec(path);
600
+ if (pageMatch) {
601
+ const page = rows(data, "/pages").find((p) => p.id === pageMatch[1]);
602
+ if (!page) return notionError("/pages", 404, "object_not_found", "Could not find page with ID.");
603
+ if (method === "GET") return ok("/pages", structuredClone(page));
604
+ if (method === "PATCH") {
605
+ if (Object.keys(params).some((k) => !["properties", "archived", "in_trash"].includes(k))) return void 0;
606
+ if (params.properties !== void 0) {
607
+ if (!isObject(params.properties)) return notionError("/pages", 400, "validation_error", "properties should be an object.");
608
+ Object.assign(page.properties, structuredClone(params.properties));
609
+ }
610
+ if (params.archived !== void 0) {
611
+ if (typeof params.archived !== "boolean") return notionError("/pages", 400, "validation_error", "archived should be a boolean.");
612
+ page.archived = params.archived;
613
+ }
614
+ page.last_edited_time = iso();
615
+ return write(200, "/pages", structuredClone(page), page);
616
+ }
617
+ return void 0;
618
+ }
619
+ const databaseMatch = /^\/v1\/databases\/([^/]+)(?:\/(query))?$/.exec(path);
620
+ if (databaseMatch) {
621
+ const database = rows(data, "/databases").find((d) => d.id === databaseMatch[1]);
622
+ if (!database) return notionError("/databases", 404, "object_not_found", "Could not find database with ID.");
623
+ if (!databaseMatch[2]) {
624
+ if (method !== "GET") return void 0;
625
+ return ok("/databases", structuredClone(database));
626
+ }
627
+ if (method !== "POST") return void 0;
628
+ if (Object.keys(params).some((k) => !["filter", "page_size", "start_cursor", "sorts"].includes(k))) return void 0;
629
+ if (params.sorts !== void 0 || params.start_cursor !== void 0) return void 0;
630
+ let limit = 100;
631
+ if (params.page_size !== void 0) {
632
+ if (!Number.isInteger(params.page_size) || Number(params.page_size) < 1 || Number(params.page_size) > 100) return notionError("/databases", 400, "validation_error", "page_size must be an integer between 1 and 100.");
633
+ limit = Number(params.page_size);
634
+ }
635
+ const pages = rows(data, "/pages").filter((p) => p.parent && p.parent.database_id === database.id);
636
+ if (params.filter !== void 0) {
637
+ const filter = params.filter;
638
+ if (!isObject(filter) || Object.keys(filter).length !== 2 || typeof filter.property !== "string") return void 0;
639
+ const [condition] = Object.keys(filter).filter((k) => k !== "property");
640
+ if (!["title", "rich_text", "number", "select", "status", "checkbox"].includes(condition)) return void 0;
641
+ const expected = isObject(filter[condition]) ? filter[condition].equals : void 0;
642
+ if (expected === void 0 || Object.keys(filter[condition]).length !== 1) return void 0;
643
+ const property = filter.property;
644
+ const results = pages.filter((p) => notionPropValue(p.properties[property]) === expected);
645
+ return ok("/pages", { object: "list", results: results.slice(0, limit).map((row) => structuredClone(row)), has_more: false, next_cursor: null, type: "page_or_database", page_or_database: {} });
646
+ }
647
+ return ok("/pages", { object: "list", results: pages.slice(0, limit).map((row) => structuredClone(row)), has_more: false, next_cursor: null, type: "page_or_database", page_or_database: {} });
648
+ }
649
+ const blockMatch = /^\/v1\/blocks\/([^/]+)\/(children)$/.exec(path);
650
+ if (blockMatch) {
651
+ if (method !== "PATCH" || blockMatch[2] !== "children") return void 0;
652
+ if (Object.keys(params).some((k) => k !== "children")) return void 0;
653
+ if (!Array.isArray(params.children) || !params.children.length || params.children.length > 100) return notionError("/blocks", 400, "validation_error", "children should be an array of 1\u2013100 block objects.");
654
+ if (!params.children.every(isObject)) return notionError("/blocks", 400, "validation_error", "children should be block objects.");
655
+ if (params.children.some((c) => typeof c.type !== "string" || !c.type)) return notionError("/blocks", 400, "validation_error", "Each child block requires a type.");
656
+ const page = rows(data, "/pages").find((p) => p.id === blockMatch[1]);
657
+ const block = rows(data, "/blocks").find((b) => b.id === blockMatch[1]);
658
+ if (!page && !block) return notionError("/blocks", 404, "object_not_found", "Could not find block with ID.");
659
+ const parent = page ? { type: "page_id", page_id: page.id } : { type: "block_id", block_id: block.id };
660
+ const createdBlocks = params.children.map((child, index) => {
661
+ const record = { object: "block", id: detUuid(`block:${sequence}:${index}`), parent, type: child.type, created_time: iso(), last_edited_time: iso(), has_children: false, archived: false, block: structuredClone(child) };
662
+ rows(data, "/blocks").push(record);
663
+ return record;
664
+ });
665
+ return write(200, "/blocks", { object: "list", results: structuredClone(createdBlocks), has_more: false, next_cursor: null, type: "block", block: {} }, createdBlocks[createdBlocks.length - 1]);
666
+ }
667
+ return void 0;
668
+ }
669
+ var hubspotEnvelope = (record) => ({ id: record.id, properties: structuredClone(record.properties), createdAt: record.createdAt, updatedAt: record.updatedAt, archived: false });
670
+ function hubspotOperation(method, path, params, _headers, data, sequence) {
671
+ const match = /^\/crm\/v3\/objects\/(contacts|companies|deals|tickets)(?:\/(search)|\/([^/]+))?$/.exec(path);
672
+ if (!match) return void 0;
673
+ const [, object3, search, id] = match;
674
+ const collection = `/crm/v3/objects/${object3}`;
675
+ const properties = isObject(params.properties) ? params.properties : void 0;
676
+ const validProperties = (value) => Object.values(value).every((v) => ["string", "number", "boolean", "object"].includes(v === null ? "object" : typeof v));
677
+ if (search) {
678
+ if (method !== "POST" || id) return void 0;
679
+ if (Object.keys(params).some((k) => !["query", "filterGroups", "limit", "after", "properties", "sorts"].includes(k))) return void 0;
680
+ if (params.properties !== void 0 || params.sorts !== void 0) return void 0;
681
+ const searchLimit = boundedInt(params.limit, 1, 100);
682
+ if (searchLimit === null) return badRequest(collection, { status: "error", message: "Unable to process: limit must be between 1 and 100", category: "VALIDATION_ERROR" });
683
+ const searchAfter = boundedInt(params.after, 0, Number.MAX_SAFE_INTEGER);
684
+ if (searchAfter === null) return badRequest(collection, { status: "error", message: "Unable to process: after must be a nonnegative integer offset", category: "VALIDATION_ERROR" });
685
+ const limit = searchLimit ?? 10, after = searchAfter ?? 0;
686
+ let filtered = rows(data, collection);
687
+ if (params.query !== void 0) {
688
+ if (typeof params.query !== "string") return void 0;
689
+ const needle = params.query.toLowerCase();
690
+ filtered = filtered.filter((r) => Object.values(r.properties).some((v) => typeof v === "string" && v.toLowerCase().includes(needle)));
691
+ }
692
+ if (params.filterGroups !== void 0) {
693
+ if (!Array.isArray(params.filterGroups) || params.filterGroups.length !== 1) return void 0;
694
+ const group = params.filterGroups[0];
695
+ if (!isObject(group) || Object.keys(group).some((k) => k !== "filters") || !Array.isArray(group.filters) || !group.filters.length || group.filters.length > 3) return void 0;
696
+ for (const filter of group.filters) {
697
+ if (!isObject(filter) || Object.keys(filter).some((k) => !["propertyName", "operator", "value"].includes(k)) || typeof filter.propertyName !== "string" || filter.operator !== "EQ" || filter.value === void 0) return void 0;
698
+ const propertyName = filter.propertyName;
699
+ filtered = filtered.filter((r) => r.properties[propertyName] === filter.value);
700
+ }
701
+ }
702
+ const page = filtered.slice(after, after + limit);
703
+ return ok(collection, { total: filtered.length, results: page.map((r) => hubspotEnvelope(r)) });
704
+ }
705
+ if (!id) {
706
+ if (method === "GET") {
707
+ if (Object.keys(params).some((k) => !["limit", "after"].includes(k))) return void 0;
708
+ const listLimit = boundedInt(params.limit, 1, 100);
709
+ if (listLimit === null) return badRequest(collection, { status: "error", message: "Unable to process: limit must be between 1 and 100", category: "VALIDATION_ERROR" });
710
+ const listAfter = boundedInt(params.after, 0, Number.MAX_SAFE_INTEGER);
711
+ if (listAfter === null) return badRequest(collection, { status: "error", message: "Unable to process: after must be a nonnegative integer offset", category: "VALIDATION_ERROR" });
712
+ const page = rows(data, collection).slice(listAfter ?? 0, (listAfter ?? 0) + (listLimit ?? 10));
713
+ return ok(collection, { total: rows(data, collection).length, results: page.map((r) => hubspotEnvelope(r)) });
714
+ }
715
+ if (method !== "POST") return void 0;
716
+ if (Object.keys(params).some((k) => k !== "properties") || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: `Invalid input JSON on line 1: Unable to process JSON: properties required for ${object3}`, category: "VALIDATION_ERROR" });
717
+ const record2 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
718
+ rows(data, collection).push(record2);
719
+ return created(collection, hubspotEnvelope(record2), record2);
720
+ }
721
+ const record = rows(data, collection).find((r) => r.id === id);
722
+ if (!record) return { status: 404, body: { status: "error", message: `Object not found: ${object3} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
723
+ if (method === "GET") return ok(collection, hubspotEnvelope(record));
724
+ if (method === "PATCH") {
725
+ if (Object.keys(params).some((k) => k !== "properties") || !properties || !validProperties(properties)) return badRequest(collection, { status: "error", message: "Unable to process JSON: properties object required", category: "VALIDATION_ERROR" });
726
+ Object.assign(record.properties, structuredClone(properties));
727
+ record.updatedAt = iso();
728
+ return write(200, collection, hubspotEnvelope(record), record);
729
+ }
730
+ return void 0;
731
+ }
732
+ var SHOPIFY_VERSION = "2024-01";
733
+ var shopifySlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
734
+ function shopifyOperation(method, path, params, _headers, data, sequence) {
735
+ const match = new RegExp(`^/admin/api/${SHOPIFY_VERSION}/(products|orders|customers)(?:/(\\d+))?\\.json$`).exec(path);
736
+ if (!match) return void 0;
737
+ const [, resource, id] = match;
738
+ const collection = `/admin/${resource}`;
739
+ const wrap = resource === "products" ? "product" : resource === "orders" ? "order" : "customer";
740
+ const rowsIn2 = rows(data, collection);
741
+ const notFoundShopify = () => notFound(collection, { errors: "Not Found" });
742
+ const enriched = (record2) => ({ ...structuredClone(record2), created_at: record2.created_at ?? iso(), updated_at: iso() });
743
+ if (!id) {
744
+ if (method === "GET") {
745
+ if (Object.keys(params).some((k) => !["limit", "since_id"].includes(k))) return void 0;
746
+ const page = pagination(params, 50, 250);
747
+ if (!page) return badRequest(collection, { errors: "limit must be between 1 and 250" });
748
+ let filtered = rowsIn2;
749
+ if (params.since_id !== void 0) {
750
+ if (!Number.isInteger(Number(params.since_id)) || Number(params.since_id) < 0) return badRequest(collection, { errors: "since_id must be a nonnegative integer" });
751
+ filtered = filtered.filter((r) => Number(r.id) > Number(params.since_id));
752
+ }
753
+ return ok(collection, { [`${resource}`]: filtered.slice(0, page.limit).map(enriched) });
754
+ }
755
+ if (method !== "POST") return void 0;
756
+ if (Object.keys(params).some((k) => k !== wrap) || !isObject(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
757
+ const body = params[wrap];
758
+ if (resource === "products" && (typeof body.title !== "string" || !body.title)) return { status: 422, body: { errors: { title: ["can't be blank"] } }, collection };
759
+ if (resource === "orders") {
760
+ if (!Array.isArray(body.line_items) || !body.line_items.length || !body.line_items.every(isObject)) return { status: 422, body: { errors: { line_items: ["can't be blank"] } }, collection };
761
+ if (body.line_items.some((item) => Object.keys(item).some((k) => !["title", "quantity", "price", "sku"].includes(k)))) return void 0;
762
+ }
763
+ const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags", "variants", "options"], orders: ["email", "phone", "line_items", "financial_status", "fulfillment_status", "note", "total_price", "currency"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource];
764
+ if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
765
+ const record2 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso(), updated_at: iso() };
766
+ if (resource === "products") Object.assign(record2, { title: body.title, body_html: body.body_html ?? null, vendor: body.vendor ?? null, product_type: body.product_type ?? null, handle: shopifySlug(String(body.title)), status: str(body.status) ?? "active", tags: body.tags ?? "", variants: Array.isArray(body.variants) ? structuredClone(body.variants) : [], options: Array.isArray(body.options) ? structuredClone(body.options) : [], image: null, images: [] });
767
+ if (resource === "orders") Object.assign(record2, { email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, line_items: structuredClone(body.line_items), total_price: typeof body.total_price === "string" ? body.total_price : Number(Array.isArray(body.line_items) ? body.line_items.reduce((sum, item) => sum + Number(item.price ?? 0) * Number(item.quantity ?? 1), 0) : 0).toFixed(2), currency: str(body.currency) ?? "USD", financial_status: str(body.financial_status) ?? "pending", fulfillment_status: body.fulfillment_status ?? null });
768
+ if (resource === "customers") Object.assign(record2, { first_name: body.first_name ?? null, last_name: body.last_name ?? null, email: body.email ?? null, phone: body.phone ?? null, note: body.note ?? null, tags: body.tags ?? "", state: "enabled", verified_email: true, accepts_marketing: false });
769
+ rowsIn2.push(record2);
770
+ return created(collection, { [wrap]: enriched(record2) }, record2);
771
+ }
772
+ const record = rowsIn2.find((r) => String(r.id) === id);
773
+ if (!record) return notFoundShopify();
774
+ if (method === "GET") return ok(collection, { [wrap]: enriched(record) });
775
+ if (method === "PUT") {
776
+ if (Object.keys(params).some((k) => k !== wrap) || !isObject(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
777
+ const body = params[wrap];
778
+ const allowed = { products: ["title", "body_html", "vendor", "product_type", "status", "tags"], orders: ["email", "phone", "note", "financial_status", "fulfillment_status"], customers: ["first_name", "last_name", "email", "phone", "note", "tags"] }[resource];
779
+ if (Object.keys(body).some((k) => !allowed.includes(k))) return void 0;
780
+ for (const [k, v] of Object.entries(body)) record[k] = v;
781
+ if (resource === "products" && body.title !== void 0) record.handle = shopifySlug(String(body.title));
782
+ record.updated_at = iso();
783
+ return write(200, collection, { [wrap]: enriched(record) }, record);
784
+ }
785
+ return void 0;
786
+ }
787
+ function datadogOperation(method, path, params, _headers, data, sequence) {
788
+ const monitorMatch = /^\/api\/v1\/monitors?\/?(\d+)?(?:\/(mute))?$/.exec(path);
789
+ if (monitorMatch) {
790
+ const [, id, mute] = monitorMatch;
791
+ if (!id) {
792
+ if (method === "GET") {
793
+ if (Object.keys(params).some((k) => k !== "name")) return void 0;
794
+ const filtered = params.name === void 0 ? rows(data, "/monitors") : rows(data, "/monitors").filter((m) => typeof params.name === "string" && String(m.name).includes(params.name));
795
+ return ok("/monitors", filtered.map((row) => structuredClone(row)));
796
+ }
797
+ if (method !== "POST") return void 0;
798
+ if (Object.keys(params).some((k) => !["name", "type", "query", "message", "tags", "options", "priority"].includes(k))) return void 0;
799
+ if (typeof params.name !== "string" || !params.name || typeof params.type !== "string" || !params.type || typeof params.query !== "string" || !params.query) return badRequest("/monitors", { errors: ["The value provided for parameter 'name', 'type' or 'query' is invalid"] });
800
+ const monitor2 = { id: sequence, name: params.name, type: params.type, query: params.query, message: str(params.message) ?? "", tags: Array.isArray(params.tags) ? structuredClone(params.tags) : [], options: isObject(params.options) ? structuredClone(params.options) : {}, priority: params.priority === void 0 ? null : params.priority, overall_state: "OK", creator: { name: "agenttwin@example.test", handle: "agenttwin@example.test" }, created: iso(), modified: iso() };
801
+ rows(data, "/monitors").push(monitor2);
802
+ return { status: 200, body: structuredClone(monitor2), collection: "/monitors", record: structuredClone(monitor2), operation: "write" };
803
+ }
804
+ const monitor = rows(data, "/monitors").find((m) => String(m.id) === id);
805
+ if (!monitor) return notFound("/monitors", { errors: ["Monitor not found"] });
806
+ if (method === "GET" && !mute) return ok("/monitors", structuredClone(monitor));
807
+ if (method === "POST" && mute === "mute") {
808
+ if (Object.keys(params).some((k) => !["scope", "end"].includes(k))) return void 0;
809
+ const options = isObject(monitor.options) ? monitor.options : {};
810
+ monitor.options = { ...options, muted: true };
811
+ monitor.modified = iso();
812
+ return write(200, "/monitors", structuredClone(monitor), monitor);
813
+ }
814
+ return void 0;
815
+ }
816
+ if (path === "/api/v1/events") {
817
+ if (method === "POST") {
818
+ if (Object.keys(params).some((k) => !["title", "text", "tags", "priority", "alert_type", "source"].includes(k))) return void 0;
819
+ 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"] });
820
+ 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" };
821
+ rows(data, "/events").push(event);
822
+ return { status: 200, body: { status: "ok", event: structuredClone(event) }, collection: "/events", record: structuredClone(event), operation: "write" };
823
+ }
824
+ if (method === "GET") {
825
+ if (Object.keys(params).some((k) => !["start", "end", "priority", "tags", "sources"].includes(k))) return void 0;
826
+ if (params.start === void 0 || params.end === void 0) return badRequest("/events", { errors: ["start and end parameters are required"] });
827
+ if (!Number.isInteger(Number(params.start)) || !Number.isInteger(Number(params.end))) return badRequest("/events", { errors: ["start and end parameters must be integers"] });
828
+ let filtered = rows(data, "/events").filter((e) => Number(e.date_happened) >= Number(params.start) && Number(e.date_happened) <= Number(params.end));
829
+ if (params.priority !== void 0) filtered = filtered.filter((e) => e.priority === params.priority);
830
+ if (params.tags !== void 0) {
831
+ if (typeof params.tags !== "string") return void 0;
832
+ const tags = params.tags.split(",").filter(Boolean);
833
+ filtered = filtered.filter((e) => tags.every((tag) => Array.isArray(e.tags) && e.tags.includes(tag)));
834
+ }
835
+ return ok("/events", { events: filtered.slice(0, 100).map((row) => structuredClone(row)) });
836
+ }
837
+ return void 0;
838
+ }
839
+ if (path === "/api/v1/query") {
840
+ if (method !== "GET") return void 0;
841
+ if (Object.keys(params).some((k) => !["from", "to", "query"].includes(k))) return void 0;
842
+ if (params.from === void 0 || params.to === void 0 || typeof params.query !== "string" || !params.query) return badRequest("/api/v1/query", { errors: ["from, to and query parameters are required"] });
843
+ if (!Number.isInteger(Number(params.from)) || !Number.isInteger(Number(params.to))) return badRequest("/api/v1/query", { errors: ["from and to must be epoch seconds"] });
844
+ const from = Number(params.from), to = Number(params.to);
845
+ if (to <= from) return badRequest("/api/v1/query", { errors: ["to must be after from"] });
846
+ const parsed = /^(?:avg|min|max|sum):([a-zA-Z0-9_.]+)\{[^}]*\}$/.exec(params.query);
847
+ if (!parsed) return badRequest("/api/v1/query", { errors: ["query must look like avg:metric.name{scope}"] });
848
+ const metric = rows(data, "/metrics").find((m) => m.metric === parsed[1]);
849
+ const pointlist = metric ? metric.points.filter(([ts]) => ts >= from && ts <= to) : [];
850
+ return ok("/metrics", { status: "ok", from_date: from * 1e3, to_date: to * 1e3, query: params.query, series: [{ metric: parsed[1], display_name: parsed[1].split(".").pop(), unit: null, pointlist: pointlist.map(([ts, value]) => [ts * 1e3, value]), scope: null, expression: params.query }] });
851
+ }
852
+ return void 0;
853
+ }
854
+ var googleError = (collection, status, message) => ({ status, body: { error: { code: status, message, status: status === 404 ? "NOT_FOUND" : "INVALID_ARGUMENT" } }, collection });
855
+ var rowsIn = (data, collection) => data[collection];
856
+ function gmailOperation(method, path, params, _headers, data, sequence) {
857
+ const MESSAGES = "/gmail/v1/users/me/messages", LABELS = "/gmail/v1/users/me/labels";
858
+ const fail = (status, message) => googleError(MESSAGES, status, message);
859
+ if (path === `${MESSAGES}/send`) {
860
+ if (method !== "POST") return void 0;
861
+ if (Object.keys(params).some((k) => !["raw", "to", "subject", "text", "threadId"].includes(k))) return void 0;
862
+ const text = str(params.text), raw = str(params.raw);
863
+ if (!text && !raw) return fail(400, "Message body is required: provide `text` or a `raw` MIME string.");
864
+ if (params.text !== void 0 && text === "") return fail(400, "Message text must not be empty.");
865
+ if (params.to !== void 0 && str(params.to) === void 0) return fail(400, "to must be a string.");
866
+ if (params.subject !== void 0 && str(params.subject) === void 0) return fail(400, "subject must be a string.");
867
+ if (params.threadId !== void 0 && str(params.threadId) === void 0) return fail(400, "threadId must be a string.");
868
+ const body = text ?? raw ?? "";
869
+ 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: [{ name: "To", value: str(params.to) ?? "" }, { name: "Subject", value: str(params.subject) ?? "" }], body: { data: body } }, sizeEstimate: body.length, internalDate: "1700000000000", historyId: String(17e8 + sequence) };
870
+ rowsIn(data, MESSAGES).push(message);
871
+ return write(200, MESSAGES, structuredClone(message), message);
872
+ }
873
+ if (path === MESSAGES) {
874
+ if (method !== "GET") return void 0;
875
+ if (Object.keys(params).some((k) => k !== "q")) return void 0;
876
+ let filtered = rowsIn(data, MESSAGES);
877
+ if (params.q !== void 0) {
878
+ if (typeof params.q !== "string") return fail(400, "q must be a string.");
879
+ filtered = filtered.filter((m) => typeof m.snippet === "string" && m.snippet.includes(params.q));
880
+ }
881
+ return ok(MESSAGES, { messages: filtered.map((m) => ({ id: m.id, threadId: m.threadId })), resultSizeEstimate: filtered.length });
882
+ }
883
+ const messageMatch = /^\/gmail\/v1\/users\/me\/messages\/([^/]+)$/.exec(path);
884
+ if (messageMatch) {
885
+ if (method !== "GET") return void 0;
886
+ const message = rowsIn(data, MESSAGES).find((m) => m.id === messageMatch[1]);
887
+ if (!message) return fail(404, `Message not found: ${messageMatch[1]}`);
888
+ return ok(MESSAGES, structuredClone(message));
889
+ }
890
+ if (path === LABELS) {
891
+ if (method !== "GET") return void 0;
892
+ if (Object.keys(params).length) return void 0;
893
+ return ok(LABELS, { labels: rowsIn(data, LABELS).map((row) => structuredClone(row)) });
894
+ }
895
+ return void 0;
896
+ }
897
+ function googleCalendarOperation(method, path, params, _headers, data, sequence) {
898
+ const CALENDAR_LIST = "/calendar/v3/users/me/calendarList", EVENTS = "/calendar/v3/calendars/primary/events";
899
+ const fail = (status, message) => googleError(EVENTS, status, message);
900
+ if (path === CALENDAR_LIST) {
901
+ if (method !== "GET") return void 0;
902
+ if (Object.keys(params).length) return void 0;
903
+ return ok(CALENDAR_LIST, { items: rowsIn(data, CALENDAR_LIST).map((row) => structuredClone(row)) });
904
+ }
905
+ const match = /^\/calendar\/v3\/calendars\/([^/]+)\/events(?:\/([^/]+))?$/.exec(path);
906
+ if (!match) return void 0;
907
+ const [, calendar, eventId] = match;
908
+ if (calendar !== "primary") return googleError(EVENTS, 404, `Not Found: no twin state for calendar ${calendar}`);
909
+ const scalar = (value) => ["summary", "description", "location"].filter((k) => params[k] !== void 0 && str(params[k]) === void 0);
910
+ const meetingField = (value) => value !== void 0 && !Array.isArray(value) && !isObject(value);
911
+ if (!eventId) {
912
+ if (method === "GET") {
913
+ const allowed = ["timeMin", "timeMax", "maxResults", "pageToken", "singleEvents", "orderBy", "conferenceDataVersion"];
914
+ if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
915
+ if (params.singleEvents !== void 0 && !["true", "false", true, false].includes(params.singleEvents)) return fail(400, "Invalid singleEvents.");
916
+ if (params.orderBy !== void 0 && params.orderBy !== "startTime") return void 0;
917
+ if (params.orderBy === "startTime" && String(params.singleEvents) !== "true") return fail(400, "startTime ordering requires singleEvents=true.");
918
+ if (params.conferenceDataVersion !== void 0 && String(params.conferenceDataVersion) !== "1") return void 0;
919
+ const timestamp = (v) => {
920
+ if (typeof v !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(v)) return NaN;
921
+ return Math.floor(Date.parse(v) / 1e3) * 1e3;
922
+ };
923
+ const lower = params.timeMin === void 0 ? -Infinity : timestamp(params.timeMin);
924
+ const upper = params.timeMax === void 0 ? Infinity : timestamp(params.timeMax);
925
+ if (Number.isNaN(lower) || Number.isNaN(upper) || lower >= upper) return fail(400, "Invalid time range.");
926
+ const limit = params.maxResults === void 0 ? 250 : boundedInt(params.maxResults, 1, 2500);
927
+ if (limit === null) return fail(400, "Invalid maxResults.");
928
+ let events = rowsIn(data, EVENTS).filter((row) => row.status !== "cancelled");
929
+ if (events.some((row) => row.recurrence || row.recurringEventId || row.conferenceData)) return void 0;
930
+ const timed = params.timeMin !== void 0 || params.timeMax !== void 0 || params.orderBy !== void 0;
931
+ 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;
932
+ if (timed) events = events.filter((row) => timestamp(row.end.dateTime) > lower && timestamp(row.start.dateTime) < upper);
933
+ if (params.orderBy === "startTime") events = [...events].sort((a, b) => timestamp(a.start.dateTime) - timestamp(b.start.dateTime));
934
+ const query = Object.fromEntries(Object.entries(params).filter(([key]) => key !== "pageToken").sort(([a], [b]) => a.localeCompare(b)));
935
+ const fingerprint = sha(JSON.stringify({ query, events })).slice(0, 20);
936
+ let offset = 0;
937
+ if (params.pageToken !== void 0) {
938
+ if (typeof params.pageToken !== "string") return fail(400, "Invalid page token.");
939
+ const token = /^at_([a-f0-9]{20})_(\d+)$/.exec(params.pageToken);
940
+ if (!token || token[1] !== fingerprint || !Number.isSafeInteger(Number(token[2])) || Number(token[2]) < 1 || Number(token[2]) >= events.length) return fail(400, "Invalid or stale page token.");
941
+ offset = Number(token[2]);
942
+ }
943
+ const next = offset + (limit ?? 250);
944
+ return ok(EVENTS, { items: structuredClone(events.slice(offset, next)), ...next < events.length ? { nextPageToken: `at_${fingerprint}_${next}` } : {} });
945
+ }
946
+ if (method !== "POST") return void 0;
947
+ if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
948
+ if (typeof params.summary !== "string" || !params.summary) return fail(400, "Event summary is required.");
949
+ if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
950
+ const scalarBad = scalar(params);
951
+ if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
952
+ const event2 = { id: detUuid(`gcal:${sequence}`), summary: params.summary, description: str(params.description) ?? null, location: str(params.location) ?? null, start: isObject(params.start) ? structuredClone(params.start) : { dateTime: iso() }, end: isObject(params.end) ? structuredClone(params.end) : { dateTime: iso() }, attendees: Array.isArray(params.attendees) ? structuredClone(params.attendees) : [], status: str(params.status) ?? "confirmed", htmlLink: null, creator: { email: "agenttwin@example.test", self: true }, created: iso(), updated: iso() };
953
+ rowsIn(data, EVENTS).push(event2);
954
+ return write(200, EVENTS, structuredClone(event2), event2);
955
+ }
956
+ const event = rowsIn(data, EVENTS).find((e) => e.id === eventId);
957
+ if (!event) return fail(404, `Not Found: event ${eventId}`);
958
+ if (method === "GET") return ok(EVENTS, structuredClone(event));
959
+ if (method === "PATCH") {
960
+ if (Object.keys(params).some((k) => !["summary", "description", "location", "start", "end", "attendees", "status"].includes(k))) return void 0;
961
+ if (["start", "end", "attendees"].some((k) => meetingField(params[k]))) return fail(400, "start, end and attendees must be objects.");
962
+ const scalarBad = scalar(params);
963
+ if (scalarBad.length) return fail(400, `${scalarBad.join(", ")} must be strings.`);
964
+ for (const [k, v] of Object.entries(params)) if (["summary", "description", "location", "start", "end", "attendees", "status"].includes(k)) event[k] = structuredClone(v);
965
+ event.updated = iso();
966
+ return write(200, EVENTS, structuredClone(event), event);
967
+ }
968
+ if (method === "DELETE") {
969
+ rowsIn(data, EVENTS).splice(rowsIn(data, EVENTS).findIndex((e) => e.id === eventId), 1);
970
+ return write(200, EVENTS, {}, structuredClone(event));
971
+ }
972
+ return void 0;
973
+ }
974
+ function gitlabOperation(method, path, params, _headers, data, sequence) {
975
+ const match = /^\/api\/v4\/(projects|issues|merge_requests)(?:\/(\d+))?(?:\/(notes)(?:\/(\d+))?)?$/.exec(path);
976
+ if (!match) return void 0;
977
+ const [, resource, id, sub] = match;
978
+ const collection = sub === "notes" ? "/api/v4/merge_requests/notes" : `/api/v4/${resource}`;
979
+ const records = rowsIn(data, collection);
980
+ const author = { id: 42, username: "agenttwin-test", name: "AgentTwin Test" };
981
+ if (sub === "notes") {
982
+ if (!id || !resource) return void 0;
983
+ const mr = rowsIn(data, "/api/v4/merge_requests").find((r) => String(r.iid) === id || String(r.id) === id);
984
+ if (!mr) return notFound(collection, { message: "404 Merge Request Not Found" });
985
+ if (method === "GET") return ok(collection, records.filter((n) => n.noteable_iid === mr.iid).map((row) => structuredClone(row)));
986
+ if (method !== "POST") return void 0;
987
+ if (Object.keys(params).some((k) => k !== "body")) return void 0;
988
+ if (typeof params.body !== "string" || !params.body) return badRequest(collection, { message: "body is required" });
989
+ const note = { id: uniqueId(records, 101 + sequence), body: params.body, author, created_at: iso(), updated_at: iso(), noteable_id: mr.id, noteable_iid: mr.iid, noteable_type: "MergeRequest" };
990
+ records.push(note);
991
+ return created(collection, structuredClone(note), note);
992
+ }
993
+ if (method === "GET" && !id) {
994
+ if (Object.keys(params).length) return void 0;
995
+ return ok(collection, records.map((row) => structuredClone(row)));
996
+ }
997
+ if (method === "POST" && !id) {
998
+ if (resource === "projects") {
999
+ if (Object.keys(params).some((k) => !["name", "description", "visibility"].includes(k))) return void 0;
1000
+ if (typeof params.name !== "string" || !params.name) return badRequest(collection, { message: "name is missing" });
1001
+ if (params.description !== void 0 && str(params.description) === void 0) return void 0;
1002
+ const project = { id: uniqueId(records, 1 + sequence), name: params.name, description: str(params.description) ?? "", visibility: str(params.visibility) ?? "private", creator_id: 42, created_at: iso() };
1003
+ records.push(project);
1004
+ return created(collection, structuredClone(project), project);
1005
+ }
1006
+ if (resource === "issues") {
1007
+ if (Object.keys(params).some((k) => !["title", "description", "project_id", "labels", "assignee_ids"].includes(k))) return void 0;
1008
+ const projectId2 = Number(params.project_id);
1009
+ if (typeof params.title !== "string" || !params.title || !Number.isInteger(projectId2)) return badRequest(collection, { message: "title and project_id are required" });
1010
+ if (!rowsIn(data, "/api/v4/projects").some((p) => String(p.id) === String(projectId2))) return notFound(collection, { message: "404 Project Not Found" });
1011
+ if (params.labels !== void 0 && (!Array.isArray(params.labels) || !params.labels.every((l) => typeof l === "string"))) return badRequest(collection, { message: "labels must be an array of strings" });
1012
+ const inProject2 = records.filter((r) => r.project_id === projectId2);
1013
+ const issue = { id: uniqueId(records, 101 + sequence), iid: inProject2.reduce((max, r) => Math.max(max, Number(r.iid) || 0), 0) + 1, project_id: projectId2, title: params.title, description: str(params.description) ?? null, state: "opened", labels: Array.isArray(params.labels) ? structuredClone(params.labels) : [], author, web_url: null, created_at: iso(), updated_at: iso() };
1014
+ records.push(issue);
1015
+ return created(collection, structuredClone(issue), issue);
1016
+ }
1017
+ if (Object.keys(params).some((k) => !["project_id", "source_branch", "target_branch", "title", "description"].includes(k))) return void 0;
1018
+ const projectId = Number(params.project_id);
1019
+ if (typeof params.title !== "string" || !params.title || !Number.isInteger(projectId) || typeof params.source_branch !== "string" || !params.source_branch || typeof params.target_branch !== "string" || !params.target_branch) return badRequest(collection, { message: "title, project_id, source_branch and target_branch are required" });
1020
+ if (!rowsIn(data, "/api/v4/projects").some((p) => String(p.id) === String(projectId))) return notFound(collection, { message: "404 Project Not Found" });
1021
+ const inProject = records.filter((r) => r.project_id === projectId);
1022
+ const mergeRequest = { id: uniqueId(records, 201 + sequence), iid: inProject.reduce((max, r) => Math.max(max, Number(r.iid) || 0), 0) + 1, project_id: projectId, source_branch: params.source_branch, target_branch: params.target_branch, title: params.title, description: str(params.description) ?? null, state: "opened", author, web_url: null, created_at: iso(), updated_at: iso() };
1023
+ records.push(mergeRequest);
1024
+ return created(collection, structuredClone(mergeRequest), mergeRequest);
1025
+ }
1026
+ const primary = id ? rowsIn(data, `/api/v4/${resource}`).find((r) => String(r.id) === id || String(r.iid) === id) : void 0;
1027
+ if (!primary) return id ? notFound(collection, { message: `404 ${resource === "merge_requests" ? "Merge Request" : resource.slice(0, -1)} Not Found` }) : void 0;
1028
+ if (method === "GET") return ok(collection, structuredClone(primary));
1029
+ return void 0;
1030
+ }
1031
+ var JIRA_TRANSITIONS = { "11": "To Do", "21": "In Progress", "31": "Done" };
1032
+ function jiraOperation(method, path, params, _headers, data, sequence) {
1033
+ const ISSUE = "/rest/api/3/issue", PROJECT = "/rest/api/3/project";
1034
+ const jiraFail = (collection, errorMessages, errors) => ({ status: 400, body: { errorMessages, errors }, collection });
1035
+ if (path === "/rest/api/3/search") {
1036
+ if (method !== "POST") return void 0;
1037
+ if (Object.keys(params).some((k) => !["jql", "maxResults", "fields", "startAt"].includes(k))) return void 0;
1038
+ const jql = str(params.jql);
1039
+ if (!jql) return jiraFail("/rest/api/3/search", ["The 'jql' parameter is required."], {});
1040
+ const parsed = /^\s*project\s*=\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_-]+))\s*$/.exec(jql);
1041
+ if (params.fields !== void 0 && (!Array.isArray(params.fields) || !params.fields.every((f) => typeof f === "string"))) return void 0;
1042
+ if (!parsed) return void 0;
1043
+ const project = parsed[1] ?? parsed[2] ?? parsed[3];
1044
+ const maxResults = boundedInt(params.maxResults, 1, 100);
1045
+ if (params.maxResults !== void 0 && maxResults === null) return jiraFail("/rest/api/3/search", ["'maxResults' must be an integer between 1 and 100."], {});
1046
+ const issueRows = rowsIn(data, ISSUE).filter((r) => r.projectKey === project);
1047
+ return ok(ISSUE, { expand: [], startAt: 0, maxResults: maxResults ?? 50, total: issueRows.length, issues: issueRows.slice(0, maxResults ?? 50).map((row) => structuredClone(row)) });
1048
+ }
1049
+ if (path === ISSUE) {
1050
+ if (method !== "POST") return void 0;
1051
+ if (Object.keys(params).some((k) => k !== "fields") || !isObject(params.fields)) return jiraFail(ISSUE, [], { fields: "fields is required" });
1052
+ const fields = params.fields;
1053
+ if (Object.keys(fields).some((k) => !["project", "issuetype", "summary", "description", "priority", "labels", "assignee"].includes(k))) return void 0;
1054
+ const projectKey = isObject(fields.project) ? str(fields.project.key) : void 0;
1055
+ const issuetype = isObject(fields.issuetype) ? str(fields.issuetype.name) : void 0;
1056
+ if (!projectKey || !issuetype || typeof fields.summary !== "string" || !fields.summary) return jiraFail(ISSUE, [], { summary: projectKey && issuetype ? "Summary is required." : `${!projectKey ? "project key" : "issuetype name"} and summary are required.` });
1057
+ if (!rowsIn(data, PROJECT).some((p) => p.key === projectKey)) return jiraFail(ISSUE, [`Project '${projectKey}' does not exist.`], {});
1058
+ const issueRows = rowsIn(data, ISSUE);
1059
+ const number = issueRows.filter((r) => r.projectKey === projectKey).reduce((max, r) => Math.max(max, Number(r.number) || 0), 0) + 1;
1060
+ const issue = { id: uniqueId(issueRows, 1e4 + sequence), key: `${projectKey}-${number}`, projectKey, number, fields: { project: structuredClone(fields.project), issuetype: structuredClone(fields.issuetype), summary: fields.summary, description: fields.description ?? null, labels: Array.isArray(fields.labels) ? structuredClone(fields.labels) : [], status: { name: "Open" }, assignee: null, created: iso() } };
1061
+ issueRows.push(issue);
1062
+ return created(ISSUE, { id: issue.id, key: issue.key, self: null }, issue);
1063
+ }
1064
+ const issueMatch = /^\/rest\/api\/3\/issue\/([^/]+)(?:\/(comment|transitions))?$/.exec(path);
1065
+ if (issueMatch) {
1066
+ const issue = rowsIn(data, ISSUE).find((r) => r.key === issueMatch[1] || String(r.id) === issueMatch[1]);
1067
+ if (!issue) return notFound(ISSUE, { errorMessages: ["Issue does not exist or you do not have permission to see it."], errors: {} });
1068
+ if (method === "GET" && !issueMatch[2]) return ok(ISSUE, structuredClone(issue));
1069
+ if (method === "POST" && issueMatch[2] === "comment") {
1070
+ if (Object.keys(params).some((k) => k !== "body")) return void 0;
1071
+ if (typeof params.body !== "string" && !isObject(params.body)) return jiraFail(ISSUE, [], { body: "body is required" });
1072
+ if (isObject(params.body) && params.body.type !== "doc") return jiraFail(ISSUE, [], { body: "Comment bodies must be Atlassian Document Format objects with type 'doc', or plain strings." });
1073
+ const commentRows = rowsIn(data, "/rest/api/3/issue/comments");
1074
+ const comment = { id: uniqueId(commentRows, 101 + sequence), issueKey: issue.key, author: { accountId: "agenttwin-test-account", displayName: "AgentTwin Test" }, created: iso(), updated: iso(), body: structuredClone(params.body) };
1075
+ commentRows.push(comment);
1076
+ return created("/rest/api/3/issue/comments", structuredClone(comment), comment);
1077
+ }
1078
+ if (method === "POST" && issueMatch[2] === "transitions") {
1079
+ if (Object.keys(params).some((k) => !["transition", "fields"].includes(k)) || !isObject(params.transition) || Object.keys(params.transition).some((k) => k !== "id")) return void 0;
1080
+ const transitionId = str(params.transition.id);
1081
+ if (!transitionId) return void 0;
1082
+ if (!JIRA_TRANSITIONS[transitionId]) return jiraFail(ISSUE, [], { transition: "Transition id must be one of 11, 21, 31" });
1083
+ issue.fields.status = { name: JIRA_TRANSITIONS[transitionId] };
1084
+ return write(200, ISSUE, {}, structuredClone(issue));
1085
+ }
1086
+ return void 0;
1087
+ }
1088
+ if (path === PROJECT) {
1089
+ if (method !== "GET") return void 0;
1090
+ if (Object.keys(params).length) return void 0;
1091
+ return ok(PROJECT, rowsIn(data, PROJECT).map((row) => structuredClone(row)));
1092
+ }
1093
+ const projectMatch = /^\/rest\/api\/3\/project\/([^/]+)$/.exec(path);
1094
+ if (projectMatch) {
1095
+ if (method !== "GET") return void 0;
1096
+ const project = rowsIn(data, PROJECT).find((p) => p.key === projectMatch[1] || String(p.id) === projectMatch[1]);
1097
+ if (!project) return notFound(PROJECT, { errorMessages: [`No project could be found with key '${projectMatch[1]}'`], errors: {} });
1098
+ return ok(PROJECT, structuredClone(project));
1099
+ }
1100
+ return void 0;
1101
+ }
1102
+ var discordError = (collection, code, message) => ({ status: code === 10003 || code === 10004 ? 404 : 400, body: { message, code }, collection });
1103
+ function discordOperation(method, path, params, _headers, data, sequence) {
1104
+ const CHANNELS = "/api/channels", MESSAGES = "/api/channels/messages", GUILDS = "/api/guilds", MEMBERS = "/api/guilds/members";
1105
+ const channelMatch = /^\/api\/channels\/([^/]+)(?:\/(messages)(?:\/([^/]+))?)?$/.exec(path);
1106
+ if (channelMatch) {
1107
+ const [, channelId, messages, messageId] = channelMatch;
1108
+ const channel = rowsIn(data, CHANNELS).find((c) => c.id === channelId);
1109
+ if (!channel) return discordError(MESSAGES, 10003, "Unknown Channel");
1110
+ if (!messages) {
1111
+ if (method !== "GET") return void 0;
1112
+ return ok(CHANNELS, structuredClone(channel));
1113
+ }
1114
+ if (messageId || method !== "GET" && method !== "POST") return void 0;
1115
+ if (method === "GET") {
1116
+ if (Object.keys(params).length) return void 0;
1117
+ return ok(MESSAGES, rowsIn(data, MESSAGES).filter((m) => m.channel_id === channelId).map((row) => structuredClone(row)).reverse());
1118
+ }
1119
+ if (Object.keys(params).some((k) => !["content", "tts"].includes(k))) return void 0;
1120
+ if (typeof params.content !== "string" || !params.content) return discordError(MESSAGES, 50035, "Invalid Form Body: content cannot be empty.");
1121
+ if (params.tts !== void 0 && typeof params.tts !== "boolean") return void 0;
1122
+ const records = rowsIn(data, MESSAGES);
1123
+ const message = { id: String(uniqueId(records, 11e14 + sequence)), channel_id: channelId, content: params.content, author: { id: "discord_at_agenttwin", username: "agenttwin-test", avatar: null }, timestamp: iso(), tts: params.tts === true, embeds: [], pinned: false, type: 0 };
1124
+ records.push(message);
1125
+ return created(MESSAGES, structuredClone(message), message);
1126
+ }
1127
+ const guildMatch = /^\/api\/guilds\/([^/]+)(?:\/(members))?$/.exec(path);
1128
+ if (guildMatch) {
1129
+ const [, guildId, members] = guildMatch;
1130
+ const guild = rowsIn(data, GUILDS).find((g) => g.id === guildId);
1131
+ if (!guild) return discordError(MEMBERS, 10004, "Unknown Guild");
1132
+ if (!members) {
1133
+ if (method !== "GET") return void 0;
1134
+ return ok(GUILDS, structuredClone(guild));
1135
+ }
1136
+ if (method !== "GET") return void 0;
1137
+ if (Object.keys(params).some((k) => k !== "limit")) return void 0;
1138
+ const limit = boundedInt(params.limit, 1, 1e3);
1139
+ if (params.limit !== void 0 && limit === null) return discordError(MEMBERS, 50035, "Invalid Form Body: limit must be between 1 and 1000.");
1140
+ return ok(MEMBERS, rowsIn(data, MEMBERS).filter((m) => m.guild_id === guildId).slice(0, limit ?? 1e3).map((row) => structuredClone(row)));
1141
+ }
1142
+ return void 0;
1143
+ }
1144
+ function twilioOperation(method, path, params, _headers, data, sequence) {
1145
+ const match = /^\/2010-04-01\/Accounts\/([^/]+)\/(Messages|Calls)(?:\.json)?$/.exec(path);
1146
+ if (!match) return void 0;
1147
+ const [, accountSid, resource] = match;
1148
+ const collection = `/2010-04-01/${resource}`;
1149
+ const records = rowsIn(data, collection);
1150
+ const fail = (status, code, message) => ({ status, body: { status, code, message, more_info: "" }, collection });
1151
+ const stamp = () => {
1152
+ const [date, time] = iso().split("T");
1153
+ return `${date} ${time.slice(0, 8)}`;
1154
+ };
1155
+ if (method === "POST") {
1156
+ const allowed = resource === "Messages" ? ["To", "From", "Body"] : ["To", "From", "Url"];
1157
+ if (!accountSid || Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
1158
+ const missing = allowed.filter((k) => typeof params[k] !== "string" || !params[k]);
1159
+ if (missing.length) return fail(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
1160
+ const prefix = resource === "Messages" ? "SM" : "CA";
1161
+ const sid = `${prefix}${sha(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
1162
+ const record = resource === "Messages" ? { account_sid: accountSid, api_version: "2010-04-01", sid, messaging_service_sid: null, status: "queued", to: params.To, from: params.From, body: params.Body, num_segments: "1", num_media: "0", direction: "outbound-api", error_code: null, error_message: null, date_created: stamp(), date_updated: stamp(), date_sent: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Messages/${sid}.json` } : { account_sid: accountSid, api_version: "2010-04-01", sid, status: "queued", to: params.To, from: params.From, url: params.Url, direction: "outbound-api", error_code: null, error_message: null, date_created: stamp(), date_updated: stamp(), start_time: null, duration: null, price: null, price_unit: null, uri: `/2010-04-01/Accounts/${accountSid}/Calls/${sid}.json` };
1163
+ records.push(record);
1164
+ return created(collection, structuredClone(record), record);
1165
+ }
1166
+ if (method === "GET") {
1167
+ if (Object.keys(params).some((k) => !["To", "From"].includes(k))) return void 0;
1168
+ let filtered = records;
1169
+ if (params.To !== void 0) {
1170
+ if (typeof params.To !== "string") return fail(400, "20001", "To must be a string");
1171
+ filtered = filtered.filter((r) => r.to === params.To);
1172
+ }
1173
+ if (params.From !== void 0) {
1174
+ if (typeof params.From !== "string") return fail(400, "20001", "From must be a string");
1175
+ filtered = filtered.filter((r) => r.from === params.From);
1176
+ }
1177
+ return ok(collection, { page: 0, page_size: filtered.length, start: 0, end: Math.max(filtered.length - 1, 0), next_page_uri: null, [resource.toLowerCase()]: filtered.map((row) => structuredClone(row)) });
1178
+ }
1179
+ return void 0;
1180
+ }
1181
+ var ZENDESK_STATUSES = ["new", "open", "pending", "solved", "closed"];
1182
+ function zendeskOperation(method, path, params, _headers, data, sequence) {
1183
+ const match = /^\/api\/v2\/(tickets|users|organizations)(?:\/(\d+))?\.json$/.exec(path);
1184
+ if (!match) return void 0;
1185
+ const [, resource, id] = match;
1186
+ const collection = `/api/v2/${resource}`;
1187
+ const records = rowsIn(data, collection);
1188
+ const envelope = (items) => ({ [resource]: items, next_page: null, previous_page: null, count: items.length });
1189
+ if (method === "POST" && !id) {
1190
+ if (resource !== "tickets") return void 0;
1191
+ if (Object.keys(params).some((k) => k !== "ticket") || !isObject(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
1192
+ const ticketParams = params.ticket;
1193
+ if (Object.keys(ticketParams).some((k) => !["subject", "comment", "requester", "status", "priority", "tags", "description", "type"].includes(k))) return void 0;
1194
+ if (typeof ticketParams.subject !== "string" || !ticketParams.subject) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: Subject can't be blank" });
1195
+ if (!isObject(ticketParams.comment) || Object.keys(ticketParams.comment).some((k) => k !== "body") || typeof ticketParams.comment.body !== "string" || !ticketParams.comment.body) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: comment body is required" });
1196
+ if (ticketParams.status !== void 0 && !ZENDESK_STATUSES.includes(String(ticketParams.status))) return badRequest(collection, { error: "InvalidStatus", description: "Status must be new, open, pending, solved or closed" });
1197
+ const ticket = { id: uniqueId(records, 1 + sequence), subject: ticketParams.subject, description: str(ticketParams.description) ?? ticketParams.comment.body, status: str(ticketParams.status) ?? "new", priority: str(ticketParams.priority) ?? "normal", tags: Array.isArray(ticketParams.tags) ? structuredClone(ticketParams.tags) : [], requester: isObject(ticketParams.requester) ? structuredClone(ticketParams.requester) : null, created_at: iso(), updated_at: iso() };
1198
+ records.push(ticket);
1199
+ return created(collection, { ticket: structuredClone(ticket), audit: null }, ticket);
1200
+ }
1201
+ if (method === "GET" && !id) {
1202
+ if (Object.keys(params).length) return void 0;
1203
+ return ok(collection, envelope(records));
1204
+ }
1205
+ if (method === "GET" && id && resource === "tickets") {
1206
+ const ticket = records.find((r) => String(r.id) === id);
1207
+ if (!ticket) return notFound(collection, { error: "RecordNotFound", description: `Not found: ${id}` });
1208
+ return ok(collection, { ticket: structuredClone(ticket) });
1209
+ }
1210
+ if (method === "PUT" && id && resource === "tickets") {
1211
+ const ticket = typeof id === "string" ? records.find((r) => String(r.id) === id) : void 0;
1212
+ if (!ticket) return notFound(collection, { error: "RecordNotFound", description: `Not found: ${id}` });
1213
+ if (Object.keys(params).some((k) => k !== "ticket") || !isObject(params.ticket)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: ticket is required" });
1214
+ const ticketParams = params.ticket;
1215
+ if (Object.keys(ticketParams).some((k) => !["subject", "status", "priority", "tags"].includes(k))) return void 0;
1216
+ if (ticketParams.status !== void 0 && !ZENDESK_STATUSES.includes(String(ticketParams.status))) return badRequest(collection, { error: "InvalidStatus", description: "Status must be new, open, pending, solved or closed" });
1217
+ if (ticketParams.subject !== void 0 && (typeof ticketParams.subject !== "string" || !ticketParams.subject)) return badRequest(collection, { error: "RecordInvalid", description: "Ticket is not valid: Subject can't be blank" });
1218
+ for (const [k, v] of Object.entries(ticketParams)) if (["subject", "status", "priority", "tags"].includes(k)) ticket[k] = structuredClone(v);
1219
+ ticket.updated_at = iso();
1220
+ return write(200, collection, { ticket: structuredClone(ticket), audit: null }, ticket);
1221
+ }
1222
+ return void 0;
1223
+ }
1224
+ var UNSUPPORTED_BODIES = {
1225
+ github: { message: "Outside the verified AgentTwin GitHub twin subset", documentation_url: "https://docs.github.com/rest", forwardedToProduction: false },
1226
+ linear: { errors: [{ message: "Outside the verified AgentTwin Linear twin subset" }], data: null, forwardedToProduction: false },
1227
+ notion: { object: "error", status: 501, code: "unsupported_operation", message: "Outside the verified AgentTwin Notion twin subset", forwardedToProduction: false },
1228
+ hubspot: { status: "error", category: "UNSUPPORTED_OPERATION", message: "Outside the verified AgentTwin HubSpot twin subset", forwardedToProduction: false },
1229
+ shopify: { errors: "Outside the verified AgentTwin Shopify twin subset", forwardedToProduction: false },
1230
+ datadog: { errors: ["Outside the verified AgentTwin Datadog twin subset"], forwardedToProduction: false },
1231
+ gmail: { error: { code: 501, status: "UNIMPLEMENTED", message: "Outside the verified AgentTwin Gmail twin subset" }, forwardedToProduction: false },
1232
+ "google-calendar": { error: { code: 501, status: "UNIMPLEMENTED", message: "Outside the verified AgentTwin Google Calendar twin subset" }, forwardedToProduction: false },
1233
+ gitlab: { message: "Outside the verified AgentTwin GitLab twin subset", forwardedToProduction: false },
1234
+ jira: { errorMessages: ["Outside the verified AgentTwin Jira twin subset"], errors: {}, forwardedToProduction: false },
1235
+ discord: { message: "Outside the verified AgentTwin Discord twin subset", code: 50101, forwardedToProduction: false },
1236
+ twilio: { status: 501, code: "50101", message: "Outside the verified AgentTwin Twilio twin subset", more_info: "", forwardedToProduction: false },
1237
+ zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false }
1238
+ };
1239
+ var REST_ADAPTERS = {
1240
+ github: githubOperation,
1241
+ linear: linearOperation,
1242
+ notion: notionOperation,
1243
+ hubspot: hubspotOperation,
1244
+ shopify: shopifyOperation,
1245
+ datadog: datadogOperation,
1246
+ gmail: gmailOperation,
1247
+ "google-calendar": googleCalendarOperation,
1248
+ gitlab: gitlabOperation,
1249
+ jira: jiraOperation,
1250
+ discord: discordOperation,
1251
+ twilio: twilioOperation,
1252
+ zendesk: zendeskOperation
1253
+ };
1254
+ function restUnsupportedBody(adapter) {
1255
+ return UNSUPPORTED_BODIES[adapter];
1256
+ }
1257
+ var REST_ADAPTER_NAMES = Object.keys(REST_ADAPTERS);
1258
+
1259
+ // src/runtime/seed.ts
1260
+ import { createHash as createHash2, randomBytes } from "crypto";
1261
+ var SEED_PATTERN = /^[a-f0-9]{32}$/;
1262
+ var normalizeHex = (value) => value.trim().toLowerCase();
1263
+ function normalizeSeed(seed) {
1264
+ if (seed === void 0 || seed.trim() === "") return randomBytes(16).toString("hex");
1265
+ const text = normalizeHex(seed);
1266
+ if (!/^[a-f0-9]+$/.test(text) || text.length > 256) throw new Error(`Seed must be up to 256 hex characters or empty to generate; got ${seed.slice(0, 40)}`);
1267
+ if (text.length === 32) return text;
1268
+ return createHash2("sha256").update(text).digest("hex").slice(0, 32);
1269
+ }
1270
+ var SeedStream = class {
1271
+ constructor(seed, purpose) {
1272
+ this.seed = seed;
1273
+ this.purpose = purpose;
1274
+ if (!SEED_PATTERN.test(seed)) throw new Error(`Invalid seed for stream: ${seed}`);
1275
+ if (!purpose) throw new Error("Seed stream purpose must be nonempty");
1276
+ }
1277
+ seed;
1278
+ purpose;
1279
+ counter = 0;
1280
+ draw() {
1281
+ const value = createHash2("sha256").update(`agenttwin-stream|${this.seed}|${this.purpose}|${this.counter}`).digest("hex");
1282
+ this.counter++;
1283
+ return value;
1284
+ }
1285
+ /** Uniform float in [0, 1). */
1286
+ next() {
1287
+ return parseInt(this.draw().slice(0, 13), 16) / 2 ** 52;
1288
+ }
1289
+ /** Uniform integer in [0, max). */
1290
+ nextInt(max) {
1291
+ if (!Number.isInteger(max) || max < 1) throw new Error("nextInt needs a positive integer max");
1292
+ const limit = Math.floor(2 ** 32 / max) * max;
1293
+ let next;
1294
+ do {
1295
+ next = parseInt(this.draw().slice(0, 8), 16);
1296
+ } while (next >= limit);
1297
+ return next % max;
1298
+ }
1299
+ nextHex(bytes) {
1300
+ if (!Number.isInteger(bytes) || bytes < 1 || bytes > 64) throw new Error("nextHex needs 1\u201364 bytes");
1301
+ return this.draw().slice(0, bytes * 2);
1302
+ }
1303
+ };
1304
+ var FAULT_SCHEDULE_WINDOW = 32;
1305
+ function faultOrdinals(selection, seed) {
1306
+ const count = selection.type === "timeout-after-write" ? 1 : selection.count ?? 1;
1307
+ const stream = new SeedStream(seed, `fault:${selection.type}:${selection.service}:${selection.path}`);
1308
+ const all = Array.from({ length: FAULT_SCHEDULE_WINDOW }, (_, i) => i);
1309
+ for (let i = all.length - 1; i > 0; i--) {
1310
+ const j = stream.nextInt(i + 1);
1311
+ [all[i], all[j]] = [all[j], all[i]];
1312
+ }
1313
+ return all.slice(0, count).sort((a, b) => a - b);
1314
+ }
1315
+
1316
+ // src/runtime/http-world.ts
1317
+ var HttpWorld = class {
1318
+ constructor(spec, seed) {
1319
+ this.spec = spec;
1320
+ this.seed = normalizeSeed(seed);
1321
+ }
1322
+ spec;
1323
+ events = [];
1324
+ state = /* @__PURE__ */ Object.create(null);
1325
+ credentials = /* @__PURE__ */ Object.create(null);
1326
+ unsupported = [];
1327
+ /** The run seed that governed every seeded twin-side decision in this world instance. */
1328
+ seed;
1329
+ servers = [];
1330
+ timers = /* @__PURE__ */ new Set();
1331
+ fired = false;
1332
+ faultActions = 0;
1333
+ candidateCounts = /* @__PURE__ */ new Map();
1334
+ epoch = 0;
1335
+ replayKeys = /* @__PURE__ */ new Map();
1336
+ sourceContext = new AsyncLocalStorage();
1337
+ record(service, operation, path, detail, record) {
1338
+ if (this.events.length >= 5e4) return;
1339
+ const source = this.sourceContext.getStore();
1340
+ this.events.push({ sequence: this.events.length + 1, service, operation, path, detail, ...record ? { record: structuredClone(record) } : {}, ...source ? { source } : {} });
1341
+ }
1342
+ rejectUnsupported(service, method, path, detail) {
1343
+ this.unsupported.push(`${service}: ${method} ${path}: ${detail}`);
1344
+ this.record(service, "unsupported", path, detail);
1345
+ }
1346
+ /** Seeded fault scheduling: the k-th matched request of the fault's scope is faulted iff the seeded draw picked ordinal k. */
1347
+ candidateIndex(key) {
1348
+ const next = this.candidateCounts.get(key) ?? 0;
1349
+ this.candidateCounts.set(key, next + 1);
1350
+ return next;
1351
+ }
1352
+ async start() {
1353
+ if (this.servers.length) throw new Error("World is already started");
1354
+ const fault = this.spec.fault;
1355
+ for (const service of this.spec.services) {
1356
+ const token = `at_world_${new SeedStream(this.seed, `credential:${service.name}`).nextHex(24)}`;
1357
+ const faultOrdinalsFor = fault && fault.service === service.name ? faultOrdinals(fault, this.seed) : null;
1358
+ const faultKey = `${fault?.type ?? ""}\0${service.name}\0${fault?.path ?? ""}`;
1359
+ const adapterService = service.adapter === "stripe" || service.adapter && REST_ADAPTER_NAMES.includes(service.adapter);
1360
+ const restAdapter = service.adapter && REST_ADAPTER_NAMES.includes(service.adapter) ? REST_ADAPTERS[service.adapter] : void 0;
1361
+ const altAuth = (headers) => service.adapter === "shopify" ? headers["x-shopify-access-token"] === token : service.adapter === "datadog" ? headers["dd-api-key"] === token && headers["dd-application-key"] === token : service.adapter === "discord" ? headers.authorization === `Bot ${token}` : false;
1362
+ const data = /* @__PURE__ */ Object.create(null);
1363
+ this.state[service.name] = data;
1364
+ for (const c of service.collections) data[c.path] = structuredClone(c.seed);
1365
+ const keys = /* @__PURE__ */ new Map();
1366
+ this.replayKeys.set(service.name, keys);
1367
+ const latency = this.spec.latency && (this.spec.latency.maxMs > this.spec.latency.minMs || this.spec.latency.minMs > 0) ? new SeedStream(this.seed, `latency:${service.name}`) : null;
1368
+ const latencyMs = () => latency && this.spec.latency ? this.spec.latency.minMs + latency.nextInt(this.spec.latency.maxMs - this.spec.latency.minMs + 1) : 0;
1369
+ const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
1370
+ const epoch = this.epoch;
1371
+ const send = (code, body) => {
1372
+ if (!res.destroyed) {
1373
+ res.writeHead(code, { "content-type": "application/json", ...code === 501 ? { "X-AgentTwin-Unsupported": "true" } : {} });
1374
+ res.end(JSON.stringify(body));
1375
+ }
1376
+ };
1377
+ const respond = (code, body) => {
1378
+ const ms = latencyMs();
1379
+ if (ms <= 0) {
1380
+ send(code, body);
1381
+ return;
1382
+ }
1383
+ const timer = setTimeout(() => {
1384
+ this.timers.delete(timer);
1385
+ if (epoch === this.epoch) send(code, body);
1386
+ }, ms);
1387
+ this.timers.add(timer);
1388
+ };
1389
+ const normalPath = (url, method) => {
1390
+ const parsed = new URL(url, "http://localhost");
1391
+ if (service.adapter === "slack") {
1392
+ const m = parsed.pathname.replace(/^\/api\//, "");
1393
+ if (m === "chat.postMessage" && method === "POST") return "/messages";
1394
+ if (m === "conversations.history" && ["GET", "POST"].includes(method ?? "")) return "/messages";
1395
+ if (m === "conversations.list" && ["GET", "POST"].includes(method ?? "")) return "/channels";
1396
+ return parsed.pathname;
1397
+ }
1398
+ return parsed.pathname;
1399
+ };
1400
+ const matchesFault = (target) => adapterService ? target === fault.path || target.startsWith(`${fault.path}/`) || target.endsWith(fault.path) : target === fault.path;
1401
+ const darkFault = () => {
1402
+ if (!fault || !faultOrdinalsFor || fault.type !== "blackhole" && fault.type !== "server-error") return "none";
1403
+ const target = normalPath(req.url ?? "/", req.method);
1404
+ if (!matchesFault(target)) return "none";
1405
+ const ordinal = this.candidateIndex(faultKey);
1406
+ if (!faultOrdinalsFor.includes(ordinal)) return "none";
1407
+ this.faultActions++;
1408
+ return fault.type;
1409
+ };
1410
+ try {
1411
+ if (req.headers.authorization !== `Bearer ${token}` && !altAuth(req.headers)) {
1412
+ this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
1413
+ respond(401, { error: "invalid_test_credential" });
1414
+ return;
1415
+ }
1416
+ if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
1417
+ respond(429, { error: "world_capacity" });
1418
+ return;
1419
+ }
1420
+ const darkness = darkFault();
1421
+ if (darkness === "blackhole") {
1422
+ this.record(service.name, "fault", fault.path, `blackhole: request dropped (matched ordinal ${this.candidateCounts.get(faultKey) - 1} of the seeded schedule); nothing committed`);
1423
+ return;
1424
+ }
1425
+ if (darkness === "server-error") {
1426
+ const windowMs = fault.windowMs ?? 0;
1427
+ const delay = windowMs <= 0 ? 0 : new SeedStream(this.seed, `server-error:${service.name}:${fault.path}`).nextInt(windowMs + 1);
1428
+ this.record(service.name, "fault", fault.path, `server-error fault: responding 500 after ${delay}ms; nothing committed`);
1429
+ const respond500 = () => respond(500, { error: { type: "api_error", message: "server_error fault" } });
1430
+ if (delay <= 0) {
1431
+ respond500();
1432
+ return;
1433
+ }
1434
+ const timer = setTimeout(() => {
1435
+ this.timers.delete(timer);
1436
+ if (epoch === this.epoch) respond500();
1437
+ }, delay);
1438
+ this.timers.add(timer);
1439
+ return;
1440
+ }
1441
+ const url = new URL(req.url ?? "/", "http://localhost");
1442
+ let path = url.pathname;
1443
+ const slack = service.adapter === "slack";
1444
+ const slackMethod = path.replace(/^\/api\//, "");
1445
+ let payload;
1446
+ if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
1447
+ const chunks = [];
1448
+ let bytes = 0;
1449
+ for await (const chunk of req) {
1450
+ bytes += chunk.length;
1451
+ if (bytes > 1024 * 1024) {
1452
+ respond(413, { error: "body_too_large" });
1453
+ return;
1454
+ }
1455
+ chunks.push(Buffer.from(chunk));
1456
+ }
1457
+ const text = Buffer.concat(chunks).toString("utf8");
1458
+ let parsed;
1459
+ try {
1460
+ parsed = (slack || service.adapter === "stripe") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text)) : JSON.parse(text);
1461
+ } catch {
1462
+ respond(400, { error: "expected_json_object" });
1463
+ return;
1464
+ }
1465
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1466
+ respond(400, { error: "expected_json_object" });
1467
+ return;
1468
+ }
1469
+ payload = parsed;
1470
+ }
1471
+ if (epoch !== this.epoch) {
1472
+ respond(409, { error: "world_reset" });
1473
+ return;
1474
+ }
1475
+ if (service.adapter === "stripe" || restAdapter) {
1476
+ const params = payload ?? Object.fromEntries(url.searchParams);
1477
+ const keyHeader2 = req.headers["idempotency-key"];
1478
+ const key2 = req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
1479
+ const signature2 = JSON.stringify(params);
1480
+ const previous2 = key2 ? keys.get(key2) : void 0;
1481
+ if (previous2) {
1482
+ if (previous2.body !== signature2) {
1483
+ respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
1484
+ return;
1485
+ }
1486
+ this.record(service.name, "replay", path, "same-key response replay", previous2.record);
1487
+ respond(previous2.status ?? 200, previous2.record);
1488
+ return;
1489
+ }
1490
+ const result = restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, this.events.length + 1) : stripeOperation(req.method ?? "", path, params, data, this.events.length + 1);
1491
+ if (!result) {
1492
+ this.rejectUnsupported(service.name, req.method ?? "", path, `unsupported ${service.adapter} operation or parameters`);
1493
+ respond(501, restAdapter ? restUnsupportedBody(service.adapter) : { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the verified AgentTwin Stripe subset" }, forwardedToProduction: false });
1494
+ return;
1495
+ }
1496
+ if (result.operation) this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
1497
+ if (key2 && (result.status === 200 || result.status === 201)) keys.set(key2, { body: signature2, record: structuredClone(result.body), status: result.status });
1498
+ const faultWritesMatch = fault?.type === "duplicate-write" && fault.service === service.name && result.operation === "write" && !key2 && matchesFault(result.collection);
1499
+ const duplicate2 = faultWritesMatch && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
1500
+ if (duplicate2) {
1501
+ const second = restAdapter ? restAdapter(req.method ?? "", path, params, req.headers, data, this.events.length + 1) : stripeOperation(req.method ?? "", path, params, data, this.events.length + 1);
1502
+ if (second?.operation === "write") {
1503
+ this.record(service.name, second.operation, second.collection, path, "record" in second ? second.record : second.body);
1504
+ this.faultActions++;
1505
+ this.record(service.name, "fault", fault.path, `duplicate-write: a single write was delivered twice (${result.collection})`);
1506
+ } else if (second) {
1507
+ this.record(service.name, "fault", fault.path, `duplicate-write: second delivery replaced by ${second.operation ?? "failure"}`);
1508
+ respond(second.status, second.body);
1509
+ return;
1510
+ }
1511
+ }
1512
+ if (!this.fired && result.operation === "write" && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === result.collection) {
1513
+ this.fired = true;
1514
+ this.faultActions++;
1515
+ this.record(service.name, "fault", result.collection, `write committed; response delayed ${fault.delayMs}ms`);
1516
+ const timer = setTimeout(() => {
1517
+ this.timers.delete(timer);
1518
+ respond(result.status, result.body);
1519
+ }, fault.delayMs);
1520
+ this.timers.add(timer);
1521
+ } else respond(result.status, result.body);
1522
+ return;
1523
+ }
1524
+ if (slack) {
1525
+ const params = payload ?? Object.fromEntries(url.searchParams);
1526
+ const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
1527
+ if (Object.keys(params).some((k) => !allowed.includes(k))) {
1528
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
1529
+ respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
1530
+ return;
1531
+ }
1532
+ if (slackMethod === "chat.postMessage" && req.method === "POST") path = "/messages";
1533
+ else if (slackMethod === "conversations.history" && ["GET", "POST"].includes(req.method ?? "")) path = "/messages";
1534
+ else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path = "/channels";
1535
+ else {
1536
+ this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
1537
+ respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
1538
+ return;
1539
+ }
1540
+ }
1541
+ if (!Object.hasOwn(data, path) || !["GET", "POST"].includes(req.method ?? "")) {
1542
+ this.rejectUnsupported(service.name, req.method ?? "", path, "unsupported operation");
1543
+ respond(501, { error: "unsupported_operation", forwardedToProduction: false });
1544
+ return;
1545
+ }
1546
+ if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
1547
+ this.record(service.name, "read", path, `${data[path].length} records`);
1548
+ if (slack && path === "/channels") respond(200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
1549
+ else if (slack) {
1550
+ const channel = payload?.channel ?? url.searchParams.get("channel");
1551
+ if (!data["/channels"].some((c) => c.id === channel)) respond(200, { ok: false, error: "channel_not_found" });
1552
+ else respond(200, { ok: true, messages: data[path].filter((m) => m.channel === channel), has_more: false });
1553
+ } else respond(200, { data: data[path] });
1554
+ return;
1555
+ }
1556
+ const body = payload;
1557
+ if (slack) {
1558
+ const message = body;
1559
+ if (!data["/channels"].some((c) => c.id === message.channel)) {
1560
+ respond(200, { ok: false, error: "channel_not_found" });
1561
+ return;
1562
+ }
1563
+ if (typeof message.text !== "string" || !message.text) {
1564
+ respond(200, { ok: false, error: "no_text" });
1565
+ return;
1566
+ }
1567
+ }
1568
+ if (data[path].length >= 1e4 || this.events.length >= 5e4) {
1569
+ respond(429, { error: "world_capacity" });
1570
+ return;
1571
+ }
1572
+ const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
1573
+ const key = typeof keyHeader === "string" ? `${path}:${keyHeader}` : void 0;
1574
+ const signature = JSON.stringify(body);
1575
+ const previous = key ? keys.get(key) : void 0;
1576
+ if (previous) {
1577
+ if (previous.body !== signature) {
1578
+ respond(409, { error: "idempotency_conflict" });
1579
+ return;
1580
+ }
1581
+ this.record(service.name, "replay", path, "same-key response replay", previous.record);
1582
+ respond(200, previous.record);
1583
+ return;
1584
+ }
1585
+ const duplicate = fault?.type === "duplicate-write" && fault.service === service.name && fault.path === path && !key && faultOrdinalsFor !== null && faultOrdinalsFor.includes(this.candidateIndex(faultKey));
1586
+ if (duplicate) this.faultActions++;
1587
+ let index = data[path].length + 1;
1588
+ while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
1589
+ const row = { ...body, id: `${service.name}_${index}` };
1590
+ if (slack) row.ts = `${index}.000001`;
1591
+ const reply = slack ? { ok: true, channel: row.channel, ts: row.ts, message: row } : row;
1592
+ data[path].push(row);
1593
+ if (key) keys.set(key, { body: signature, record: row });
1594
+ this.record(service.name, "write", path, String(row.id), row);
1595
+ if (duplicate) {
1596
+ index++;
1597
+ while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
1598
+ const second = { ...body, id: `${service.name}_${index}` };
1599
+ if (slack) second.ts = `${index}.000001`;
1600
+ data[path].push(second);
1601
+ this.record(service.name, "write", path, String(second.id), second);
1602
+ this.record(service.name, "fault", fault.path, `duplicate-write: one write committed as two records (${row.id}, ${second.id})`);
1603
+ }
1604
+ const faultResponse = slack ? 200 : 201;
1605
+ if (!this.fired && fault?.type === "timeout-after-write" && fault.service === service.name && fault.path === path) {
1606
+ this.fired = true;
1607
+ this.faultActions++;
1608
+ this.record(service.name, "fault", path, `write committed; response delayed ${fault.delayMs}ms`);
1609
+ const timer = setTimeout(() => {
1610
+ this.timers.delete(timer);
1611
+ respond(faultResponse, reply);
1612
+ }, fault.delayMs);
1613
+ this.timers.add(timer);
1614
+ } else respond(faultResponse, reply);
1615
+ } catch {
1616
+ respond(500, { error: "world_request_error" });
1617
+ }
1618
+ }));
1619
+ server.requestTimeout = 1e4;
1620
+ await new Promise((resolve5, reject) => {
1621
+ server.once("error", reject);
1622
+ server.listen(0, "127.0.0.1", resolve5);
1623
+ });
1624
+ this.servers.push(server);
1625
+ this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server.address().port}`, token };
1626
+ }
1627
+ return this.credentials;
1628
+ }
1629
+ assertions() {
1630
+ return this.spec.assertions.map((a) => {
1631
+ const rows2 = this.state[a.service][a.path].filter((row) => !a.where || Object.entries(a.where).every(([k, v]) => isDeepStrictEqual(row[k], v)));
1632
+ return { ...a, actual: rows2.length, passed: rows2.length === a.count };
1633
+ });
1634
+ }
1635
+ get faultTriggered() {
1636
+ return this.faultActions > 0;
1637
+ }
1638
+ snapshot() {
1639
+ return structuredClone(this.state);
1640
+ }
1641
+ quiesce() {
1642
+ this.epoch++;
1643
+ for (const server of this.servers) server.closeAllConnections();
1644
+ for (const timer of this.timers) clearTimeout(timer);
1645
+ this.timers.clear();
1646
+ }
1647
+ reset() {
1648
+ this.quiesce();
1649
+ for (const service of this.spec.services) {
1650
+ for (const collection of service.collections) this.state[service.name][collection.path] = structuredClone(collection.seed);
1651
+ this.replayKeys.get(service.name)?.clear();
1652
+ }
1653
+ this.events.length = 0;
1654
+ this.unsupported.length = 0;
1655
+ this.fired = false;
1656
+ this.faultActions = 0;
1657
+ this.candidateCounts.clear();
1658
+ return this.snapshot();
1659
+ }
1660
+ async close() {
1661
+ this.epoch++;
1662
+ for (const timer of this.timers) clearTimeout(timer);
1663
+ this.timers.clear();
1664
+ await Promise.all(this.servers.map((server) => new Promise((resolve5) => {
1665
+ server.close(() => resolve5());
1666
+ server.closeAllConnections();
1667
+ })));
1668
+ this.servers.length = 0;
1669
+ }
1670
+ };
1671
+
1672
+ // src/runtime/browser-execution.ts
1673
+ import { chromium } from "playwright";
1674
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "util";
1675
+ async function browserExecution(spec, world, signal) {
1676
+ signal?.throwIfAborted();
1677
+ const recipe = spec.browser;
1678
+ const browser = await chromium.launch({ headless: true, timeout: spec.timeoutSeconds * 1e3, ...process.env.AGENTTWIN_CHROMIUM_EXECUTABLE_PATH ? { executablePath: process.env.AGENTTWIN_CHROMIUM_EXECUTABLE_PATH } : {} });
1679
+ const abort = () => {
1680
+ void browser.close().catch(() => {
1681
+ });
1682
+ };
1683
+ signal?.addEventListener("abort", abort, { once: true });
1684
+ try {
1685
+ signal?.throwIfAborted();
1686
+ const context = await browser.newContext({ serviceWorkers: "block", viewport: { width: 1280, height: 720 } });
1687
+ const origins = /* @__PURE__ */ new Set([new URL(recipe.baseUrl).origin, ...Object.values(world.credentials).map((c) => new URL(c.endpoint).origin)]);
1688
+ const blocked = /* @__PURE__ */ new Set();
1689
+ await context.route("**/*", (route) => {
1690
+ const origin = new URL(route.request().url()).origin;
1691
+ if (origins.has(origin)) return route.continue();
1692
+ if (blocked.size < 100) blocked.add(origin);
1693
+ return route.abort("blockedbyclient");
1694
+ });
1695
+ const page = await context.newPage();
1696
+ page.setDefaultTimeout(Math.min(spec.timeoutSeconds * 500, 1e4));
1697
+ const deadline = Date.now() + Math.min(spec.timeoutSeconds * 1e3, 1e4);
1698
+ while (true) {
1699
+ signal?.throwIfAborted();
1700
+ try {
1701
+ const r = await fetch(recipe.baseUrl, { signal: AbortSignal.timeout(300) });
1702
+ if (r.ok) break;
1703
+ } catch {
1704
+ }
1705
+ if (Date.now() > deadline) throw new Error("Application browser readiness timed out");
1706
+ await new Promise((r) => setTimeout(r, 50));
1707
+ }
1708
+ const steps = [];
1709
+ let error;
1710
+ for (const step of recipe.steps) {
1711
+ signal?.throwIfAborted();
1712
+ try {
1713
+ if (step.action === "goto") await page.goto(new URL(step.path, recipe.baseUrl).href);
1714
+ else if (step.action === "click") await page.locator(step.selector).click();
1715
+ else if (step.action === "fill") await page.locator(step.selector).fill(step.value);
1716
+ else await page.locator(step.selector).filter({ hasText: step.text }).waitFor({ state: "visible" });
1717
+ steps.push({ action: step.action, passed: true });
1718
+ } catch (cause) {
1719
+ error = cause instanceof Error ? cause.message : String(cause);
1720
+ for (const s of recipe.steps) if (s.action === "fill" && s.value) error = error.split(s.value).join("[input]");
1721
+ steps.push({ action: step.action, passed: false });
1722
+ break;
1723
+ }
1724
+ }
1725
+ let screenshot;
1726
+ try {
1727
+ const bytes = await page.screenshot({ type: "jpeg", quality: 65 });
1728
+ if (bytes.length <= 768 * 1024) screenshot = { mimeType: "image/jpeg", base64: bytes.toString("base64") };
1729
+ } catch {
1730
+ }
1731
+ for (const origin of blocked) world.unsupported.push(`browser: blocked unmodeled request origin ${origin}`);
1732
+ return { engine: "playwright-chromium", steps, passed: !error, error, blockedOrigins: [...blocked], screenshot };
1733
+ } finally {
1734
+ signal?.removeEventListener("abort", abort);
1735
+ await browser.close();
1736
+ }
1737
+ }
1738
+ async function waitBackground(spec, world, signal) {
1739
+ const check = spec.background, deadline = Date.now() + check.timeoutMs;
1740
+ while (true) {
1741
+ signal?.throwIfAborted();
1742
+ const actual = world.state[check.service][check.path].filter((row) => !check.where || Object.entries(check.where).every(([k, v]) => isDeepStrictEqual2(row[k], v))).length;
1743
+ if (actual === check.count) return { ...check, actual, passed: true };
1744
+ if (Date.now() >= deadline) return { ...check, actual, passed: false };
1745
+ await new Promise((r) => setTimeout(r, 25));
1746
+ }
1747
+ }
1748
+
1749
+ // src/runtime/local.ts
1750
+ import { spawn } from "child_process";
1751
+
1752
+ // src/runtime/evaluation.ts
1753
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "util";
1754
+ var matches = (row, where) => !where || Object.entries(where).every(([k, v]) => isDeepStrictEqual3(row[k], v));
1755
+ function evaluateState(spec, initial, final, events) {
1756
+ const checks = spec.assertions.map((a, index) => {
1757
+ const before = initial[a.service]?.[a.path];
1758
+ const after = final[a.service]?.[a.path];
1759
+ const actual = after?.filter((row) => matches(row, a.where)).length;
1760
+ return {
1761
+ id: `assertion_${index + 1}`,
1762
+ kind: "required-outcome",
1763
+ service: a.service,
1764
+ path: a.path,
1765
+ passed: actual === a.count,
1766
+ expected: a.count,
1767
+ actual: actual ?? null,
1768
+ evidence: {
1769
+ initial: `/initialState/${escape(a.service)}/${escape(a.path)}`,
1770
+ final: `/finalState/${escape(a.service)}/${escape(a.path)}`,
1771
+ beforeCount: before?.filter((row) => matches(row, a.where)).length ?? null,
1772
+ eventSequences: events.filter((e) => e.service === a.service && e.path === a.path).map((e) => e.sequence)
1773
+ }
1774
+ };
1775
+ });
1776
+ const forbidden = (spec.forbiddenEffects ?? []).map((policy) => {
1777
+ const hits = events.filter((e) => e.service === policy.service && e.path === policy.path && e.operation === policy.operation && (!policy.where || e.record !== void 0 && matches(e.record, policy.where)));
1778
+ const unknown = events.some((e) => e.service === policy.service && e.path === policy.path && e.operation === policy.operation && policy.where && !e.record);
1779
+ return {
1780
+ id: policy.id,
1781
+ kind: "forbidden-effect",
1782
+ service: policy.service,
1783
+ path: policy.path,
1784
+ passed: hits.length === 0 && !unknown,
1785
+ expected: 0,
1786
+ actual: hits.length,
1787
+ evidence: { eventSequences: hits.map((e) => e.sequence), evidenceGap: unknown }
1788
+ };
1789
+ });
1790
+ const preserved = (spec.preservedState ?? []).map((policy) => {
1791
+ const before = initial[policy.service]?.[policy.path];
1792
+ const after = final[policy.service]?.[policy.path];
1793
+ const passed = !!before && !!after && isDeepStrictEqual3(before.filter((row) => matches(row, policy.where)), after.filter((row) => matches(row, policy.where)));
1794
+ return {
1795
+ id: policy.id,
1796
+ kind: "preserved-state",
1797
+ service: policy.service,
1798
+ path: policy.path,
1799
+ passed,
1800
+ expected: "unchanged",
1801
+ actual: passed ? "unchanged" : "changed or missing",
1802
+ evidence: { initial: `/initialState/${escape(policy.service)}/${escape(policy.path)}`, final: `/finalState/${escape(policy.service)}/${escape(policy.path)}` }
1803
+ };
1804
+ });
1805
+ const properties = (spec.properties ?? []).map((policy) => evaluateProperty(policy, final, events));
1806
+ const taskPassed = checks.every((c) => c.passed);
1807
+ const safe = [...forbidden, ...preserved, ...properties].every((c) => c.passed);
1808
+ return { schema: "agenttwin/evaluation-v1", outcome: !safe ? "unsafe" : taskPassed ? "passed" : "failed", taskPassed, safe, checks: [...checks, ...forbidden, ...preserved, ...properties] };
1809
+ }
1810
+ 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;
1811
+ var short = (value, limit = 120) => value.length <= limit ? value : `${value.slice(0, limit)}\u2026`;
1812
+ function evaluateProperty(policy, final, events) {
1813
+ const base = { id: policy.id, kind: "property", propertyKind: policy.kind, service: policy.service, path: policy.path, passed: false };
1814
+ const rows2 = final[policy.service]?.[policy.path];
1815
+ if (!rows2) return { ...base, expected: "intact", actual: "missing collection", evidence: { evidenceGap: `final state has no collection "${policy.path}" in "${policy.service}"` } };
1816
+ const eventsFor = (operation2, where2) => events.filter((e) => e.service === policy.service && e.path === policy.path && e.operation === operation2 && (!where2 || e.record !== void 0 && matches(e.record, where2)));
1817
+ if (policy.kind === "unique-per-act") {
1818
+ const field = String(policy.params?.field);
1819
+ const keyed = /* @__PURE__ */ new Map();
1820
+ for (const row of rows2) {
1821
+ if (row[field] === void 0) continue;
1822
+ const key = JSON.stringify(canonical(row[field]));
1823
+ keyed.set(key, [...keyed.get(key) ?? [], row.id ?? row]);
1824
+ }
1825
+ const duplicates = [...keyed.entries()].filter(([, list]) => list.length > 1);
1826
+ return {
1827
+ ...base,
1828
+ passed: duplicates.length === 0,
1829
+ expected: 0,
1830
+ actual: duplicates.length,
1831
+ 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) }
1832
+ };
1833
+ }
1834
+ if (policy.kind === "no-loss") {
1835
+ const writes = eventsFor("write", policy.params?.where);
1836
+ const lost = writes.filter((e) => {
1837
+ if (!e.record) return false;
1838
+ const record = e.record;
1839
+ if (typeof record.id === "string" && record.id) return !rows2.some((row) => row.id === record.id);
1840
+ return !rows2.some((row) => isDeepStrictEqual3(row, record));
1841
+ });
1842
+ const unknown2 = writes.some((e) => !e.record);
1843
+ return {
1844
+ ...base,
1845
+ passed: lost.length === 0 && !unknown2,
1846
+ expected: 0,
1847
+ actual: unknown2 ? "unknown" : lost.length,
1848
+ evidence: { evidenceGap: unknown2, eventSequences: lost.map((e) => e.sequence), lost: lost.map((e) => String(e.detail)) }
1849
+ };
1850
+ }
1851
+ const count = Number(policy.params?.count);
1852
+ const operation = String(policy.params?.operation ?? "write");
1853
+ const where = policy.params?.where;
1854
+ const hits = eventsFor(operation, where);
1855
+ const unknown = where !== void 0 && hits.length > 0 && hits.some((e) => !e.record);
1856
+ return {
1857
+ ...base,
1858
+ expected: count,
1859
+ actual: unknown ? "unknown" : hits.length,
1860
+ passed: hits.length === count && !unknown,
1861
+ evidence: { operation, eventSequences: hits.map((e) => e.sequence), evidenceGap: unknown }
1862
+ };
1863
+ }
1864
+ var escape = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
1865
+
1866
+ // src/runtime/local.ts
1867
+ init_contracts();
1868
+ async function executeLocal(app, spec, signal, existingWorld, seed) {
1869
+ if (spec.postgres || spec.redis) throw new Error("This world needs PostgreSQL or Redis. Use --runtime hosted or --runtime e2b, or prepare a workflow using HTTP twins only. No local containers are started.");
1870
+ signal?.throwIfAborted();
1871
+ const world = existingWorld ?? new HttpWorld(spec, seed), started = Date.now();
1872
+ try {
1873
+ const credentials = existingWorld ? world.credentials : await world.start();
1874
+ const initialState = world.snapshot();
1875
+ const env = { PATH: process.env.PATH ?? "", NODE_ENV: "test" };
1876
+ for (const [name, c] of Object.entries(credentials)) {
1877
+ env[`AGENTTWIN_${name.toUpperCase()}_URL`] = c.endpoint;
1878
+ env[`AGENTTWIN_${name.toUpperCase()}_TOKEN`] = c.token;
1879
+ }
1880
+ let stdout = "", stderr = "", timedOut = false;
1881
+ const hook = await createRequestSourceHook(app, spec, credentials);
1882
+ const child = spawn(process.execPath, ["--require", hook.path, ...spec.command.slice(1)], { cwd: app, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32" });
1883
+ child.stdout.on("data", (b) => {
1884
+ stdout = (stdout + b.toString()).slice(-65536);
1885
+ });
1886
+ child.stderr.on("data", (b) => {
1887
+ stderr = (stderr + b.toString()).slice(-65536);
1888
+ });
1889
+ const kill = () => {
1890
+ if (child.pid) {
1891
+ try {
1892
+ process.platform === "win32" ? child.kill("SIGKILL") : process.kill(-child.pid, "SIGKILL");
1893
+ } catch {
1894
+ }
1895
+ }
1896
+ };
1897
+ const executionAbort = new AbortController();
1898
+ const abort = () => {
1899
+ executionAbort.abort();
1900
+ kill();
1901
+ };
1902
+ signal?.addEventListener("abort", abort, { once: true });
1903
+ const timer = setTimeout(() => {
1904
+ timedOut = true;
1905
+ executionAbort.abort();
1906
+ kill();
1907
+ }, spec.timeoutSeconds * 1e3);
1908
+ const completion = new Promise((resolve5, reject) => {
1909
+ child.once("error", reject);
1910
+ child.once("close", resolve5);
1911
+ });
1912
+ let browser, background, executionError;
1913
+ let exitCode;
1914
+ try {
1915
+ if (spec.browser || spec.background) {
1916
+ const work = (async () => {
1917
+ if (spec.browser) browser = await browserExecution(spec, world, executionAbort.signal);
1918
+ if (spec.background) background = await waitBackground(spec, world, executionAbort.signal);
1919
+ return 0;
1920
+ })();
1921
+ exitCode = await Promise.race([work, completion.then((code) => {
1922
+ if (!spec.browser && code === 0) return work;
1923
+ throw new Error(`Application exited before browser/background completion (${code})`);
1924
+ })]);
1925
+ } else exitCode = await completion;
1926
+ } catch (error) {
1927
+ executionError = error instanceof Error ? error.message : String(error);
1928
+ exitCode = 1;
1929
+ } finally {
1930
+ executionAbort.abort();
1931
+ clearTimeout(timer);
1932
+ signal?.removeEventListener("abort", abort);
1933
+ kill();
1934
+ await completion.catch(() => {
1935
+ });
1936
+ await hook.close();
1937
+ }
1938
+ signal?.throwIfAborted();
1939
+ if (existingWorld) world.quiesce();
1940
+ else await world.close();
1941
+ for (const c of Object.values(credentials)) {
1942
+ stdout = stdout.split(c.token).join("[test-token]");
1943
+ stderr = stderr.split(c.token).join("[test-token]");
1944
+ }
1945
+ const assertions = world.assertions();
1946
+ const evaluation = evaluateState(spec, initialState, world.state, world.events);
1947
+ const status = world.unsupported.length || spec.fault && !world.faultTriggered ? "incomplete" : timedOut || exitCode !== 0 ? "error" : background?.passed === false || browser?.passed === false ? "failed" : evaluation.outcome === "passed" ? "passed" : "failed";
1948
+ return { schema: "agenttwin/run-v1", name: spec.name, workflowId: spec.workflowId, status, browser, background, executionError, application: { command: spec.command, exitCode, timedOut, stdout, stderr }, assertions, evaluation, contracts: operationMatrix(spec), scenario: spec.scenario, infrastructureAssertions: [], fault: spec.fault ? { ...spec.fault, triggered: world.faultTriggered } : null, seed: world.seed, reproducibility: "Seed " + world.seed + " deterministically drives twin-side fault scheduling, latency jitter and test credentials. The seed does not control the application's own randomness, wall-clock behavior or threading; compare runs only over twin events and final state.", initialState, finalState: world.snapshot(), events: structuredClone(world.events), unsupported: [...world.unsupported], durationMs: Date.now() - started, coverage: "CLI Node execution with fresh in-process HTTP collections and advertised provider subsets. Optional Chromium browser steps and bounded collection-state background completion. Not a VM or network/filesystem isolation boundary. No production environment variables inherited; reviewed code can still access the host filesystem and network.", isolation: { kind: "process", productionCredentialsInherited: false, network: "host network; not isolated", rootFilesystem: "host-accessible; explicit files staged in temporary directory" } };
1949
+ } finally {
1950
+ if (existingWorld) world.quiesce();
1951
+ else await world.close();
1952
+ }
1953
+ }
1954
+
1955
+ // src/runtime/spec.ts
1956
+ var ADAPTER_COLLECTIONS = {
1957
+ slack: ["/messages", "/channels"],
1958
+ stripe: ["/v1/customers", "/v1/payment_intents"],
1959
+ github: ["/repos", "/issues", "/comments", "/pulls", "/check-runs"],
1960
+ linear: ["/issues", "/projects", "/users", "/comments"],
1961
+ notion: ["/pages", "/databases", "/blocks"],
1962
+ hubspot: ["/crm/v3/objects/contacts", "/crm/v3/objects/companies", "/crm/v3/objects/deals", "/crm/v3/objects/tickets"],
1963
+ shopify: ["/admin/products", "/admin/orders", "/admin/customers"],
1964
+ datadog: ["/monitors", "/events", "/metrics"],
1965
+ gmail: ["/gmail/v1/users/me/messages", "/gmail/v1/users/me/labels"],
1966
+ "google-calendar": ["/calendar/v3/users/me/calendarList", "/calendar/v3/calendars/primary/events"],
1967
+ gitlab: ["/api/v4/projects", "/api/v4/issues", "/api/v4/merge_requests", "/api/v4/merge_requests/notes"],
1968
+ jira: ["/rest/api/3/issue", "/rest/api/3/issue/comments", "/rest/api/3/project"],
1969
+ discord: ["/api/channels", "/api/channels/messages", "/api/guilds", "/api/guilds/members"],
1970
+ twilio: ["/2010-04-01/Messages", "/2010-04-01/Calls"],
1971
+ zendesk: ["/api/v2/tickets", "/api/v2/users", "/api/v2/organizations"]
1972
+ };
1973
+ var FAULT_TYPES = ["timeout-after-write", "blackhole", "server-error", "duplicate-write"];
1974
+ var PROPERTY_KINDS = ["unique-per-act", "no-loss", "effect-count"];
1975
+ var object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1976
+ var namePattern = /^[a-z][a-z0-9_]{0,39}$/;
1977
+ var inRangeInt = (x, min, max) => Number.isInteger(x) && Number(x) >= min && Number(x) <= max;
1978
+ function parseWorld(value) {
1979
+ const invalid = (message) => {
1980
+ throw new Error(`Invalid world: ${message}`);
1981
+ };
1982
+ if (!object(value) || value.schema !== "agenttwin/world-v1") invalid("schema must be agenttwin/world-v1");
1983
+ const v = value;
1984
+ if (typeof v.name !== "string" || !namePattern.test(v.name)) invalid("name must be lowercase letters, digits or underscores");
1985
+ if (!Array.isArray(v.files) || !v.files.length || v.files.length > 100 || !v.files.every((f) => typeof f === "string" && f.length > 0)) invalid("files must explicitly list 1\u2013100 application files");
1986
+ if (new Set(v.files).size !== v.files.length) invalid("files must be unique");
1987
+ if (!Array.isArray(v.command) || !v.command.length || !v.command.every((c) => typeof c === "string" && c.length > 0) || v.command[0] !== "node") invalid("command must be an argv array starting with node; supply a bundled Node application");
1988
+ if (!Number.isInteger(v.timeoutSeconds) || Number(v.timeoutSeconds) < 1 || Number(v.timeoutSeconds) > 300) invalid("timeoutSeconds must be 1\u2013300");
1989
+ if (v.workflowId !== void 0 && (typeof v.workflowId !== "string" || !v.workflowId)) invalid("workflowId must be a nonempty string");
1990
+ if (!Array.isArray(v.services) || !v.services.length || v.services.length > 10) invalid("services must contain 1\u201310 HTTP services");
1991
+ const services = /* @__PURE__ */ new Map();
1992
+ for (const service of v.services) {
1993
+ if (!object(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
1994
+ const item = service;
1995
+ if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
1996
+ if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk"].includes(String(item.adapter))) invalid("unsupported service adapter");
1997
+ const paths = /* @__PURE__ */ new Set();
1998
+ for (const entry of item.collections) {
1999
+ if (!object(entry) || typeof entry.path !== "string" || !/^\/[a-zA-Z0-9_/-]+$/.test(entry.path) || entry.path.includes("//") || paths.has(entry.path)) invalid("collection paths must be unique absolute HTTP paths");
2000
+ const collection = entry;
2001
+ if (!Array.isArray(collection.seed) || collection.seed.length > 1e3 || !collection.seed.every(object)) invalid("seed must be an array of up to 1000 JSON records");
2002
+ paths.add(collection.path);
2003
+ }
2004
+ const required = ADAPTER_COLLECTIONS[item.adapter];
2005
+ if (required && (paths.size !== required.length || !required.every((p) => paths.has(p)))) invalid(`${item.adapter} adapter requires exactly ${required.join(", ")} collections`);
2006
+ services.set(item.name, paths);
2007
+ }
2008
+ const known = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
2009
+ if (!Array.isArray(v.assertions) || !v.assertions.length || v.assertions.length > 100) invalid("at least one final-state assertion is required (maximum 100)");
2010
+ for (const assertion of v.assertions) {
2011
+ if (!object(assertion) || !known(assertion) || !Number.isSafeInteger(assertion.count) || Number(assertion.count) < 0 || assertion.where !== void 0 && !object(assertion.where)) invalid("assertions need an existing service/path, nonnegative count, and optional where object");
2012
+ }
2013
+ const policyIds = /* @__PURE__ */ new Set();
2014
+ for (const field of ["forbiddenEffects", "preservedState"]) {
2015
+ if (v[field] === void 0) continue;
2016
+ if (!Array.isArray(v[field]) || v[field].length > 100) invalid(`${field} must contain at most 100 checks`);
2017
+ for (const entry of v[field]) {
2018
+ if (!object(entry) || typeof entry.id !== "string" || !namePattern.test(entry.id) || policyIds.has(entry.id) || !known(entry) || entry.where !== void 0 && !object(entry.where)) invalid(`${field} requires unique ids, known collections and an optional where object`);
2019
+ const item = entry;
2020
+ if (field === "forbiddenEffects" && !["write", "read", "replay"].includes(String(item.operation))) invalid("forbiddenEffects operation must be write, read or replay");
2021
+ if (Object.keys(item).some((k) => !["id", "service", "path", "where", ...field === "forbiddenEffects" ? ["operation"] : []].includes(k))) invalid(`unknown ${field} field`);
2022
+ policyIds.add(item.id);
2023
+ }
2024
+ }
2025
+ if (v.scenario !== void 0 && (!object(v.scenario) || typeof v.scenario.id !== "string" || !namePattern.test(v.scenario.id) || !Number.isSafeInteger(v.scenario.version) || Number(v.scenario.version) < 1 || typeof v.scenario.digest !== "string" || !/^[a-f0-9]{64}$/.test(v.scenario.digest) || Object.keys(v.scenario).some((k) => !["id", "version", "digest"].includes(k)))) invalid("scenario requires id, positive version and SHA-256 digest");
2026
+ if (v.postgres !== void 0) {
2027
+ if (!object(v.postgres) || v.postgres.seedFile !== void 0 && !v.files.includes(String(v.postgres.seedFile)) || !Array.isArray(v.postgres.assertions) || !v.postgres.assertions.length || v.postgres.assertions.length > 100) invalid("postgres requires assertions and seedFile must be listed in files");
2028
+ for (const a of v.postgres.assertions) {
2029
+ if (!object(a) || typeof a.query !== "string" || !/^select\s/i.test(a.query) || a.query.includes(";") || !Array.isArray(a.equals) || !a.equals.every(object)) invalid("postgres assertions require a SELECT query without semicolons and an equals array");
2030
+ }
2031
+ }
2032
+ if (v.redis !== void 0) {
2033
+ if (!object(v.redis) || !Array.isArray(v.redis.assertions) || !v.redis.assertions.length || v.redis.assertions.length > 100) invalid("redis requires assertions");
2034
+ for (const a of v.redis.assertions) {
2035
+ if (!object(a) || typeof a.key !== "string" || !a.key || a.equals !== null && typeof a.equals !== "string") invalid("redis assertions require key and string/null equals");
2036
+ }
2037
+ }
2038
+ if (v.fault !== void 0) {
2039
+ if (!object(v.fault) || !known(v.fault) || !FAULT_TYPES.includes(v.fault.type)) invalid("fault requires an existing service/path and a supported type: timeout-after-write, blackhole, server-error or duplicate-write");
2040
+ const f = v.fault;
2041
+ const allowed = ["service", "path", "type"];
2042
+ const count = f.count, windowMs = f.windowMs;
2043
+ if (f.type === "timeout-after-write") {
2044
+ if (!inRangeInt(f.delayMs, 1, 1e4)) invalid("timeout-after-write fault requires delayMs 1\u201310000; the delay is declared application-visible behavior, never seeded");
2045
+ allowed.push("delayMs");
2046
+ } else if (f.delayMs !== void 0) invalid(`${f.type} fault does not take delayMs`);
2047
+ if (f.type === "server-error") {
2048
+ if (!inRangeInt(count, 1, 100)) invalid("server-error fault requires count 1\u2013100 (how many matching requests are rejected)");
2049
+ if (windowMs !== void 0 && !inRangeInt(windowMs, 0, 1e4)) invalid("server-error windowMs must be 0\u201310000 (the seeded upper delay before the rejection response)");
2050
+ allowed.push("count", "windowMs");
2051
+ } else {
2052
+ if (!["blackhole", "duplicate-write"].includes(f.type) && windowMs !== void 0) invalid(`${f.type} fault does not take windowMs`);
2053
+ if (["blackhole", "duplicate-write"].includes(f.type) && count !== void 0 && !inRangeInt(count, 1, 100)) invalid(`${f.type} fault count must be 1\u2013100`);
2054
+ if (["blackhole", "duplicate-write"].includes(f.type)) allowed.push("count");
2055
+ }
2056
+ if (Object.keys(f).some((k) => !allowed.includes(k))) invalid(`unknown fault field for ${f.type}`);
2057
+ }
2058
+ if (v.properties !== void 0) {
2059
+ if (!Array.isArray(v.properties) || !v.properties.length || v.properties.length > 50) invalid("properties must contain 1\u201350 named invariants");
2060
+ for (const raw of v.properties) {
2061
+ const p = raw;
2062
+ if (!p || !known(p)) invalid("properties need existing service/path collections and closed kinds");
2063
+ if (typeof p.id !== "string" || !namePattern.test(p.id)) invalid("property id must be a lowercase identifier");
2064
+ if (policyIds.has(p.id)) invalid("property ids must be unique ids across the world's policies");
2065
+ if (!PROPERTY_KINDS.includes(p.kind)) invalid(`unknown property kind: use one of ${PROPERTY_KINDS.join(", ")}`);
2066
+ const params = object(p.params) ? p.params : {};
2067
+ if (p.kind === "unique-per-act") {
2068
+ const field = params.field;
2069
+ if (typeof field !== "string" || !field || field.length > 64 || Object.keys(params).some((k) => k !== "field")) invalid(`property "${p.id}" (unique-per-act) requires params.field (a record field name), nothing else`);
2070
+ } else if (p.kind === "no-loss") {
2071
+ if (p.params !== void 0 && (!object(params) || !object(params.where) || Object.keys(params).some((k) => k !== "where"))) invalid(`property "${p.id}" (no-loss) takes only an optional params.where object`);
2072
+ } else {
2073
+ if (!object(params) || !inRangeInt(params.count, 0, 1e5)) invalid(`property "${p.id}" (effect-count) requires params.count 0\u2013100000`);
2074
+ if (params.operation !== void 0 && !["write", "read", "replay"].includes(String(params.operation))) invalid(`property "${p.id}" (effect-count) operation must be write, read or replay`);
2075
+ if (params.where !== void 0 && !object(params.where)) invalid(`property "${p.id}" (effect-count) params.where must be an object`);
2076
+ if (Object.keys(params).some((k) => !["count", "operation", "where"].includes(k))) invalid(`property "${p.id}" (effect-count) takes only count, operation and where`);
2077
+ }
2078
+ policyIds.add(p.id);
2079
+ }
2080
+ }
2081
+ if (v.latency !== void 0) {
2082
+ const allowed = ["minMs", "maxMs"];
2083
+ if (!object(v.latency) || Object.keys(v.latency).some((k) => !allowed.includes(k))) invalid("latency requires minMs and maxMs");
2084
+ const l = v.latency;
2085
+ if (!inRangeInt(l.minMs, 0, 1e4) || !inRangeInt(l.maxMs, 0, 1e4) || Number(l.minMs) > Number(l.maxMs)) invalid("latency requires minMs and maxMs in 0\u201310000 with minMs <= maxMs");
2086
+ }
2087
+ if (v.browser !== void 0) {
2088
+ if (!object(v.browser) || typeof v.browser.baseUrl !== "string") invalid("browser requires baseUrl");
2089
+ const browser = v.browser;
2090
+ let u;
2091
+ try {
2092
+ u = new URL(String(v.browser.baseUrl));
2093
+ } catch {
2094
+ invalid("browser baseUrl must be a loopback HTTP URL");
2095
+ }
2096
+ if (u.protocol !== "http:" || u.hostname !== "127.0.0.1" || !u.port || u.username || u.password || u.pathname !== "/" || u.search || u.hash) invalid("browser baseUrl must be http://127.0.0.1:<port>");
2097
+ if (!Array.isArray(browser.steps) || !browser.steps.length || browser.steps.length > 100 || Object.keys(browser).some((k) => !["baseUrl", "steps"].includes(k))) invalid("browser needs 1\u2013100 steps");
2098
+ for (const raw of browser.steps) {
2099
+ const step = raw;
2100
+ if (!object(step) || !["goto", "click", "fill", "expectText"].includes(String(step.action))) invalid("unsupported browser action");
2101
+ if (step.action === "goto") {
2102
+ if (typeof step.path !== "string" || !step.path.startsWith("/") || step.path.startsWith("//") || step.path.includes("\\") || Object.keys(step).some((k) => !["action", "path"].includes(k))) invalid("goto requires a relative application path");
2103
+ } else {
2104
+ if (typeof step.selector !== "string" || !step.selector || step.action === "fill" && typeof step.value !== "string" || step.action === "expectText" && typeof step.text !== "string" || Object.keys(step).some((k) => !["action", "selector", ...step.action === "fill" ? ["value"] : step.action === "expectText" ? ["text"] : []].includes(k))) invalid("invalid browser selector/action parameters");
2105
+ }
2106
+ }
2107
+ }
2108
+ if (v.background !== void 0 && (!object(v.background) || !known(v.background) || !Number.isSafeInteger(v.background.count) || Number(v.background.count) < 0 || !Number.isInteger(v.background.timeoutMs) || Number(v.background.timeoutMs) < 1 || Number(v.background.timeoutMs) > Number(v.timeoutSeconds) * 1e3 || v.background.where !== void 0 && !object(v.background.where) || Object.keys(v.background).some((k) => !["service", "path", "count", "where", "timeoutMs"].includes(k)))) invalid("background requires a known collection, expected count, optional where, and bounded timeoutMs");
2109
+ const keys = ["schema", "name", "workflowId", "files", "command", "timeoutSeconds", "browser", "background", "services", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "latency"];
2110
+ if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
2111
+ return v;
2112
+ }
2113
+
2114
+ // src/runtime/scenarios.ts
2115
+ import { createHash as createHash3 } from "crypto";
2116
+ import { mkdir, readFile, readdir, writeFile as writeFile2 } from "fs/promises";
2117
+ import { join as join2 } from "path";
2118
+ import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
2119
+ var identifier = /^[a-z][a-z0-9_]{0,39}$/;
2120
+ var object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
2121
+ var sort = (v) => Array.isArray(v) ? v.map(sort) : object2(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
2122
+ var scenarioDigest = (scenario) => createHash3("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
2123
+ function parseScenario(value) {
2124
+ const fail = (detail) => {
2125
+ throw new Error(`Invalid scenario: ${detail}`);
2126
+ };
2127
+ if (!object2(value) || value.schema !== "agenttwin/scenario-v1" || typeof value.id !== "string" || !identifier.test(value.id) || !Number.isSafeInteger(value.version) || Number(value.version) < 1 || typeof value.description !== "string" || value.description.length > 2e3 || !Array.isArray(value.services) || !Array.isArray(value.entities) || value.entities.length > 100 || Object.keys(value).some((k) => !["schema", "id", "version", "description", "services", "entities"].includes(k))) fail("schema, id, version, description, services and entities are required");
2128
+ const scenario = value;
2129
+ parseWorld({
2130
+ schema: "agenttwin/world-v1",
2131
+ name: scenario.id,
2132
+ files: ["app.mjs"],
2133
+ command: ["node", "app.mjs"],
2134
+ timeoutSeconds: 1,
2135
+ services: scenario.services,
2136
+ assertions: [{ service: scenario.services[0]?.name, path: scenario.services[0]?.collections?.[0]?.path, count: 0 }]
2137
+ });
2138
+ const ids = /* @__PURE__ */ new Set();
2139
+ for (const entity of scenario.entities) {
2140
+ if (!object2(entity) || typeof entity.id !== "string" || !identifier.test(entity.id) || ids.has(entity.id) || !Array.isArray(entity.refs) || entity.refs.length < 2 || entity.refs.length > 20 || Object.keys(entity).some((k) => !["id", "refs"].includes(k))) fail("entities need unique ids and 2\u201320 cross-service references");
2141
+ ids.add(entity.id);
2142
+ const services = /* @__PURE__ */ new Set();
2143
+ for (const ref of entity.refs) {
2144
+ if (!object2(ref) || typeof ref.service !== "string" || typeof ref.path !== "string" || !object2(ref.where) || !Object.keys(ref.where).length || Object.keys(ref).some((k) => !["service", "path", "where"].includes(k))) fail("entity reference needs service, path and a nonempty where selector");
2145
+ const rows2 = scenario.services.find((s) => s.name === ref.service)?.collections.find((c) => c.path === ref.path)?.seed;
2146
+ if (!rows2 || rows2.filter((row) => Object.entries(ref.where).every(([k, v]) => isDeepStrictEqual4(row[k], v))).length !== 1) fail(`entity ${entity.id} reference must resolve to exactly one seeded record`);
2147
+ services.add(ref.service);
2148
+ }
2149
+ if (services.size < 2) fail(`entity ${entity.id} must link at least two services`);
2150
+ }
2151
+ return structuredClone(scenario);
2152
+ }
2153
+ function reference(ref) {
2154
+ const match = /^([a-z][a-z0-9_]{0,39})@([1-9][0-9]*)$/.exec(ref);
2155
+ if (!match || !Number.isSafeInteger(Number(match[2]))) throw new Error("Scenario reference must be id@version");
2156
+ return { id: match[1], version: Number(match[2]) };
2157
+ }
2158
+ async function loadScenario(cwd, ref) {
2159
+ const { id, version } = reference(ref);
2160
+ const path = join2(cwd, ".agenttwin/scenarios", id, `${version}.json`);
2161
+ const bytes = await readFile(path);
2162
+ if (bytes.length > 2 * 1024 * 1024) throw new Error("Scenario exceeds 2 MiB");
2163
+ const scenario = parseScenario(JSON.parse(bytes.toString()));
2164
+ if (scenario.id !== id || scenario.version !== version) throw new Error("Scenario identity does not match its stored version");
2165
+ return scenario;
2166
+ }
2167
+ function applyScenario(world, scenario) {
2168
+ const shape = (services) => services.map((s) => ({ name: s.name, adapter: s.adapter ?? "json-collection", paths: s.collections.map((c) => c.path).sort() })).sort((a, b) => a.name.localeCompare(b.name));
2169
+ if (!isDeepStrictEqual4(shape(world.services), shape(scenario.services))) throw new Error("Scenario services, adapters and collections must exactly match the world");
2170
+ return parseWorld({ ...world, services: structuredClone(scenario.services), scenario: { id: scenario.id, version: scenario.version, digest: scenarioDigest(scenario) } });
2171
+ }
2172
+
2173
+ // src/runtime/world-session.ts
2174
+ init_contracts();
2175
+
2176
+ // src/commands/run.ts
2177
+ import { mkdtemp as mkdtemp2, mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5, realpath as realpath2, lstat, rm as rm3, copyFile } from "fs/promises";
2178
+ import { tmpdir as tmpdir2 } from "os";
2179
+ import { basename, dirname, isAbsolute, join as join7, relative as relative2, resolve as resolve3, sep } from "path";
2180
+ import { fileURLToPath } from "url";
2181
+ import { createHash as createHash5, randomUUID } from "crypto";
2182
+
2183
+ // src/runtime/credentials.ts
2184
+ import { homedir } from "os";
2185
+ import { join as join3 } from "path";
2186
+ import { readFile as readFile2, mkdir as mkdir2, writeFile as writeFile3, chmod, rm as rm2 } from "fs/promises";
2187
+
2188
+ // src/runtime/remote.ts
2189
+ import { readFile as readFile3 } from "fs/promises";
2190
+ import { join as join4 } from "path";
2191
+
2192
+ // src/lib/exit.ts
2193
+ var EXIT = {
2194
+ OK: 0,
2195
+ ERROR: 1,
2196
+ BLOCKED: 2,
2197
+ USAGE: 3
2198
+ };
2199
+ var CliError = class extends Error {
2200
+ code;
2201
+ action;
2202
+ resume;
2203
+ constructor(message, opts = {}) {
2204
+ super(message);
2205
+ this.name = "CliError";
2206
+ this.code = opts.code ?? EXIT.ERROR;
2207
+ this.action = opts.action;
2208
+ this.resume = opts.resume;
2209
+ }
2210
+ };
2211
+
2212
+ // src/commands/run.ts
2213
+ init_git();
2214
+
2215
+ // src/runtime/e2b.ts
2216
+ import { Sandbox } from "e2b";
2217
+ import { readFile as readFile4 } from "fs/promises";
2218
+ import { randomBytes as randomBytes2 } from "crypto";
2219
+ import { homedir as homedir2 } from "os";
2220
+ import { join as join5 } from "path";
2221
+
2222
+ // src/runtime/matrix.ts
2223
+ import { createHash as createHash4 } from "crypto";
2224
+ import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
2225
+ import { join as join6, relative, resolve as resolve2 } from "path";
2226
+
2227
+ // src/commands/run.ts
2228
+ async function stageApplication(root, files, destination) {
2229
+ const canonicalRoot = await realpath2(root);
2230
+ const digests = {};
2231
+ let bytes = 0;
2232
+ for (const file of files) {
2233
+ if (isAbsolute(file) || file.includes("\\") || file.split("/").some((p) => p === ".." || /^(\.env.*|\.git|\.ssh|\.aws|\.azure|\.config|\.npmrc|\.netrc|credentials.*)$/i.test(p)) || /\.(pem|key|p12|pfx)$/i.test(file)) throw new CliError(`Unsafe application file: ${file}`, { code: EXIT.USAGE });
2234
+ const source = await realpath2(resolve3(canonicalRoot, file));
2235
+ const rel = relative2(canonicalRoot, source);
2236
+ if (rel.startsWith(`..${sep}`) || rel === ".." || isAbsolute(rel) || source !== resolve3(canonicalRoot, file) || !(await lstat(source)).isFile()) throw new CliError(`Files must be regular files within the project, without symlinks: ${file}`, { code: EXIT.USAGE });
2237
+ const contents = await readFile6(source);
2238
+ bytes += contents.length;
2239
+ if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
2240
+ const target = join7(destination, file);
2241
+ await mkdir4(dirname(target), { recursive: true });
2242
+ await writeFile5(target, contents, { mode: 420 });
2243
+ digests[file] = createHash5("sha256").update(contents).digest("hex");
2244
+ }
2245
+ return digests;
2246
+ }
2247
+
2248
+ // src/runtime/world-session.ts
2249
+ init_git();
2250
+ var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
2251
+ var hash = (spec) => createHash6("sha256").update(JSON.stringify(spec)).digest("hex");
2252
+ function duration(value) {
2253
+ if (!Number.isInteger(value) || value < 1 || value > 86400) throw new Error("ttlSeconds must be 1\u201386400");
2254
+ return value;
2255
+ }
2256
+ async function persist(directory2, session) {
2257
+ const temporary = join8(directory2, `${randomUUID2()}.tmp`);
2258
+ await writeFile6(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
2259
+ await rename(temporary, join8(directory2, "session.json"));
2260
+ }
2261
+ var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
2262
+ async function serveWorldSession(directory2) {
2263
+ const session = JSON.parse(await readFile7(join8(directory2, "session.json"), "utf8"));
2264
+ if (session.status !== "provisioning" || !uuid.test(session.id)) throw new Error("Session is not awaiting provisioning");
2265
+ const spec = parseWorld(JSON.parse(await readFile7(join8(directory2, "world.json"), "utf8")));
2266
+ const world = new HttpWorld(spec);
2267
+ let control;
2268
+ let timer;
2269
+ let active;
2270
+ let busy = false;
2271
+ let stopping = false;
2272
+ let shutdownPromise;
2273
+ let saving = Promise.resolve();
2274
+ const save = () => {
2275
+ const snapshot = { ...session };
2276
+ const next = saving.catch(() => {
2277
+ }).then(() => persist(directory2, snapshot));
2278
+ saving = next;
2279
+ return next;
2280
+ };
2281
+ const shutdown = (status) => {
2282
+ if (shutdownPromise) return shutdownPromise;
2283
+ stopping = true;
2284
+ clearTimeout(timer);
2285
+ active?.abort();
2286
+ shutdownPromise = (async () => {
2287
+ session.status = status;
2288
+ session.credentials = void 0;
2289
+ await world.close();
2290
+ if (control) await new Promise((resolve5) => {
2291
+ control.close(() => resolve5());
2292
+ control.closeAllConnections();
2293
+ });
2294
+ await save();
2295
+ })();
2296
+ return shutdownPromise;
2297
+ };
2298
+ const arm = () => {
2299
+ clearTimeout(timer);
2300
+ timer = setTimeout(() => {
2301
+ void shutdown("expired");
2302
+ }, Math.max(1, Date.parse(session.expiresAt) - Date.now()));
2303
+ };
2304
+ try {
2305
+ session.credentials = await world.start();
2306
+ control = createServer2(async (req, res) => {
2307
+ const reply = (status, value) => {
2308
+ if (!res.destroyed) {
2309
+ res.writeHead(status, { "content-type": "application/json" });
2310
+ res.end(JSON.stringify(value));
2311
+ }
2312
+ };
2313
+ if (req.headers.origin || req.headers.authorization !== `Bearer ${session.controlToken}`) {
2314
+ reply(401, { error: "Unauthorized world control request" });
2315
+ return;
2316
+ }
2317
+ if (stopping || Date.now() >= Date.parse(session.expiresAt)) {
2318
+ reply(410, { error: "World expired or terminated" });
2319
+ void shutdown("expired");
2320
+ return;
2321
+ }
2322
+ const action = req.url?.slice(1);
2323
+ if (action === "status" && req.method === "GET") {
2324
+ reply(200, { ...view(session), contracts: operationMatrix(spec) });
2325
+ return;
2326
+ }
2327
+ if (req.method !== "POST" || !["reset", "extend", "run", "teardown"].includes(action ?? "")) {
2328
+ reply(404, { error: "Unknown world control operation" });
2329
+ return;
2330
+ }
2331
+ if (busy && action !== "teardown") {
2332
+ reply(409, { error: "World is busy; wait for the active operation to finish" });
2333
+ return;
2334
+ }
2335
+ busy = true;
2336
+ try {
2337
+ const chunks = [];
2338
+ let bytes = 0;
2339
+ for await (const chunk of req) {
2340
+ bytes += chunk.length;
2341
+ if (bytes > 8192) throw new Error("Control request exceeds 8 KiB");
2342
+ chunks.push(Buffer.from(chunk));
2343
+ }
2344
+ const input = JSON.parse(Buffer.concat(chunks).toString() || "{}");
2345
+ if (!input || typeof input !== "object" || Array.isArray(input) || Object.keys(input).some((k) => action !== "extend" || k !== "ttlSeconds")) throw new Error("Unknown control parameters");
2346
+ if (action === "teardown") {
2347
+ reply(200, { id: session.id, status: "terminated" });
2348
+ setImmediate(() => {
2349
+ void shutdown("terminated");
2350
+ });
2351
+ return;
2352
+ }
2353
+ if (action === "extend") {
2354
+ session.expiresAt = new Date(Date.now() + duration(Number(input.ttlSeconds ?? 3600)) * 1e3).toISOString();
2355
+ await save();
2356
+ if (!stopping) arm();
2357
+ reply(200, view(session));
2358
+ return;
2359
+ }
2360
+ if (action === "reset") {
2361
+ world.reset();
2362
+ reply(200, { ...view(session), state: world.snapshot() });
2363
+ return;
2364
+ }
2365
+ let current = parseWorld(JSON.parse(await readFile7(session.file, "utf8")));
2366
+ if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
2367
+ if (hash(current) !== hash(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
2368
+ const stage = await mkdtemp3(join8(tmpdir3(), "agenttwin-session-run-"));
2369
+ active = new AbortController();
2370
+ let result;
2371
+ try {
2372
+ if (stopping) throw new Error("World expired during execution");
2373
+ session.status = "running";
2374
+ await save();
2375
+ active.signal.throwIfAborted();
2376
+ const sourceDigests = await stageApplication(dirname2(session.file), spec.files, stage);
2377
+ active.signal.throwIfAborted();
2378
+ world.reset();
2379
+ const report = await executeLocal(stage, spec, active.signal, world);
2380
+ if (stopping) throw new Error("World expired during execution");
2381
+ const runId = randomUUID2();
2382
+ let project = "local-workspace";
2383
+ try {
2384
+ project = JSON.parse(await readFile7(join8(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
2385
+ } catch {
2386
+ }
2387
+ const receipt = { ...report, sourceDirectory: relative3(session.cwd, dirname2(session.file)).split(sep2).join("/"), runId, worldId: session.id, runtime: "local", project, git: await captureGit(session.cwd), createdAt: (/* @__PURE__ */ new Date()).toISOString(), sourceDigests, specDigest: hash(spec), provenance: "CLI-reported execution; not independently attested" };
2388
+ const out = join8(session.cwd, ".agenttwin/runs", runId);
2389
+ await mkdir5(out, { recursive: true, mode: 448 });
2390
+ const evidencePath = join8(out, "run.json");
2391
+ await writeFile6(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
2392
+ await writeFile6(join8(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
2393
+ session.lastRunId = runId;
2394
+ result = { ...receipt, evidencePath };
2395
+ } finally {
2396
+ active = void 0;
2397
+ await rm4(stage, { recursive: true, force: true });
2398
+ if (!stopping) {
2399
+ session.status = "ready";
2400
+ await save();
2401
+ }
2402
+ }
2403
+ reply(200, result);
2404
+ } catch (error) {
2405
+ reply(400, { error: error instanceof Error ? error.message : "World operation failed" });
2406
+ } finally {
2407
+ busy = false;
2408
+ }
2409
+ });
2410
+ control.requestTimeout = 1e4;
2411
+ await new Promise((resolve5, reject) => {
2412
+ control.once("error", reject);
2413
+ control.listen(0, "127.0.0.1", resolve5);
2414
+ });
2415
+ const latest = JSON.parse(await readFile7(join8(directory2, "session.json"), "utf8"));
2416
+ if (latest.status !== "provisioning") throw new Error("Provisioning was abandoned");
2417
+ session.controlUrl = `http://127.0.0.1:${control.address().port}`;
2418
+ if (stopping) throw new Error("World expired during provisioning");
2419
+ session.status = "ready";
2420
+ await save();
2421
+ if (!stopping) arm();
2422
+ return { session: view(session), close: () => shutdown("terminated") };
2423
+ } catch (error) {
2424
+ session.error = error instanceof Error ? error.message : "Provisioning failed";
2425
+ await shutdown("failed");
2426
+ throw error;
2427
+ }
2428
+ }
2429
+
2430
+ // src/runtime/world-host.ts
2431
+ var directory = process.argv[2];
2432
+ if (!directory) throw new Error("World host requires a session directory");
2433
+ serveWorldSession(directory).then((host) => {
2434
+ const stop = () => {
2435
+ void host.close();
2436
+ };
2437
+ process.once("SIGTERM", stop);
2438
+ process.once("SIGINT", stop);
2439
+ }).catch((error) => {
2440
+ process.stderr.write(String(error) + "\n");
2441
+ process.exitCode = 1;
2442
+ });