agenttwin 0.3.7 → 0.3.9
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.
- package/README.md +4 -1
- package/dist/api.js +1985 -206
- package/dist/cli.js +3404 -425
- package/dist/dashboard/assets/next/static/chunks/787-2d5f834d2374e355.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/848-000d4eb3e2f5358f.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-762d3d9f26e6c774.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-4edbabcdd90d97e8.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-018bb6762d3d7df4.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-39cdf1f2e2ba688f.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/{page-df1d4cae513d5eed.js → page-02aaf1666f32d5c1.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/app/pricing/page-f6fb7e78443d1220.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-d23686e9489aa12d.js +1 -0
- package/dist/dashboard/assets/next/static/chunks/app/v2/{page-ca672c49c2235ce2.js → page-c8aaddcc7111e5e3.js} +1 -1
- package/dist/dashboard/assets/next/static/chunks/{webpack-29cc60ad58d8aefe.js → webpack-7acd0493fe574225.js} +1 -1
- package/dist/dashboard/assets/next/static/css/{0071f19b19d3d0c1.css → 556c40e9d291ee02.css} +1 -1
- package/dist/dashboard/assets/next/static/css/ec9722ff890f136c.css +1 -0
- package/dist/dashboard/assets/next/static/css/f9c2780fff15fd22.css +1 -0
- package/dist/dashboard/assets/next/static/xDiek0iCt0gykeKT7O5aO/_buildManifest.js +1 -0
- package/dist/dashboard/index.html +16 -1
- package/dist/gateway.js +2020 -210
- package/dist/worker.js +1426 -63
- package/dist/world-host.js +1472 -111
- package/package.json +1 -1
- package/dist/dashboard/assets/next/static/P_sIw5q7daW7e4IJEGveg/_buildManifest.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/549-f8859485ba130d9c.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/787-e53be69d23ff02f5.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-a11f5eeef34fdff9.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-df1468fc904db4f7.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-e58bc195fd4bc31c.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/pricing/page-21130c3524f7e45e.js +0 -1
- package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-04e82fd8f3044022.js +0 -1
- package/dist/dashboard/assets/next/static/css/98cc7bbbb43b84df.css +0 -1
- /package/dist/dashboard/assets/next/static/{P_sIw5q7daW7e4IJEGveg → xDiek0iCt0gykeKT7O5aO}/_ssgManifest.js +0 -0
package/dist/world-host.js
CHANGED
|
@@ -14,7 +14,7 @@ function operationMatrix(spec) {
|
|
|
14
14
|
name: s.name,
|
|
15
15
|
adapter: s.adapter ?? "json-collection",
|
|
16
16
|
version: CONTRACTS[s.adapter ?? "json-collection"].version,
|
|
17
|
-
operations: s.adapter === "slack" ? CONTRACTS.slack.operations : s.adapter === "stripe" ? CONTRACTS.stripe.operations : s.collections.flatMap((c) => CONTRACTS["json-collection"].operations.map((op) => ({ ...op, endpoint: c.path })))
|
|
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
18
|
})) ?? []
|
|
19
19
|
};
|
|
20
20
|
}
|
|
@@ -53,6 +53,187 @@ var init_contracts = __esm({
|
|
|
53
53
|
{ method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
|
|
54
54
|
],
|
|
55
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"]
|
|
56
237
|
}
|
|
57
238
|
};
|
|
58
239
|
}
|
|
@@ -76,8 +257,8 @@ async function captureGit(cwd, previousHead) {
|
|
|
76
257
|
}
|
|
77
258
|
}
|
|
78
259
|
return { head, branch: branch || "detached HEAD", totalCommits: Number(total), dirty: !!status, capturedAt: (/* @__PURE__ */ new Date()).toISOString(), commits: history ? history.split("\n").map((line) => {
|
|
79
|
-
const [
|
|
80
|
-
return { sha, date };
|
|
260
|
+
const [sha2, date] = line.split(" ");
|
|
261
|
+
return { sha: sha2, date };
|
|
81
262
|
}) : [], changedFiles: [...new Set(changed.split("\n").filter(Boolean))].slice(0, 1e3), ...previousHead ? { previousHead } : {} };
|
|
82
263
|
} catch {
|
|
83
264
|
return void 0;
|
|
@@ -91,16 +272,15 @@ var init_git = __esm({
|
|
|
91
272
|
|
|
92
273
|
// src/runtime/world-session.ts
|
|
93
274
|
import { createServer as createServer2 } from "http";
|
|
94
|
-
import { randomBytes as randomBytes3, randomUUID as randomUUID2, createHash as
|
|
95
|
-
import { mkdir as
|
|
96
|
-
import { dirname as dirname2, join as
|
|
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";
|
|
97
278
|
import { tmpdir as tmpdir3 } from "os";
|
|
98
279
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
99
280
|
import { spawn as spawn2 } from "child_process";
|
|
100
281
|
|
|
101
282
|
// src/runtime/http-world.ts
|
|
102
283
|
import { createServer } from "http";
|
|
103
|
-
import { randomBytes } from "crypto";
|
|
104
284
|
import { isDeepStrictEqual } from "util";
|
|
105
285
|
import { AsyncLocalStorage } from "async_hooks";
|
|
106
286
|
|
|
@@ -141,20 +321,20 @@ function stripeOperation(method, path, params, data, sequence) {
|
|
|
141
321
|
const error = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
|
|
142
322
|
const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path);
|
|
143
323
|
if (!match || !["GET", "POST"].includes(method)) return void 0;
|
|
144
|
-
const [, resource, id, action] = match, collection = `/v1/${resource}`,
|
|
324
|
+
const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
|
|
145
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;
|
|
146
326
|
if (!allowed || resource === "customers" && action || resource === "payment_intents" && method === "GET" && !id) return void 0;
|
|
147
327
|
if (Object.keys(params).some((k) => !allowed.includes(k))) return void 0;
|
|
148
328
|
if (method === "GET" && !id) {
|
|
149
329
|
const limit = params.limit === void 0 ? 10 : Number(params.limit);
|
|
150
330
|
if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...error(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
|
|
151
|
-
const ordered = [...
|
|
331
|
+
const ordered = [...rows2].reverse();
|
|
152
332
|
const index = params.starting_after === void 0 ? -1 : ordered.findIndex((r) => r.id === params.starting_after);
|
|
153
333
|
if (params.starting_after !== void 0 && index === -1) return { ...error(400, "resource_missing", "No such starting_after customer", "starting_after"), collection };
|
|
154
334
|
const page = ordered.slice(index + 1, index + 1 + limit);
|
|
155
335
|
return { status: 200, body: { object: "list", data: page, has_more: ordered.length > index + 1 + limit, url: collection }, collection, operation: "read" };
|
|
156
336
|
}
|
|
157
|
-
const row = id ?
|
|
337
|
+
const row = id ? rows2.find((r) => r.id === id) : void 0;
|
|
158
338
|
if (id && !row) return { ...error(404, "resource_missing", `No such ${resource}: '${id}'`), collection };
|
|
159
339
|
if (method === "GET") return { status: 200, body: row, collection, operation: "read" };
|
|
160
340
|
if (action === "confirm") {
|
|
@@ -168,11 +348,11 @@ function stripeOperation(method, path, params, data, sequence) {
|
|
|
168
348
|
}
|
|
169
349
|
const prefix = resource === "customers" ? "cus" : "pi";
|
|
170
350
|
let suffix = sequence;
|
|
171
|
-
while (
|
|
172
|
-
const
|
|
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 };
|
|
173
353
|
if (resource === "customers") {
|
|
174
354
|
if (params.email !== void 0 && typeof params.email !== "string") return { ...error(400, "parameter_invalid", "email must be a string", "email"), collection };
|
|
175
|
-
Object.assign(
|
|
355
|
+
Object.assign(created2, { email: null, name: null, description: null, ...params });
|
|
176
356
|
} else {
|
|
177
357
|
const amount = Number(params.amount);
|
|
178
358
|
if (!Number.isSafeInteger(amount) || amount < 1) return { ...error(400, "parameter_invalid_integer", "amount must be a positive integer", "amount"), collection };
|
|
@@ -182,27 +362,975 @@ function stripeOperation(method, path, params, data, sequence) {
|
|
|
182
362
|
if (params.confirm !== void 0 && !["true", "false", true, false].includes(params.confirm)) return { ...error(400, "parameter_invalid", "confirm must be boolean", "confirm"), collection };
|
|
183
363
|
const confirm = params.confirm === "true" || params.confirm === true;
|
|
184
364
|
if (confirm && !params.payment_method) return { ...error(400, "parameter_missing", "Missing payment_method", "payment_method"), collection };
|
|
185
|
-
Object.assign(
|
|
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 });
|
|
186
366
|
}
|
|
187
|
-
if (
|
|
188
|
-
|
|
367
|
+
if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
|
|
368
|
+
rows2.push(created2);
|
|
189
369
|
const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
|
|
190
|
-
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(
|
|
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);
|
|
191
1314
|
}
|
|
192
1315
|
|
|
193
1316
|
// src/runtime/http-world.ts
|
|
194
1317
|
var HttpWorld = class {
|
|
195
|
-
constructor(spec) {
|
|
1318
|
+
constructor(spec, seed) {
|
|
196
1319
|
this.spec = spec;
|
|
1320
|
+
this.seed = normalizeSeed(seed);
|
|
197
1321
|
}
|
|
198
1322
|
spec;
|
|
199
1323
|
events = [];
|
|
200
1324
|
state = /* @__PURE__ */ Object.create(null);
|
|
201
1325
|
credentials = /* @__PURE__ */ Object.create(null);
|
|
202
1326
|
unsupported = [];
|
|
1327
|
+
/** The run seed that governed every seeded twin-side decision in this world instance. */
|
|
1328
|
+
seed;
|
|
203
1329
|
servers = [];
|
|
204
1330
|
timers = /* @__PURE__ */ new Set();
|
|
205
1331
|
fired = false;
|
|
1332
|
+
faultActions = 0;
|
|
1333
|
+
candidateCounts = /* @__PURE__ */ new Map();
|
|
206
1334
|
epoch = 0;
|
|
207
1335
|
replayKeys = /* @__PURE__ */ new Map();
|
|
208
1336
|
sourceContext = new AsyncLocalStorage();
|
|
@@ -215,15 +1343,29 @@ var HttpWorld = class {
|
|
|
215
1343
|
this.unsupported.push(`${service}: ${method} ${path}: ${detail}`);
|
|
216
1344
|
this.record(service, "unsupported", path, detail);
|
|
217
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
|
+
}
|
|
218
1352
|
async start() {
|
|
219
1353
|
if (this.servers.length) throw new Error("World is already started");
|
|
1354
|
+
const fault = this.spec.fault;
|
|
220
1355
|
for (const service of this.spec.services) {
|
|
221
|
-
const token = `at_world_${
|
|
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;
|
|
222
1362
|
const data = /* @__PURE__ */ Object.create(null);
|
|
223
1363
|
this.state[service.name] = data;
|
|
224
1364
|
for (const c of service.collections) data[c.path] = structuredClone(c.seed);
|
|
225
1365
|
const keys = /* @__PURE__ */ new Map();
|
|
226
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;
|
|
227
1369
|
const server = createServer((req, res) => this.sourceContext.run(parseRequestSource(req.headers["x-agenttwin-source"], this.spec), async () => {
|
|
228
1370
|
const epoch = this.epoch;
|
|
229
1371
|
const send = (code, body) => {
|
|
@@ -232,14 +1374,68 @@ var HttpWorld = class {
|
|
|
232
1374
|
res.end(JSON.stringify(body));
|
|
233
1375
|
}
|
|
234
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
|
+
};
|
|
235
1410
|
try {
|
|
236
|
-
if (req.headers.authorization !== `Bearer ${token}`) {
|
|
1411
|
+
if (req.headers.authorization !== `Bearer ${token}` && !altAuth(req.headers)) {
|
|
237
1412
|
this.record(service.name, "auth-denied", req.url ?? "", "invalid test credential");
|
|
238
|
-
|
|
1413
|
+
respond(401, { error: "invalid_test_credential" });
|
|
239
1414
|
return;
|
|
240
1415
|
}
|
|
241
1416
|
if (this.events.length >= 5e4 || this.unsupported.length >= 1e3) {
|
|
242
|
-
|
|
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);
|
|
243
1439
|
return;
|
|
244
1440
|
}
|
|
245
1441
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
@@ -247,13 +1443,13 @@ var HttpWorld = class {
|
|
|
247
1443
|
const slack = service.adapter === "slack";
|
|
248
1444
|
const slackMethod = path.replace(/^\/api\//, "");
|
|
249
1445
|
let payload;
|
|
250
|
-
if (req.method
|
|
1446
|
+
if (["POST", "PUT", "PATCH"].includes(req.method ?? "")) {
|
|
251
1447
|
const chunks = [];
|
|
252
1448
|
let bytes = 0;
|
|
253
1449
|
for await (const chunk of req) {
|
|
254
1450
|
bytes += chunk.length;
|
|
255
1451
|
if (bytes > 1024 * 1024) {
|
|
256
|
-
|
|
1452
|
+
respond(413, { error: "body_too_large" });
|
|
257
1453
|
return;
|
|
258
1454
|
}
|
|
259
1455
|
chunks.push(Buffer.from(chunk));
|
|
@@ -263,20 +1459,20 @@ var HttpWorld = class {
|
|
|
263
1459
|
try {
|
|
264
1460
|
parsed = (slack || service.adapter === "stripe") && req.headers["content-type"]?.startsWith("application/x-www-form-urlencoded") ? Object.fromEntries(new URLSearchParams(text)) : JSON.parse(text);
|
|
265
1461
|
} catch {
|
|
266
|
-
|
|
1462
|
+
respond(400, { error: "expected_json_object" });
|
|
267
1463
|
return;
|
|
268
1464
|
}
|
|
269
1465
|
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
270
|
-
|
|
1466
|
+
respond(400, { error: "expected_json_object" });
|
|
271
1467
|
return;
|
|
272
1468
|
}
|
|
273
1469
|
payload = parsed;
|
|
274
1470
|
}
|
|
275
1471
|
if (epoch !== this.epoch) {
|
|
276
|
-
|
|
1472
|
+
respond(409, { error: "world_reset" });
|
|
277
1473
|
return;
|
|
278
1474
|
}
|
|
279
|
-
if (service.adapter === "stripe") {
|
|
1475
|
+
if (service.adapter === "stripe" || restAdapter) {
|
|
280
1476
|
const params = payload ?? Object.fromEntries(url.searchParams);
|
|
281
1477
|
const keyHeader2 = req.headers["idempotency-key"];
|
|
282
1478
|
const key2 = req.method === "POST" && typeof keyHeader2 === "string" ? `${path}:${keyHeader2}` : void 0;
|
|
@@ -284,31 +1480,45 @@ var HttpWorld = class {
|
|
|
284
1480
|
const previous2 = key2 ? keys.get(key2) : void 0;
|
|
285
1481
|
if (previous2) {
|
|
286
1482
|
if (previous2.body !== signature2) {
|
|
287
|
-
|
|
1483
|
+
respond(400, { error: { type: "idempotency_error", message: "Keys for idempotent requests can only be used with the same parameters" } });
|
|
288
1484
|
return;
|
|
289
1485
|
}
|
|
290
1486
|
this.record(service.name, "replay", path, "same-key response replay", previous2.record);
|
|
291
|
-
|
|
1487
|
+
respond(previous2.status ?? 200, previous2.record);
|
|
292
1488
|
return;
|
|
293
1489
|
}
|
|
294
|
-
const result = stripeOperation(req.method ?? "", path, params, data, this.events.length + 1);
|
|
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);
|
|
295
1491
|
if (!result) {
|
|
296
|
-
this.rejectUnsupported(service.name, req.method ?? "", path,
|
|
297
|
-
|
|
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 });
|
|
298
1494
|
return;
|
|
299
1495
|
}
|
|
300
1496
|
if (result.operation) this.record(service.name, result.operation, result.collection, path, "record" in result ? result.record : result.body);
|
|
301
|
-
if (key2 && result.status === 200) keys.set(key2, { body: signature2, record: structuredClone(result.body) });
|
|
302
|
-
const
|
|
303
|
-
|
|
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) {
|
|
304
1513
|
this.fired = true;
|
|
305
|
-
this.
|
|
1514
|
+
this.faultActions++;
|
|
1515
|
+
this.record(service.name, "fault", result.collection, `write committed; response delayed ${fault.delayMs}ms`);
|
|
306
1516
|
const timer = setTimeout(() => {
|
|
307
1517
|
this.timers.delete(timer);
|
|
308
|
-
|
|
309
|
-
},
|
|
1518
|
+
respond(result.status, result.body);
|
|
1519
|
+
}, fault.delayMs);
|
|
310
1520
|
this.timers.add(timer);
|
|
311
|
-
} else
|
|
1521
|
+
} else respond(result.status, result.body);
|
|
312
1522
|
return;
|
|
313
1523
|
}
|
|
314
1524
|
if (slack) {
|
|
@@ -316,7 +1526,7 @@ var HttpWorld = class {
|
|
|
316
1526
|
const allowed = slackMethod === "chat.postMessage" ? ["channel", "text"] : slackMethod === "conversations.history" ? ["channel"] : [];
|
|
317
1527
|
if (Object.keys(params).some((k) => !allowed.includes(k))) {
|
|
318
1528
|
this.rejectUnsupported(service.name, req.method ?? "", url.pathname, `unsupported parameters for ${slackMethod}`);
|
|
319
|
-
|
|
1529
|
+
respond(501, { ok: false, error: "unsupported_parameters", forwardedToProduction: false });
|
|
320
1530
|
return;
|
|
321
1531
|
}
|
|
322
1532
|
if (slackMethod === "chat.postMessage" && req.method === "POST") path = "/messages";
|
|
@@ -324,39 +1534,39 @@ var HttpWorld = class {
|
|
|
324
1534
|
else if (slackMethod === "conversations.list" && ["GET", "POST"].includes(req.method ?? "")) path = "/channels";
|
|
325
1535
|
else {
|
|
326
1536
|
this.rejectUnsupported(service.name, req.method ?? "", url.pathname, "unsupported operation");
|
|
327
|
-
|
|
1537
|
+
respond(501, { ok: false, error: "unsupported_operation", forwardedToProduction: false });
|
|
328
1538
|
return;
|
|
329
1539
|
}
|
|
330
1540
|
}
|
|
331
1541
|
if (!Object.hasOwn(data, path) || !["GET", "POST"].includes(req.method ?? "")) {
|
|
332
1542
|
this.rejectUnsupported(service.name, req.method ?? "", path, "unsupported operation");
|
|
333
|
-
|
|
1543
|
+
respond(501, { error: "unsupported_operation", forwardedToProduction: false });
|
|
334
1544
|
return;
|
|
335
1545
|
}
|
|
336
1546
|
if (req.method === "GET" || slack && slackMethod !== "chat.postMessage") {
|
|
337
1547
|
this.record(service.name, "read", path, `${data[path].length} records`);
|
|
338
|
-
if (slack && path === "/channels")
|
|
1548
|
+
if (slack && path === "/channels") respond(200, { ok: true, channels: data[path], response_metadata: { next_cursor: "" } });
|
|
339
1549
|
else if (slack) {
|
|
340
1550
|
const channel = payload?.channel ?? url.searchParams.get("channel");
|
|
341
|
-
if (!data["/channels"].some((c) => c.id === channel))
|
|
342
|
-
else
|
|
343
|
-
} else
|
|
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] });
|
|
344
1554
|
return;
|
|
345
1555
|
}
|
|
346
1556
|
const body = payload;
|
|
347
1557
|
if (slack) {
|
|
348
1558
|
const message = body;
|
|
349
1559
|
if (!data["/channels"].some((c) => c.id === message.channel)) {
|
|
350
|
-
|
|
1560
|
+
respond(200, { ok: false, error: "channel_not_found" });
|
|
351
1561
|
return;
|
|
352
1562
|
}
|
|
353
1563
|
if (typeof message.text !== "string" || !message.text) {
|
|
354
|
-
|
|
1564
|
+
respond(200, { ok: false, error: "no_text" });
|
|
355
1565
|
return;
|
|
356
1566
|
}
|
|
357
1567
|
}
|
|
358
1568
|
if (data[path].length >= 1e4 || this.events.length >= 5e4) {
|
|
359
|
-
|
|
1569
|
+
respond(429, { error: "world_capacity" });
|
|
360
1570
|
return;
|
|
361
1571
|
}
|
|
362
1572
|
const keyHeader = slack ? void 0 : req.headers["idempotency-key"];
|
|
@@ -365,13 +1575,15 @@ var HttpWorld = class {
|
|
|
365
1575
|
const previous = key ? keys.get(key) : void 0;
|
|
366
1576
|
if (previous) {
|
|
367
1577
|
if (previous.body !== signature) {
|
|
368
|
-
|
|
1578
|
+
respond(409, { error: "idempotency_conflict" });
|
|
369
1579
|
return;
|
|
370
1580
|
}
|
|
371
1581
|
this.record(service.name, "replay", path, "same-key response replay", previous.record);
|
|
372
|
-
|
|
1582
|
+
respond(200, previous.record);
|
|
373
1583
|
return;
|
|
374
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++;
|
|
375
1587
|
let index = data[path].length + 1;
|
|
376
1588
|
while (data[path].some((r) => r.id === `${service.name}_${index}`)) index++;
|
|
377
1589
|
const row = { ...body, id: `${service.name}_${index}` };
|
|
@@ -380,24 +1592,34 @@ var HttpWorld = class {
|
|
|
380
1592
|
data[path].push(row);
|
|
381
1593
|
if (key) keys.set(key, { body: signature, record: row });
|
|
382
1594
|
this.record(service.name, "write", path, String(row.id), row);
|
|
383
|
-
|
|
384
|
-
|
|
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) {
|
|
385
1606
|
this.fired = true;
|
|
1607
|
+
this.faultActions++;
|
|
386
1608
|
this.record(service.name, "fault", path, `write committed; response delayed ${fault.delayMs}ms`);
|
|
387
1609
|
const timer = setTimeout(() => {
|
|
388
1610
|
this.timers.delete(timer);
|
|
389
|
-
|
|
1611
|
+
respond(faultResponse, reply);
|
|
390
1612
|
}, fault.delayMs);
|
|
391
1613
|
this.timers.add(timer);
|
|
392
|
-
} else
|
|
1614
|
+
} else respond(faultResponse, reply);
|
|
393
1615
|
} catch {
|
|
394
|
-
|
|
1616
|
+
respond(500, { error: "world_request_error" });
|
|
395
1617
|
}
|
|
396
1618
|
}));
|
|
397
1619
|
server.requestTimeout = 1e4;
|
|
398
|
-
await new Promise((
|
|
1620
|
+
await new Promise((resolve5, reject) => {
|
|
399
1621
|
server.once("error", reject);
|
|
400
|
-
server.listen(0, "127.0.0.1",
|
|
1622
|
+
server.listen(0, "127.0.0.1", resolve5);
|
|
401
1623
|
});
|
|
402
1624
|
this.servers.push(server);
|
|
403
1625
|
this.credentials[service.name] = { endpoint: `http://127.0.0.1:${server.address().port}`, token };
|
|
@@ -406,12 +1628,12 @@ var HttpWorld = class {
|
|
|
406
1628
|
}
|
|
407
1629
|
assertions() {
|
|
408
1630
|
return this.spec.assertions.map((a) => {
|
|
409
|
-
const
|
|
410
|
-
return { ...a, actual:
|
|
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 };
|
|
411
1633
|
});
|
|
412
1634
|
}
|
|
413
1635
|
get faultTriggered() {
|
|
414
|
-
return this.
|
|
1636
|
+
return this.faultActions > 0;
|
|
415
1637
|
}
|
|
416
1638
|
snapshot() {
|
|
417
1639
|
return structuredClone(this.state);
|
|
@@ -431,14 +1653,16 @@ var HttpWorld = class {
|
|
|
431
1653
|
this.events.length = 0;
|
|
432
1654
|
this.unsupported.length = 0;
|
|
433
1655
|
this.fired = false;
|
|
1656
|
+
this.faultActions = 0;
|
|
1657
|
+
this.candidateCounts.clear();
|
|
434
1658
|
return this.snapshot();
|
|
435
1659
|
}
|
|
436
1660
|
async close() {
|
|
437
1661
|
this.epoch++;
|
|
438
1662
|
for (const timer of this.timers) clearTimeout(timer);
|
|
439
1663
|
this.timers.clear();
|
|
440
|
-
await Promise.all(this.servers.map((server) => new Promise((
|
|
441
|
-
server.close(() =>
|
|
1664
|
+
await Promise.all(this.servers.map((server) => new Promise((resolve5) => {
|
|
1665
|
+
server.close(() => resolve5());
|
|
442
1666
|
server.closeAllConnections();
|
|
443
1667
|
})));
|
|
444
1668
|
this.servers.length = 0;
|
|
@@ -578,18 +1802,73 @@ function evaluateState(spec, initial, final, events) {
|
|
|
578
1802
|
evidence: { initial: `/initialState/${escape(policy.service)}/${escape(policy.path)}`, final: `/finalState/${escape(policy.service)}/${escape(policy.path)}` }
|
|
579
1803
|
};
|
|
580
1804
|
});
|
|
1805
|
+
const properties = (spec.properties ?? []).map((policy) => evaluateProperty(policy, final, events));
|
|
581
1806
|
const taskPassed = checks.every((c) => c.passed);
|
|
582
|
-
const safe = [...forbidden, ...preserved].every((c) => c.passed);
|
|
583
|
-
return { schema: "agenttwin/evaluation-v1", outcome: !safe ? "unsafe" : taskPassed ? "passed" : "failed", taskPassed, safe, checks: [...checks, ...forbidden, ...preserved] };
|
|
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
|
+
};
|
|
584
1863
|
}
|
|
585
1864
|
var escape = (value) => value.replace(/~/g, "~0").replace(/\//g, "~1");
|
|
586
1865
|
|
|
587
1866
|
// src/runtime/local.ts
|
|
588
1867
|
init_contracts();
|
|
589
|
-
async function executeLocal(app, spec, signal, existingWorld) {
|
|
1868
|
+
async function executeLocal(app, spec, signal, existingWorld, seed) {
|
|
590
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.");
|
|
591
1870
|
signal?.throwIfAborted();
|
|
592
|
-
const world = existingWorld ?? new HttpWorld(spec), started = Date.now();
|
|
1871
|
+
const world = existingWorld ?? new HttpWorld(spec, seed), started = Date.now();
|
|
593
1872
|
try {
|
|
594
1873
|
const credentials = existingWorld ? world.credentials : await world.start();
|
|
595
1874
|
const initialState = world.snapshot();
|
|
@@ -626,9 +1905,9 @@ async function executeLocal(app, spec, signal, existingWorld) {
|
|
|
626
1905
|
executionAbort.abort();
|
|
627
1906
|
kill();
|
|
628
1907
|
}, spec.timeoutSeconds * 1e3);
|
|
629
|
-
const completion = new Promise((
|
|
1908
|
+
const completion = new Promise((resolve5, reject) => {
|
|
630
1909
|
child.once("error", reject);
|
|
631
|
-
child.once("close",
|
|
1910
|
+
child.once("close", resolve5);
|
|
632
1911
|
});
|
|
633
1912
|
let browser, background, executionError;
|
|
634
1913
|
let exitCode;
|
|
@@ -666,7 +1945,7 @@ async function executeLocal(app, spec, signal, existingWorld) {
|
|
|
666
1945
|
const assertions = world.assertions();
|
|
667
1946
|
const evaluation = evaluateState(spec, initialState, world.state, world.events);
|
|
668
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";
|
|
669
|
-
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, 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" } };
|
|
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" } };
|
|
670
1949
|
} finally {
|
|
671
1950
|
if (existingWorld) world.quiesce();
|
|
672
1951
|
else await world.close();
|
|
@@ -674,8 +1953,28 @@ async function executeLocal(app, spec, signal, existingWorld) {
|
|
|
674
1953
|
}
|
|
675
1954
|
|
|
676
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"];
|
|
677
1975
|
var object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
678
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;
|
|
679
1978
|
function parseWorld(value) {
|
|
680
1979
|
const invalid = (message) => {
|
|
681
1980
|
throw new Error(`Invalid world: ${message}`);
|
|
@@ -694,7 +1993,7 @@ function parseWorld(value) {
|
|
|
694
1993
|
if (!object(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
|
|
695
1994
|
const item = service;
|
|
696
1995
|
if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
|
|
697
|
-
if (item.adapter !== void 0 && !["json-collection", "slack", "stripe"].includes(String(item.adapter))) invalid("unsupported service adapter");
|
|
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");
|
|
698
1997
|
const paths = /* @__PURE__ */ new Set();
|
|
699
1998
|
for (const entry of item.collections) {
|
|
700
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");
|
|
@@ -702,8 +2001,8 @@ function parseWorld(value) {
|
|
|
702
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");
|
|
703
2002
|
paths.add(collection.path);
|
|
704
2003
|
}
|
|
705
|
-
|
|
706
|
-
if (
|
|
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`);
|
|
707
2006
|
services.set(item.name, paths);
|
|
708
2007
|
}
|
|
709
2008
|
const known = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
|
|
@@ -736,7 +2035,64 @@ function parseWorld(value) {
|
|
|
736
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");
|
|
737
2036
|
}
|
|
738
2037
|
}
|
|
739
|
-
if (v.
|
|
2038
|
+
if (v.faults !== void 0) {
|
|
2039
|
+
if (!object(v.faults) || Object.keys(v.faults).length > 16) invalid("faults must contain at most 16 named fault presets");
|
|
2040
|
+
for (const [name, fault] of Object.entries(v.faults)) {
|
|
2041
|
+
if (!/^[a-z][a-z0-9_-]{0,63}$/.test(name) || ["none", "configured"].includes(name)) invalid("fault preset names must be lowercase identifiers; none and configured are reserved");
|
|
2042
|
+
const { faults: _presets, ...base } = v;
|
|
2043
|
+
parseWorld({ ...base, fault });
|
|
2044
|
+
if (fault === void 0) invalid("fault presets require a fault definition");
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
if (v.fault !== void 0) {
|
|
2048
|
+
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");
|
|
2049
|
+
const f = v.fault;
|
|
2050
|
+
const allowed = ["service", "path", "type"];
|
|
2051
|
+
const count = f.count, windowMs = f.windowMs;
|
|
2052
|
+
if (f.type === "timeout-after-write") {
|
|
2053
|
+
if (!inRangeInt(f.delayMs, 1, 1e4)) invalid("timeout-after-write fault requires delayMs 1\u201310000; the delay is declared application-visible behavior, never seeded");
|
|
2054
|
+
allowed.push("delayMs");
|
|
2055
|
+
} else if (f.delayMs !== void 0) invalid(`${f.type} fault does not take delayMs`);
|
|
2056
|
+
if (f.type === "server-error") {
|
|
2057
|
+
if (!inRangeInt(count, 1, 100)) invalid("server-error fault requires count 1\u2013100 (how many matching requests are rejected)");
|
|
2058
|
+
if (windowMs !== void 0 && !inRangeInt(windowMs, 0, 1e4)) invalid("server-error windowMs must be 0\u201310000 (the seeded upper delay before the rejection response)");
|
|
2059
|
+
allowed.push("count", "windowMs");
|
|
2060
|
+
} else {
|
|
2061
|
+
if (!["blackhole", "duplicate-write"].includes(f.type) && windowMs !== void 0) invalid(`${f.type} fault does not take windowMs`);
|
|
2062
|
+
if (["blackhole", "duplicate-write"].includes(f.type) && count !== void 0 && !inRangeInt(count, 1, 100)) invalid(`${f.type} fault count must be 1\u2013100`);
|
|
2063
|
+
if (["blackhole", "duplicate-write"].includes(f.type)) allowed.push("count");
|
|
2064
|
+
}
|
|
2065
|
+
if (Object.keys(f).some((k) => !allowed.includes(k))) invalid(`unknown fault field for ${f.type}`);
|
|
2066
|
+
}
|
|
2067
|
+
if (v.properties !== void 0) {
|
|
2068
|
+
if (!Array.isArray(v.properties) || !v.properties.length || v.properties.length > 50) invalid("properties must contain 1\u201350 named invariants");
|
|
2069
|
+
for (const raw of v.properties) {
|
|
2070
|
+
const p = raw;
|
|
2071
|
+
if (!p || !known(p)) invalid("properties need existing service/path collections and closed kinds");
|
|
2072
|
+
if (typeof p.id !== "string" || !namePattern.test(p.id)) invalid("property id must be a lowercase identifier");
|
|
2073
|
+
if (policyIds.has(p.id)) invalid("property ids must be unique ids across the world's policies");
|
|
2074
|
+
if (!PROPERTY_KINDS.includes(p.kind)) invalid(`unknown property kind: use one of ${PROPERTY_KINDS.join(", ")}`);
|
|
2075
|
+
const params = object(p.params) ? p.params : {};
|
|
2076
|
+
if (p.kind === "unique-per-act") {
|
|
2077
|
+
const field = params.field;
|
|
2078
|
+
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`);
|
|
2079
|
+
} else if (p.kind === "no-loss") {
|
|
2080
|
+
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`);
|
|
2081
|
+
} else {
|
|
2082
|
+
if (!object(params) || !inRangeInt(params.count, 0, 1e5)) invalid(`property "${p.id}" (effect-count) requires params.count 0\u2013100000`);
|
|
2083
|
+
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`);
|
|
2084
|
+
if (params.where !== void 0 && !object(params.where)) invalid(`property "${p.id}" (effect-count) params.where must be an object`);
|
|
2085
|
+
if (Object.keys(params).some((k) => !["count", "operation", "where"].includes(k))) invalid(`property "${p.id}" (effect-count) takes only count, operation and where`);
|
|
2086
|
+
}
|
|
2087
|
+
policyIds.add(p.id);
|
|
2088
|
+
}
|
|
2089
|
+
}
|
|
2090
|
+
if (v.latency !== void 0) {
|
|
2091
|
+
const allowed = ["minMs", "maxMs"];
|
|
2092
|
+
if (!object(v.latency) || Object.keys(v.latency).some((k) => !allowed.includes(k))) invalid("latency requires minMs and maxMs");
|
|
2093
|
+
const l = v.latency;
|
|
2094
|
+
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");
|
|
2095
|
+
}
|
|
740
2096
|
if (v.browser !== void 0) {
|
|
741
2097
|
if (!object(v.browser) || typeof v.browser.baseUrl !== "string") invalid("browser requires baseUrl");
|
|
742
2098
|
const browser = v.browser;
|
|
@@ -759,20 +2115,20 @@ function parseWorld(value) {
|
|
|
759
2115
|
}
|
|
760
2116
|
}
|
|
761
2117
|
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");
|
|
762
|
-
const keys = ["schema", "name", "workflowId", "files", "command", "timeoutSeconds", "browser", "background", "services", "assertions", "forbiddenEffects", "preservedState", "scenario", "postgres", "redis", "fault"];
|
|
2118
|
+
const keys = ["schema", "name", "workflowId", "files", "command", "timeoutSeconds", "browser", "background", "services", "assertions", "forbiddenEffects", "preservedState", "properties", "scenario", "postgres", "redis", "fault", "faults", "latency"];
|
|
763
2119
|
if (Object.keys(v).some((k) => !keys.includes(k))) invalid("unknown world field");
|
|
764
2120
|
return v;
|
|
765
2121
|
}
|
|
766
2122
|
|
|
767
2123
|
// src/runtime/scenarios.ts
|
|
768
|
-
import { createHash } from "crypto";
|
|
2124
|
+
import { createHash as createHash3 } from "crypto";
|
|
769
2125
|
import { mkdir, readFile, readdir, writeFile as writeFile2 } from "fs/promises";
|
|
770
2126
|
import { join as join2 } from "path";
|
|
771
2127
|
import { isDeepStrictEqual as isDeepStrictEqual4 } from "util";
|
|
772
2128
|
var identifier = /^[a-z][a-z0-9_]{0,39}$/;
|
|
773
2129
|
var object2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
774
2130
|
var sort = (v) => Array.isArray(v) ? v.map(sort) : object2(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sort(v[k])])) : v;
|
|
775
|
-
var scenarioDigest = (scenario) =>
|
|
2131
|
+
var scenarioDigest = (scenario) => createHash3("sha256").update(JSON.stringify(sort(scenario))).digest("hex");
|
|
776
2132
|
function parseScenario(value) {
|
|
777
2133
|
const fail = (detail) => {
|
|
778
2134
|
throw new Error(`Invalid scenario: ${detail}`);
|
|
@@ -795,8 +2151,8 @@ function parseScenario(value) {
|
|
|
795
2151
|
const services = /* @__PURE__ */ new Set();
|
|
796
2152
|
for (const ref of entity.refs) {
|
|
797
2153
|
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");
|
|
798
|
-
const
|
|
799
|
-
if (!
|
|
2154
|
+
const rows2 = scenario.services.find((s) => s.name === ref.service)?.collections.find((c) => c.path === ref.path)?.seed;
|
|
2155
|
+
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`);
|
|
800
2156
|
services.add(ref.service);
|
|
801
2157
|
}
|
|
802
2158
|
if (services.size < 2) fail(`entity ${entity.id} must link at least two services`);
|
|
@@ -827,11 +2183,11 @@ function applyScenario(world, scenario) {
|
|
|
827
2183
|
init_contracts();
|
|
828
2184
|
|
|
829
2185
|
// src/commands/run.ts
|
|
830
|
-
import { mkdtemp as mkdtemp2, mkdir as
|
|
2186
|
+
import { mkdtemp as mkdtemp2, mkdir as mkdir4, readFile as readFile6, writeFile as writeFile5, realpath as realpath2, lstat, rm as rm3, copyFile } from "fs/promises";
|
|
831
2187
|
import { tmpdir as tmpdir2 } from "os";
|
|
832
|
-
import { basename, dirname, isAbsolute, join as
|
|
2188
|
+
import { basename, dirname, isAbsolute, join as join7, relative as relative2, resolve as resolve3, sep } from "path";
|
|
833
2189
|
import { fileURLToPath } from "url";
|
|
834
|
-
import { createHash as
|
|
2190
|
+
import { createHash as createHash5, randomUUID } from "crypto";
|
|
835
2191
|
|
|
836
2192
|
// src/runtime/credentials.ts
|
|
837
2193
|
import { homedir } from "os";
|
|
@@ -872,6 +2228,11 @@ import { randomBytes as randomBytes2 } from "crypto";
|
|
|
872
2228
|
import { homedir as homedir2 } from "os";
|
|
873
2229
|
import { join as join5 } from "path";
|
|
874
2230
|
|
|
2231
|
+
// src/runtime/matrix.ts
|
|
2232
|
+
import { createHash as createHash4 } from "crypto";
|
|
2233
|
+
import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
|
|
2234
|
+
import { join as join6, relative, resolve as resolve2 } from "path";
|
|
2235
|
+
|
|
875
2236
|
// src/commands/run.ts
|
|
876
2237
|
async function stageApplication(root, files, destination) {
|
|
877
2238
|
const canonicalRoot = await realpath2(root);
|
|
@@ -879,16 +2240,16 @@ async function stageApplication(root, files, destination) {
|
|
|
879
2240
|
let bytes = 0;
|
|
880
2241
|
for (const file of files) {
|
|
881
2242
|
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 });
|
|
882
|
-
const source = await realpath2(
|
|
883
|
-
const rel =
|
|
884
|
-
if (rel.startsWith(`..${sep}`) || rel === ".." || isAbsolute(rel) || source !==
|
|
885
|
-
const contents = await
|
|
2243
|
+
const source = await realpath2(resolve3(canonicalRoot, file));
|
|
2244
|
+
const rel = relative2(canonicalRoot, source);
|
|
2245
|
+
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 });
|
|
2246
|
+
const contents = await readFile6(source);
|
|
886
2247
|
bytes += contents.length;
|
|
887
2248
|
if (bytes > 20 * 1024 * 1024) throw new CliError("Application files exceed 20 MiB; supply a smaller built bundle", { code: EXIT.USAGE });
|
|
888
|
-
const target =
|
|
889
|
-
await
|
|
890
|
-
await
|
|
891
|
-
digests[file] =
|
|
2249
|
+
const target = join7(destination, file);
|
|
2250
|
+
await mkdir4(dirname(target), { recursive: true });
|
|
2251
|
+
await writeFile5(target, contents, { mode: 420 });
|
|
2252
|
+
digests[file] = createHash5("sha256").update(contents).digest("hex");
|
|
892
2253
|
}
|
|
893
2254
|
return digests;
|
|
894
2255
|
}
|
|
@@ -896,21 +2257,21 @@ async function stageApplication(root, files, destination) {
|
|
|
896
2257
|
// src/runtime/world-session.ts
|
|
897
2258
|
init_git();
|
|
898
2259
|
var uuid = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
|
|
899
|
-
var hash = (spec) =>
|
|
2260
|
+
var hash = (spec) => createHash6("sha256").update(JSON.stringify(spec)).digest("hex");
|
|
900
2261
|
function duration(value) {
|
|
901
2262
|
if (!Number.isInteger(value) || value < 1 || value > 86400) throw new Error("ttlSeconds must be 1\u201386400");
|
|
902
2263
|
return value;
|
|
903
2264
|
}
|
|
904
2265
|
async function persist(directory2, session) {
|
|
905
|
-
const temporary =
|
|
906
|
-
await
|
|
907
|
-
await rename(temporary,
|
|
2266
|
+
const temporary = join8(directory2, `${randomUUID2()}.tmp`);
|
|
2267
|
+
await writeFile6(temporary, JSON.stringify(session, null, 2) + "\n", { mode: 384 });
|
|
2268
|
+
await rename(temporary, join8(directory2, "session.json"));
|
|
908
2269
|
}
|
|
909
2270
|
var view = ({ controlToken: _token, cwd: _cwd, file: _file, controlUrl: _control, ...session }) => session;
|
|
910
2271
|
async function serveWorldSession(directory2) {
|
|
911
|
-
const session = JSON.parse(await
|
|
2272
|
+
const session = JSON.parse(await readFile7(join8(directory2, "session.json"), "utf8"));
|
|
912
2273
|
if (session.status !== "provisioning" || !uuid.test(session.id)) throw new Error("Session is not awaiting provisioning");
|
|
913
|
-
const spec = parseWorld(JSON.parse(await
|
|
2274
|
+
const spec = parseWorld(JSON.parse(await readFile7(join8(directory2, "world.json"), "utf8")));
|
|
914
2275
|
const world = new HttpWorld(spec);
|
|
915
2276
|
let control;
|
|
916
2277
|
let timer;
|
|
@@ -935,8 +2296,8 @@ async function serveWorldSession(directory2) {
|
|
|
935
2296
|
session.status = status;
|
|
936
2297
|
session.credentials = void 0;
|
|
937
2298
|
await world.close();
|
|
938
|
-
if (control) await new Promise((
|
|
939
|
-
control.close(() =>
|
|
2299
|
+
if (control) await new Promise((resolve5) => {
|
|
2300
|
+
control.close(() => resolve5());
|
|
940
2301
|
control.closeAllConnections();
|
|
941
2302
|
});
|
|
942
2303
|
await save();
|
|
@@ -1010,10 +2371,10 @@ async function serveWorldSession(directory2) {
|
|
|
1010
2371
|
reply(200, { ...view(session), state: world.snapshot() });
|
|
1011
2372
|
return;
|
|
1012
2373
|
}
|
|
1013
|
-
let current = parseWorld(JSON.parse(await
|
|
2374
|
+
let current = parseWorld(JSON.parse(await readFile7(session.file, "utf8")));
|
|
1014
2375
|
if (session.scenario) current = applyScenario(current, await loadScenario(session.cwd, session.scenario));
|
|
1015
2376
|
if (hash(current) !== hash(spec)) throw new Error("World specification or scenario changed; provision a new world. Source patches are allowed.");
|
|
1016
|
-
const stage = await mkdtemp3(
|
|
2377
|
+
const stage = await mkdtemp3(join8(tmpdir3(), "agenttwin-session-run-"));
|
|
1017
2378
|
active = new AbortController();
|
|
1018
2379
|
let result;
|
|
1019
2380
|
try {
|
|
@@ -1029,15 +2390,15 @@ async function serveWorldSession(directory2) {
|
|
|
1029
2390
|
const runId = randomUUID2();
|
|
1030
2391
|
let project = "local-workspace";
|
|
1031
2392
|
try {
|
|
1032
|
-
project = JSON.parse(await
|
|
2393
|
+
project = JSON.parse(await readFile7(join8(session.cwd, ".agenttwin/inventory.json"), "utf8")).name ?? project;
|
|
1033
2394
|
} catch {
|
|
1034
2395
|
}
|
|
1035
|
-
const receipt = { ...report, sourceDirectory:
|
|
1036
|
-
const out =
|
|
1037
|
-
await
|
|
1038
|
-
const evidencePath =
|
|
1039
|
-
await
|
|
1040
|
-
await
|
|
2396
|
+
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" };
|
|
2397
|
+
const out = join8(session.cwd, ".agenttwin/runs", runId);
|
|
2398
|
+
await mkdir5(out, { recursive: true, mode: 448 });
|
|
2399
|
+
const evidencePath = join8(out, "run.json");
|
|
2400
|
+
await writeFile6(evidencePath, JSON.stringify(receipt, null, 2) + "\n", { mode: 384 });
|
|
2401
|
+
await writeFile6(join8(out, "world.json"), JSON.stringify(spec, null, 2) + "\n", { mode: 384 });
|
|
1041
2402
|
session.lastRunId = runId;
|
|
1042
2403
|
result = { ...receipt, evidencePath };
|
|
1043
2404
|
} finally {
|
|
@@ -1056,11 +2417,11 @@ async function serveWorldSession(directory2) {
|
|
|
1056
2417
|
}
|
|
1057
2418
|
});
|
|
1058
2419
|
control.requestTimeout = 1e4;
|
|
1059
|
-
await new Promise((
|
|
2420
|
+
await new Promise((resolve5, reject) => {
|
|
1060
2421
|
control.once("error", reject);
|
|
1061
|
-
control.listen(0, "127.0.0.1",
|
|
2422
|
+
control.listen(0, "127.0.0.1", resolve5);
|
|
1062
2423
|
});
|
|
1063
|
-
const latest = JSON.parse(await
|
|
2424
|
+
const latest = JSON.parse(await readFile7(join8(directory2, "session.json"), "utf8"));
|
|
1064
2425
|
if (latest.status !== "provisioning") throw new Error("Provisioning was abandoned");
|
|
1065
2426
|
session.controlUrl = `http://127.0.0.1:${control.address().port}`;
|
|
1066
2427
|
if (stopping) throw new Error("World expired during provisioning");
|