agenttwin 0.3.18 → 0.3.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +51 -12
  2. package/dist/api.js +282 -61
  3. package/dist/dashboard/assets/next/static/chunks/{2743-a0efd6f4aeb11cc5.js → 2743-72610a5d5a3f8462.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/2868-c6050a0282a369e1.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/{5531-fde254dbd21c3153.js → 5531-26f7b8cab53bcc9b.js} +1 -1
  6. package/dist/dashboard/assets/next/static/chunks/9675.bd96abcfbdbe8f5d.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/app/_not-found/{page-4fac636e5cfc0494.js → page-43db8aef3fa81958.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/app/about/page-d22238684b039da0.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/account/password/{page-d1baf10bff8f328c.js → page-c2ce3c796c817ca1.js} +1 -1
  10. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-d22238684b039da0.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/auth/page-d22238684b039da0.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/page-11a5fdc2662ff51d.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/page-11a5fdc2662ff51d.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/page-11a5fdc2662ff51d.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/page-11a5fdc2662ff51d.js +1 -0
  16. package/dist/dashboard/assets/next/static/chunks/app/blog/choose-first-agent-workflow-test/page-11a5fdc2662ff51d.js +1 -0
  17. package/dist/dashboard/assets/next/static/chunks/app/blog/clean-baseline-before-fault-injection/page-11a5fdc2662ff51d.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/blog/idempotency-keys-and-safe-retries/page-11a5fdc2662ff51d.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/blog/keep-real-service-tests-with-digital-twins/page-11a5fdc2662ff51d.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-11a5fdc2662ff51d.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-79fdc32cfab4fadc.js +1 -0
  22. package/dist/dashboard/assets/next/static/chunks/app/blog/page-11a5fdc2662ff51d.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/blog/read-workflow-test-receipts/page-11a5fdc2662ff51d.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-11a5fdc2662ff51d.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-11a5fdc2662ff51d.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/blog/test-boundaries-for-ai-agents/page-11a5fdc2662ff51d.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/blog/workflow-testing-evaluation-checklist/page-11a5fdc2662ff51d.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/blog/write-better-workflow-assertions/page-11a5fdc2662ff51d.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/compare/page-d22238684b039da0.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/contact/page-d22238684b039da0.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-048b67fe23aebd32.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-2b917a10f42bbe12.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/demo/page-4dc63755e0013e7c.js +1 -0
  34. package/dist/dashboard/assets/next/static/chunks/app/developers/page-d22238684b039da0.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-d38e75a59c7ec797.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-196949610d7f83cb.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/app/guides/page-d22238684b039da0.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/layout-3d238e57d36309e9.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/login/page-d6d4276397724d29.js +1 -0
  40. package/dist/dashboard/assets/next/static/chunks/app/onboarding/{page-8eb71ef88bdd9396.js → page-bc480c9258e5cc4d.js} +1 -1
  41. package/dist/dashboard/assets/next/static/chunks/app/page-f5558383e4c83dad.js +1 -0
  42. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-946d793ef57d4bca.js +1 -0
  43. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-d22238684b039da0.js +1 -0
  44. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-d22238684b039da0.js +1 -0
  45. package/dist/dashboard/assets/next/static/chunks/app/signup/page-d6d4276397724d29.js +1 -0
  46. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-11a5fdc2662ff51d.js +1 -0
  47. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-a5cf565e017886d3.js +1 -0
  48. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-34574448d210c775.js +1 -0
  49. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-abbd9f3b8811f559.js +1 -0
  50. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-4f4a342a4c28f9de.js +1 -0
  51. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/{page-d20759b1be50643f.js → page-f04c0b236abaead3.js} +1 -1
  52. package/dist/dashboard/assets/next/static/chunks/app/v2/page-f4abe13820aa0702.js +1 -0
  53. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-4f4a342a4c28f9de.js +1 -0
  54. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-d22238684b039da0.js +1 -0
  55. package/dist/dashboard/assets/next/static/chunks/{main-app-9030513b2ea7c6ba.js → main-app-1ec13ceef4a34729.js} +1 -1
  56. package/dist/dashboard/assets/next/static/chunks/{webpack-f293c9680eabd154.js → webpack-c87af79eff6d12e4.js} +1 -1
  57. package/dist/dashboard/assets/next/static/css/2c38dfe54afd9bb6.css +1 -0
  58. package/dist/dashboard/assets/next/static/css/423c6df577acd447.css +1 -0
  59. package/dist/dashboard/assets/next/static/css/{d131a6499fe6cf19.css → 60c671ffc0625248.css} +1 -1
  60. package/dist/dashboard/assets/next/static/css/7109685b391c1c46.css +1 -0
  61. package/dist/dashboard/assets/next/static/css/f8022624e73ea325.css +1 -0
  62. package/dist/dashboard/assets/next/static/nmF4MQHuQ_kwtZ9CxBcqC/_buildManifest.js +1 -0
  63. package/dist/dashboard/index.html +6 -2
  64. package/dist/engine.js +2518 -1644
  65. package/dist/gateway.js +282 -61
  66. package/dist/worker.js +449 -252
  67. package/dist/world-host.js +471 -265
  68. package/package.json +5 -2
  69. package/dist/dashboard/assets/next/static/EvU7zdQimTNRzxI3sTw-q/_buildManifest.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/2868-b80a3af454408935.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/9675.14739028910476e4.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/about/page-bbf125ee6ef16d17.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-bbf125ee6ef16d17.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/auth/page-bbf125ee6ef16d17.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-mockoon/page-ba841d868e5d124a.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-pact/page-ba841d868e5d124a.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-testcontainers/page-ba841d868e5d124a.js +0 -1
  78. package/dist/dashboard/assets/next/static/chunks/app/blog/agenttwin-vs-wiremock/page-ba841d868e5d124a.js +0 -1
  79. package/dist/dashboard/assets/next/static/chunks/app/blog/keploy-alternatives-for-database-and-payment-workflows/page-ba841d868e5d124a.js +0 -1
  80. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-434c5265a09af3b9.js +0 -1
  81. package/dist/dashboard/assets/next/static/chunks/app/blog/page-ba841d868e5d124a.js +0 -1
  82. package/dist/dashboard/assets/next/static/chunks/app/blog/reset-test-environment-between-runs/page-ba841d868e5d124a.js +0 -1
  83. package/dist/dashboard/assets/next/static/chunks/app/blog/simulate-timeouts-and-duplicate-events/page-ba841d868e5d124a.js +0 -1
  84. package/dist/dashboard/assets/next/static/chunks/app/compare/page-bbf125ee6ef16d17.js +0 -1
  85. package/dist/dashboard/assets/next/static/chunks/app/contact/page-bbf125ee6ef16d17.js +0 -1
  86. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-1632d9fae63c9cd6.js +0 -1
  87. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-6894a8a3e5ba859a.js +0 -1
  88. package/dist/dashboard/assets/next/static/chunks/app/demo/page-c1267bf857a3fca8.js +0 -1
  89. package/dist/dashboard/assets/next/static/chunks/app/developers/page-bbf125ee6ef16d17.js +0 -1
  90. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-5cec0850a8226e15.js +0 -1
  91. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-f21347075a09d6d4.js +0 -1
  92. package/dist/dashboard/assets/next/static/chunks/app/guides/page-bbf125ee6ef16d17.js +0 -1
  93. package/dist/dashboard/assets/next/static/chunks/app/layout-b924dc5a0d35506b.js +0 -1
  94. package/dist/dashboard/assets/next/static/chunks/app/login/page-65179e6b5aba8504.js +0 -1
  95. package/dist/dashboard/assets/next/static/chunks/app/page-648a42537e0af8ae.js +0 -1
  96. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-5970ed83a07bed67.js +0 -1
  97. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-bbf125ee6ef16d17.js +0 -1
  98. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-bbf125ee6ef16d17.js +0 -1
  99. package/dist/dashboard/assets/next/static/chunks/app/signup/page-65179e6b5aba8504.js +0 -1
  100. package/dist/dashboard/assets/next/static/chunks/app/sitemap.xml/route-ba841d868e5d124a.js +0 -1
  101. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-bf73782281ca3196.js +0 -1
  102. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-dcce64b2a778b11d.js +0 -1
  103. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-c9122f78d0d3c100.js +0 -1
  104. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-5b17dafd5bf2fe36.js +0 -1
  105. package/dist/dashboard/assets/next/static/chunks/app/v2/page-fee1ecf1d39d4204.js +0 -1
  106. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-5b17dafd5bf2fe36.js +0 -1
  107. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-bbf125ee6ef16d17.js +0 -1
  108. package/dist/dashboard/assets/next/static/css/14eee9340ebc5f8b.css +0 -1
  109. package/dist/dashboard/assets/next/static/css/f27d5fbb1f484d9d.css +0 -1
  110. /package/dist/dashboard/assets/next/static/{EvU7zdQimTNRzxI3sTw-q → nmF4MQHuQ_kwtZ9CxBcqC}/_ssgManifest.js +0 -0
package/dist/api.js CHANGED
@@ -160,7 +160,7 @@ function parseWorld(value) {
160
160
  if (!object2(service) || typeof service.name !== "string" || !namePattern.test(service.name) || services.has(service.name)) invalid("service names must be unique lowercase identifiers");
161
161
  const item = service;
162
162
  if (!Array.isArray(item.collections) || !item.collections.length || item.collections.length > 20) invalid("each service needs 1\u201320 collections");
163
- if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio"].includes(String(item.adapter))) invalid("unsupported service adapter");
163
+ if (item.adapter !== void 0 && !["json-collection", "slack", "stripe", "openai", "anthropic", "github", "linear", "notion", "hubspot", "shopify", "datadog", "gmail", "google-calendar", "gitlab", "jira", "discord", "twilio", "zendesk", "google-oauth", "composio"].includes(String(item.adapter))) invalid("unsupported service adapter");
164
164
  const paths = /* @__PURE__ */ new Set();
165
165
  for (const entry of item.collections) {
166
166
  if (!object2(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");
@@ -169,8 +169,9 @@ function parseWorld(value) {
169
169
  paths.add(collection.path);
170
170
  }
171
171
  const required = ADAPTER_COLLECTIONS[item.adapter];
172
- if (required && (paths.size !== required.length || !required.every((p) => paths.has(p)))) invalid(`${item.adapter} adapter requires exactly ${required.join(", ")} collections`);
173
- services.set(item.name, paths);
172
+ const optional = ADAPTER_OPTIONAL_COLLECTIONS[item.adapter] ?? [];
173
+ if (required && (!required.every((p) => paths.has(p)) || [...paths].some((p) => !required.includes(p) && !optional.includes(p)))) invalid(`${item.adapter} adapter requires exactly ${required.join(", ")} collections${optional.length ? ` (optionally ${optional.join(", ")})` : ""}`);
174
+ services.set(item.name, /* @__PURE__ */ new Set([...paths, ...optional]));
174
175
  }
175
176
  const known2 = (entry) => typeof entry.service === "string" && typeof entry.path === "string" && services.get(entry.service)?.has(entry.path);
176
177
  if (!Array.isArray(v.assertions) || !v.assertions.length || v.assertions.length > 100) invalid("at least one final-state assertion is required (maximum 100)");
@@ -315,15 +316,20 @@ function selectWorldFault(world, selection) {
315
316
  }
316
317
  return parseWorld(selected);
317
318
  }
318
- var ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, object2, namePattern, inRangeInt;
319
+ var ADAPTER_OPTIONAL_COLLECTIONS, ADAPTER_COLLECTIONS, FAULT_TYPES, PROPERTY_KINDS, object2, namePattern, inRangeInt;
319
320
  var init_spec = __esm({
320
321
  "src/runtime/spec.ts"() {
321
322
  "use strict";
322
323
  init_postgres_clock();
323
324
  init_application_clock();
325
+ ADAPTER_OPTIONAL_COLLECTIONS = {
326
+ stripe: ["/v1/charges", "/v1/refunds", "/v1/events"]
327
+ };
324
328
  ADAPTER_COLLECTIONS = {
325
329
  slack: ["/messages", "/channels"],
326
330
  stripe: ["/v1/customers", "/v1/payment_intents"],
331
+ openai: ["/responses", "/requests"],
332
+ anthropic: ["/responses", "/requests"],
327
333
  github: ["/repos", "/issues", "/comments", "/pulls", "/check-runs"],
328
334
  linear: ["/issues", "/projects", "/users", "/comments"],
329
335
  notion: ["/pages", "/databases", "/blocks"],
@@ -588,8 +594,85 @@ var init_request_source = __esm({
588
594
  });
589
595
 
590
596
  // src/runtime/stripe-adapter.ts
597
+ function nextId(rows2, prefix, sequence) {
598
+ let suffix = sequence;
599
+ while (rows2.some((r) => r.id === `${prefix}_at_${suffix}`)) suffix++;
600
+ return `${prefix}_at_${suffix}`;
601
+ }
602
+ function chargeFor(intent, data, sequence) {
603
+ const charges = data["/v1/charges"];
604
+ if (!charges || intent.latest_charge) return;
605
+ const charge = { id: nextId(charges, "ch", sequence), object: "charge", amount: intent.amount, amount_refunded: 0, currency: intent.currency, customer: intent.customer ?? null, payment_intent: intent.id, paid: true, refunded: false, status: "succeeded", created: 17e8, livemode: false };
606
+ charges.push(charge);
607
+ intent.latest_charge = charge.id;
608
+ }
609
+ function metadataOf(params) {
610
+ const entries = Object.entries(params).filter(([key]) => /^metadata\[[^\]]+\]$/.test(key));
611
+ if (params.metadata && typeof params.metadata === "object" && !Array.isArray(params.metadata)) return params.metadata;
612
+ return Object.fromEntries(entries.map(([key, value]) => [key.slice(9, -1), String(value)]));
613
+ }
614
+ function refundOperation(method, id, params, data, sequence) {
615
+ const collection = "/v1/refunds", refunds = data[collection], charges = data["/v1/charges"];
616
+ if (!refunds || !charges) return void 0;
617
+ if (method === "GET") {
618
+ if (id) {
619
+ if (Object.keys(params).length) return void 0;
620
+ const row = refunds.find((r) => r.id === id);
621
+ return row ? { status: 200, body: row, collection, operation: "read" } : { ...stripeError(404, "resource_missing", `No such refund: '${id}'`), collection };
622
+ }
623
+ if (Object.keys(params).some((k) => !["limit", "starting_after", "charge", "payment_intent"].includes(k))) return void 0;
624
+ const limit = params.limit === void 0 ? 10 : Number(params.limit);
625
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...stripeError(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
626
+ const ordered = [...refunds].reverse().filter((r) => (params.charge === void 0 || r.charge === params.charge) && (params.payment_intent === void 0 || r.payment_intent === params.payment_intent));
627
+ const index = params.starting_after === void 0 ? -1 : ordered.findIndex((r) => r.id === params.starting_after);
628
+ if (params.starting_after !== void 0 && index === -1) return { ...stripeError(400, "resource_missing", "No such starting_after refund", "starting_after"), collection };
629
+ return { status: 200, body: { object: "list", data: ordered.slice(index + 1, index + 1 + limit), has_more: ordered.length > index + 1 + limit, url: collection }, collection, operation: "read" };
630
+ }
631
+ if (method !== "POST" || id) return void 0;
632
+ if (Object.keys(params).some((k) => !["charge", "payment_intent", "amount", "reason", "metadata"].includes(k) && !/^metadata\[[^\]]+\]$/.test(k))) return void 0;
633
+ if (params.charge === void 0 === (params.payment_intent === void 0)) return { ...stripeError(400, "parameter_missing", "Provide exactly one of charge or payment_intent"), collection };
634
+ let charge;
635
+ if (params.payment_intent !== void 0) {
636
+ const intent = data["/v1/payment_intents"]?.find((r) => r.id === params.payment_intent);
637
+ if (!intent) return { ...stripeError(400, "resource_missing", `No such payment_intent: '${String(params.payment_intent)}'`, "payment_intent"), collection };
638
+ if (intent.status !== "succeeded") return { ...stripeError(400, "charge_not_refundable", "This PaymentIntent does not have a successful charge to refund.", "payment_intent"), collection };
639
+ chargeFor(intent, data, sequence);
640
+ charge = charges.find((r) => r.id === intent.latest_charge);
641
+ } else charge = charges.find((r) => r.id === params.charge);
642
+ if (!charge) return { ...stripeError(400, "resource_missing", `No such charge: '${String(params.charge)}'`, "charge"), collection };
643
+ const remaining = Number(charge.amount) - Number(charge.amount_refunded ?? 0);
644
+ if (remaining <= 0) return { ...stripeError(400, "charge_already_refunded", `Charge ${String(charge.id)} has already been refunded.`), collection };
645
+ const amount = params.amount === void 0 ? remaining : Number(params.amount);
646
+ if (!Number.isSafeInteger(amount) || amount < 1) return { ...stripeError(400, "parameter_invalid_integer", "amount must be a positive integer", "amount"), collection };
647
+ if (amount > remaining) return { ...stripeError(400, "amount_too_large", `Refund amount (${amount}) is greater than unrefunded amount on charge (${remaining})`, "amount"), collection };
648
+ if (params.reason !== void 0 && !["duplicate", "fraudulent", "requested_by_customer"].includes(String(params.reason))) return { ...stripeError(400, "parameter_invalid", "reason must be duplicate, fraudulent or requested_by_customer", "reason"), collection };
649
+ if (refunds.length >= 1e4) return { ...stripeError(429, "world_capacity", "World record capacity reached"), collection };
650
+ const refund = { id: nextId(refunds, "re", sequence), object: "refund", amount, currency: charge.currency, charge: charge.id, payment_intent: charge.payment_intent ?? null, reason: params.reason ?? null, metadata: metadataOf(params), status: "succeeded", created: 17e8 };
651
+ refunds.push(refund);
652
+ charge.amount_refunded = Number(charge.amount_refunded ?? 0) + amount;
653
+ charge.refunded = charge.amount_refunded === charge.amount;
654
+ const events = data["/v1/events"];
655
+ if (events) events.push({ id: nextId(events, "evt", sequence), object: "event", type: "charge.refunded", created: 17e8, livemode: false, data: { object: structuredClone(charge) } });
656
+ return { status: 200, body: refund, collection, record: structuredClone(refund), operation: "write" };
657
+ }
658
+ function readOnlyOperation(method, resource, id, params, data) {
659
+ const collection = `/v1/${resource}`, rows2 = data[collection];
660
+ if (!rows2 || method !== "GET") return void 0;
661
+ if (id) {
662
+ if (Object.keys(params).length) return void 0;
663
+ const row = rows2.find((r) => r.id === id);
664
+ return row ? { status: 200, body: row, collection, operation: "read" } : { ...stripeError(404, "resource_missing", `No such ${resource.slice(0, -1)}: '${id}'`), collection };
665
+ }
666
+ if (Object.keys(params).some((k) => !["limit", "type"].includes(k))) return void 0;
667
+ const limit = params.limit === void 0 ? 10 : Number(params.limit);
668
+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) return { ...stripeError(400, "parameter_invalid_integer", "limit must be 1\u2013100", "limit"), collection };
669
+ const ordered = [...rows2].reverse().filter((r) => params.type === void 0 || r.type === params.type);
670
+ return { status: 200, body: { object: "list", data: ordered.slice(0, limit), has_more: ordered.length > limit, url: collection }, collection, operation: "read" };
671
+ }
591
672
  function stripeOperation(method, path2, params, data, sequence) {
592
- const error = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
673
+ const error = stripeError;
674
+ const other = /^\/v1\/(refunds|charges|events)(?:\/([^/]+))?$/.exec(path2);
675
+ if (other) return other[1] === "refunds" ? refundOperation(method, other[2], params, data, sequence) : readOnlyOperation(method, other[1], other[2], params, data);
593
676
  const match = /^\/v1\/(customers|payment_intents)(?:\/([^/]+))?(?:\/(confirm))?$/.exec(path2);
594
677
  if (!match || !["GET", "POST"].includes(method)) return void 0;
595
678
  const [, resource, id, action] = match, collection = `/v1/${resource}`, rows2 = data[collection];
@@ -614,6 +697,7 @@ function stripeOperation(method, path2, params, data, sequence) {
614
697
  if (payment !== "pm_card_visa" && payment !== "pm_card_chargeDeclined") return { ...error(400, "parameter_invalid", "Only pm_card_visa and pm_card_chargeDeclined are supported", "payment_method"), collection };
615
698
  row.payment_method = payment;
616
699
  row.status = payment === "pm_card_visa" ? "succeeded" : "requires_payment_method";
700
+ if (row.status === "succeeded") chargeFor(row, data, sequence);
617
701
  row.last_payment_error = payment === "pm_card_chargeDeclined" ? { code: "card_declined", decline_code: "generic_decline", message: "Your card was declined." } : null;
618
702
  return { status: payment === "pm_card_chargeDeclined" ? 402 : 200, body: payment === "pm_card_chargeDeclined" ? { error: { type: "card_error", code: "card_declined", decline_code: "generic_decline", message: "Your card was declined.", payment_intent: structuredClone(row) } } : row, collection, record: structuredClone(row), operation: "write" };
619
703
  }
@@ -637,12 +721,104 @@ function stripeOperation(method, path2, params, data, sequence) {
637
721
  }
638
722
  if (rows2.length >= 1e4) return { ...error(429, "world_capacity", "World record capacity reached"), collection };
639
723
  rows2.push(created2);
724
+ if (created2.status === "succeeded") chargeFor(created2, data, sequence);
640
725
  const declined = resource === "payment_intents" && (params.confirm === "true" || params.confirm === true) && params.payment_method === "pm_card_chargeDeclined";
641
726
  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" };
642
727
  }
728
+ var stripeError;
643
729
  var init_stripe_adapter = __esm({
644
730
  "src/runtime/stripe-adapter.ts"() {
645
731
  "use strict";
732
+ stripeError = (status, code, message, param) => ({ status, body: { error: { type: "invalid_request_error", code, message, ...param ? { param } : {} } } });
733
+ }
734
+ });
735
+
736
+ // src/runtime/llm-adapter.ts
737
+ function lastUserText(messages) {
738
+ if (!Array.isArray(messages)) return "";
739
+ const user = [...messages].reverse().find((m) => m && typeof m === "object" && m.role === "user");
740
+ const content = user?.content;
741
+ if (typeof content === "string") return content;
742
+ if (Array.isArray(content)) return content.map((part) => part && typeof part === "object" && typeof part.text === "string" ? part.text : "").join("\n");
743
+ return "";
744
+ }
745
+ function nextScripted(data, prompt) {
746
+ const scripts = data["/responses"];
747
+ if (!scripts) return void 0;
748
+ const usable = (row) => !row.used || row.repeat === true;
749
+ const matched = scripts.find((row) => usable(row) && typeof row.match === "string" && prompt.includes(row.match));
750
+ const script = matched ?? scripts.find((row) => usable(row) && row.match === void 0);
751
+ if (!script) return void 0;
752
+ script.used = true;
753
+ const calls = Array.isArray(script.tool_calls) ? script.tool_calls.filter((call) => !!call && typeof call === "object" && typeof call.name === "string") : [];
754
+ return { content: typeof script.content === "string" ? script.content : null, calls };
755
+ }
756
+ function record(data, provider, model, prompt, responseId, toolCalls) {
757
+ const requests = data["/requests"];
758
+ if (requests.length >= 1e4) return void 0;
759
+ const entry = { id: `req_at_${requests.length + 1}`, provider, model: typeof model === "string" ? model : null, prompt: prompt.slice(0, 2e3), response: responseId, tool_calls: toolCalls };
760
+ requests.push(entry);
761
+ return entry;
762
+ }
763
+ function parsedInput(value) {
764
+ if (typeof value !== "string") return value ?? {};
765
+ try {
766
+ return JSON.parse(value);
767
+ } catch {
768
+ return { value };
769
+ }
770
+ }
771
+ function openaiOperation(method, path2, params, _headers, data, sequence) {
772
+ const collection = "/requests";
773
+ if (path2 === "/v1/requests" || path2 === "/requests") return method === "GET" ? { status: 200, body: { object: "list", data: data[collection] }, collection, operation: "read" } : void 0;
774
+ if (method !== "POST" || !["/v1/chat/completions", "/chat/completions"].includes(path2)) return void 0;
775
+ if (params.stream === true || !Array.isArray(params.messages)) return void 0;
776
+ const prompt = lastUserText(params.messages);
777
+ const script = nextScripted(data, prompt);
778
+ if (!script) return void 0;
779
+ const id = `chatcmpl_at_${sequence}`;
780
+ const toolCalls = script.calls.map((call, index) => ({ id: `call_at_${sequence}_${index}`, type: "function", function: { name: String(call.name), arguments: arg(call.arguments) } }));
781
+ const entry = record(data, "openai", params.model, prompt, id, toolCalls.map((call) => call.function.name));
782
+ if (!entry) return { status: 429, body: { error: { type: "world_capacity", message: "World record capacity reached" } }, collection };
783
+ const body2 = {
784
+ id,
785
+ object: "chat.completion",
786
+ created: 17e8,
787
+ model: params.model ?? "agenttwin-scripted",
788
+ choices: [{ index: 0, message: { role: "assistant", content: script.content, refusal: null, ...toolCalls.length ? { tool_calls: toolCalls } : {} }, logprobs: null, finish_reason: toolCalls.length ? "tool_calls" : "stop" }],
789
+ usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 }
790
+ };
791
+ return { status: 200, body: body2, collection, record: entry, operation: "write" };
792
+ }
793
+ function anthropicOperation(method, path2, params, _headers, data, sequence) {
794
+ const collection = "/requests";
795
+ if (path2 === "/v1/requests" || path2 === "/requests") return method === "GET" ? { status: 200, body: { data: data[collection] }, collection, operation: "read" } : void 0;
796
+ if (method !== "POST" || !["/v1/messages", "/messages"].includes(path2)) return void 0;
797
+ if (params.stream === true || !Array.isArray(params.messages)) return void 0;
798
+ const prompt = lastUserText(params.messages);
799
+ const script = nextScripted(data, prompt);
800
+ if (!script) return void 0;
801
+ const id = `msg_at_${sequence}`;
802
+ const toolUses = script.calls.map((call, index) => ({ type: "tool_use", id: `toolu_at_${sequence}_${index}`, name: String(call.name), input: parsedInput(call.arguments) }));
803
+ const entry = record(data, "anthropic", params.model, prompt, id, toolUses.map((use) => use.name));
804
+ if (!entry) return { status: 429, body: { type: "error", error: { type: "world_capacity", message: "World record capacity reached" } }, collection };
805
+ const body2 = {
806
+ id,
807
+ type: "message",
808
+ role: "assistant",
809
+ model: params.model ?? "agenttwin-scripted",
810
+ content: [...script.content !== null ? [{ type: "text", text: script.content }] : [], ...toolUses],
811
+ stop_reason: toolUses.length ? "tool_use" : "end_turn",
812
+ stop_sequence: null,
813
+ usage: { input_tokens: 0, output_tokens: 0 }
814
+ };
815
+ return { status: 200, body: body2, collection, record: entry, operation: "write" };
816
+ }
817
+ var arg;
818
+ var init_llm_adapter = __esm({
819
+ "src/runtime/llm-adapter.ts"() {
820
+ "use strict";
821
+ arg = (value) => typeof value === "string" ? value : JSON.stringify(value ?? {});
646
822
  }
647
823
  });
648
824
 
@@ -698,9 +874,9 @@ var init_composio_twin = __esm({
698
874
  for (const [left, right] of [["to", "recipient_email"], ["body", "message"], ["threadId", "thread_id"]]) if (args[left] !== void 0 && args[right] !== void 0 && args[left] !== args[right]) return error(400, "Conflicting message aliases");
699
875
  const to = args.to ?? args.recipient_email, body2 = args.body ?? args.message, threadId = args.threadId ?? args.thread_id;
700
876
  if (typeof to !== "string" || !to || typeof args.subject !== "string" || typeof body2 !== "string" || threadId !== void 0 && typeof threadId !== "string") return error(400, "Message fields required");
701
- const id = "composio_message_" + sequence, record = { id, to, subject: args.subject, body: body2, user_id: params.user_id, connected_account_id: selected.id, ...threadId === void 0 ? {} : { threadId } };
702
- data["/messages"].push(record);
703
- return { status: 200, collection: "/messages", operation: "write", record, body: { successful: true, error: null, data: { id, messageId: id }, log_id: "synthetic-log-" + sequence } };
877
+ const id = "composio_message_" + sequence, record2 = { id, to, subject: args.subject, body: body2, user_id: params.user_id, connected_account_id: selected.id, ...threadId === void 0 ? {} : { threadId } };
878
+ data["/messages"].push(record2);
879
+ return { status: 200, collection: "/messages", operation: "write", record: record2, body: { successful: true, error: null, data: { id, messageId: id }, log_id: "synthetic-log-" + sequence } };
704
880
  };
705
881
  }
706
882
  });
@@ -725,9 +901,9 @@ var init_google_oauth_twin = __esm({
725
901
  if (typeof grant.scope !== "string" || !grant.scope || !Number.isInteger(grant.expires_in) || Number(grant.expires_in) < 1 || Number(grant.expires_in) > 86400) return;
726
902
  const access_token = "synthetic-access-" + createHash5("sha256").update(JSON.stringify([params.client_id, params.refresh_token, sequence])).digest("hex").slice(0, 24);
727
903
  const body2 = { access_token, token_type: "Bearer", expires_in: grant.expires_in, scope: grant.scope };
728
- const record = { id: "issuance_" + sequence, client_id: params.client_id, ...body2 };
729
- data["/tokens"].push(record);
730
- return { status: 200, collection: "/tokens", body: body2, record, operation: "write" };
904
+ const record2 = { id: "issuance_" + sequence, client_id: params.client_id, ...body2 };
905
+ data["/tokens"].push(record2);
906
+ return { status: 200, collection: "/tokens", body: body2, record: record2, operation: "write" };
731
907
  };
732
908
  }
733
909
  });
@@ -873,7 +1049,7 @@ function linearOperation(method, path2, params, _headers, data, sequence) {
873
1049
  const root = new RegExp(isMutation ? "\\bmutation\\b[^{]*\\{\\s*(\\w+)" : "\\bquery\\b[^{]*\\{\\s*(\\w+)").exec(query);
874
1050
  if (!root) return void 0;
875
1051
  const variables = isObject(params.variables) ? params.variables : {};
876
- 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);
1052
+ const arg2 = (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);
877
1053
  const input = variables.input ?? void 0;
878
1054
  if (!isMutation) {
879
1055
  if (root[1] === "viewer") {
@@ -889,13 +1065,13 @@ function linearOperation(method, path2, params, _headers, data, sequence) {
889
1065
  return ok("/projects", { data: { projects: { nodes: rows(data, "/projects").map((row) => structuredClone(row)) } } });
890
1066
  }
891
1067
  if (root[1] === "issue") {
892
- const issue = rows(data, "/issues").find((r) => r.id === arg("id"));
893
- if (Object.keys(variables).some((k) => k !== "id") || arg("id") === void 0) return void 0;
1068
+ const issue = rows(data, "/issues").find((r) => r.id === arg2("id"));
1069
+ if (Object.keys(variables).some((k) => k !== "id") || arg2("id") === void 0) return void 0;
894
1070
  return issue ? ok("/issues", { data: { issue: structuredClone(issue) } }) : notFoundNode("Issue");
895
1071
  }
896
1072
  if (root[1] === "project") {
897
- const project = rows(data, "/projects").find((r) => r.id === arg("id"));
898
- if (Object.keys(variables).some((k) => k !== "id") || arg("id") === void 0) return void 0;
1073
+ const project = rows(data, "/projects").find((r) => r.id === arg2("id"));
1074
+ if (Object.keys(variables).some((k) => k !== "id") || arg2("id") === void 0) return void 0;
899
1075
  return project ? ok("/projects", { data: { project: structuredClone(project) } }) : notFoundNode("Project");
900
1076
  }
901
1077
  return void 0;
@@ -909,8 +1085,8 @@ function linearOperation(method, path2, params, _headers, data, sequence) {
909
1085
  return write(200, "/issues", { data: { issueCreate: { success: true, issue: structuredClone(issue) } } }, issue);
910
1086
  }
911
1087
  if (root[1] === "issueUpdate") {
912
- if (!isObject(input) || arg("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
913
- const issue = rows(data, "/issues").find((r) => r.id === arg("id"));
1088
+ if (!isObject(input) || arg2("id") === void 0 || Object.keys(variables).some((k) => !["id", "input"].includes(k))) return void 0;
1089
+ const issue = rows(data, "/issues").find((r) => r.id === arg2("id"));
914
1090
  if (!issue) return notFoundNode("Issue");
915
1091
  if (Object.keys(input).some((k) => !["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k))) return void 0;
916
1092
  for (const [k, v] of Object.entries(input)) if (["title", "description", "state", "assigneeId", "projectId", "priority"].includes(k)) issue[k] = v;
@@ -1007,9 +1183,9 @@ function notionOperation(method, path2, params, headers, data, sequence) {
1007
1183
  if (!page && !block) return notionError("/blocks", 404, "object_not_found", "Could not find block with ID.");
1008
1184
  const parent = page ? { type: "page_id", page_id: page.id } : { type: "block_id", block_id: block.id };
1009
1185
  const createdBlocks = params.children.map((child, index) => {
1010
- 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) };
1011
- rows(data, "/blocks").push(record);
1012
- return record;
1186
+ const record2 = { 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) };
1187
+ rows(data, "/blocks").push(record2);
1188
+ return record2;
1013
1189
  });
1014
1190
  return write(200, "/blocks", { object: "list", results: structuredClone(createdBlocks), has_more: false, next_cursor: null, type: "block", block: {} }, createdBlocks[createdBlocks.length - 1]);
1015
1191
  }
@@ -1062,18 +1238,18 @@ function hubspotOperation(method, path2, params, _headers, data, sequence) {
1062
1238
  }
1063
1239
  if (method !== "POST") return void 0;
1064
1240
  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 ${object5}`, category: "VALIDATION_ERROR" });
1065
- const record2 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
1066
- rows(data, collection).push(record2);
1067
- return created(collection, hubspotEnvelope(record2), record2);
1241
+ const record3 = { id: uniqueId(rows(data, collection), 501 + sequence), properties: structuredClone(properties), createdAt: iso(), updatedAt: iso() };
1242
+ rows(data, collection).push(record3);
1243
+ return created(collection, hubspotEnvelope(record3), record3);
1068
1244
  }
1069
- const record = rows(data, collection).find((r) => r.id === id);
1070
- if (!record) return { status: 404, body: { status: "error", message: `Object not found: ${object5} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
1071
- if (method === "GET") return ok(collection, hubspotEnvelope(record));
1245
+ const record2 = rows(data, collection).find((r) => r.id === id);
1246
+ if (!record2) return { status: 404, body: { status: "error", message: `Object not found: ${object5} with id ${id}`, category: "OBJECT_NOT_FOUND" }, collection };
1247
+ if (method === "GET") return ok(collection, hubspotEnvelope(record2));
1072
1248
  if (method === "PATCH") {
1073
1249
  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" });
1074
- Object.assign(record.properties, structuredClone(properties));
1075
- record.updatedAt = iso();
1076
- return write(200, collection, hubspotEnvelope(record), record);
1250
+ Object.assign(record2.properties, structuredClone(properties));
1251
+ record2.updatedAt = iso();
1252
+ return write(200, collection, hubspotEnvelope(record2), record2);
1077
1253
  }
1078
1254
  return void 0;
1079
1255
  }
@@ -1085,7 +1261,7 @@ function shopifyOperation(method, path2, params, _headers, data, sequence) {
1085
1261
  const wrap = resource === "products" ? "product" : resource === "orders" ? "order" : "customer";
1086
1262
  const rowsIn2 = rows(data, collection);
1087
1263
  const notFoundShopify = () => notFound(collection, { errors: "Not Found" });
1088
- const enriched = (record2) => ({ ...structuredClone(record2), created_at: record2.created_at ?? iso(), updated_at: iso() });
1264
+ const enriched = (record3) => ({ ...structuredClone(record3), created_at: record3.created_at ?? iso(), updated_at: iso() });
1089
1265
  if (!id) {
1090
1266
  if (method === "GET") {
1091
1267
  if (Object.keys(params).some((k) => !["limit", "since_id"].includes(k))) return void 0;
@@ -1108,25 +1284,25 @@ function shopifyOperation(method, path2, params, _headers, data, sequence) {
1108
1284
  }
1109
1285
  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];
1110
1286
  if (Object.keys(body2).some((k) => !allowed.includes(k))) return void 0;
1111
- const record2 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso(), updated_at: iso() };
1112
- if (resource === "products") Object.assign(record2, { title: body2.title, body_html: body2.body_html ?? null, vendor: body2.vendor ?? null, product_type: body2.product_type ?? null, handle: shopifySlug(String(body2.title)), status: str(body2.status) ?? "active", tags: body2.tags ?? "", variants: Array.isArray(body2.variants) ? structuredClone(body2.variants) : [], options: Array.isArray(body2.options) ? structuredClone(body2.options) : [], image: null, images: [] });
1113
- if (resource === "orders") Object.assign(record2, { email: body2.email ?? null, phone: body2.phone ?? null, note: body2.note ?? null, line_items: structuredClone(body2.line_items), total_price: typeof body2.total_price === "string" ? body2.total_price : Number(Array.isArray(body2.line_items) ? body2.line_items.reduce((sum, item) => sum + Number(item.price ?? 0) * Number(item.quantity ?? 1), 0) : 0).toFixed(2), currency: str(body2.currency) ?? "USD", financial_status: str(body2.financial_status) ?? "pending", fulfillment_status: body2.fulfillment_status ?? null });
1114
- if (resource === "customers") Object.assign(record2, { first_name: body2.first_name ?? null, last_name: body2.last_name ?? null, email: body2.email ?? null, phone: body2.phone ?? null, note: body2.note ?? null, tags: body2.tags ?? "", state: "enabled", verified_email: true, accepts_marketing: false });
1115
- rowsIn2.push(record2);
1116
- return created(collection, { [wrap]: enriched(record2) }, record2);
1117
- }
1118
- const record = rowsIn2.find((r) => String(r.id) === id);
1119
- if (!record) return notFoundShopify();
1120
- if (method === "GET") return ok(collection, { [wrap]: enriched(record) });
1287
+ const record3 = { id: uniqueId(rowsIn2, { products: 632910392, orders: 450789469, customers: 207119551 }[resource] + sequence), created_at: iso(), updated_at: iso() };
1288
+ if (resource === "products") Object.assign(record3, { title: body2.title, body_html: body2.body_html ?? null, vendor: body2.vendor ?? null, product_type: body2.product_type ?? null, handle: shopifySlug(String(body2.title)), status: str(body2.status) ?? "active", tags: body2.tags ?? "", variants: Array.isArray(body2.variants) ? structuredClone(body2.variants) : [], options: Array.isArray(body2.options) ? structuredClone(body2.options) : [], image: null, images: [] });
1289
+ if (resource === "orders") Object.assign(record3, { email: body2.email ?? null, phone: body2.phone ?? null, note: body2.note ?? null, line_items: structuredClone(body2.line_items), total_price: typeof body2.total_price === "string" ? body2.total_price : Number(Array.isArray(body2.line_items) ? body2.line_items.reduce((sum, item) => sum + Number(item.price ?? 0) * Number(item.quantity ?? 1), 0) : 0).toFixed(2), currency: str(body2.currency) ?? "USD", financial_status: str(body2.financial_status) ?? "pending", fulfillment_status: body2.fulfillment_status ?? null });
1290
+ if (resource === "customers") Object.assign(record3, { first_name: body2.first_name ?? null, last_name: body2.last_name ?? null, email: body2.email ?? null, phone: body2.phone ?? null, note: body2.note ?? null, tags: body2.tags ?? "", state: "enabled", verified_email: true, accepts_marketing: false });
1291
+ rowsIn2.push(record3);
1292
+ return created(collection, { [wrap]: enriched(record3) }, record3);
1293
+ }
1294
+ const record2 = rowsIn2.find((r) => String(r.id) === id);
1295
+ if (!record2) return notFoundShopify();
1296
+ if (method === "GET") return ok(collection, { [wrap]: enriched(record2) });
1121
1297
  if (method === "PUT") {
1122
1298
  if (Object.keys(params).some((k) => k !== wrap) || !isObject(params[wrap])) return badRequest(collection, { errors: { [wrap]: ["expected a root object"] } });
1123
1299
  const body2 = params[wrap];
1124
1300
  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];
1125
1301
  if (Object.keys(body2).some((k) => !allowed.includes(k))) return void 0;
1126
- for (const [k, v] of Object.entries(body2)) record[k] = v;
1127
- if (resource === "products" && body2.title !== void 0) record.handle = shopifySlug(String(body2.title));
1128
- record.updated_at = iso();
1129
- return write(200, collection, { [wrap]: enriched(record) }, record);
1302
+ for (const [k, v] of Object.entries(body2)) record2[k] = v;
1303
+ if (resource === "products" && body2.title !== void 0) record2.handle = shopifySlug(String(body2.title));
1304
+ record2.updated_at = iso();
1305
+ return write(200, collection, { [wrap]: enriched(record2) }, record2);
1130
1306
  }
1131
1307
  return void 0;
1132
1308
  }
@@ -1506,9 +1682,9 @@ function twilioOperation(method, path2, params, _headers, data, sequence) {
1506
1682
  if (missing.length) return fail2(400, missing.length === allowed.length ? "21211" : "21606", `No parameter provided for ${allowed.filter((k) => missing.includes(k)).join(", ")}`);
1507
1683
  const prefix = resource === "Messages" ? "SM" : "CA";
1508
1684
  const sid = `${prefix}${sha2(`${prefix.toLowerCase()}:${sequence}:${accountSid}`).slice(0, 32)}`;
1509
- 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` };
1510
- records.push(record);
1511
- return created(collection, structuredClone(record), record);
1685
+ const record2 = 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` };
1686
+ records.push(record2);
1687
+ return created(collection, structuredClone(record2), record2);
1512
1688
  }
1513
1689
  if (method === "GET") {
1514
1690
  if (Object.keys(params).some((k) => !["To", "From"].includes(k))) return void 0;
@@ -1574,6 +1750,7 @@ var EPOCH, iso, sha2, detUuid, rows, notFound, badRequest, ok, created, write, i
1574
1750
  var init_rest_adapters = __esm({
1575
1751
  "src/runtime/rest-adapters.ts"() {
1576
1752
  "use strict";
1753
+ init_llm_adapter();
1577
1754
  init_composio_twin();
1578
1755
  init_google_oauth_twin();
1579
1756
  init_gmail_mime();
@@ -1591,8 +1768,8 @@ var init_rest_adapters = __esm({
1591
1768
  notFound = (collection, body2) => ({ status: 404, body: body2, collection });
1592
1769
  badRequest = (collection, body2) => ({ status: 400, body: body2, collection });
1593
1770
  ok = (collection, body2, operation = "read") => ({ status: 200, body: body2, collection, operation });
1594
- created = (collection, body2, record) => ({ status: 201, body: body2, collection, record: structuredClone(record), operation: "write" });
1595
- write = (status, collection, body2, record) => ({ status, body: body2, collection, record: structuredClone(record), operation: "write" });
1771
+ created = (collection, body2, record2) => ({ status: 201, body: body2, collection, record: structuredClone(record2), operation: "write" });
1772
+ write = (status, collection, body2, record2) => ({ status, body: body2, collection, record: structuredClone(record2), operation: "write" });
1596
1773
  isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
1597
1774
  str = (v) => typeof v === "string" ? v : void 0;
1598
1775
  pagination = (params, limitDefault, limitMax) => {
@@ -1620,7 +1797,7 @@ var init_rest_adapters = __esm({
1620
1797
  };
1621
1798
  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 });
1622
1799
  notionError = (collection, status, code, message) => ({ status, body: { object: "error", status, code, message }, collection });
1623
- hubspotEnvelope = (record) => ({ id: record.id, properties: structuredClone(record.properties), createdAt: record.createdAt, updatedAt: record.updatedAt, archived: false });
1800
+ hubspotEnvelope = (record2) => ({ id: record2.id, properties: structuredClone(record2.properties), createdAt: record2.createdAt, updatedAt: record2.updatedAt, archived: false });
1624
1801
  SHOPIFY_VERSION = "2024-01";
1625
1802
  shopifySlug = (value) => value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1626
1803
  googleError = (collection, status, message) => ({ status, body: { error: { code: status, message, status: status === 404 ? "NOT_FOUND" : "INVALID_ARGUMENT" } }, collection });
@@ -1643,9 +1820,13 @@ var init_rest_adapters = __esm({
1643
1820
  twilio: { status: 501, code: "50101", message: "Outside the verified AgentTwin Twilio twin subset", more_info: "", forwardedToProduction: false },
1644
1821
  composio: { error: { message: "Outside the AgentTwin Composio Gmail subset" }, forwardedToProduction: false },
1645
1822
  "google-oauth": { error: "unsupported_operation", error_description: "Outside the AgentTwin Google OAuth refresh subset", forwardedToProduction: false },
1823
+ openai: { error: { type: "invalid_request_error", code: "unsupported_operation", message: "Outside the AgentTwin scripted OpenAI subset, or no scripted response is left" }, forwardedToProduction: false },
1824
+ anthropic: { type: "error", error: { type: "invalid_request_error", message: "Outside the AgentTwin scripted Anthropic subset, or no scripted response is left" }, forwardedToProduction: false },
1646
1825
  zendesk: { error: "UnsupportedOperation", description: "Outside the verified AgentTwin Zendesk twin subset", forwardedToProduction: false }
1647
1826
  };
1648
1827
  REST_ADAPTERS = {
1828
+ openai: openaiOperation,
1829
+ anthropic: anthropicOperation,
1649
1830
  github: githubOperation,
1650
1831
  linear: linearOperation,
1651
1832
  notion: notionOperation,
@@ -1747,6 +1928,7 @@ var init_http_world = __esm({
1747
1928
  init_stripe_adapter();
1748
1929
  init_rest_adapters();
1749
1930
  init_seed();
1931
+ init_spec();
1750
1932
  HttpWorld = class {
1751
1933
  constructor(spec, seed) {
1752
1934
  this.spec = spec;
@@ -1767,10 +1949,10 @@ var init_http_world = __esm({
1767
1949
  epoch = 0;
1768
1950
  replayKeys = /* @__PURE__ */ new Map();
1769
1951
  sourceContext = new AsyncLocalStorage();
1770
- record(service, operation, path2, detail, record) {
1952
+ record(service, operation, path2, detail, record2) {
1771
1953
  if (this.events.length >= 5e4) return;
1772
1954
  const source = this.sourceContext.getStore();
1773
- this.events.push({ sequence: this.events.length + 1, service, operation, path: path2, detail, ...record ? { record: structuredClone(record) } : {}, ...source ? { source } : {} });
1955
+ this.events.push({ sequence: this.events.length + 1, service, operation, path: path2, detail, ...record2 ? { record: structuredClone(record2) } : {}, ...source ? { source } : {} });
1774
1956
  }
1775
1957
  rejectUnsupported(service, method, path2, detail) {
1776
1958
  this.unsupported.push(`${service}: ${method} ${path2}: ${detail}`);
@@ -1791,10 +1973,11 @@ var init_http_world = __esm({
1791
1973
  const faultKey = `${fault?.type ?? ""}\0${service.name}\0${fault?.path ?? ""}`;
1792
1974
  const adapterService = service.adapter === "stripe" || service.adapter && REST_ADAPTER_NAMES.includes(service.adapter);
1793
1975
  const restAdapter = service.adapter && REST_ADAPTER_NAMES.includes(service.adapter) ? REST_ADAPTERS[service.adapter] : void 0;
1794
- const altAuth = (headers) => service.adapter === "composio" ? headers["x-api-key"] === token : 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;
1976
+ const altAuth = (headers) => service.adapter === "composio" || service.adapter === "anthropic" ? headers["x-api-key"] === token : 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;
1795
1977
  const data = /* @__PURE__ */ Object.create(null);
1796
1978
  this.state[service.name] = data;
1797
1979
  for (const c of service.collections) data[c.path] = structuredClone(c.seed);
1980
+ for (const path2 of ADAPTER_OPTIONAL_COLLECTIONS[service.adapter] ?? []) data[path2] ??= [];
1798
1981
  const keys = /* @__PURE__ */ new Map();
1799
1982
  this.replayKeys.set(service.name, keys);
1800
1983
  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;
@@ -2107,6 +2290,7 @@ var init_http_world = __esm({
2107
2290
  this.quiesce();
2108
2291
  for (const service of this.spec.services) {
2109
2292
  for (const collection of service.collections) this.state[service.name][collection.path] = structuredClone(collection.seed);
2293
+ for (const path2 of ADAPTER_OPTIONAL_COLLECTIONS[service.adapter] ?? []) if (!service.collections.some((c) => c.path === path2)) this.state[service.name][path2] = [];
2110
2294
  this.replayKeys.get(service.name)?.clear();
2111
2295
  }
2112
2296
  this.events.length = 0;
@@ -2213,9 +2397,9 @@ function evaluateProperty(policy, final, events) {
2213
2397
  const writes = eventsFor("write", policy.params?.where);
2214
2398
  const lost = writes.filter((e) => {
2215
2399
  if (!e.record) return false;
2216
- const record = e.record;
2217
- if (typeof record.id === "string" && record.id) return !rows2.some((row) => row.id === record.id);
2218
- return !rows2.some((row) => isDeepStrictEqual3(row, record));
2400
+ const record2 = e.record;
2401
+ if (typeof record2.id === "string" && record2.id) return !rows2.some((row) => row.id === record2.id);
2402
+ return !rows2.some((row) => isDeepStrictEqual3(row, record2));
2219
2403
  });
2220
2404
  const unknown2 = writes.some((e) => !e.record);
2221
2405
  return {
@@ -2290,6 +2474,24 @@ var init_contracts = __esm({
2290
2474
  ],
2291
2475
  limitations: ["Custom API contract, not a vendor replica", "No update/delete, pagination, OAuth, webhooks or schema validation", "Idempotency compares the exact parsed JSON serialization"]
2292
2476
  },
2477
+ openai: {
2478
+ version: "1.0.0",
2479
+ authentication: "Bearer run-scoped test token; official OpenAI SDK configured with the twin base URL",
2480
+ operations: [
2481
+ { method: "POST", endpoint: "/v1/chat/completions", effect: "return the next scripted response (text and/or tool calls) and record the call in /requests", parameters: ["model", "messages", "tools", "tool_choice", "other generation parameters are accepted and ignored"], errors: ["501 no scripted response left", "501 stream: true"] },
2482
+ { method: "GET", endpoint: "/v1/requests", effect: "list recorded model calls", parameters: [], errors: [] }
2483
+ ],
2484
+ limitations: ["Scripted responses from the world file, not a language model; nothing is generated", "Responses are selected in order, or by a match substring of the last user message", "No streaming, embeddings, assistants, images or audio", "Token usage is reported as zero"]
2485
+ },
2486
+ anthropic: {
2487
+ version: "1.0.0",
2488
+ authentication: "x-api-key run-scoped test token; official Anthropic SDK configured with the twin base URL",
2489
+ operations: [
2490
+ { method: "POST", endpoint: "/v1/messages", effect: "return the next scripted response (text and/or tool_use blocks) and record the call in /requests", parameters: ["model", "messages", "tools", "system", "other generation parameters are accepted and ignored"], errors: ["501 no scripted response left", "501 stream: true"] },
2491
+ { method: "GET", endpoint: "/v1/requests", effect: "list recorded model calls", parameters: [], errors: [] }
2492
+ ],
2493
+ limitations: ["Scripted responses from the world file, not a language model; nothing is generated", "Responses are selected in order, or by a match substring of the last user message", "No streaming, batches or token counting", "Token usage is reported as zero"]
2494
+ },
2293
2495
  stripe: {
2294
2496
  version: "1.0.0",
2295
2497
  authentication: "Bearer run-scoped test token; official Stripe SDK configured with test endpoint",
@@ -2298,9 +2500,13 @@ var init_contracts = __esm({
2298
2500
  { method: "GET", endpoint: "/v1/customers[/<id>]", effect: "retrieve or list customers", parameters: ["limit", "starting_after"], errors: ["404 resource_missing", "400 invalid pagination"] },
2299
2501
  { method: "POST", endpoint: "/v1/payment_intents", effect: "create test payment intent", parameters: ["amount", "currency", "customer", "payment_method", "confirm"], errors: ["400 invalid parameters", "400 resource_missing", "402 card_declined"] },
2300
2502
  { method: "GET", endpoint: "/v1/payment_intents/<id>", effect: "retrieve intent", parameters: [], errors: ["404 resource_missing"] },
2301
- { method: "POST", endpoint: "/v1/payment_intents/<id>/confirm", effect: "test success or decline", parameters: ["payment_method"], errors: ["404 resource_missing", "400 unsupported test method", "402 card_declined"] }
2503
+ { method: "POST", endpoint: "/v1/payment_intents/<id>/confirm", effect: "test success or decline; success creates a charge", parameters: ["payment_method"], errors: ["404 resource_missing", "400 unsupported test method", "402 card_declined"] },
2504
+ { method: "POST", endpoint: "/v1/refunds", effect: "refund all or part of a charge; updates amount_refunded and records charge.refunded", parameters: ["charge", "payment_intent", "amount", "reason", "metadata"], errors: ["400 resource_missing", "400 charge_not_refundable", "400 charge_already_refunded", "400 amount_too_large"] },
2505
+ { method: "GET", endpoint: "/v1/refunds[/<id>]", effect: "retrieve or list refunds", parameters: ["limit", "starting_after", "charge", "payment_intent"], errors: ["404 resource_missing"] },
2506
+ { method: "GET", endpoint: "/v1/charges[/<id>]", effect: "retrieve or list charges", parameters: ["limit"], errors: ["404 resource_missing"] },
2507
+ { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] }
2302
2508
  ],
2303
- limitations: ["Bounded subset, not full Stripe parity; minimal object fields only; no real money", "Only pm_card_visa and pm_card_chargeDeclined test methods", "No webhooks, refunds, subscriptions, payment-method APIs, metadata, updates or deletes", "Customers list supports limit/starting_after; payment intent listing unsupported", "POST idempotency supported; reset clears records and keys; unsupported operations/parameters return 501 and make coverage incomplete"]
2509
+ limitations: ["Bounded subset, not full Stripe parity; minimal object fields only; no real money", "Only pm_card_visa and pm_card_chargeDeclined test methods", "Events are recorded and listable but webhooks are not pushed to your application", "No subscriptions, payment-method APIs, refund cancellation, updates or deletes", "Customers list supports limit/starting_after; payment intent listing unsupported", "POST idempotency supported; reset clears records and keys; unsupported operations/parameters return 501 and make coverage incomplete"]
2304
2510
  },
2305
2511
  slack: {
2306
2512
  version: "1.0.0",
@@ -4128,7 +4334,7 @@ var init_catalog = __esm({
4128
4334
  id: "openai",
4129
4335
  title: "OpenAI",
4130
4336
  category: "ai",
4131
- twin: planned(NO_TWIN),
4337
+ twin: partial("openai"),
4132
4338
  signatures: {
4133
4339
  packages: {
4134
4340
  node: ["openai"],
@@ -4141,11 +4347,26 @@ var init_catalog = __esm({
4141
4347
  envPrefixes: ["OPENAI_"]
4142
4348
  }
4143
4349
  },
4350
+ {
4351
+ id: "gemini",
4352
+ title: "Google Gemini",
4353
+ category: "ai",
4354
+ twin: planned(NO_TWIN),
4355
+ signatures: {
4356
+ packages: {
4357
+ node: ["@google/genai", "@google/generative-ai"],
4358
+ python: ["google-genai", "google-generativeai"]
4359
+ },
4360
+ imports: ["@google/genai", "@google/generative-ai", "GoogleGenAI\\(", "GoogleGenerativeAI\\("],
4361
+ hosts: ["generativelanguage.googleapis.com"],
4362
+ envPrefixes: ["GEMINI_", "GOOGLE_GENAI_"]
4363
+ }
4364
+ },
4144
4365
  {
4145
4366
  id: "anthropic",
4146
4367
  title: "Anthropic",
4147
4368
  category: "ai",
4148
- twin: planned(NO_TWIN),
4369
+ twin: partial("anthropic"),
4149
4370
  signatures: {
4150
4371
  packages: {
4151
4372
  node: ["@anthropic-ai/sdk"],