agenttwin 0.3.37 → 0.3.39

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 (107) hide show
  1. package/dist/api.js +25518 -16009
  2. package/dist/cli.js +49 -2
  3. package/dist/dashboard/assets/next/static/chunks/{1937-2369d8ef2eae7700.js → 1937-6c86fddc443de922.js} +1 -1
  4. package/dist/dashboard/assets/next/static/chunks/424-5191e91fec0be2c7.js +1 -0
  5. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-f05b53aa432a7110.js +1 -0
  6. package/dist/dashboard/assets/next/static/chunks/app/about/page-8378255082922f7c.js +1 -0
  7. package/dist/dashboard/assets/next/static/chunks/app/account/password/{page-0478a7f18cc5e31b.js → page-4db0777af7564cb4.js} +1 -1
  8. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-6706d2afc96be601.js +1 -0
  9. package/dist/dashboard/assets/next/static/chunks/app/auth/page-6706d2afc96be601.js +1 -0
  10. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-d92d0846e7847b0f.js +1 -0
  11. package/dist/dashboard/assets/next/static/chunks/app/compare/page-6706d2afc96be601.js +1 -0
  12. package/dist/dashboard/assets/next/static/chunks/app/contact/page-6706d2afc96be601.js +1 -0
  13. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-cbd7e31c6d430a1a.js +1 -0
  14. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-f45f96c066eb9de2.js +1 -0
  15. package/dist/dashboard/assets/next/static/chunks/app/demo/{page-ac6e235c635cb130.js → page-db243af5ea4b6376.js} +1 -1
  16. package/dist/dashboard/assets/next/static/chunks/app/developers/page-6706d2afc96be601.js +1 -0
  17. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-83fc0a3aa3425b02.js +1 -0
  18. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-6706d2afc96be601.js +1 -0
  19. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-2451558ccbe066c9.js +1 -0
  20. package/dist/dashboard/assets/next/static/chunks/app/guides/page-6706d2afc96be601.js +1 -0
  21. package/dist/dashboard/assets/next/static/chunks/app/{layout-8aa153f632f0aa20.js → layout-13d2f06cab6f3ef6.js} +1 -1
  22. package/dist/dashboard/assets/next/static/chunks/app/login/page-589519cc705ec22f.js +1 -0
  23. package/dist/dashboard/assets/next/static/chunks/app/not-found-6706d2afc96be601.js +1 -0
  24. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-c4292b08dedb1e5c.js +1 -0
  25. package/dist/dashboard/assets/next/static/chunks/app/page-bfcf9194963bf52b.js +1 -0
  26. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-e65353f9ee62da36.js +1 -0
  27. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-6706d2afc96be601.js +1 -0
  28. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-6706d2afc96be601.js +1 -0
  29. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-6706d2afc96be601.js +1 -0
  30. package/dist/dashboard/assets/next/static/chunks/app/security/page-6706d2afc96be601.js +1 -0
  31. package/dist/dashboard/assets/next/static/chunks/app/signup/page-589519cc705ec22f.js +1 -0
  32. package/dist/dashboard/assets/next/static/chunks/app/status/page-47f0d1533bf1206f.js +1 -0
  33. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-6706d2afc96be601.js +1 -0
  34. package/dist/dashboard/assets/next/static/chunks/app/terms/page-6706d2afc96be601.js +1 -0
  35. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-76020499f90782bd.js +1 -0
  36. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-cb63082b6709d22e.js +1 -0
  37. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-d3227c5987005526.js +1 -0
  38. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-40a3cf0903538784.js +1 -0
  39. package/dist/dashboard/assets/next/static/chunks/app/v2/onboarding/{page-7c08d2c43f0be9d5.js → page-921ad64530803c42.js} +1 -1
  40. package/dist/dashboard/assets/next/static/chunks/app/v2/page-d0b682a723aa566f.js +1 -0
  41. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-40a3cf0903538784.js +1 -0
  42. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-6706d2afc96be601.js +1 -0
  43. package/dist/dashboard/assets/next/static/chunks/{main-app-4051d8ba998bea15.js → main-app-cc626a1cec570e8f.js} +1 -1
  44. package/dist/dashboard/assets/next/static/chunks/{webpack-b1e92d10ff1fbc69.js → webpack-a48857e1e72fd84a.js} +1 -1
  45. package/dist/dashboard/assets/next/static/css/4bee95c06986ad43.css +1 -0
  46. package/dist/dashboard/assets/next/static/css/75f812c09155fe4d.css +1 -0
  47. package/dist/dashboard/assets/next/static/css/8b41516b04992d45.css +1 -0
  48. package/dist/dashboard/assets/next/static/css/923568b6c3a9a99a.css +1 -0
  49. package/dist/dashboard/index.html +2 -2
  50. package/dist/discover-worker.js +5800 -0
  51. package/dist/engine.js +22482 -8402
  52. package/dist/gateway.js +25520 -16006
  53. package/dist/scan-worker.js +3312 -0
  54. package/dist/twins/catalog.json +122 -161
  55. package/dist/twins/packs/algolia/index.mjs +1 -1
  56. package/dist/twins/packs/openai/index.mjs +4 -4
  57. package/dist/twins/packs/polar/index.mjs +1 -1
  58. package/dist/twins/packs/slack/index.mjs +1 -1
  59. package/dist/twins/packs/stripe/index.mjs +7 -7
  60. package/dist/twins/packs/twilio/index.mjs +1 -1
  61. package/dist/worker.js +2375 -2153
  62. package/dist/world-host.js +3149 -2876
  63. package/package.json +4 -1
  64. package/dist/dashboard/assets/next/static/chunks/424-83736cfafc224fc6.js +0 -1
  65. package/dist/dashboard/assets/next/static/chunks/app/_not-found/page-b60a5aad66f3bf1d.js +0 -1
  66. package/dist/dashboard/assets/next/static/chunks/app/about/page-a30c6925cc9ac983.js +0 -1
  67. package/dist/dashboard/assets/next/static/chunks/app/api-policy/page-91ad6c5e4226778f.js +0 -1
  68. package/dist/dashboard/assets/next/static/chunks/app/auth/page-91ad6c5e4226778f.js +0 -1
  69. package/dist/dashboard/assets/next/static/chunks/app/blog/layout-6c159db381b82832.js +0 -1
  70. package/dist/dashboard/assets/next/static/chunks/app/compare/page-91ad6c5e4226778f.js +0 -1
  71. package/dist/dashboard/assets/next/static/chunks/app/contact/page-91ad6c5e4226778f.js +0 -1
  72. package/dist/dashboard/assets/next/static/chunks/app/dashboard/layout-0050f308b9f77c24.js +0 -1
  73. package/dist/dashboard/assets/next/static/chunks/app/dashboard/page-3d8c07ca2af8081c.js +0 -1
  74. package/dist/dashboard/assets/next/static/chunks/app/developers/page-91ad6c5e4226778f.js +0 -1
  75. package/dist/dashboard/assets/next/static/chunks/app/docs/[[...slug]]/page-c86920ba0d1f3bc0.js +0 -1
  76. package/dist/dashboard/assets/next/static/chunks/app/dpa/page-91ad6c5e4226778f.js +0 -1
  77. package/dist/dashboard/assets/next/static/chunks/app/enterprise/page-11514cc52285b7f3.js +0 -1
  78. package/dist/dashboard/assets/next/static/chunks/app/guides/page-91ad6c5e4226778f.js +0 -1
  79. package/dist/dashboard/assets/next/static/chunks/app/login/page-99ebb4d265222728.js +0 -1
  80. package/dist/dashboard/assets/next/static/chunks/app/not-found-91ad6c5e4226778f.js +0 -1
  81. package/dist/dashboard/assets/next/static/chunks/app/onboarding/page-9e59af0296c9366b.js +0 -1
  82. package/dist/dashboard/assets/next/static/chunks/app/page-76277dc68b6a22bd.js +0 -1
  83. package/dist/dashboard/assets/next/static/chunks/app/pricing/page-c7015af858f4db8e.js +0 -1
  84. package/dist/dashboard/assets/next/static/chunks/app/privacy/page-91ad6c5e4226778f.js +0 -1
  85. package/dist/dashboard/assets/next/static/chunks/app/sandbox/page-91ad6c5e4226778f.js +0 -1
  86. package/dist/dashboard/assets/next/static/chunks/app/scoreboard/page-91ad6c5e4226778f.js +0 -1
  87. package/dist/dashboard/assets/next/static/chunks/app/security/page-91ad6c5e4226778f.js +0 -1
  88. package/dist/dashboard/assets/next/static/chunks/app/signup/page-99ebb4d265222728.js +0 -1
  89. package/dist/dashboard/assets/next/static/chunks/app/status/page-fd41c4e7838d9949.js +0 -1
  90. package/dist/dashboard/assets/next/static/chunks/app/subprocessors/page-91ad6c5e4226778f.js +0 -1
  91. package/dist/dashboard/assets/next/static/chunks/app/terms/page-91ad6c5e4226778f.js +0 -1
  92. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/layout-a79d128eb3b0b7d2.js +0 -1
  93. package/dist/dashboard/assets/next/static/chunks/app/v2/dashboard/page-a9fa05c9ae5c24dc.js +0 -1
  94. package/dist/dashboard/assets/next/static/chunks/app/v2/layout-2e97381ae7a59ba0.js +0 -1
  95. package/dist/dashboard/assets/next/static/chunks/app/v2/login/page-57afbac97afd31fa.js +0 -1
  96. package/dist/dashboard/assets/next/static/chunks/app/v2/page-35998431fb40a9c9.js +0 -1
  97. package/dist/dashboard/assets/next/static/chunks/app/v2/signup/page-57afbac97afd31fa.js +0 -1
  98. package/dist/dashboard/assets/next/static/chunks/app/what-is-agenttwin/page-91ad6c5e4226778f.js +0 -1
  99. package/dist/dashboard/assets/next/static/css/2c38dfe54afd9bb6.css +0 -1
  100. package/dist/dashboard/assets/next/static/css/605ac70c9cf7a260.css +0 -1
  101. package/dist/dashboard/assets/next/static/css/734b61a26b31f1d1.css +0 -1
  102. package/dist/dashboard/assets/next/static/css/96134c7d160c4fc3.css +0 -1
  103. package/dist/twins/packs/vgauth/LICENSE +0 -202
  104. package/dist/twins/packs/vgauth/NOTICE +0 -7
  105. package/dist/twins/packs/vgauth/index.mjs +0 -2
  106. /package/dist/dashboard/assets/next/static/{RsIyq0Rz3py_mKuoIqn42 → KNTxh0SQ8GqNZPTSXNcRe}/_buildManifest.js +0 -0
  107. /package/dist/dashboard/assets/next/static/{RsIyq0Rz3py_mKuoIqn42 → KNTxh0SQ8GqNZPTSXNcRe}/_ssgManifest.js +0 -0
@@ -0,0 +1,3312 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/flow/scan-worker.ts
4
+ import { parentPort, workerData } from "worker_threads";
5
+
6
+ // src/flow/call-input.ts
7
+ function inputBinding(node, name, aliases) {
8
+ if (node?.type === "Identifier" && name && node.name === name) return { kind: "input" };
9
+ if (node?.type === "Identifier" && aliases?.has(node.name)) return aliases.get(node.name);
10
+ if (["StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"].includes(node?.type)) return { kind: "literal", value: node.type === "NullLiteral" ? null : node.value };
11
+ if (node?.type === "MemberExpression" && !node.computed) return { kind: "field", base: inputBinding(node.object, name, aliases), key: node.property.name };
12
+ if (node?.type === "ObjectExpression") {
13
+ const fields = {};
14
+ for (const p of node.properties) {
15
+ const key2 = p.key?.name ?? p.key?.value;
16
+ if (p.type !== "ObjectProperty" || p.computed || ["__proto__", "constructor", "prototype"].includes(key2) || Object.hasOwn(fields, key2)) return { kind: "unknown" };
17
+ fields[key2] = inputBinding(p.value, name, aliases);
18
+ }
19
+ return { kind: "object", fields };
20
+ }
21
+ return { kind: "unknown" };
22
+ }
23
+
24
+ // src/flow/kafka-assertions.ts
25
+ function kafkaSendFromAst(node, inputName) {
26
+ const props = (n) => {
27
+ if (n?.type !== "ObjectExpression") return;
28
+ const result2 = /* @__PURE__ */ new Map();
29
+ for (const p of n.properties) {
30
+ if (p.type !== "ObjectProperty" || p.computed) return;
31
+ const k = p.key.name ?? p.key.value;
32
+ if (result2.has(k)) return;
33
+ result2.set(k, p.value);
34
+ }
35
+ return result2;
36
+ };
37
+ const value2 = (n) => {
38
+ if (n?.type === "StringLiteral") return { kind: "literal", value: n.value };
39
+ if (n?.type === "NullLiteral") return { kind: "literal", value: null };
40
+ let json = false;
41
+ if (n?.type === "CallExpression" && n.callee?.type === "MemberExpression" && !n.callee.computed && n.callee.object?.name === "JSON" && n.callee.property?.name === "stringify" && n.arguments.length === 1) {
42
+ json = true;
43
+ n = n.arguments[0];
44
+ }
45
+ if (inputName && n?.type === "Identifier" && n.name === inputName && json) return { kind: "input", json };
46
+ if (inputName && n?.type === "MemberExpression" && !n.computed && n.object?.type === "Identifier" && n.object.name === inputName) return { kind: "input", field: n.property.name, json };
47
+ };
48
+ const args = props(node), topic = args?.get("topic");
49
+ const result = { ...topic?.type === "StringLiteral" ? { topic: topic.value } : {} };
50
+ const messages = args?.get("messages");
51
+ if (messages?.type !== "ArrayExpression") return result;
52
+ const parsed = [];
53
+ for (const message of messages.elements) {
54
+ const p = props(message);
55
+ if (!p) return result;
56
+ if ([...p.keys()].some((k) => !["key", "value", "partition"].includes(k))) return result;
57
+ if (p.has("partition") && !(p.get("partition")?.type === "NumericLiteral" && p.get("partition").value === 0)) return result;
58
+ const key2 = p.has("key") ? value2(p.get("key")) : { kind: "literal", value: null }, v = value2(p.get("value"));
59
+ if (!key2 || !v) return result;
60
+ parsed.push({ key: key2, value: v });
61
+ }
62
+ result.messages = parsed;
63
+ return result;
64
+ }
65
+
66
+ // src/flow/rabbitmq-assertions.ts
67
+ function rabbitmqSendFromAst(operation, args, inputName) {
68
+ const publishing = /(^|\.)publish$/.test(operation), queue = args[publishing ? 1 : 0], body = args[publishing ? 2 : 1], options = args[publishing ? 3 : 2];
69
+ if (publishing && !(args[0]?.type === "StringLiteral" && args[0].value === "")) return {};
70
+ const topic = queue?.type === "StringLiteral" ? queue.value : void 0;
71
+ if (body?.type !== "CallExpression" || body.callee?.type !== "MemberExpression" || body.callee.computed || body.callee.object?.name !== "Buffer" || body.callee.property?.name !== "from" || body.arguments.length < 1 || body.arguments.length > 2) return { topic };
72
+ if (body.arguments.length === 2 && !(body.arguments[1]?.type === "StringLiteral" && ["utf8", "utf-8"].includes(body.arguments[1].value))) return { topic };
73
+ const prop = (name, value2) => ({ type: "ObjectProperty", computed: false, key: { type: "Identifier", name }, value: value2 });
74
+ let key2 = { type: "NullLiteral" };
75
+ if (options) {
76
+ if (options.type !== "ObjectExpression") return { topic };
77
+ const seen = /* @__PURE__ */ new Set();
78
+ for (const p of options.properties) {
79
+ if (p.type !== "ObjectProperty" || p.computed) return { topic };
80
+ const name = p.key.name ?? p.key.value;
81
+ if (seen.has(name)) return { topic };
82
+ seen.add(name);
83
+ if (name === "messageId") key2 = p.value;
84
+ }
85
+ }
86
+ return kafkaSendFromAst({ type: "ObjectExpression", properties: [prop("topic", queue), prop("messages", { type: "ArrayExpression", elements: [{ type: "ObjectExpression", properties: [prop("key", key2), prop("value", body.arguments[0])] }] })] }, inputName);
87
+ }
88
+
89
+ // src/runtime/packs.ts
90
+ import { existsSync, readdirSync, readFileSync } from "fs";
91
+ import { dirname, join, resolve } from "path";
92
+ import { fileURLToPath, pathToFileURL } from "url";
93
+
94
+ // src/runtime/compatible-packs.ts
95
+ var OPENAI_COMPATIBLE = [
96
+ // https://console.groq.com/docs/openai
97
+ { name: "groq", title: "Groq", host: "api.groq.com", prefix: "/openai/v1", sdks: ["groq-sdk", "@ai-sdk/groq"], pypi: ["groq"], env: ["GROQ_API_KEY"] },
98
+ // https://inference-docs.cerebras.ai/resources/openai
99
+ { name: "cerebras", title: "Cerebras", host: "api.cerebras.ai", prefix: "/v1", sdks: ["@cerebras/cerebras_cloud_sdk", "@ai-sdk/cerebras"], pypi: ["cerebras-cloud-sdk"], env: ["CEREBRAS_API_KEY"] },
100
+ // https://docs.perplexity.ai/guides/chat-completions-guide (POST https://api.perplexity.ai/chat/completions)
101
+ { name: "perplexity", title: "Perplexity", host: "api.perplexity.ai", prefix: "", sdks: ["@ai-sdk/perplexity", "@perplexity-ai/perplexity_ai"], pypi: ["perplexityai"], env: ["PERPLEXITY_API_KEY", "PPLX_API_KEY"] },
102
+ // https://docs.sambanova.ai/cloud/docs/capabilities/openai-compatibility
103
+ { name: "sambanova", title: "SambaNova", host: "api.sambanova.ai", prefix: "/v1", sdks: ["sambanova", "@ai-sdk/sambanova"], pypi: ["sambanova"], env: ["SAMBANOVA_API_KEY"] }
104
+ ];
105
+ var BASE_PACK = "openai";
106
+
107
+ // src/runtime/packs.ts
108
+ function packsDir() {
109
+ const here = dirname(fileURLToPath(import.meta.url));
110
+ const candidates = [process.env.AGENTTWIN_TWINS_DIR, join(here, "twins"), join(here, "../twins"), resolve(here, "../../../twins/dist")];
111
+ return candidates.find((dir) => !!dir && existsSync(join(dir, "catalog.json")));
112
+ }
113
+ var cached;
114
+ function packCatalog() {
115
+ if (cached !== void 0) return cached;
116
+ const dir = packsDir();
117
+ cached = dir ? JSON.parse(readFileSync(join(dir, "catalog.json"), "utf8")) : null;
118
+ const base = cached?.packs[BASE_PACK];
119
+ if (cached && base) for (const v of OPENAI_COMPATIBLE) {
120
+ if (Object.hasOwn(cached.packs, v.name)) continue;
121
+ const field = base.credentialDoor?.fill.OPENAI_API_KEY ?? "api_key";
122
+ cached.packs[v.name] = {
123
+ ...base,
124
+ name: v.name,
125
+ vendor: v.name,
126
+ servedBy: BASE_PACK,
127
+ description: `${v.title} (OpenAI-compatible API), served by the OpenAI twin`,
128
+ hosts: [{ host: v.host }],
129
+ adoption: { sdks: v.sdks, envStems: v.env.map((e) => e.replace(/_API_KEY$/, "")), pypi: v.pypi },
130
+ credentialDoor: base.credentialDoor ? { ...base.credentialDoor, fill: Object.fromEntries(v.env.map((e) => [e, field])) } : null
131
+ };
132
+ delete cached.excluded?.[v.name];
133
+ }
134
+ return cached;
135
+ }
136
+
137
+ // src/flow/analyze.ts
138
+ import { parse as parse4 } from "@babel/parser";
139
+
140
+ // src/flow/zod-input.ts
141
+ import { parse } from "@babel/parser";
142
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
143
+ import { dirname as dirname3, join as join3, resolve as resolve3 } from "path";
144
+
145
+ // src/flow/tsconfig-paths.ts
146
+ import { existsSync as existsSync2, readFileSync as readFileSync2, readdirSync as readdirSync2 } from "fs";
147
+
148
+ // src/lib/tsconfig.ts
149
+ function parseJsonc(text) {
150
+ let out = "", inString = false;
151
+ for (let i = 0; i < text.length; i++) {
152
+ const c = text[i];
153
+ if (inString) {
154
+ out += c;
155
+ if (c === "\\") {
156
+ out += text[++i] ?? "";
157
+ } else if (c === '"') inString = false;
158
+ continue;
159
+ }
160
+ if (c === '"') {
161
+ inString = true;
162
+ out += c;
163
+ continue;
164
+ }
165
+ if (c === "/" && text[i + 1] === "/") {
166
+ while (i < text.length && text[i] !== "\n") i++;
167
+ out += "\n";
168
+ continue;
169
+ }
170
+ if (c === "/" && text[i + 1] === "*") {
171
+ i = text.indexOf("*/", i + 2);
172
+ if (i < 0) break;
173
+ i++;
174
+ continue;
175
+ }
176
+ out += c;
177
+ }
178
+ return JSON.parse(out.replace(/,(\s*[}\]])/g, "$1"));
179
+ }
180
+ var MAX_DEPTH = 8;
181
+ function resolveExtends(spec, dir, io) {
182
+ const { path } = io;
183
+ const from = (base, rest2) => path.isAbsolute(rest2) ? path.normalize(rest2) : path.normalize(path.join(base, rest2));
184
+ const files = (target) => [target, target + ".json", path.join(target, "tsconfig.json")];
185
+ if (spec.startsWith(".") || path.isAbsolute(spec)) return files(from(dir, spec)).find((f) => f.endsWith(".json") && io.read(f) !== void 0);
186
+ const parts = spec.split("/"), name = spec.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0], rest = parts.slice(spec.startsWith("@") ? 2 : 1).join("/");
187
+ const inside = (root2) => files(rest ? path.join(root2, rest) : path.join(root2, "tsconfig.json")).find((f) => f.endsWith(".json") && io.read(f) !== void 0);
188
+ const workspace = io.workspacePackage?.(name), local = workspace !== void 0 ? inside(workspace) : void 0;
189
+ if (local) return local;
190
+ for (let current = dir, guard = 0; guard < 40; guard++) {
191
+ const found = inside(path.join(current, "node_modules", name));
192
+ if (found) return found;
193
+ const parent = path.dirname(current);
194
+ if (parent === current || current === "." || current === "") break;
195
+ current = parent;
196
+ }
197
+ return void 0;
198
+ }
199
+ function effective(file, io, depth, chain3) {
200
+ if (depth > MAX_DEPTH || chain3.has(file)) return void 0;
201
+ const text = io.read(file);
202
+ if (text === void 0) return void 0;
203
+ let config;
204
+ try {
205
+ config = parseJsonc(text);
206
+ } catch {
207
+ return void 0;
208
+ }
209
+ const dir = io.path.dirname(file), next = new Set(chain3).add(file);
210
+ let out = {};
211
+ const parents = Array.isArray(config?.extends) ? config.extends : [config?.extends];
212
+ for (const spec of parents) {
213
+ if (typeof spec !== "string") continue;
214
+ const target = resolveExtends(spec, dir, io), parent = target ? effective(target, io, depth + 1, next) : void 0;
215
+ if (parent) out = { ...out, ...parent.baseUrl ? { baseUrl: parent.baseUrl } : {}, ...parent.paths ? { paths: parent.paths } : {} };
216
+ }
217
+ const options = config?.compilerOptions ?? {};
218
+ if (typeof options.baseUrl === "string") out = { ...out, baseUrl: { value: options.baseUrl, dir } };
219
+ if (options.paths && typeof options.paths === "object") {
220
+ const entries = Object.entries(options.paths).filter((e) => Array.isArray(e[1]) && e[1].every((t) => typeof t === "string"));
221
+ if (entries.length) out = { ...out, paths: { value: entries, dir, file } };
222
+ }
223
+ return out;
224
+ }
225
+ function resolveTsconfigPaths(file, io) {
226
+ const layer = effective(file, io, 0, /* @__PURE__ */ new Set());
227
+ if (!layer?.paths) return void 0;
228
+ const { path } = io;
229
+ const base = layer.baseUrl ? path.isAbsolute(layer.baseUrl.value) ? path.normalize(layer.baseUrl.value) : path.normalize(path.join(layer.baseUrl.dir, layer.baseUrl.value)) : layer.paths.dir;
230
+ return { file: layer.paths.file, base, paths: layer.paths.value };
231
+ }
232
+
233
+ // src/flow/tsconfig-paths.ts
234
+ import { dirname as dirname2, isAbsolute, join as join2, normalize, posix, relative, resolve as resolve2, sep } from "path";
235
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git", ".next", "dist", "build", "out", "coverage", ".turbo", ".agenttwin"]);
236
+ function workspacePackages(root2) {
237
+ const found = /* @__PURE__ */ new Map();
238
+ const visit = (dir, depth) => {
239
+ try {
240
+ const pkg = join2(dir, "package.json");
241
+ if (existsSync2(pkg)) {
242
+ const name = JSON.parse(readFileSync2(pkg, "utf8")).name;
243
+ if (typeof name === "string" && !found.has(name)) found.set(name, dir);
244
+ }
245
+ } catch {
246
+ }
247
+ if (depth >= 4) return;
248
+ let entries;
249
+ try {
250
+ entries = readdirSync2(dir, { withFileTypes: true });
251
+ } catch {
252
+ return;
253
+ }
254
+ for (const entry of entries) if (entry.isDirectory() && !SKIP_DIRS.has(entry.name) && !entry.name.startsWith(".")) visit(join2(dir, entry.name), depth + 1);
255
+ };
256
+ visit(root2, 0);
257
+ return found;
258
+ }
259
+ function tsconfigAliases(root2) {
260
+ const absoluteRoot = resolve2(root2), byDirectory = /* @__PURE__ */ new Map();
261
+ let workspace;
262
+ const io = {
263
+ path: { dirname: dirname2, join: join2, normalize, isAbsolute },
264
+ read: (file) => {
265
+ try {
266
+ return existsSync2(file) ? readFileSync2(file, "utf8") : void 0;
267
+ } catch {
268
+ return void 0;
269
+ }
270
+ },
271
+ workspacePackage: (name) => (workspace ??= workspacePackages(absoluteRoot)).get(name)
272
+ };
273
+ const load = (file) => resolveTsconfigPaths(file, io);
274
+ const nearest = (directory) => {
275
+ if (byDirectory.has(directory)) return byDirectory.get(directory);
276
+ let found;
277
+ for (const name of ["tsconfig.json", "jsconfig.json"]) {
278
+ const file = join2(directory, name);
279
+ if (existsSync2(file)) {
280
+ found = load(file);
281
+ if (found) break;
282
+ }
283
+ }
284
+ if (!found && directory !== absoluteRoot && directory.startsWith(absoluteRoot + sep)) found = nearest(dirname2(directory));
285
+ byDirectory.set(directory, found);
286
+ return found;
287
+ };
288
+ const inside = (path) => {
289
+ const rel = relative(absoluteRoot, path);
290
+ return rel && !rel.startsWith("..") && !isAbsolute(rel) ? rel.split(sep).join(posix.sep) : void 0;
291
+ };
292
+ return {
293
+ /** The tsconfig whose aliases apply to this project file (root-relative), if any declares some. */
294
+ configFor(file) {
295
+ return nearest(dirname2(resolve2(absoluteRoot, file)))?.file;
296
+ },
297
+ /** Root-relative paths (without extension) an aliased import may refer to; empty when no alias matches. */
298
+ resolve(from, source) {
299
+ const aliases = nearest(dirname2(resolve2(absoluteRoot, from)));
300
+ if (!aliases) return [];
301
+ let best;
302
+ for (const [pattern, targets] of aliases.paths) {
303
+ const at = pattern.indexOf("*");
304
+ if (at < 0) {
305
+ if (pattern === source) return targets.map((t) => inside(resolve2(aliases.base, t))).filter((p) => !!p);
306
+ continue;
307
+ }
308
+ const prefix = pattern.slice(0, at), suffix = pattern.slice(at + 1);
309
+ if (source.length >= prefix.length + suffix.length && source.startsWith(prefix) && source.endsWith(suffix) && (!best || prefix.length > best.prefix)) best = { targets, star: source.slice(prefix.length, source.length - suffix.length), prefix: prefix.length };
310
+ }
311
+ return best ? best.targets.map((t) => inside(resolve2(aliases.base, t.replace("*", best.star)))).filter((p) => !!p) : [];
312
+ }
313
+ };
314
+ }
315
+
316
+ // src/flow/zod-input.ts
317
+ var SOURCE_EXT = [".ts", ".tsx", ".mts", ".js", ".mjs", ".jsx"];
318
+ var UUID = "00000000-0000-4000-8000-000000000001";
319
+ var WRAPPERS = /* @__PURE__ */ new Set(["optional", "nullable", "nullish", "default", "catch", "describe", "brand", "readonly", "transform", "refine", "superRefine", "pipe", "prefault", "meta", "or", "and", "check"]);
320
+ var parseFile = (file) => {
321
+ try {
322
+ return parse(readFileSync3(file, "utf8"), { sourceType: "unambiguous", plugins: ["typescript", "jsx"], errorRecovery: true }).program;
323
+ } catch {
324
+ return void 0;
325
+ }
326
+ };
327
+ var resolveImport = (root2, from, source, aliases) => {
328
+ const bases = source.startsWith(".") ? [resolve3(dirname3(resolve3(root2, from)), source)] : aliases.resolve(from, source).map((p) => resolve3(root2, p));
329
+ for (const base of bases) for (const ext of ["", ...SOURCE_EXT, ...SOURCE_EXT.map((e) => `/index${e}`)]) {
330
+ const f = base + ext;
331
+ if (existsSync3(f) && !f.endsWith("/")) try {
332
+ if (readFileSync3(f, "utf8").length) return f;
333
+ } catch {
334
+ }
335
+ }
336
+ return void 0;
337
+ };
338
+ var declaration = (scope, name) => {
339
+ for (const stmt of scope.program.body) {
340
+ const decl = stmt.type === "ExportNamedDeclaration" ? stmt.declaration : stmt;
341
+ if (decl?.type === "VariableDeclaration") {
342
+ for (const d of decl.declarations) if (d.id?.type === "Identifier" && d.id.name === name && d.init) return { init: d.init, scope };
343
+ }
344
+ }
345
+ for (const stmt of scope.program.body) {
346
+ if (stmt.type !== "ImportDeclaration") continue;
347
+ for (const spec of stmt.specifiers) {
348
+ if (spec.local?.name !== name) continue;
349
+ const imported = spec.type === "ImportSpecifier" ? spec.imported?.name ?? spec.imported?.value : "default";
350
+ const target = resolveImport(scope.root, scope.file, stmt.source.value, scope.aliases);
351
+ if (!target) return void 0;
352
+ const program = parseFile(target);
353
+ if (!program) return void 0;
354
+ return declaration({ ...scope, file: relativeTo(scope.root, target), program }, imported === "default" ? name : imported);
355
+ }
356
+ }
357
+ return void 0;
358
+ };
359
+ var relativeTo = (root2, file) => file.startsWith(resolve3(root2)) ? file.slice(resolve3(root2).length + 1) : file;
360
+ var chain = (node) => {
361
+ const calls = [];
362
+ let cur = node;
363
+ while (cur && cur.type === "CallExpression" && cur.callee?.type === "MemberExpression") {
364
+ calls.unshift({ name: String(cur.callee.property?.name ?? cur.callee.property?.value), args: cur.arguments });
365
+ cur = cur.callee.object;
366
+ }
367
+ return { base: cur, calls };
368
+ };
369
+ var isZ = (n) => n?.type === "Identifier" && (n.name === "z" || n.name === "zod" || n.name === "v");
370
+ var literal = (n) => n?.type === "StringLiteral" || n?.type === "NumericLiteral" || n?.type === "BooleanLiteral" ? n.value : n?.type === "NullLiteral" ? null : n?.type === "UnaryExpression" && n.operator === "-" && n.argument?.type === "NumericLiteral" ? -n.argument.value : void 0;
371
+ function sample(node, scope, depth = 0) {
372
+ if (!node || depth > 12) return void 0;
373
+ if (node.type === "Identifier") {
374
+ const d = declaration(scope, node.name);
375
+ return d ? sample(d.init, d.scope, depth + 1) : void 0;
376
+ }
377
+ const { base, calls } = chain(node);
378
+ let head, rest = calls, start;
379
+ if (base?.type === "MemberExpression" && isZ(base.object)) {
380
+ head = { name: String(base.property?.name), args: [] };
381
+ rest = calls;
382
+ } else if (calls.length && base?.type === "Identifier" && isZ(base)) {
383
+ head = calls[0];
384
+ rest = calls.slice(1);
385
+ } else if (calls.length && base?.type === "MemberExpression" && base.object?.type === "MemberExpression" && isZ(base.object.object)) {
386
+ head = { name: String(base.property?.name), args: [] };
387
+ rest = calls;
388
+ } else if (base?.type === "Identifier") {
389
+ start = base;
390
+ }
391
+ if (!head && start) {
392
+ const d = declaration(scope, start.name);
393
+ const inner = d ? sample(d.init, d.scope, depth + 1) : void 0;
394
+ if (!inner) return void 0;
395
+ return applyWrappers(inner, rest);
396
+ }
397
+ if (!head) return void 0;
398
+ const kind = head.name;
399
+ let value2;
400
+ const first = rest.find((c) => ["number", "string", "boolean", "date", "bigint"].includes(c.name) && base?.object && base.property?.name === "coerce");
401
+ const k = first?.name ?? kind;
402
+ switch (k) {
403
+ case "string":
404
+ case "templateLiteral":
405
+ value2 = "synthetic-text";
406
+ break;
407
+ case "uuid":
408
+ case "guid":
409
+ value2 = UUID;
410
+ break;
411
+ case "email":
412
+ value2 = "customer@example.test";
413
+ break;
414
+ case "url":
415
+ case "uri":
416
+ value2 = "https://example.test/x";
417
+ break;
418
+ case "number":
419
+ case "int":
420
+ case "float":
421
+ value2 = 1;
422
+ break;
423
+ case "bigint":
424
+ value2 = 1;
425
+ break;
426
+ case "boolean":
427
+ value2 = true;
428
+ break;
429
+ case "date":
430
+ value2 = "2026-11-04T12:00:00.000Z";
431
+ break;
432
+ case "literal":
433
+ value2 = literal(head.args[0]);
434
+ break;
435
+ case "enum":
436
+ case "nativeEnum": {
437
+ const arg = head.args[0];
438
+ if (arg?.type === "ArrayExpression") value2 = literal(arg.elements[0]);
439
+ else if (arg?.type === "Identifier") {
440
+ const d = declaration(scope, arg.name);
441
+ const o = d?.init;
442
+ if (o?.type === "ArrayExpression") value2 = literal(o.elements[0]);
443
+ else if (o?.type === "ObjectExpression" && o.properties[0]) value2 = literal(o.properties[0].value);
444
+ else if (o?.type === "TSAsExpression" && o.expression?.type === "ArrayExpression") value2 = literal(o.expression.elements[0]);
445
+ }
446
+ break;
447
+ }
448
+ case "array": {
449
+ const item = sample(head.args[0], scope, depth + 1);
450
+ value2 = item && !item.skip ? [item.value] : [];
451
+ break;
452
+ }
453
+ case "tuple": {
454
+ value2 = (head.args[0]?.elements ?? []).map((e) => sample(e, scope, depth + 1)?.value);
455
+ break;
456
+ }
457
+ case "union":
458
+ case "discriminatedUnion": {
459
+ const list = head.args.find((a) => a?.type === "ArrayExpression");
460
+ const firstOption = list?.elements?.[0];
461
+ const s = firstOption ? sample(firstOption, scope, depth + 1) : void 0;
462
+ value2 = s?.value;
463
+ break;
464
+ }
465
+ case "record":
466
+ case "map":
467
+ value2 = {};
468
+ break;
469
+ case "any":
470
+ case "unknown":
471
+ value2 = {};
472
+ break;
473
+ case "null":
474
+ value2 = null;
475
+ break;
476
+ case "object":
477
+ case "strictObject":
478
+ case "looseObject": {
479
+ const obj = head.args[0]?.type === "ObjectExpression" ? head.args[0] : void 0;
480
+ value2 = {};
481
+ for (const p of obj?.properties ?? []) {
482
+ if (p.type !== "ObjectProperty") continue;
483
+ const key2 = p.key?.name ?? p.key?.value;
484
+ if (typeof key2 !== "string") continue;
485
+ const s = sample(p.value, scope, depth + 1);
486
+ if (s && !s.skip && s.value !== void 0) value2[key2] = s.value;
487
+ }
488
+ break;
489
+ }
490
+ default:
491
+ return void 0;
492
+ }
493
+ return applyWrappers({ value: value2 }, rest);
494
+ }
495
+ function applyWrappers(inner, calls) {
496
+ let { value: value2 } = inner, skip = inner.skip;
497
+ for (const c of calls) {
498
+ if (c.name === "optional" || c.name === "nullish") skip = true;
499
+ else if (c.name === "default") skip = true;
500
+ else if (c.name === "uuid") value2 = UUID;
501
+ else if (c.name === "email") value2 = "customer@example.test";
502
+ else if (c.name === "url") value2 = "https://example.test/x";
503
+ else if (c.name === "min" || c.name === "gte" || c.name === "gt" || c.name === "positive" || c.name === "length" || c.name === "nonempty" || c.name === "max" || c.name === "lte" || c.name === "lt") {
504
+ const n = c.name === "positive" || c.name === "nonempty" ? 1 : literal(c.args[0]);
505
+ if (typeof n === "number" && typeof value2 === "string") {
506
+ if (c.name === "min" || c.name === "length" || c.name === "nonempty") value2 = value2.length >= n ? value2 : value2.padEnd(n, "x");
507
+ else if (c.name === "max" && value2.length > n) value2 = value2.slice(0, Math.max(1, n));
508
+ } else if (typeof n === "number" && typeof value2 === "number") {
509
+ if (c.name === "min" || c.name === "gte" || c.name === "positive") value2 = Math.max(value2, n);
510
+ else if (c.name === "gt") value2 = Math.max(value2, n + 1);
511
+ else if (c.name === "max" || c.name === "lte") value2 = Math.min(value2, n);
512
+ else if (c.name === "lt") value2 = Math.min(value2, n - 1);
513
+ } else if (typeof n === "number" && Array.isArray(value2) && (c.name === "min" || c.name === "length" || c.name === "nonempty") && value2.length > 0 && value2.length < n) value2 = Array.from({ length: n }, () => value2[0]);
514
+ } else if (!WRAPPERS.has(c.name) && !["int", "finite", "trim", "toLowerCase", "toUpperCase", "regex", "startsWith", "endsWith", "includes", "strict", "passthrough", "strip", "nonnegative", "nonpositive", "negative", "multipleOf", "safe", "datetime", "date", "time", "cuid", "cuid2", "ulid", "nanoid", "ip", "emoji", "base64", "jwt", "catchall", "partial", "deepPartial", "required", "extend", "merge", "pick", "omit", "keyof"].includes(c.name)) {
515
+ }
516
+ }
517
+ return { value: value2, ...skip ? { skip } : {} };
518
+ }
519
+ function zodBodySample(root2, file, fnSource) {
520
+ const abs = join3(root2, file);
521
+ const program = parseFile(abs);
522
+ if (!program) return void 0;
523
+ const scope = { root: root2, file, program, aliases: tsconfigAliases(root2) };
524
+ const names = [...fnSource.matchAll(/\b([A-Za-z_$][\w$]*)\s*\.\s*(?:parse|safeParse|parseAsync|safeParseAsync)\s*\(/g)].map((m) => m[1]);
525
+ for (const name of names) {
526
+ const s = sample({ type: "Identifier", name }, scope);
527
+ if (s && !s.skip && s.value && typeof s.value === "object" && !Array.isArray(s.value) && Object.keys(s.value).length) return s.value;
528
+ }
529
+ return void 0;
530
+ }
531
+
532
+ // src/flow/analyze.ts
533
+ import { readdir as readdir2, readFile as readFile2, stat as stat2 } from "fs/promises";
534
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
535
+ import { join as join6, relative as relative3, sep as sep3, posix as posix3 } from "path";
536
+
537
+ // src/flow/sdk-detect.ts
538
+ import { existsSync as existsSync4, readFileSync as readFileSync4, readdirSync as readdirSync3, statSync } from "fs";
539
+ import { join as join4 } from "path";
540
+
541
+ // src/runtime/twin-clock.ts
542
+ import { AsyncLocalStorage } from "async_hooks";
543
+ var key = /* @__PURE__ */ Symbol.for("agenttwin.twinClock.v1");
544
+ var registry = globalThis;
545
+ var context = registry[key] ?? new AsyncLocalStorage();
546
+ if (!registry[key]) Object.defineProperty(registry, key, { value: context });
547
+
548
+ // src/runtime/enterprise-twins.ts
549
+ import { createHash } from "crypto";
550
+ var SF_OBJECTS = {
551
+ Account: { prefix: "001", required: ["Name"] },
552
+ Contact: { prefix: "003", required: ["LastName"] },
553
+ Lead: { prefix: "00Q", required: ["LastName", "Company"] },
554
+ Opportunity: { prefix: "006", required: ["Name", "StageName", "CloseDate"] },
555
+ Case: { prefix: "500", required: [] }
556
+ };
557
+ var SN_TABLES = { incident: "INC", change_request: "CHG", problem: "PRB", sc_request: "REQ", sys_user: null };
558
+ var NS_TYPES = ["customer", "vendor", "salesOrder", "invoice", "vendorBill"];
559
+ var ENTERPRISE_OPTIONAL_COLLECTIONS = {
560
+ salesforce: Object.keys(SF_OBJECTS).map((o) => `/sobjects/${o}`),
561
+ servicenow: Object.keys(SN_TABLES).map((t) => `/${t}`),
562
+ workday: ["/workers", "/timeOffRequests"],
563
+ sap: ["/A_BusinessPartner", "/A_SalesOrder"],
564
+ "microsoft-teams": ["/channels", "/chats", "/messages"],
565
+ outlook: ["/messages"],
566
+ "entra-id": ["/users", "/groups", "/groupMembers"],
567
+ okta: ["/users", "/groups", "/groupMemberships"],
568
+ confluence: ["/pages", "/spaces", "/comments"],
569
+ sharepoint: ["/lists", "/listItems", "/driveItems"],
570
+ snowflake: ["/statements"],
571
+ netsuite: NS_TYPES.map((t) => `/${t}`),
572
+ pagerduty: ["/services", "/incidents", "/notes", "/events"]
573
+ };
574
+ var unsupported = (body) => ({ ...body, forwardedToProduction: false });
575
+ var ENTERPRISE_UNSUPPORTED = {
576
+ salesforce: [unsupported({ errorCode: "UNSUPPORTED_OPERATION", message: "Outside the AgentTwin Salesforce REST subset" })],
577
+ servicenow: unsupported({ error: { message: "Unsupported operation", detail: "Outside the AgentTwin ServiceNow Table API subset" }, status: "failure" }),
578
+ workday: unsupported({ error: "Unsupported operation", errors: [{ error: "Outside the AgentTwin Workday REST subset" }] }),
579
+ sap: unsupported({ error: { code: "UNSUPPORTED", message: { lang: "en", value: "Outside the AgentTwin SAP OData subset" } } }),
580
+ "microsoft-teams": unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Microsoft Teams Graph subset" } }),
581
+ outlook: unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Outlook mail Graph subset" } }),
582
+ "entra-id": unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin Entra ID Graph subset" } }),
583
+ okta: unsupported({ errorCode: "E0000022", errorSummary: "The endpoint does not support the provided HTTP method", errorCauses: [{ errorSummary: "Outside the AgentTwin Okta subset" }] }),
584
+ confluence: unsupported({ errors: [{ status: 501, code: "UNSUPPORTED", title: "Outside the AgentTwin Confluence v2 subset" }] }),
585
+ sharepoint: unsupported({ error: { code: "UnsupportedOperation", message: "Outside the AgentTwin SharePoint Graph subset" } }),
586
+ snowflake: unsupported({ code: "000002", message: "Statement or SQL feature outside the AgentTwin Snowflake subset (single-table SELECT/INSERT/UPDATE/DELETE with equality filters)" }),
587
+ netsuite: unsupported({ title: "Unsupported", status: 501, "o:errorDetails": [{ detail: "Outside the AgentTwin NetSuite REST record subset", "o:errorCode": "UNSUPPORTED" }] }),
588
+ pagerduty: unsupported({ error: { message: "Outside the AgentTwin PagerDuty subset", code: 2e3 } })
589
+ };
590
+ var op = (method, endpoint, effect, errors = []) => ({ method, endpoint, effect, parameters: [], errors });
591
+ var ENTERPRISE_CONTRACTS = {
592
+ salesforce: {
593
+ version: "1.0.0",
594
+ authentication: "Bearer run-scoped test token (OAuth access token shape)",
595
+ operations: [op("POST", "/services/data/vXX.X/sobjects/<Account|Contact|Lead|Opportunity|Case>", "create record (18-char id with object prefix)", ["400 REQUIRED_FIELD_MISSING", "404 NOT_FOUND"]), op("GET", "/services/data/vXX.X/sobjects/<object>/<id>", "retrieve record with attributes", ["404 NOT_FOUND"]), op("PATCH", "/services/data/vXX.X/sobjects/<object>/<id>", "update fields (204)"), op("DELETE", "/services/data/vXX.X/sobjects/<object>/<id>", "delete record (204)"), op("GET", "/services/data/vXX.X/query?q=SOQL", "single-object SOQL with = / != filters joined by AND and LIMIT", ["400 INVALID_TYPE"])],
596
+ limitations: ["Five standard objects; no custom objects, relationships, ORDER BY, OR, LIKE, aggregates or Composite/Bulk API", "No validation rules, triggers, flows or sharing; only standard required fields are enforced"]
597
+ },
598
+ servicenow: {
599
+ version: "1.0.0",
600
+ authentication: "Bearer run-scoped test token",
601
+ operations: [op("GET", "/api/now/table/<incident|change_request|problem|sc_request|sys_user>", "list with sysparm_query (= and != joined by ^), sysparm_limit/offset/fields; X-Total-Count header"), op("POST", "/api/now/table/<table>", "create record with sys_id and number (INC0010001\u2026)"), op("GET", "/api/now/table/<table>/<sys_id>", "retrieve", ["404 No Record found"]), op("PATCH|PUT", "/api/now/table/<table>/<sys_id>", "update; values stored as strings"), op("DELETE", "/api/now/table/<table>/<sys_id>", "delete (204)")],
602
+ limitations: ["Five tables; no ^OR, LIKE, ORDERBY, dot-walking, display values, business rules, ACLs or workflows"]
603
+ },
604
+ workday: {
605
+ version: "1.0.0",
606
+ authentication: "Bearer run-scoped test token",
607
+ operations: [op("GET", "/ccx/api/v1/<tenant>/workers", "list/search workers"), op("GET", "/ccx/api/v1/<tenant>/workers/<id>", "retrieve worker", ["404 Invalid ID"]), op("POST", "/ccx/api/absenceManagement/v1/<tenant>/workers/<id>/requestTimeOff", "submit time off; rejects dates already requested", ["400 Validation error"]), op("GET", "/ccx/api/absenceManagement/v1/<tenant>/workers/<id>/timeOffDetails", "list a worker's requests")],
608
+ limitations: ["Workers and time off only; business processes never advance past Submitted", "No SOAP Web Services, RaaS reports, compensation, hiring or approvals"]
609
+ },
610
+ sap: {
611
+ version: "1.0.0",
612
+ authentication: "Bearer run-scoped test token; writes require the x-csrf-token fetched by a prior GET (x-csrf-token: Fetch)",
613
+ operations: [op("GET", "/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner[('<id>')]", "list ($filter eq/and, $top, $skip) or read"), op("POST", "/sap/opu/odata/sap/API_BUSINESS_PARTNER/A_BusinessPartner", "create business partner", ["403 CSRF token validation failed"]), op("GET", "/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder[('<id>')]", "list or read sales orders"), op("POST", "/sap/opu/odata/sap/API_SALES_ORDER_SRV/A_SalesOrder", "create sales order with deep-inserted to_Item; sold-to party must exist", ["400 V1/302", "403 CSRF"]), op("PATCH|MERGE", "<entity>('<id>')", "update header fields (204)")],
614
+ limitations: ["OData v2 JSON only; no $expand, $batch, $orderby, pricing, ATP checks or delivery/billing documents"]
615
+ },
616
+ "microsoft-teams": {
617
+ version: "1.0.0",
618
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
619
+ operations: [op("GET", "/v1.0/teams/<team>/channels", "list channels"), op("POST", "/v1.0/teams/<team>/channels/<channel>/messages", "post channel message", ["400 Missing body content", "404 NotFound"]), op("GET", "/v1.0/teams/<team>/channels/<channel>/messages", "list top-level messages"), op("POST|GET", "/v1.0/teams/<team>/channels/<channel>/messages/<id>/replies", "reply / list replies"), op("POST|GET", "/v1.0/chats/<chat>/messages", "send / list chat messages")],
620
+ limitations: ["No adaptive card rendering, mentions resolution, reactions, edits, deletes, meetings or change notifications"]
621
+ },
622
+ outlook: {
623
+ version: "1.0.0",
624
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
625
+ operations: [op("POST", "/v1.0/me/sendMail (or /users/<id>/sendMail)", "send mail (202); stored in sentitems", ["400 ErrorInvalidRecipients"]), op("GET", "/v1.0/me/messages, /me/mailFolders/<inbox|sentitems>/messages", "list with $filter eq, $top, $select"), op("GET|PATCH", "/v1.0/me/messages/<id>", "read / update isRead, categories, importance, flag", ["404 ErrorItemNotFound"]), op("POST", "/v1.0/me/messages/<id>/reply", "reply (202)")],
626
+ limitations: ["No attachments, drafts, forward, rules, calendar or delta queries; inbound mail exists only as seeded records"]
627
+ },
628
+ "entra-id": {
629
+ version: "1.0.0",
630
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
631
+ operations: [op("GET|POST", "/v1.0/users", "list ($filter eq, $top, $select) / create user; duplicate UPN rejected", ["400 Request_BadRequest"]), op("GET|PATCH|DELETE", "/v1.0/users/<id|upn>", "read / update (204) / delete (204)"), op("GET", "/v1.0/groups[/<id>]", "list / read groups"), op("GET", "/v1.0/groups/<id>/members", "list members"), op("POST", "/v1.0/groups/<id>/members/$ref", "add member (204); duplicates rejected"), op("DELETE", "/v1.0/groups/<id>/members/<user>/$ref", "remove member (204)")],
632
+ limitations: ["Passwords are accepted but never stored; no sign-in, licences, roles, app registrations or conditional access"]
633
+ },
634
+ okta: {
635
+ version: "1.0.0",
636
+ authentication: "SSWS run-scoped test token (Okta API token header)",
637
+ operations: [op("GET|POST", "/api/v1/users", "list (q, filter eq, limit) / create (?activate=false stages); duplicate login rejected", ["400 E0000001"]), op("GET|POST|DELETE", "/api/v1/users/<id|login>", "read / partial profile update / delete (first DELETE deactivates, second removes)", ["404 E0000007"]), op("POST", "/api/v1/users/<id>/lifecycle/<activate|deactivate|suspend|unsuspend>", "status transitions; invalid ones rejected"), op("GET", "/api/v1/groups[/<id>]", "list / read groups"), op("GET|PUT|DELETE", "/api/v1/groups/<id>/users[/<user>]", "list / add / remove members")],
638
+ limitations: ["No authentication flows, factors, apps, policies, event hooks or rate-limit headers; pagination links omitted"]
639
+ },
640
+ confluence: {
641
+ version: "1.0.0",
642
+ authentication: "Bearer run-scoped test token",
643
+ operations: [op("GET|POST", "/wiki/api/v2/pages", "list (space-id, title, status, limit) / create; duplicate title in a space rejected", ["400 BAD_REQUEST"]), op("GET|PUT|DELETE", "/wiki/api/v2/pages/<id>", "read (body-format=storage) / update requiring version+1 / trash", ["409 CONFLICT", "404 NOT_FOUND"]), op("GET", "/wiki/api/v2/spaces", "list spaces"), op("POST", "/wiki/api/v2/footer-comments", "comment on a page")],
644
+ limitations: ["Storage representation only; no attachments, labels, permissions, page tree moves, CQL search or v1 content API"]
645
+ },
646
+ sharepoint: {
647
+ version: "1.0.0",
648
+ authentication: "Bearer run-scoped test token (Graph access token shape)",
649
+ operations: [op("GET", "/v1.0/sites/<site>/lists", "list lists"), op("GET|POST", "/v1.0/sites/<site>/lists/<list>/items", "list (expand=fields, $top) / create item"), op("GET|DELETE", "/v1.0/sites/<site>/lists/<list>/items/<id>", "read / delete", ["404 itemNotFound"]), op("PATCH", "/v1.0/sites/<site>/lists/<list>/items/<id>/fields", "update fields"), op("GET|POST", "/v1.0/sites/<site>/drive/root/children", "list / create folder; name conflicts honour conflictBehavior", ["409 nameAlreadyExists"])],
650
+ limitations: ["No file content upload or download, versions, permissions, column validation or search"]
651
+ },
652
+ snowflake: {
653
+ version: "1.0.0",
654
+ authentication: "Bearer run-scoped test token (key-pair JWT shape)",
655
+ operations: [op("POST", "/api/v2/statements", "execute one single-table SELECT (WHERE =/!= AND, ORDER BY, LIMIT), INSERT \u2026 VALUES, UPDATE \u2026 SET \u2026 WHERE or DELETE; ? bindings supported; values returned as strings", ["422 002003 object does not exist"]), op("GET", "/api/v2/statements/<handle>", "fetch a previous result")],
656
+ limitations: ["Twins the HTTP SQL API v2; the native drivers (snowflake-sdk, snowflake-connector-python) speak a different wire protocol and must be pointed at the SQL API or a json-collection stand-in", "Each table is a declared collection named in upper case; no joins, functions, aggregates, transactions, DDL, async execution or result partitions"]
657
+ },
658
+ netsuite: {
659
+ version: "1.0.0",
660
+ authentication: "Bearer run-scoped test token (OAuth 2.0 shape)",
661
+ operations: [op("GET", "/services/rest/record/v1/<customer|vendor|salesOrder|invoice|vendorBill>", 'list ids and links only (q: field IS "v", limit, offset)'), op("POST", "/services/rest/record/v1/<type>", "create; 204 with Location header and no body", ["400 USER_ERROR", "400 INVALID_KEY_OR_REF"]), op("GET|PATCH|DELETE", "/services/rest/record/v1/<type>/<id>", "read / update (204) / delete (204)", ["404 NONEXISTENT_ID"])],
662
+ limitations: ["Five record types; no SuiteQL, sublists beyond item lines, subsidiaries, workflows or SuiteScript; X-NetSuite-Idempotency-Key is honoured like Idempotency-Key"]
663
+ },
664
+ pagerduty: {
665
+ version: "1.0.0",
666
+ authentication: "Token token=<run-scoped test token> for REST; Events API v2 uses the seeded service integration_key as routing_key",
667
+ operations: [op("POST", "/v2/enqueue", "Events API v2 trigger/acknowledge/resolve; an open dedup_key groups instead of paging again (202)", ["400 invalid event"]), op("GET|POST", "/incidents", "list (statuses[], service_ids[], incident_key) / create; requires From header; open incident_key rejected", ["400 2001"]), op("GET|PUT", "/incidents/<id>", "read / acknowledge or resolve"), op("GET|POST", "/incidents/<id>/notes", "list / add notes"), op("GET", "/services", "list seeded services")],
668
+ limitations: ["No escalation policies, schedules, on-call, notifications, alert grouping windows or webhooks"]
669
+ }
670
+ };
671
+
672
+ // src/runtime/contracts.ts
673
+ var CONTRACTS = {
674
+ composio: {
675
+ version: "1.0.0",
676
+ authentication: "Run-scoped transport token; SDK tests use synthetic API keys",
677
+ operations: [{ method: "GET", endpoint: "/api/v3[.1]/connected_accounts", effect: "list filtered seeded accounts", parameters: ["user_ids", "statuses", "toolkit_slugs", "limit", "cursor"], errors: ["501 unsupported filters"] }, { method: "DELETE", endpoint: "/api/v3[.1]/connected_accounts/<id>", effect: "mark seeded connection deleted and disabled", parameters: [], errors: ["404 not found"] }, { method: "GET", endpoint: "/api/v3[.1]/tools/<GMAIL_SEND_EMAIL|GMAIL_SEND_MESSAGE>", effect: "read bounded immutable SDK metadata", parameters: ["version=latest", "toolkit_versions=latest"], errors: ["501 unsupported tool/version"] }, { method: "POST", endpoint: "/api/v3[.1]/tools/execute/<GMAIL_SEND_EMAIL|GMAIL_SEND_MESSAGE>", effect: "append a synthetic message for an active user-owned Gmail connection", parameters: ["user_id", "connected_account_id", "arguments", "version=latest"], errors: ["400 invalid fields or ambiguous connection", "501 unsupported tool or argument"] }],
678
+ limitations: ["Only two Gmail send slugs, connected-account list/delete and their SDK metadata; not arbitrary tools.execute support", "Synthetic messages are held in this service, not shared with a separately configured Gmail twin", "No real OAuth, refresh, ACLs, account creation, revocation, attachments, HTML or proxy calls", "Synthetic offset cursor and fixture order; not provider pagination/order guarantees", "No Idempotency-Key guarantee; duplicate sends are possible", "Only latest schema shape, verified against @composio/core 0.18.0; pinned toolkit versions require implementation", "Unknown operations/parameters return 501 and make coverage incomplete"]
679
+ },
680
+ "google-oauth": {
681
+ version: "1.0.0",
682
+ authentication: "Run-scoped transport token plus explicitly seeded synthetic confidential-client credentials",
683
+ operations: [{ method: "POST", endpoint: "/token", effect: "validate a seeded active refresh grant and append synthetic token issuance", parameters: ["client_id", "client_secret", "grant_type=refresh_token", "refresh_token"], errors: ["400 invalid_request", "400 invalid_grant", "401 invalid_client", "501 unsupported operation"] }],
684
+ limitations: ["Offline confidential-client refresh subset only; fixtures must use synthetic- credential prefixes", "No authorization-code exchange, consent, DPoP, refresh rotation, expiry clock or real provider validation", "No idempotency guarantee; retries can issue multiple access tokens", "Seed-only /clients and /grants; /tokens is an issuance ledger, not a public Google API endpoint", "Issued tokens are not coupled to Gmail scope or expiry enforcement; resource twins authenticate their run-scoped transport token", "Unknown grants, fields, methods and endpoints return 501 and make coverage incomplete"]
685
+ },
686
+ "json-collection": {
687
+ version: "1.0.0",
688
+ authentication: "Bearer run-scoped test token",
689
+ operations: [
690
+ { method: "GET", endpoint: "<collection path>", effect: "read", response: "{data: records}", errors: ["401 invalid_test_credential", "429 world_capacity"] },
691
+ { method: "POST", endpoint: "<collection path>", effect: "append", response: "201 record; 200 idempotency replay", errors: ["400 expected_json_object", "409 idempotency_conflict", "413 body_too_large", "429 world_capacity"] }
692
+ ],
693
+ limitations: ["Custom API contract, not a vendor replica", "No update/delete, pagination, OAuth, webhooks or schema validation", "Idempotency compares the exact parsed JSON serialization"]
694
+ },
695
+ openai: {
696
+ version: "1.0.0",
697
+ authentication: "Bearer run-scoped test token; official OpenAI SDK configured with the twin base URL",
698
+ operations: [
699
+ { 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"] },
700
+ { method: "GET", endpoint: "/v1/requests", effect: "list recorded model calls", parameters: [], errors: [] }
701
+ ],
702
+ 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"]
703
+ },
704
+ anthropic: {
705
+ version: "1.0.0",
706
+ authentication: "x-api-key run-scoped test token; official Anthropic SDK configured with the twin base URL",
707
+ operations: [
708
+ { 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"] },
709
+ { method: "GET", endpoint: "/v1/requests", effect: "list recorded model calls", parameters: [], errors: [] }
710
+ ],
711
+ 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"]
712
+ },
713
+ stripe: {
714
+ version: "1.0.0",
715
+ authentication: "Bearer run-scoped test token; official Stripe SDK configured with test endpoint",
716
+ operations: [
717
+ { method: "POST", endpoint: "/v1/customers", effect: "append customer", parameters: ["email", "name", "description"], errors: ["400 invalid parameters"] },
718
+ { method: "GET", endpoint: "/v1/customers[/<id>]", effect: "retrieve or list customers", parameters: ["limit", "starting_after"], errors: ["404 resource_missing", "400 invalid pagination"] },
719
+ { 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"] },
720
+ { method: "GET", endpoint: "/v1/payment_intents/<id>", effect: "retrieve intent", parameters: [], errors: ["404 resource_missing"] },
721
+ { 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"] },
722
+ { 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"] },
723
+ { method: "GET", endpoint: "/v1/refunds[/<id>]", effect: "retrieve or list refunds", parameters: ["limit", "starting_after", "charge", "payment_intent"], errors: ["404 resource_missing"] },
724
+ { method: "GET", endpoint: "/v1/charges[/<id>]", effect: "retrieve or list charges", parameters: ["limit"], errors: ["404 resource_missing"] },
725
+ { method: "GET", endpoint: "/v1/events[/<id>]", effect: "retrieve or list recorded charge.refunded events", parameters: ["limit", "type"], errors: ["404 resource_missing"] },
726
+ { method: "GET", endpoint: "/v1/subscription_items/<id>", effect: "retrieve a seeded subscription item", parameters: [], errors: ["404 resource_missing"] },
727
+ { method: "POST", endpoint: "/v1/subscription_items/<id>", effect: "update the quantity on a seeded subscription item", parameters: ["quantity"], errors: ["400 invalid quantity", "404 resource_missing"] }
728
+ ],
729
+ 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 subscription lifecycle, proration, payment-method APIs, refund cancellation 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"]
730
+ },
731
+ slack: {
732
+ version: "1.0.0",
733
+ authentication: "Bearer run-scoped test token; no Slack OAuth",
734
+ operations: [
735
+ { method: "POST", endpoint: "/api/chat.postMessage", effect: "append /messages", parameters: ["channel", "text"], errors: ["channel_not_found", "no_text"] },
736
+ { method: "GET|POST", endpoint: "/api/conversations.history", effect: "read /messages", parameters: ["channel"], errors: ["channel_not_found"] },
737
+ { method: "GET|POST", endpoint: "/api/conversations.list", effect: "read /channels", parameters: [], errors: [] }
738
+ ],
739
+ limitations: ["JSON and form bodies only", "User-ID posts require a seeded user in /users (dmAllowed can disable DMs) or a seeded DM in /channels with is_im and user; the run token represents one bot", "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"]
740
+ },
741
+ github: {
742
+ version: "1.0.0",
743
+ authentication: "Bearer run-scoped test token; GitHub-style Authorization header",
744
+ operations: [
745
+ { method: "GET", endpoint: "/repos", effect: "list repositories", parameters: [], errors: [] },
746
+ { method: "GET", endpoint: "/repos/<repo>", effect: "retrieve repository by name or full_name", parameters: [], errors: ["404 Not Found"] },
747
+ { method: "GET", endpoint: "/repos/<repo>/issues", effect: "list issues", parameters: ["state", "page", "per_page"], errors: ["404 Not Found", "422 validation"] },
748
+ { method: "POST", endpoint: "/repos/<repo>/issues", effect: "create issue", parameters: ["title", "body", "labels"], errors: ["404 Not Found", "422 validation"] },
749
+ { method: "GET", endpoint: "/repos/<repo>/issues/<number>", effect: "retrieve issue", parameters: [], errors: ["404 Not Found"] },
750
+ { method: "PATCH", endpoint: "/repos/<repo>/issues/<number>", effect: "update title/body or close", parameters: ["state", "title", "body"], errors: ["404 Not Found", "422 validation"] },
751
+ { method: "POST", endpoint: "/repos/<repo>/issues/<number>/comments", effect: "create comment", parameters: ["body"], errors: ["404 Not Found", "422 validation"] },
752
+ { method: "GET", endpoint: "/repos/<repo>/issues/<number>/comments", effect: "list comments", parameters: [], errors: ["404 Not Found"] },
753
+ { method: "GET", endpoint: "/repos/<repo>/pulls", effect: "list pull requests", parameters: ["state"], errors: ["404 Not Found", "422 validation"] },
754
+ { method: "GET", endpoint: "/repos/<repo>/pulls/<number>", effect: "retrieve pull request", parameters: [], errors: ["404 Not Found"] },
755
+ { 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"] },
756
+ { method: "POST", endpoint: "/repos/<repo>/check-runs", effect: "create check run", parameters: ["name", "head_sha", "status", "conclusion"], errors: ["404 Not Found", "422 validation"] }
757
+ ],
758
+ 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"]
759
+ },
760
+ linear: {
761
+ version: "1.0.0",
762
+ authentication: "Bearer run-scoped test token; GraphQL endpoint shape",
763
+ operations: [
764
+ { method: "POST", endpoint: "/graphql query viewer", effect: "read first seeded user as viewer", parameters: [], errors: [] },
765
+ { method: "POST", endpoint: "/graphql query issues", effect: "list issues", parameters: [], errors: [] },
766
+ { method: "POST", endpoint: "/graphql query issue(id:)", effect: "retrieve issue", parameters: ["id"], errors: ["data:null with Entity not found error"] },
767
+ { method: "POST", endpoint: "/graphql query projects", effect: "list projects", parameters: [], errors: [] },
768
+ { method: "POST", endpoint: "/graphql query project(id:)", effect: "retrieve project", parameters: ["id"], errors: ["data:null with Entity not found error"] },
769
+ { method: "POST", endpoint: "/graphql mutation issueCreate", effect: "create issue", parameters: ["input:title,description,state,assigneeId,projectId,priority"], errors: ["Issue title required"] },
770
+ { 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"] },
771
+ { 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"] }
772
+ ],
773
+ 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"]
774
+ },
775
+ notion: {
776
+ version: "1.0.0",
777
+ authentication: "Bearer run-scoped test token; requires Notion-Version header",
778
+ operations: [
779
+ { method: "GET", endpoint: "/v1/pages/<id>", effect: "retrieve page", parameters: [], errors: ["404 object_not_found"] },
780
+ { 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"] },
781
+ { method: "PATCH", endpoint: "/v1/pages/<id>", effect: "update properties or archive", parameters: ["properties", "archived"], errors: ["404 object_not_found", "400 validation_error"] },
782
+ { method: "GET", endpoint: "/v1/databases/<id>", effect: "retrieve database", parameters: [], errors: ["404 object_not_found"] },
783
+ { 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"] },
784
+ { method: "PATCH", endpoint: "/v1/blocks/<id>/children", effect: "append child blocks", parameters: ["children (1-100)"], errors: ["404 object_not_found", "400 validation_error"] }
785
+ ],
786
+ 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"]
787
+ },
788
+ hubspot: {
789
+ version: "1.0.0",
790
+ authentication: "Bearer run-scoped test token; HubSpot-style Bearer private token",
791
+ operations: [
792
+ { method: "GET", endpoint: "/crm/v3/objects/<contacts|companies|deals|tickets>", effect: "list objects", parameters: ["limit", "after"], errors: ["400 validation"] },
793
+ { method: "POST", endpoint: "/crm/v3/objects/<contacts|companies|deals|tickets>", effect: "create object", parameters: ["properties"], errors: ["400 validation"] },
794
+ { method: "GET", endpoint: "/crm/v3/objects/<object>/<id>", effect: "retrieve object", parameters: [], errors: ["404 OBJECT_NOT_FOUND"] },
795
+ { method: "PATCH", endpoint: "/crm/v3/objects/<object>/<id>", effect: "update properties", parameters: ["properties"], errors: ["404 OBJECT_NOT_FOUND", "400 validation"] },
796
+ { method: "POST", endpoint: "/crm/v3/objects/<object>/search", effect: "search objects", parameters: ["query", "filterGroups(EQ only, max 3 filters)", "limit", "after"], errors: ["400 validation"] }
797
+ ],
798
+ 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"]
799
+ },
800
+ shopify: {
801
+ version: "1.0.0",
802
+ authentication: "Bearer run-scoped test token; also accepts X-Shopify-Access-Token",
803
+ operations: [
804
+ { method: "GET", endpoint: "/admin/api/2024-01/products.json", effect: "list products", parameters: ["limit", "since_id"], errors: ["400 validation"] },
805
+ { 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"] },
806
+ { method: "GET|PUT", endpoint: "/admin/api/2024-01/products/<id>.json", effect: "retrieve or update product", parameters: ["product"], errors: ["404 Not Found"] },
807
+ { method: "GET", endpoint: "/admin/api/2024-01/orders.json", effect: "list orders", parameters: ["limit", "since_id"], errors: ["400 validation"] },
808
+ { 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"] },
809
+ { method: "GET|PUT", endpoint: "/admin/api/2024-01/orders/<id>.json", effect: "retrieve or update order", parameters: ["order"], errors: ["404 Not Found"] },
810
+ { method: "GET", endpoint: "/admin/api/2024-01/customers.json", effect: "list customers", parameters: ["limit", "since_id"], errors: ["400 validation"] },
811
+ { method: "POST", endpoint: "/admin/api/2024-01/customers.json", effect: "create customer", parameters: ["customer:first_name,last_name,email,phone,note,tags"], errors: [] },
812
+ { method: "GET|PUT", endpoint: "/admin/api/2024-01/customers/<id>.json", effect: "retrieve or update customer", parameters: ["customer"], errors: ["404 Not Found"] }
813
+ ],
814
+ 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"]
815
+ },
816
+ datadog: {
817
+ version: "1.0.0",
818
+ authentication: "Bearer run-scoped test token; also accepts DD-API-KEY and DD-APPLICATION-KEY headers",
819
+ operations: [
820
+ { method: "GET", endpoint: "/api/v1/monitors", effect: "list monitors", parameters: ["name"], errors: [] },
821
+ { method: "POST", endpoint: "/api/v1/monitors", effect: "create monitor", parameters: ["name", "type", "query", "message", "tags", "options", "priority"], errors: ["400 invalid name/type/query"] },
822
+ { method: "GET", endpoint: "/api/v1/monitor/<id>", effect: "retrieve monitor", parameters: [], errors: ["404 Monitor not found"] },
823
+ { method: "POST", endpoint: "/api/v1/monitor/<id>/mute", effect: "mute monitor", parameters: ["scope", "end"], errors: ["404 Monitor not found"] },
824
+ { method: "POST", endpoint: "/api/v1/events", effect: "post event", parameters: ["title", "text", "tags", "priority", "alert_type", "source"], errors: ["400 invalid title/text"] },
825
+ { method: "GET", endpoint: "/api/v1/events", effect: "list events in window", parameters: ["start", "end", "priority", "tags"], errors: ["400 start/end required"] },
826
+ { 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"] }
827
+ ],
828
+ 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"]
829
+ },
830
+ gmail: {
831
+ version: "1.0.0",
832
+ authentication: "Bearer run-scoped test token; Google-style OAuth2 Bearer header",
833
+ operations: [
834
+ { 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"] },
835
+ { method: "GET", endpoint: "/gmail/v1/users/me/messages", effect: "list message ids with a snippet q filter", parameters: ["q"], errors: ["400 validation"] },
836
+ { method: "GET", endpoint: "/gmail/v1/users/me/messages/<id>", effect: "retrieve message", parameters: [], errors: ["404 NOT_FOUND"] },
837
+ { method: "GET", endpoint: "/gmail/v1/users/me/labels", effect: "list seeded labels", parameters: [], errors: [] },
838
+ { method: "POST", endpoint: "/gmail/v1/users/me/labels", effect: "create a user label", parameters: ["name", "labelListVisibility", "messageListVisibility", "color"], errors: ["400 invalid name", "409 name exists"] },
839
+ { method: "POST", endpoint: "/gmail/v1/users/me/{messages|threads}/<id>/modify", effect: "add and remove labels on a message or every message of a thread; bumps the mailbox historyId", parameters: ["addLabelIds", "removeLabelIds"], errors: ["400 Invalid label", "404 not found"] },
840
+ { method: "GET", endpoint: "/gmail/v1/users/me/threads", effect: "list threads, newest first, excluding SPAM/TRASH", parameters: ["q (from:/to: address terms, OR-joined)", "maxResults", "labelIds"], errors: ["400 validation"] },
841
+ { method: "GET", endpoint: "/gmail/v1/users/me/threads/<id>", effect: "retrieve a thread with its messages, oldest first", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
842
+ { method: "GET", endpoint: "/gmail/v1/users/me/history", effect: "messagesAdded records for messages whose historyId is after startHistoryId", parameters: ["startHistoryId", "historyTypes", "maxResults"], errors: ["400 validation"] },
843
+ { method: "GET", endpoint: "/gmail/v1/users/me/settings/sendAs", effect: "list seeded send-as aliases", parameters: [], errors: [] },
844
+ { method: "POST", endpoint: "/gmail/v1/users/me/drafts", effect: "create a draft; its DRAFT-labelled message joins the thread", parameters: ["message.raw", "message.threadId"], errors: ["400 invalid MIME or fields", "404 unknown threadId"] },
845
+ { method: "GET", endpoint: "/gmail/v1/users/me/drafts", effect: "list drafts, newest first", parameters: ["maxResults"], errors: ["400 validation"] },
846
+ { method: "GET", endpoint: "/gmail/v1/users/me/drafts/<id>", effect: "retrieve a draft with its full message", parameters: ["format=full"], errors: ["404 NOT_FOUND"] },
847
+ { method: "DELETE", endpoint: "/gmail/v1/users/me/drafts/<id>", effect: "delete a draft and its message (204)", parameters: [], errors: ["404 NOT_FOUND"] },
848
+ { method: "POST", endpoint: "/gmail/v1/users/me/messages", effect: "insert a received message (messages.insert) into the mailbox, optionally into an existing thread; nothing is sent", parameters: ["raw", "threadId", "labelIds", "internalDateSource"], errors: ["400 invalid MIME, label or internalDateSource", "404 unknown thread"] },
849
+ { method: "POST", endpoint: "/gmail/v1/users/me/watch", effect: "record one push registration with the current historyId and an expiration seven days after the twin clock; no Pub/Sub notifications are delivered", parameters: ["topicName", "labelIds", "labelFilterBehavior"], errors: ["400 invalid topicName, label or labelFilterBehavior"] },
850
+ { method: "PUSH", endpoint: "seeded /pubsub/subscriptions pushEndpoint", effect: "while a watch is active, an inserted or sent message with a watched label publishes {emailAddress, historyId} to each subscription on the watch topic; the world POSTs it once to a loopback http pushEndpoint after the response and records the HTTP status in /pubsub/messages", parameters: ["subscription name", "topic", "pushEndpoint (http://127.0.0.1, localhost or [::1] only)"], errors: ["non-loopback endpoints are rejected and recorded, never called"] },
851
+ { method: "POST", endpoint: "/gmail/v1/users/me/stop", effect: "remove the push registration", parameters: [], errors: [] },
852
+ { method: "PUT", endpoint: "/gmail/v1/users/me/drafts/{id}", effect: "update a draft: replace its message (new message id) in the same thread, keeping the draft id", parameters: ["id", "message.raw", "message.threadId (same thread only)"], errors: ["400 invalid MIME or mismatched id", "404 unknown draft"] },
853
+ { method: "POST/PUT", endpoint: "/upload/gmail/v1/users/me/drafts[/{id}]?uploadType=multipart", effect: "media-upload form of drafts create/update: multipart/related JSON metadata plus a message/rfc822 part, as googleapis sends with media", parameters: ["uploadType=multipart", "metadata message.threadId", "message/rfc822 body"], errors: ["400 malformed multipart body", "404 unknown draft"] },
854
+ { method: "POST", endpoint: "/gmail/v1/users/me/drafts/send", effect: "send a draft: its message becomes SENT in the same thread and the draft is removed", parameters: ["id", "message.raw", "message.threadId (same thread only)"], errors: ["400 missing id, invalid MIME or no recipient", "404 unknown draft"] },
855
+ { method: "POST", endpoint: "/batch/gmail/v1", effect: "multipart batch of up to 100 body-less GET messages/<id> or threads/<id> requests", parameters: ["multipart/mixed body"], errors: ["400 malformed batch"] }
856
+ ],
857
+ limitations: ["Bounded Gmail v1 subset: send, messages list/get, labels, threads list/get, sendAs list, drafts create/list/get/update/delete/send (JSON and media upload), history list, messages insert, watch/stop with loopback Pub/Sub push and read-only batch", "Sends and drafts accept folded/UTF-8 encoded headers, quoted-printable/base64 bodies and text or multipart/alternative text+html, without attachments", "Thread search supports only from:/to: address terms; no pageToken or history paging, label-change history, modify or trash; Pub/Sub push is delivered once with no retry, ack deadline or ordering guarantees, and only to loopback endpoints", "Draft records add flat threadId, to, subject, inReplyTo and references evidence fields for assertions", "Unknown fields and operations return 501 and make coverage incomplete"]
858
+ },
859
+ "upstash-redis": {
860
+ version: "1.0.0",
861
+ authentication: "Bearer run-scoped test token (the Upstash REST token header)",
862
+ operations: [
863
+ { method: "POST", endpoint: "/", effect: "run one Redis command given as a JSON array", parameters: ['["COMMAND", ...args]', "Upstash-Encoding: base64"], errors: ["400 Redis error reply or malformed command"] },
864
+ { method: "POST", endpoint: "/pipeline", effect: "run commands in order; one {result}|{error} per command", parameters: ["[[...], ...] up to 1000 commands"], errors: ["400 malformed body"] },
865
+ { method: "POST", endpoint: "/multi-exec", effect: "run commands in order as one transaction", parameters: ["[[...], ...] up to 1000 commands"], errors: ["400 malformed body"] }
866
+ ],
867
+ limitations: ["Commands run on AgentTwin's in-process Redis engine (strings, hashes, lists, sets, sorted sets, expiry), not Redis itself", "Keys are mirrored in /keys as {key, type, value, expireAt?} rows", "EVAL/EVALSHA/scripts, blocking pops, pub/sub subscriptions, MULTI/EXEC/WATCH inside a request and any engine-unknown command return 501", "Expiry uses the host clock; no replication, persistence, ACLs or read-your-writes sync tokens"]
868
+ },
869
+ "google-calendar": {
870
+ version: "1.1.0",
871
+ authentication: "Bearer run-scoped test token; Google-style OAuth2 Bearer header",
872
+ operations: [
873
+ { method: "GET", endpoint: "/calendar/v3/users/me/calendarList", effect: "list seeded calendars", parameters: [], errors: [] },
874
+ { 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"] },
875
+ { 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"] },
876
+ { method: "GET", endpoint: "/calendar/v3/calendars/primary/events/<id>", effect: "retrieve event", parameters: [], errors: ["404 NOT_FOUND"] },
877
+ { 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"] },
878
+ { 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"] }
879
+ ],
880
+ 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"]
881
+ },
882
+ gitlab: {
883
+ version: "1.0.0",
884
+ authentication: "Bearer run-scoped test token; GitLab-style Bearer/OAuth token",
885
+ operations: [
886
+ { method: "GET", endpoint: "/api/v4/projects", effect: "list projects", parameters: [], errors: [] },
887
+ { method: "POST", endpoint: "/api/v4/projects", effect: "create project", parameters: ["name", "description", "visibility"], errors: ["400 name missing"] },
888
+ { method: "GET", endpoint: "/api/v4/projects/<id>", effect: "retrieve project", parameters: [], errors: ["404 Not Found"] },
889
+ { method: "GET", endpoint: "/api/v4/issues", effect: "list issues", parameters: [], errors: [] },
890
+ { 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"] },
891
+ { method: "GET", endpoint: "/api/v4/issues/<id>", effect: "retrieve issue", parameters: [], errors: ["404 Not Found"] },
892
+ { method: "GET", endpoint: "/api/v4/merge_requests", effect: "list merge requests", parameters: [], errors: [] },
893
+ { 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"] },
894
+ { method: "GET", endpoint: "/api/v4/merge_requests/<iid>", effect: "retrieve merge request", parameters: [], errors: ["404 Not Found"] },
895
+ { method: "GET", endpoint: "/api/v4/merge_requests/<iid>/notes", effect: "list merge request notes", parameters: [], errors: ["404 Merge Request Not Found"] },
896
+ { 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"] }
897
+ ],
898
+ 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"]
899
+ },
900
+ jira: {
901
+ version: "1.0.0",
902
+ authentication: "Bearer run-scoped test token; Atlassian PAT Bearer header",
903
+ operations: [
904
+ { 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"] },
905
+ { method: "GET", endpoint: "/rest/api/3/issue/<keyOrId>", effect: "retrieve issue", parameters: [], errors: ["404 Issue does not exist"] },
906
+ { 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 ="] },
907
+ { 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"] },
908
+ { 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"] },
909
+ { method: "GET", endpoint: "/rest/api/3/project", effect: "list seeded projects", parameters: [], errors: [] },
910
+ { method: "GET", endpoint: "/rest/api/3/project/<key>", effect: "retrieve project", parameters: [], errors: ["404 No project could be found"] }
911
+ ],
912
+ 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"]
913
+ },
914
+ discord: {
915
+ version: "1.0.0",
916
+ authentication: "Bearer run-scoped test token; also accepts the Discord-idiomatic Authorization: Bot header",
917
+ operations: [
918
+ { method: "GET", endpoint: "/api/channels/<id>", effect: "retrieve seeded channel", parameters: [], errors: ["404 Unknown Channel"] },
919
+ { method: "GET", endpoint: "/api/channels/<id>/messages", effect: "list channel messages (newest first)", parameters: [], errors: ["404 Unknown Channel"] },
920
+ { 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"] },
921
+ { method: "GET", endpoint: "/api/guilds/<id>", effect: "retrieve seeded guild", parameters: [], errors: ["404 Unknown Guild"] },
922
+ { method: "GET", endpoint: "/api/guilds/<id>/members", effect: "list guild members", parameters: ["limit"], errors: ["404 Unknown Guild", "400 invalid limit"] }
923
+ ],
924
+ 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"]
925
+ },
926
+ twilio: {
927
+ version: "1.0.0",
928
+ authentication: "Bearer run-scoped test token; production Twilio HTTP Basic auth is not required by this twin",
929
+ operations: [
930
+ { method: "POST", endpoint: "/2010-04-01/Accounts/<sid>/Messages.json", effect: "create outbound message (status queued)", parameters: ["To", "From", "Body"], errors: ["400 missing parameters"] },
931
+ { method: "GET", endpoint: "/2010-04-01/Accounts/<sid>/Messages.json", effect: "list messages", parameters: ["To", "From"], errors: ["400 validation"] },
932
+ { method: "POST", endpoint: "/2010-04-01/Accounts/<sid>/Calls.json", effect: "create outbound call (status queued)", parameters: ["To", "From", "Url"], errors: ["400 missing parameters"] },
933
+ { method: "GET", endpoint: "/2010-04-01/Accounts/<sid>/Calls.json", effect: "list calls", parameters: ["To", "From"], errors: ["400 validation"] }
934
+ ],
935
+ 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"]
936
+ },
937
+ zendesk: {
938
+ version: "1.0.0",
939
+ authentication: "Bearer run-scoped test token; production Zendesk Basic auth is not required by this twin",
940
+ operations: [
941
+ { method: "GET", endpoint: "/api/v2/tickets.json", effect: "list tickets", parameters: [], errors: [] },
942
+ { 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"] },
943
+ { method: "GET", endpoint: "/api/v2/tickets/<id>.json", effect: "retrieve ticket", parameters: [], errors: ["404 RecordNotFound"] },
944
+ { method: "PUT", endpoint: "/api/v2/tickets/<id>.json", effect: "update ticket fields", parameters: ["ticket:subject,status,priority,tags"], errors: ["404 RecordNotFound", "400 InvalidStatus"] },
945
+ { method: "GET", endpoint: "/api/v2/users.json", effect: "list seeded users", parameters: [], errors: [] },
946
+ { method: "GET", endpoint: "/api/v2/organizations.json", effect: "list seeded organizations", parameters: [], errors: [] }
947
+ ],
948
+ 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"]
949
+ },
950
+ ...ENTERPRISE_CONTRACTS
951
+ };
952
+
953
+ // src/discovery/masking.ts
954
+ var TOKENISH = /\b(sk|rk|pk|ghp|gho|ghs|xox[baprs]|AKIA|AIza)[A-Za-z0-9_-]{6,}\b/g;
955
+ function maskSecret(value2) {
956
+ return value2.replace(TOKENISH, (match) => `${match.slice(0, 4)}***`);
957
+ }
958
+ function maskUrl(value2) {
959
+ try {
960
+ const url = new URL(value2);
961
+ return `${url.protocol}//${url.host}${url.pathname}`;
962
+ } catch {
963
+ return maskSecret(value2);
964
+ }
965
+ }
966
+
967
+ // src/discovery/probes/providers/stripe.ts
968
+ var stripeProbe = {
969
+ id: "stripe.readonly",
970
+ providerId: "stripe",
971
+ title: "Enumerate Stripe account configuration (read-only)",
972
+ description: "Reads products, prices and webhook endpoints. Read-only; issues no writes.",
973
+ readScope: {
974
+ endpoints: [
975
+ "GET /v1/products",
976
+ "GET /v1/prices",
977
+ "GET /v1/webhook_endpoints"
978
+ ],
979
+ methods: ["GET"]
980
+ },
981
+ credentials: [
982
+ {
983
+ envVar: "STRIPE_SECRET_KEY",
984
+ label: "Stripe restricted key (read scopes)",
985
+ required: true,
986
+ scopes: ["products:read", "prices:read", "webhook_endpoints:read"],
987
+ hint: "Prefer a restricted key (rk_...) with read scopes over a full sk_live_ key."
988
+ }
989
+ ],
990
+ async run(ctx) {
991
+ const spec = this.credentials[0];
992
+ const key2 = ctx.credential(spec);
993
+ if (!key2) {
994
+ return {
995
+ providerId: this.providerId,
996
+ ok: false,
997
+ summary: "no credential present",
998
+ resources: [],
999
+ evidence: []
1000
+ };
1001
+ }
1002
+ const get = async (path) => {
1003
+ const response = await ctx.fetch(`https://api.stripe.com${path}`, {
1004
+ method: "GET",
1005
+ headers: { Authorization: `Bearer ${key2}` },
1006
+ signal: ctx.signal
1007
+ });
1008
+ if (!response.ok) {
1009
+ throw new Error(`Stripe ${path} -> HTTP ${response.status}`);
1010
+ }
1011
+ return await response.json();
1012
+ };
1013
+ try {
1014
+ const [products, prices, hooks] = await Promise.all([
1015
+ get("/v1/products?limit=100"),
1016
+ get("/v1/prices?limit=100"),
1017
+ get("/v1/webhook_endpoints?limit=100")
1018
+ ]);
1019
+ return {
1020
+ providerId: this.providerId,
1021
+ ok: true,
1022
+ summary: `${products.data.length} products, ${prices.data.length} prices, ${hooks.data.length} webhook endpoints`,
1023
+ resources: [
1024
+ {
1025
+ kind: "products",
1026
+ count: products.data.length,
1027
+ sample: products.data.slice(0, 5).map((p) => ({
1028
+ id: p.id,
1029
+ name: p.name,
1030
+ active: p.active
1031
+ }))
1032
+ },
1033
+ { kind: "prices", count: prices.data.length },
1034
+ {
1035
+ kind: "webhook_endpoints",
1036
+ count: hooks.data.length,
1037
+ sample: hooks.data.slice(0, 5).map((h) => ({
1038
+ url: typeof h.url === "string" ? maskUrl(h.url) : void 0,
1039
+ status: h.status
1040
+ }))
1041
+ }
1042
+ ],
1043
+ evidence: [
1044
+ {
1045
+ ref: "probe:stripe",
1046
+ pass: "probe",
1047
+ signal: "probe",
1048
+ detail: "account reachable via read scopes"
1049
+ }
1050
+ ]
1051
+ };
1052
+ } catch (error) {
1053
+ return {
1054
+ providerId: this.providerId,
1055
+ ok: false,
1056
+ error: { message: error instanceof Error ? error.message : String(error) },
1057
+ summary: "probe failed",
1058
+ resources: [],
1059
+ evidence: []
1060
+ };
1061
+ }
1062
+ }
1063
+ };
1064
+
1065
+ // src/discovery/probes/providers/github.ts
1066
+ var githubProbe = {
1067
+ id: "github.readonly",
1068
+ providerId: "github",
1069
+ title: "Enumerate GitHub account (read-only)",
1070
+ description: "Reads the authenticated user and their repositories. Read-only.",
1071
+ readScope: {
1072
+ endpoints: ["GET /user", "GET /user/repos"],
1073
+ methods: ["GET"]
1074
+ },
1075
+ credentials: [
1076
+ {
1077
+ envVar: "GITHUB_TOKEN",
1078
+ label: "GitHub token (read:user, repo:read)",
1079
+ required: true,
1080
+ scopes: ["read:user", "public_repo"],
1081
+ hint: "A fine-grained token with read-only repository access is sufficient."
1082
+ }
1083
+ ],
1084
+ async run(ctx) {
1085
+ const key2 = ctx.credential(this.credentials[0]);
1086
+ if (!key2) {
1087
+ return {
1088
+ providerId: this.providerId,
1089
+ ok: false,
1090
+ summary: "no credential present",
1091
+ resources: [],
1092
+ evidence: []
1093
+ };
1094
+ }
1095
+ const headers = {
1096
+ Authorization: `Bearer ${key2}`,
1097
+ Accept: "application/vnd.github+json",
1098
+ "User-Agent": "agenttwin-discovery"
1099
+ };
1100
+ try {
1101
+ const userResponse = await ctx.fetch("https://api.github.com/user", {
1102
+ method: "GET",
1103
+ headers,
1104
+ signal: ctx.signal
1105
+ });
1106
+ if (!userResponse.ok) {
1107
+ throw new Error(`GitHub /user -> HTTP ${userResponse.status}`);
1108
+ }
1109
+ const user = await userResponse.json();
1110
+ const reposResponse = await ctx.fetch(
1111
+ "https://api.github.com/user/repos?per_page=100&sort=updated",
1112
+ { method: "GET", headers, signal: ctx.signal }
1113
+ );
1114
+ const repos = reposResponse.ok ? await reposResponse.json() : [];
1115
+ return {
1116
+ providerId: this.providerId,
1117
+ ok: true,
1118
+ summary: `${repos.length} repositories readable for @${user.login ?? "unknown"}`,
1119
+ resources: [
1120
+ {
1121
+ kind: "repositories",
1122
+ count: repos.length,
1123
+ sample: repos.slice(0, 5).map((r) => ({
1124
+ name: r.name,
1125
+ private: r.private,
1126
+ archived: r.archived
1127
+ }))
1128
+ }
1129
+ ],
1130
+ evidence: [
1131
+ {
1132
+ ref: "probe:github",
1133
+ pass: "probe",
1134
+ signal: "probe",
1135
+ detail: "account reachable via read scopes"
1136
+ }
1137
+ ]
1138
+ };
1139
+ } catch (error) {
1140
+ return {
1141
+ providerId: this.providerId,
1142
+ ok: false,
1143
+ error: { message: error instanceof Error ? error.message : String(error) },
1144
+ summary: "probe failed",
1145
+ resources: [],
1146
+ evidence: []
1147
+ };
1148
+ }
1149
+ }
1150
+ };
1151
+
1152
+ // src/discovery/providers/catalog.ts
1153
+ function planned(unknown) {
1154
+ return { supported: [], verified: [], unknown, implemented: false };
1155
+ }
1156
+ function partial(adapter) {
1157
+ return { implemented: true, supported: CONTRACTS[adapter].operations.map((operation) => `${operation.method} ${operation.endpoint}`), verified: [], unknown: [...CONTRACTS[adapter].limitations, "Customer workflow coverage requires preparation and execution"] };
1158
+ }
1159
+ function partialMerged(adapters) {
1160
+ return { implemented: true, supported: adapters.flatMap((a) => CONTRACTS[a].operations.map((operation) => `${operation.method} ${operation.endpoint}`)), verified: [], unknown: [...adapters.flatMap((a) => [...CONTRACTS[a].limitations]), "Customer workflow coverage requires preparation and execution"] };
1161
+ }
1162
+ var NO_TWIN = ["all behavior (no twin implemented)"];
1163
+ var PROVIDERS = [
1164
+ {
1165
+ id: "betterstack",
1166
+ title: "Better Stack",
1167
+ category: "observability",
1168
+ twin: planned(NO_TWIN),
1169
+ signatures: {
1170
+ packages: { node: ["@logtail/node", "@logtail/browser"], python: ["logtail-python"], go: ["github.com/BetterStackHQ/slog-betterstack"] },
1171
+ imports: ["@logtail/node", "@logtail/browser", "logtail"],
1172
+ hosts: ["telemetry.betterstack.com", "in.logs.betterstack.com", "uptime.betterstack.com"],
1173
+ envPrefixes: ["BETTERSTACK_", "LOGTAIL_"]
1174
+ },
1175
+ docs: "https://betterstack.com/docs/"
1176
+ },
1177
+ {
1178
+ id: "opentelemetry",
1179
+ title: "OpenTelemetry",
1180
+ category: "observability",
1181
+ twin: planned(NO_TWIN),
1182
+ signatures: {
1183
+ packages: { node: ["@opentelemetry/api", "@opentelemetry/sdk-node", "@opentelemetry/exporter-trace-otlp-http"], python: ["opentelemetry-api", "opentelemetry-sdk"], go: ["go.opentelemetry.io/otel"] },
1184
+ imports: ["@opentelemetry/", "opentelemetry", "go\\.opentelemetry\\.io/otel"],
1185
+ envPrefixes: ["OTEL_"]
1186
+ },
1187
+ docs: "https://opentelemetry.io/docs/"
1188
+ },
1189
+ {
1190
+ id: "stripe",
1191
+ title: "Stripe",
1192
+ category: "payments",
1193
+ twin: partial("stripe"),
1194
+ probe: stripeProbe,
1195
+ signatures: {
1196
+ packages: {
1197
+ node: ["stripe", "@stripe/agent-toolkit"],
1198
+ python: ["stripe"],
1199
+ go: ["stripe-go"],
1200
+ java: ["stripe-java"],
1201
+ ruby: ["stripe"],
1202
+ php: ["stripe/stripe-php"],
1203
+ dotnet: ["Stripe.net"]
1204
+ },
1205
+ imports: ["new Stripe\\(", `from ["']stripe["']`, `require\\(['"]stripe['"]\\)`, "stripe-go"],
1206
+ hosts: ["api.stripe.com"],
1207
+ envPrefixes: ["STRIPE_"],
1208
+ webhookPaths: ["/webhooks/stripe", "/stripe/webhook", "/webhook/stripe"]
1209
+ },
1210
+ docs: "https://stripe.com/docs/api"
1211
+ },
1212
+ {
1213
+ id: "slack",
1214
+ title: "Slack",
1215
+ category: "comms",
1216
+ twin: partial("slack"),
1217
+ signatures: {
1218
+ packages: {
1219
+ node: ["@slack/web-api", "@slack/bolt", "@slack/events-api", "@slack/socket-mode"],
1220
+ python: ["slack_sdk", "slack-bolt"],
1221
+ go: ["slack-go"],
1222
+ java: ["slack-java-sdk"],
1223
+ ruby: ["slack-ruby-client"]
1224
+ },
1225
+ imports: ["@slack/web-api", "WebClient\\(", "slack_sdk"],
1226
+ hosts: ["slack.com", "api.slack.com", "hooks.slack.com"],
1227
+ envPrefixes: ["SLACK_"]
1228
+ }
1229
+ },
1230
+ {
1231
+ id: "github",
1232
+ title: "GitHub",
1233
+ category: "vcs",
1234
+ twin: partial("github"),
1235
+ probe: githubProbe,
1236
+ signatures: {
1237
+ packages: {
1238
+ node: ["@octokit/", "octokit"],
1239
+ python: ["PyGithub", "github"],
1240
+ go: ["google/go-github"],
1241
+ java: ["github-api"],
1242
+ ruby: ["octokit"]
1243
+ },
1244
+ imports: ["Octokit", "@octokit/", "PyGithub"],
1245
+ hosts: ["api.github.com"],
1246
+ envPrefixes: ["GITHUB_", "GH_"],
1247
+ webhookPaths: ["/webhooks/github", "/github/webhook"]
1248
+ }
1249
+ },
1250
+ {
1251
+ id: "gitlab",
1252
+ title: "GitLab",
1253
+ category: "vcs",
1254
+ twin: partial("gitlab"),
1255
+ signatures: {
1256
+ packages: {
1257
+ node: ["@gitbeaker/core", "@gitbeaker/rest", "@gitbeaker/node"],
1258
+ python: ["python-gitlab"],
1259
+ go: ["xanzy/go-gitlab"],
1260
+ java: ["org.gitlab.api"],
1261
+ ruby: ["gitlab"]
1262
+ },
1263
+ imports: ["gitbeaker", "python-gitlab", "go-gitlab"],
1264
+ hosts: ["gitlab.com", "gitlab.example.com"],
1265
+ envPrefixes: ["GITLAB_"],
1266
+ webhookPaths: ["/webhooks/gitlab", "/gitlab/webhook"]
1267
+ },
1268
+ docs: "https://docs.gitlab.com/ee/api/"
1269
+ },
1270
+ {
1271
+ id: "atlassian",
1272
+ title: "Atlassian (Jira)",
1273
+ category: "pm",
1274
+ twin: partial("jira"),
1275
+ signatures: {
1276
+ packages: {
1277
+ node: ["jira.js", "atlassian-connect-express"],
1278
+ python: ["jira", "atlassian-python-api"],
1279
+ go: ["andygrunwald/go-jira"],
1280
+ java: ["atlassian-jira-rest-java-client-core"],
1281
+ ruby: ["jira-ruby"]
1282
+ },
1283
+ imports: ["jira.js", "atlassian-python-api", "go-jira"],
1284
+ hosts: ["atlassian.com", "api.atlassian.com"],
1285
+ envPrefixes: ["JIRA_", "ATLASSIAN_"]
1286
+ },
1287
+ docs: "https://developer.atlassian.com/cloud/jira/platform/rest/v3/"
1288
+ },
1289
+ {
1290
+ id: "discord",
1291
+ title: "Discord",
1292
+ category: "comms",
1293
+ twin: partial("discord"),
1294
+ signatures: {
1295
+ packages: {
1296
+ node: ["discord.js", "@discordjs/rest"],
1297
+ python: ["discord.py", "py-cord"],
1298
+ go: ["bwmarrin/discordgo"],
1299
+ java: ["JDA"],
1300
+ ruby: ["discordrb"]
1301
+ },
1302
+ imports: ["discord.js", "discord.py", "discordgo"],
1303
+ hosts: ["discord.com", "discordapp.com", "gateway.discord.gg"],
1304
+ envPrefixes: ["DISCORD_"],
1305
+ webhookPaths: ["/webhooks/discord", "/discord/webhook"]
1306
+ }
1307
+ },
1308
+ {
1309
+ id: "aws",
1310
+ title: "AWS",
1311
+ category: "cloud",
1312
+ twin: planned(["service coverage (LocalStack passthrough planned)"]),
1313
+ envWeak: true,
1314
+ signatures: {
1315
+ packages: {
1316
+ node: ["@aws-sdk/", "aws-sdk"],
1317
+ python: ["boto3", "botocore"],
1318
+ go: ["aws-sdk-go", "aws-sdk-go-v2"],
1319
+ java: ["software.amazon.awssdk", "aws-java-sdk"],
1320
+ ruby: ["aws-sdk-"],
1321
+ php: ["aws/aws-sdk-php"],
1322
+ dotnet: ["AWSSDK."]
1323
+ },
1324
+ imports: ["@aws-sdk/", "boto3", "aws-sdk-go"],
1325
+ hosts: ["amazonaws.com"],
1326
+ envPrefixes: ["AWS_"]
1327
+ }
1328
+ },
1329
+ {
1330
+ id: "google",
1331
+ title: "Google (Gmail / Calendar / Workspace)",
1332
+ category: "comms",
1333
+ twin: partialMerged(["gmail", "google-calendar", "google-oauth"]),
1334
+ envWeak: true,
1335
+ signatures: {
1336
+ packages: {
1337
+ node: ["googleapis", "google-auth-library"],
1338
+ python: ["google-api-python-client", "google-cloud", "google-auth"],
1339
+ go: ["google.golang.org/api"],
1340
+ java: ["google-api-client"],
1341
+ ruby: ["google-apis-"]
1342
+ },
1343
+ imports: ["googleapis", "google-api-python-client", "google.golang.org/api"],
1344
+ hosts: ["googleapis.com", "gmail.googleapis.com", "www.googleapis.com", "oauth2.googleapis.com"],
1345
+ envPrefixes: ["GOOGLE_", "GCP_", "GMAIL_"]
1346
+ }
1347
+ },
1348
+ {
1349
+ id: "openai",
1350
+ title: "OpenAI",
1351
+ category: "ai",
1352
+ twin: partial("openai"),
1353
+ signatures: {
1354
+ packages: {
1355
+ node: ["openai", "@ai-sdk/openai", "@langchain/openai", "@openai/agents"],
1356
+ python: ["openai"],
1357
+ go: ["go-openai"],
1358
+ ruby: ["ruby-openai"]
1359
+ },
1360
+ imports: ["OpenAI\\(", `from ["']openai["']`, "go-openai"],
1361
+ hosts: ["api.openai.com"],
1362
+ envPrefixes: ["OPENAI_"]
1363
+ }
1364
+ },
1365
+ {
1366
+ id: "gemini",
1367
+ title: "Google Gemini",
1368
+ category: "ai",
1369
+ twin: planned(NO_TWIN),
1370
+ signatures: {
1371
+ packages: {
1372
+ node: ["@google/genai", "@google/generative-ai", "@ai-sdk/google", "@langchain/google-genai"],
1373
+ python: ["google-genai", "google-generativeai"]
1374
+ },
1375
+ imports: ["@google/genai", "@google/generative-ai", "GoogleGenAI\\(", "GoogleGenerativeAI\\("],
1376
+ hosts: ["generativelanguage.googleapis.com"],
1377
+ envPrefixes: ["GEMINI_", "GOOGLE_GENAI_"]
1378
+ }
1379
+ },
1380
+ {
1381
+ id: "anthropic",
1382
+ title: "Anthropic",
1383
+ category: "ai",
1384
+ twin: partial("anthropic"),
1385
+ signatures: {
1386
+ packages: {
1387
+ node: ["@anthropic-ai/sdk", "@ai-sdk/anthropic", "@langchain/anthropic", "@anthropic-ai/claude-agent-sdk", "@anthropic-ai/claude-code"],
1388
+ python: ["anthropic"],
1389
+ go: ["anthropic-sdk-go"]
1390
+ },
1391
+ imports: ["@anthropic-ai/sdk", "Anthropic\\("],
1392
+ hosts: ["api.anthropic.com"],
1393
+ envPrefixes: ["ANTHROPIC_"]
1394
+ }
1395
+ },
1396
+ {
1397
+ id: "shopify",
1398
+ title: "Shopify",
1399
+ category: "commerce",
1400
+ twin: partial("shopify"),
1401
+ signatures: {
1402
+ packages: {
1403
+ node: ["@shopify/", "shopify-api"],
1404
+ python: ["ShopifyAPI"],
1405
+ ruby: ["shopify_api"]
1406
+ },
1407
+ imports: ["@shopify/", "ShopifyAPI"],
1408
+ hosts: ["myshopify.com", "shopify.com"],
1409
+ envPrefixes: ["SHOPIFY_"]
1410
+ }
1411
+ },
1412
+ {
1413
+ id: "twilio",
1414
+ title: "Twilio",
1415
+ category: "comms",
1416
+ twin: partial("twilio"),
1417
+ signatures: {
1418
+ packages: {
1419
+ node: ["twilio"],
1420
+ python: ["twilio"],
1421
+ java: ["twilio"],
1422
+ ruby: ["twilio-ruby"],
1423
+ php: ["twilio/sdk"]
1424
+ },
1425
+ imports: ["twilio"],
1426
+ hosts: ["api.twilio.com"],
1427
+ envPrefixes: ["TWILIO_"]
1428
+ }
1429
+ },
1430
+ {
1431
+ id: "sendgrid",
1432
+ title: "SendGrid",
1433
+ category: "comms",
1434
+ twin: planned(NO_TWIN),
1435
+ signatures: {
1436
+ packages: {
1437
+ node: ["@sendgrid/mail", "@sendgrid/client"],
1438
+ python: ["sendgrid"],
1439
+ ruby: ["sendgrid-ruby"]
1440
+ },
1441
+ imports: ["@sendgrid/", "sendgrid"],
1442
+ hosts: ["api.sendgrid.com"],
1443
+ envPrefixes: ["SENDGRID_"]
1444
+ }
1445
+ },
1446
+ {
1447
+ id: "hubspot",
1448
+ title: "HubSpot",
1449
+ category: "crm",
1450
+ twin: partial("hubspot"),
1451
+ signatures: {
1452
+ packages: {
1453
+ node: ["@hubspot/api-client"],
1454
+ python: ["hubspot-api-client"],
1455
+ ruby: ["hubspot-api-client"]
1456
+ },
1457
+ imports: ["@hubspot/api-client", "hubspot-api-client"],
1458
+ hosts: ["api.hubapi.com"],
1459
+ envPrefixes: ["HUBSPOT_"]
1460
+ }
1461
+ },
1462
+ {
1463
+ id: "salesforce",
1464
+ title: "Salesforce",
1465
+ category: "crm",
1466
+ twin: partial("salesforce"),
1467
+ signatures: {
1468
+ packages: {
1469
+ node: ["jsforce", "@salesforce/"],
1470
+ python: ["simple-salesforce"],
1471
+ java: ["force-wsc"]
1472
+ },
1473
+ imports: ["jsforce", "simple-salesforce"],
1474
+ hosts: ["salesforce.com", "force.com"],
1475
+ envPrefixes: ["SALESFORCE_", "SF_"]
1476
+ }
1477
+ },
1478
+ {
1479
+ id: "zendesk",
1480
+ title: "Zendesk",
1481
+ category: "support",
1482
+ twin: partial("zendesk"),
1483
+ signatures: {
1484
+ packages: {
1485
+ node: ["node-zendesk"],
1486
+ python: ["zendesk", "zenpy"],
1487
+ ruby: ["zendesk_api"]
1488
+ },
1489
+ imports: ["node-zendesk", "zenpy"],
1490
+ hosts: ["zendesk.com"],
1491
+ envPrefixes: ["ZENDESK_"]
1492
+ }
1493
+ },
1494
+ {
1495
+ id: "linear",
1496
+ title: "Linear",
1497
+ category: "pm",
1498
+ twin: partial("linear"),
1499
+ signatures: {
1500
+ packages: { node: ["@linear/sdk"], python: ["linear"] },
1501
+ imports: ["@linear/sdk"],
1502
+ hosts: ["api.linear.app"],
1503
+ envPrefixes: ["LINEAR_"]
1504
+ }
1505
+ },
1506
+ {
1507
+ id: "notion",
1508
+ title: "Notion",
1509
+ category: "docs",
1510
+ twin: partial("notion"),
1511
+ signatures: {
1512
+ packages: { node: ["@notionhq/client"], python: ["notion-client"] },
1513
+ imports: ["@notionhq/client", "notion-client"],
1514
+ hosts: ["api.notion.com"],
1515
+ envPrefixes: ["NOTION_"]
1516
+ }
1517
+ },
1518
+ {
1519
+ id: "resend",
1520
+ title: "Resend",
1521
+ category: "comms",
1522
+ twin: planned(NO_TWIN),
1523
+ signatures: {
1524
+ packages: { node: ["resend"] },
1525
+ imports: [`from ["']resend["']`],
1526
+ hosts: ["api.resend.com"],
1527
+ envPrefixes: ["RESEND_"]
1528
+ }
1529
+ },
1530
+ {
1531
+ id: "datadog",
1532
+ title: "Datadog",
1533
+ category: "observability",
1534
+ twin: partial("datadog"),
1535
+ signatures: {
1536
+ packages: { node: ["dogapi", "datadog-metrics", "dd-trace"], python: ["datadog"], go: ["DataDog/datadog-api-client-go"] },
1537
+ imports: ["datadog", "dd-trace"],
1538
+ hosts: ["api.datadoghq.com", "api.us5.datadoghq.com", "api.datadoghq.eu"],
1539
+ envPrefixes: ["DATADOG_", "DD_"]
1540
+ },
1541
+ docs: "https://docs.datadoghq.com/api/latest/"
1542
+ },
1543
+ {
1544
+ id: "servicenow",
1545
+ title: "ServiceNow",
1546
+ category: "support",
1547
+ twin: partial("servicenow"),
1548
+ signatures: { packages: { node: ["servicenow-rest-api", "@servicenow/sdk"], python: ["pysnc", "pysnow"] }, imports: ["servicenow-rest-api", "pysnc", "pysnow"], hosts: ["service-now.com", "servicenowservices.com"], envPrefixes: ["SERVICENOW_", "SNOW_"] }
1549
+ },
1550
+ {
1551
+ id: "workday",
1552
+ title: "Workday",
1553
+ category: "hr",
1554
+ twin: partial("workday"),
1555
+ signatures: { packages: { python: ["workday"] }, imports: [], hosts: ["myworkday.com", "workday.com"], envPrefixes: ["WORKDAY_"] }
1556
+ },
1557
+ {
1558
+ id: "sap",
1559
+ title: "SAP S/4HANA",
1560
+ category: "erp",
1561
+ twin: partial("sap"),
1562
+ signatures: { packages: { node: ["@sap-cloud-sdk/http-client", "@sap-cloud-sdk/odata-v2", "@sap-cloud-sdk/connectivity"], python: ["pyodata"], java: ["com.sap.cloud.sdk"] }, imports: ["@sap-cloud-sdk/", "pyodata"], hosts: ["s4hana.ondemand.com", "hana.ondemand.com", "/sap/opu/odata/"], envPrefixes: ["SAP_"] }
1563
+ },
1564
+ {
1565
+ id: "microsoft",
1566
+ title: "Microsoft 365 (Graph)",
1567
+ category: "workspace",
1568
+ twin: partialMerged(["microsoft-teams", "outlook", "entra-id", "sharepoint"]),
1569
+ signatures: { packages: { node: ["@microsoft/microsoft-graph-client", "@microsoft/msgraph-sdk", "@azure/msal-node"], python: ["msgraph-sdk", "O365", "msal"], dotnet: ["Microsoft.Graph"], java: ["com.microsoft.graph"] }, imports: ["@microsoft/microsoft-graph-client", "@microsoft/msgraph-sdk", "msgraph", "O365"], hosts: ["graph.microsoft.com", "login.microsoftonline.com"], envPrefixes: ["MS_GRAPH_", "AZURE_AD_", "ENTRA_", "MICROSOFT_"] }
1570
+ },
1571
+ {
1572
+ id: "microsoft-teams",
1573
+ title: "Microsoft Teams",
1574
+ category: "messaging",
1575
+ twin: partial("microsoft-teams"),
1576
+ signatures: { packages: { node: ["botbuilder", "@microsoft/teams-ai", "@microsoft/teams.apps"], python: ["botbuilder-core", "teams-ai"] }, imports: ["botbuilder", "@microsoft/teams-ai", "teams_ai"], hosts: ["webhook.office.com", "teams.microsoft.com"], envPrefixes: ["TEAMS_", "MICROSOFT_APP_"] }
1577
+ },
1578
+ {
1579
+ id: "okta",
1580
+ title: "Okta",
1581
+ category: "identity",
1582
+ twin: partial("okta"),
1583
+ signatures: { packages: { node: ["@okta/okta-sdk-nodejs"], python: ["okta"], go: ["github.com/okta/okta-sdk-golang"], java: ["com.okta.sdk"] }, imports: ["@okta/okta-sdk-nodejs", "okta.client"], hosts: ["okta.com", "oktapreview.com"], envPrefixes: ["OKTA_"] }
1584
+ },
1585
+ {
1586
+ id: "confluence",
1587
+ title: "Confluence",
1588
+ category: "docs",
1589
+ twin: partial("confluence"),
1590
+ signatures: { packages: { node: ["confluence.js", "confluence-api"] }, imports: ["confluence.js", "confluence-api", "atlassian.Confluence"], hosts: ["/wiki/api/v2", "/wiki/rest/api"], envPrefixes: ["CONFLUENCE_"] }
1591
+ },
1592
+ {
1593
+ id: "snowflake",
1594
+ title: "Snowflake",
1595
+ category: "data",
1596
+ twin: partial("snowflake"),
1597
+ signatures: { packages: { node: ["snowflake-sdk"], python: ["snowflake-connector-python", "snowflake-snowpark-python", "snowflake-sqlalchemy"], go: ["github.com/snowflakedb/gosnowflake"], java: ["net.snowflake"] }, imports: ["snowflake-sdk", "snowflake.connector", "snowflake.snowpark", "gosnowflake"], hosts: ["snowflakecomputing.com"], envPrefixes: ["SNOWFLAKE_", "SNOWSQL_"] }
1598
+ },
1599
+ {
1600
+ id: "netsuite",
1601
+ title: "NetSuite",
1602
+ category: "erp",
1603
+ twin: partial("netsuite"),
1604
+ signatures: { packages: { node: ["netsuite-rest"], python: ["netsuite"] }, imports: ["netsuite-rest", "netsuite"], hosts: ["suitetalk.api.netsuite.com", "netsuite.com"], envPrefixes: ["NETSUITE_", "NS_ACCOUNT"] }
1605
+ },
1606
+ {
1607
+ id: "pagerduty",
1608
+ title: "PagerDuty",
1609
+ category: "observability",
1610
+ twin: partial("pagerduty"),
1611
+ signatures: { packages: { node: ["@pagerduty/pdjs", "node-pagerduty"], python: ["pdpyras", "pagerduty"], go: ["github.com/PagerDuty/go-pagerduty"] }, imports: ["@pagerduty/pdjs", "pdpyras", "go-pagerduty"], hosts: ["api.pagerduty.com", "events.pagerduty.com"], envPrefixes: ["PAGERDUTY_", "PD_API_"] }
1612
+ }
1613
+ ];
1614
+ for (const [id, title, category, node, python, hosts] of [
1615
+ ["composio", "Composio", "integration", ["@composio/core", "@composio/client"], ["composio", "composio-core"], ["backend.composio.dev"]],
1616
+ ["kernel", "Kernel", "browser", ["@onkernel/sdk"], ["kernel"], ["api.onkernel.com"]],
1617
+ ["e2b", "E2B", "runtime", ["e2b", "@e2b/code-interpreter"], ["e2b", "e2b-code-interpreter"], ["api.e2b.dev"]],
1618
+ ["mem0", "Mem0", "ai", ["mem0ai"], ["mem0ai"], ["api.mem0.ai"]],
1619
+ ["ollama", "Ollama", "ai", ["ollama"], ["ollama"], []],
1620
+ ["onepassword", "1Password", "security", ["@1password/sdk"], ["onepassword-sdk"], []],
1621
+ ["supabase", "Supabase", "data", ["@supabase/supabase-js", "@supabase/ssr", "@supabase/auth-helpers-nextjs"], ["supabase"], ["supabase.co"]],
1622
+ ["firecrawl", "Firecrawl", "search", ["@mendable/firecrawl-js", "firecrawl"], ["firecrawl-py"], ["api.firecrawl.dev"]],
1623
+ ["exa", "Exa", "search", ["exa-js"], ["exa-py"], ["api.exa.ai"]],
1624
+ ["tavily", "Tavily", "search", ["@tavily/core"], ["tavily-python"], ["api.tavily.com"]],
1625
+ ["vercel-ai-gateway", "Vercel AI Gateway", "ai", ["@ai-sdk/gateway"], [], ["ai-gateway.vercel.sh"]],
1626
+ ["vercel-blob", "Vercel Blob", "storage", ["@vercel/blob"], [], ["blob.vercel-storage.com"]],
1627
+ ["smtp", "Email (SMTP)", "comms", ["nodemailer"], [], []]
1628
+ ]) PROVIDERS.push({ id, title, category, twin: id === "composio" ? partial("composio") : planned(NO_TWIN), signatures: { packages: { node: [...node], python: [...python] }, imports: id === "vercel-ai-gateway" ? ["@ai-sdk/gateway", "gateway\\.languageModel\\("] : [...node, ...python], hosts: [...hosts] } });
1629
+ var EXTRA_PROVIDERS = [
1630
+ // Model vendors
1631
+ ["mistral", "Mistral AI", "ai", ["@mistralai/mistralai", "@langchain/mistralai", "@ai-sdk/mistral"], ["mistralai", "langchain-mistralai"], ["api.mistral.ai"], ["MISTRAL_"], []],
1632
+ ["groq", "Groq", "ai", ["groq-sdk", "@langchain/groq", "@ai-sdk/groq"], ["groq", "langchain-groq"], ["api.groq.com"], ["GROQ_"], []],
1633
+ ["cohere", "Cohere", "ai", ["cohere-ai", "@langchain/cohere", "@ai-sdk/cohere"], ["cohere", "langchain-cohere"], ["api.cohere.com", "api.cohere.ai"], ["COHERE_"], []],
1634
+ ["xai", "xAI (Grok)", "ai", ["@ai-sdk/xai", "@langchain/xai"], ["xai-sdk"], ["api.x.ai"], ["XAI_"], ["xai_sdk"]],
1635
+ ["deepseek", "DeepSeek", "ai", ["@ai-sdk/deepseek", "@langchain/deepseek"], ["langchain-deepseek"], ["api.deepseek.com"], ["DEEPSEEK_"], []],
1636
+ ["perplexity", "Perplexity", "ai", ["@ai-sdk/perplexity", "@perplexity-ai/perplexity_ai"], ["perplexityai"], ["api.perplexity.ai"], ["PERPLEXITY_"], ["perplexity"]],
1637
+ ["together", "Together AI", "ai", ["together-ai", "@ai-sdk/togetherai"], ["together"], ["api.together.xyz", "api.together.ai"], ["TOGETHER_"], []],
1638
+ ["fireworks", "Fireworks AI", "ai", ["@ai-sdk/fireworks"], ["fireworks-ai"], ["api.fireworks.ai"], ["FIREWORKS_"], ["fireworks"]],
1639
+ ["huggingface", "Hugging Face", "ai", ["@huggingface/inference", "@huggingface/hub"], ["huggingface-hub", "huggingface_hub"], ["api-inference.huggingface.co", "router.huggingface.co"], ["HF_TOKEN", "HUGGINGFACE_"], ["huggingface_hub"]],
1640
+ ["replicate", "Replicate", "ai", ["replicate"], ["replicate"], ["api.replicate.com"], ["REPLICATE_"], []],
1641
+ ["elevenlabs", "ElevenLabs", "ai", ["elevenlabs", "@elevenlabs/elevenlabs-js"], ["elevenlabs"], ["api.elevenlabs.io"], ["ELEVENLABS_"], []],
1642
+ ["openrouter", "OpenRouter", "ai", ["@openrouter/ai-sdk-provider", "@openrouter/sdk"], [], ["openrouter.ai"], ["OPENROUTER_"], []],
1643
+ // AI gateways and model routers
1644
+ ["litellm", "LiteLLM", "ai", ["litellm"], ["litellm"], [], ["LITELLM_"], []],
1645
+ ["portkey", "Portkey", "ai", ["portkey-ai"], ["portkey-ai"], ["api.portkey.ai"], ["PORTKEY_"], ["portkey_ai"]],
1646
+ ["helicone", "Helicone", "ai", ["@helicone/helpers"], ["helicone"], ["oai.helicone.ai", "ai-gateway.helicone.ai", "anthropic.helicone.ai"], ["HELICONE_"], []],
1647
+ ["cloudflare-ai-gateway", "Cloudflare AI Gateway", "ai", [], [], ["gateway.ai.cloudflare.com"], ["CLOUDFLARE_AI_GATEWAY_"], []],
1648
+ // Vector stores
1649
+ ["pinecone", "Pinecone", "vector-store", ["@pinecone-database/pinecone", "@langchain/pinecone"], ["pinecone", "pinecone-client"], ["api.pinecone.io", "svc.pinecone.io"], ["PINECONE_"], []],
1650
+ ["qdrant", "Qdrant", "vector-store", ["@qdrant/js-client-rest", "@langchain/qdrant"], ["qdrant-client"], ["cloud.qdrant.io"], ["QDRANT_"], ["qdrant_client"]],
1651
+ ["weaviate", "Weaviate", "vector-store", ["weaviate-client", "weaviate-ts-client"], ["weaviate-client"], ["weaviate.cloud", "weaviate.io"], ["WEAVIATE_"], ["weaviate"]],
1652
+ ["chroma", "Chroma", "vector-store", ["chromadb"], ["chromadb"], ["api.trychroma.com"], ["CHROMA_"], []],
1653
+ ["milvus", "Milvus / Zilliz", "vector-store", ["@zilliz/milvus2-sdk-node"], ["pymilvus"], ["zillizcloud.com"], ["MILVUS_", "ZILLIZ_"], []],
1654
+ // Queues, streams and durable workflow runtimes
1655
+ ["kafka", "Kafka", "queue", ["kafkajs", "@confluentinc/kafka-javascript", "node-rdkafka"], ["kafka-python", "confluent-kafka", "aiokafka"], ["confluent.cloud"], ["KAFKA_"], ["kafka", "confluent_kafka", "aiokafka"]],
1656
+ ["rabbitmq", "RabbitMQ", "queue", ["amqplib", "amqp-connection-manager"], ["pika", "aio-pika"], ["cloudamqp.com"], ["RABBITMQ_", "AMQP_"], ["pika", "aio_pika"]],
1657
+ ["nats", "NATS", "queue", ["nats"], ["nats-py"], [], ["NATS_"], ["nats"]],
1658
+ ["bullmq", "BullMQ", "queue", ["bullmq", "bull"], [], [], [], []],
1659
+ ["temporal", "Temporal", "queue", ["@temporalio/client", "@temporalio/worker"], ["temporalio"], ["tmprl.cloud"], ["TEMPORAL_"], []],
1660
+ ["inngest", "Inngest", "queue", ["inngest"], ["inngest"], ["inn.gs", "api.inngest.com"], ["INNGEST_"], []],
1661
+ ["triggerdev", "Trigger.dev", "queue", ["@trigger.dev/sdk"], ["trigger-dev"], ["api.trigger.dev"], ["TRIGGER_SECRET_KEY", "TRIGGER_API_"], []],
1662
+ // Search
1663
+ ["elasticsearch", "Elasticsearch", "search", ["@elastic/elasticsearch"], ["elasticsearch"], ["elastic-cloud.com", "es.io"], ["ELASTICSEARCH_", "ELASTIC_"], []],
1664
+ ["algolia", "Algolia", "search", ["algoliasearch"], ["algoliasearch"], ["algolia.net", "algolianet.com"], ["ALGOLIA_"], []],
1665
+ ["meilisearch", "Meilisearch", "search", ["meilisearch"], ["meilisearch"], ["meilisearch.com"], ["MEILISEARCH_", "MEILI_"], []],
1666
+ ["typesense", "Typesense", "search", ["typesense"], ["typesense"], ["typesense.net"], ["TYPESENSE_"], []],
1667
+ // Email and messaging
1668
+ ["mailgun", "Mailgun", "comms", ["mailgun.js", "mailgun-js"], ["mailgun"], ["api.mailgun.net", "api.eu.mailgun.net"], ["MAILGUN_"], []],
1669
+ ["postmark", "Postmark", "comms", ["postmark"], ["postmarker"], ["api.postmarkapp.com"], ["POSTMARK_"], []],
1670
+ ["mailchimp", "Mailchimp", "comms", ["@mailchimp/mailchimp_marketing", "@mailchimp/mailchimp_transactional"], ["mailchimp-marketing"], ["api.mailchimp.com", "mandrillapp.com"], ["MAILCHIMP_", "MANDRILL_"], []],
1671
+ ["telegram", "Telegram", "comms", ["node-telegram-bot-api", "telegraf", "grammy"], ["python-telegram-bot", "aiogram", "pyTelegramBotAPI"], ["api.telegram.org"], ["TELEGRAM_"], ["telegram", "aiogram", "telebot"]],
1672
+ ["vonage", "Vonage", "comms", ["@vonage/server-sdk"], ["vonage"], ["api.nexmo.com", "rest.nexmo.com"], ["VONAGE_", "NEXMO_"], []],
1673
+ ["zoom", "Zoom", "comms", [], [], ["api.zoom.us"], ["ZOOM_"], []],
1674
+ // Payments
1675
+ ["paypal", "PayPal", "payments", ["@paypal/checkout-server-sdk", "@paypal/paypal-server-sdk"], ["paypalrestsdk", "paypal-server-sdk"], ["api-m.paypal.com", "api.paypal.com"], ["PAYPAL_"], []],
1676
+ ["adyen", "Adyen", "payments", ["@adyen/api-library"], ["Adyen"], ["checkout-test.adyen.com", "adyenpayments.com"], ["ADYEN_"], ["Adyen"]],
1677
+ ["paddle", "Paddle", "payments", ["@paddle/paddle-node-sdk"], ["paddle-python-sdk"], ["api.paddle.com", "sandbox-api.paddle.com"], ["PADDLE_"], []],
1678
+ ["lemonsqueezy", "Lemon Squeezy", "payments", ["@lemonsqueezy/lemonsqueezy.js"], [], ["api.lemonsqueezy.com"], ["LEMONSQUEEZY_"], []],
1679
+ ["square", "Square", "payments", ["square"], ["squareup"], ["connect.squareup.com"], ["SQUARE_"], []],
1680
+ ["plaid", "Plaid", "payments", ["plaid"], ["plaid-python"], ["production.plaid.com", "sandbox.plaid.com"], ["PLAID_"], ["plaid"]],
1681
+ ["braintree", "Braintree", "payments", ["braintree"], ["braintree"], ["api.braintreegateway.com"], ["BRAINTREE_"], []],
1682
+ ["razorpay", "Razorpay", "payments", ["razorpay"], ["razorpay"], ["api.razorpay.com"], ["RAZORPAY_"], []],
1683
+ // Identity
1684
+ ["auth0", "Auth0", "identity", ["auth0", "@auth0/nextjs-auth0"], ["auth0-python"], ["auth0.com"], ["AUTH0_"], ["auth0"]],
1685
+ ["clerk", "Clerk", "identity", ["@clerk/backend", "@clerk/nextjs", "@clerk/clerk-sdk-node"], ["clerk-backend-api"], ["api.clerk.com"], ["CLERK_"], []],
1686
+ ["firebase", "Firebase", "data", ["firebase-admin", "firebase"], ["firebase-admin"], ["firebaseio.com", "firestore.googleapis.com"], ["FIREBASE_"], ["firebase_admin"]],
1687
+ // Analytics, errors and LLM observability
1688
+ ["sentry", "Sentry", "observability", ["@sentry/node", "@sentry/nextjs", "@sentry/browser"], ["sentry-sdk"], ["sentry.io"], ["SENTRY_"], ["sentry_sdk"]],
1689
+ ["posthog", "PostHog", "observability", ["posthog-node", "posthog-js"], ["posthog"], ["app.posthog.com", "us.i.posthog.com", "eu.i.posthog.com"], ["POSTHOG_"], []],
1690
+ ["segment", "Segment", "observability", ["@segment/analytics-node", "analytics-node"], ["segment-analytics-python"], ["api.segment.io"], ["SEGMENT_"], []],
1691
+ ["langfuse", "Langfuse", "observability", ["langfuse", "@langfuse/client"], ["langfuse"], ["cloud.langfuse.com"], ["LANGFUSE_"], []],
1692
+ ["langsmith", "LangSmith", "observability", ["langsmith"], ["langsmith"], ["api.smith.langchain.com"], ["LANGSMITH_", "LANGCHAIN_API_KEY"], []],
1693
+ // Agent tool protocol
1694
+ ["mcp", "Model Context Protocol (MCP)", "ai", ["@modelcontextprotocol/sdk"], ["mcp", "fastmcp"], [], ["MCP_"], ["mcp\\.server", "fastmcp"]],
1695
+ // Media storage
1696
+ ["cloudinary", "Cloudinary", "storage", ["cloudinary"], ["cloudinary"], ["api.cloudinary.com"], ["CLOUDINARY_"], []]
1697
+ ];
1698
+ for (const [id, title, category, node, python, hosts, envPrefixes, extraImports] of EXTRA_PROVIDERS) {
1699
+ if (PROVIDERS.some((p) => p.id === id)) continue;
1700
+ PROVIDERS.push({ id, title, category, twin: planned(NO_TWIN), signatures: { packages: { node: [...node], python: [...python] }, imports: [...node, ...python, ...extraImports], hosts: [...hosts], ...envPrefixes.length ? { envPrefixes: [...envPrefixes] } : {} } });
1701
+ }
1702
+
1703
+ // src/flow/sdk-detect.ts
1704
+ var HTTP_CLIENT_PACKAGES = /* @__PURE__ */ new Set(["axios", "node-fetch", "got", "undici", "cross-fetch", "ky", "superagent", "request", "isomorphic-fetch", "needle", "phin", "ofetch", "wretch"]);
1705
+ var SOCKET_PACKAGES = /* @__PURE__ */ new Set(["mysql2", "mysql", "mongodb", "kafkajs", "amqplib", "nodemailer", "@grpc/grpc-js", "ioredis", "redis", "pg", "postgres", "ws", "memcached", "cassandra-driver", "tedious", "mssql", "oracledb", "nats", "mqtt", "@confluentinc/kafka-javascript", "node-rdkafka"]);
1706
+ var OUTBOUND_HTTP = /\bhttps?\.(?:request|get)\s*\(|(?<![\w.$])fetch\s*\(|new\s+XMLHttpRequest|\b(?:require\(|from\s*)['"](?:undici|node-fetch|axios|got|cross-fetch|ky|superagent|isomorphic-fetch|@aws-sdk\/(?:node-http-handler|fetch-http-handler))['"]/;
1707
+ var OUTBOUND_SOCKET = /\b(?:net|tls)\.(?:connect|createConnection)\s*\(|new\s+(?:net|tls)\.(?:Socket|TLSSocket)\b/;
1708
+ var SKIP_DIR = /(^|\/)(test|tests|__tests__|docs?|examples?|\.github|types|typings|bin|scripts|coverage)(\/|$)/i;
1709
+ var NOISE_HOST = /(^|\.)(github\.com|githubusercontent\.com|npmjs\.(?:com|org)|w3\.org|json-schema\.org|mozilla\.org|example\.(?:com|org)|localhost|wikipedia\.org|stackoverflow\.com|apache\.org|ietf\.org|readthedocs\.io|nodejs\.org|creativecommons\.org|opensource\.org|schema\.org|microsoft\.com|google\.com|twitter\.com|x\.com|facebook\.com|linkedin\.com|youtube\.com|medium\.com|unpkg\.com|jsdelivr\.net|cloudflare\.com|npmjs\.com|typescriptlang\.org|swagger\.io|openapis\.org|xml\.org|iana\.org|rfc-editor\.org|gnu\.org|ecma-international\.org|whatwg\.org|spec\.whatwg\.org|json\.org|sentry\.io)$/i;
1710
+ var DOC_HOST = /^(?:docs?|developers?|help|support|blog|www|status|learn|community|dashboard|app|console)\./i;
1711
+ var cache = /* @__PURE__ */ new Map();
1712
+ var NOT_SERVICES = /^(?:typescript|tslib|dotenv|zod|lodash|uuid|express|fastify|koa|hono|next|react|react-dom|vitest|jest|tsx|esbuild|prettier|eslint|@types\/|@babel\/|chalk|commander|yargs|debug|ms|semver|nanoid|date-fns|dayjs|moment|cors|helmet|body-parser|morgan|winston|pino|@opentelemetry\/api)/;
1713
+ function packageDir(root2, pkg) {
1714
+ let dir = root2;
1715
+ for (let i = 0; i < 6; i++) {
1716
+ const candidate = join4(dir, "node_modules", pkg);
1717
+ if (existsSync4(join4(candidate, "package.json"))) return candidate;
1718
+ const parent = join4(dir, "..");
1719
+ if (parent === dir) break;
1720
+ dir = parent;
1721
+ }
1722
+ }
1723
+ function sourceFiles(dir, budget) {
1724
+ const out = [];
1725
+ const walk2 = (d, depth) => {
1726
+ if (depth > 5 || budget.files <= 0) return;
1727
+ let entries;
1728
+ try {
1729
+ entries = readdirSync3(d, { withFileTypes: true });
1730
+ } catch {
1731
+ return;
1732
+ }
1733
+ for (const e of entries) {
1734
+ if (budget.files <= 0) return;
1735
+ const path = join4(d, e.name);
1736
+ if (e.isDirectory()) {
1737
+ if (e.name === "node_modules" || SKIP_DIR.test(e.name + "/")) continue;
1738
+ walk2(path, depth + 1);
1739
+ } else if (/\.(?:[cm]?js)$/.test(e.name) && !/\.min\.|\.d\.ts$|\.test\.|\.spec\./.test(e.name)) {
1740
+ let size = 0;
1741
+ try {
1742
+ size = statSync(path).size;
1743
+ } catch {
1744
+ continue;
1745
+ }
1746
+ if (size > 6e5 || budget.bytes - size < 0) continue;
1747
+ budget.files--;
1748
+ budget.bytes -= size;
1749
+ out.push(path);
1750
+ }
1751
+ }
1752
+ };
1753
+ walk2(dir, 0);
1754
+ return out;
1755
+ }
1756
+ var SHORT_LINK = /^(?:aka\.ms|bit\.ly|goo\.gl|t\.co|tinyurl\.com|ow\.ly|git\.io|is\.gd|buff\.ly|rebrand\.ly|lnkd\.in)$/i;
1757
+ var DOC_PATH = /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?(?:docs?|documentation|guides?|reference|tutorials?|blog|learn|help|support|faq|wiki|issues|pull|discussions|changelog|releases)(?:[/?#.]|$)/i;
1758
+ var withoutComments = (text) => text.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:"'`\\/])\/\/[^\n]*/g, "$1");
1759
+ var hostsIn = (source) => {
1760
+ const found = /* @__PURE__ */ new Map();
1761
+ const text = withoutComments(source);
1762
+ for (const m of text.matchAll(/https?:\/\/((?:[a-z0-9-]+\.)+[a-z]{2,})(?=[/:"'`\s?#)]|$)([^\s"'`)]*)/gi)) {
1763
+ const host = m[1].toLowerCase(), path = m[2] ?? "";
1764
+ if (NOISE_HOST.test(host) || DOC_HOST.test(host) || SHORT_LINK.test(host) || DOC_PATH.test(path.replace(/^:\d+/, "")) || /\.(?:md|js|ts|json|png|svg)$/.test(host)) continue;
1765
+ found.set(host, (found.get(host) ?? 0) + 1);
1766
+ }
1767
+ for (const m of text.matchAll(/['"`](api[.-](?:[a-z0-9-]+\.)+[a-z]{2,})['"`]/gi)) {
1768
+ const host = m[1].toLowerCase();
1769
+ if (!NOISE_HOST.test(host)) found.set(host, (found.get(host) ?? 0) + 1);
1770
+ }
1771
+ return [...found.entries()].sort((a, b) => (/^api[.-]|\bapi\b/.test(b[0]) ? 1 : 0) - (/^api[.-]|\bapi\b/.test(a[0]) ? 1 : 0) || b[1] - a[1]).map(([h]) => h);
1772
+ };
1773
+ var packageName = (source) => source.startsWith("@") ? source.split("/").slice(0, 2).join("/") : source.split("/")[0];
1774
+ function sdkInfo(root2, source) {
1775
+ const pkg = packageName(source);
1776
+ const key2 = root2 + "\0" + pkg;
1777
+ if (cache.has(key2)) return cache.get(key2);
1778
+ const result = (() => {
1779
+ if (!pkg || pkg.startsWith(".") || pkg.startsWith("/") || pkg.startsWith("node:") || NOT_SERVICES.test(pkg)) return null;
1780
+ const dir = packageDir(root2, pkg);
1781
+ if (!dir) return null;
1782
+ let manifest = {};
1783
+ try {
1784
+ manifest = JSON.parse(readFileSync4(join4(dir, "package.json"), "utf8"));
1785
+ } catch {
1786
+ return null;
1787
+ }
1788
+ if (Object.keys(manifest.peerDependencies ?? {}).some((d) => /^(react|react-dom|vue|svelte|solid-js|preact)$/.test(d))) return null;
1789
+ let http = HTTP_CLIENT_PACKAGES.has(pkg) || Object.keys(manifest.dependencies ?? {}).some((d) => HTTP_CLIENT_PACKAGES.has(d));
1790
+ let socket = SOCKET_PACKAGES.has(pkg);
1791
+ const budget = { files: 300, bytes: 4e6 };
1792
+ let text = "";
1793
+ for (const file of sourceFiles(dir, budget)) {
1794
+ let body = "";
1795
+ try {
1796
+ body = readFileSync4(file, "utf8");
1797
+ } catch {
1798
+ continue;
1799
+ }
1800
+ if (!http && OUTBOUND_HTTP.test(body)) http = true;
1801
+ if (!socket && OUTBOUND_SOCKET.test(body)) socket = true;
1802
+ if (text.length < 2e6) text += body.slice(0, 2e5) + "\n";
1803
+ }
1804
+ const scope = pkg.startsWith("@") ? pkg.split("/")[0] + "/" : void 0;
1805
+ if (!http && !socket) for (const dep of Object.keys(manifest.dependencies ?? {}).filter((d) => !NOT_SERVICES.test(d) && (!!scope && d.startsWith(scope))).slice(0, 12)) {
1806
+ const depDir = packageDir(root2, dep);
1807
+ if (!depDir) continue;
1808
+ const depBudget = { files: 80, bytes: 15e5 };
1809
+ for (const file of sourceFiles(depDir, depBudget)) {
1810
+ let body = "";
1811
+ try {
1812
+ body = readFileSync4(file, "utf8");
1813
+ } catch {
1814
+ continue;
1815
+ }
1816
+ if (!http && OUTBOUND_HTTP.test(body)) http = true;
1817
+ if (!socket && OUTBOUND_SOCKET.test(body)) socket = true;
1818
+ if (http || socket) break;
1819
+ }
1820
+ if (http || socket) break;
1821
+ }
1822
+ if (!http && !socket) return null;
1823
+ return { pkg, network: http && socket ? "both" : socket ? "socket" : "http", hosts: hostsIn(text).slice(0, 6) };
1824
+ })();
1825
+ cache.set(key2, result);
1826
+ return result;
1827
+ }
1828
+
1829
+ // src/flow/analyze-python.ts
1830
+ import { readdir, readFile, stat } from "fs/promises";
1831
+ import { join as join5, relative as relative2, sep as sep2 } from "path";
1832
+ var SKIP = /(^|\/)(\.venv|venv|env|site-packages|node_modules|__pycache__|\.git|\.agenttwin|dist|build|tests?|migrations)(\/|$)|(^|\/)(test_[^/]*|[^/]*_test)\.py$|(^|\/)(setup|conftest|manage)\.py$/;
1833
+ var MODULES = { stripe: "stripe", openai: "openai", anthropic: "anthropic", slack_sdk: "slack", slack_bolt: "slack", twilio: "twilio", hubspot: "hubspot", github: "github", notion_client: "notion", linear: "linear", shopify: "shopify", psycopg: "postgres", psycopg2: "postgres", asyncpg: "postgres" };
1834
+ var WRITE = /^(create|update|delete|del|remove|cancel|refund|capture|send|post|post_message|postmessage|reply|upsert|insert|confirm|finalize|pay|void|publish|update_message|chat_postmessage|add|set|charge|transfer|invite|open|close|archive|upload)/i;
1835
+ var camel = (s) => s.replace(/_([a-z])/g, (_, c) => c.toUpperCase());
1836
+ function jsOperation(service, chain3) {
1837
+ if (service === "stripe") {
1838
+ const parts = chain3.filter((p) => p !== "v1");
1839
+ const method = parts.at(-1), resource = parts.at(-2) ?? "";
1840
+ const snake = /[A-Z]/.test(resource[0] ?? "") ? resource.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase() : resource;
1841
+ const plural = snake.endsWith("s") ? snake : snake + "s";
1842
+ return `${camel(plural)}.${camel(method)}`;
1843
+ }
1844
+ if (service === "slack" && chain3.length === 1 && chain3[0].includes("_")) {
1845
+ const [ns, ...rest] = chain3[0].split("_");
1846
+ return `${ns}.${camel(rest.join("_"))}`;
1847
+ }
1848
+ return chain3.map(camel).join(".");
1849
+ }
1850
+ function literals(args) {
1851
+ const out = {};
1852
+ for (const m of args.matchAll(/(?:^|[,(\s])([A-Za-z_]\w*)\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|-?\d+(?:\.\d+)?|True|False|\[[^\]]*\])/g)) out[m[1]] = value(m[2]);
1853
+ for (const m of args.matchAll(/["']([A-Za-z_]\w*)["']\s*:\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|-?\d+(?:\.\d+)?|True|False|\[[^\]]*\])/g)) out[m[1]] ??= value(m[2]);
1854
+ return out;
1855
+ }
1856
+ function value(raw) {
1857
+ if (/^["']/.test(raw)) return raw.slice(1, -1);
1858
+ if (raw === "True" || raw === "False") return raw === "True";
1859
+ if (raw.startsWith("[")) return [...raw.matchAll(/["']([^"']*)["']/g)].map((m) => m[1]);
1860
+ return Number(raw);
1861
+ }
1862
+ async function pythonFiles(root2) {
1863
+ const files = [];
1864
+ const visit = async (dir) => {
1865
+ if (files.length >= 500) return;
1866
+ let entries;
1867
+ try {
1868
+ entries = await readdir(dir, { withFileTypes: true });
1869
+ } catch {
1870
+ return;
1871
+ }
1872
+ for (const e of entries) {
1873
+ const path = join5(dir, e.name), rel = relative2(root2, path).split(sep2).join("/");
1874
+ if (e.name.startsWith(".") && e.name !== ".") continue;
1875
+ if (SKIP.test(rel + (e.isDirectory() ? "/" : ""))) continue;
1876
+ if (e.isDirectory()) await visit(path);
1877
+ else if (e.isFile() && e.name.endsWith(".py")) files.push(rel);
1878
+ }
1879
+ };
1880
+ await visit(root2);
1881
+ return files;
1882
+ }
1883
+ async function analyzePythonWorkflows(root2) {
1884
+ const files = await pythonFiles(root2);
1885
+ if (!files.length) return [];
1886
+ const pypi = /* @__PURE__ */ new Map();
1887
+ for (const p of Object.values(packCatalog()?.packs ?? {})) for (const name of p.adoption.pypi) pypi.set(name.replace(/-/g, "_"), `pack:${p.name}`);
1888
+ const candidates = [];
1889
+ for (const file of files) {
1890
+ const info = await stat(join5(root2, file)).catch(() => void 0);
1891
+ if (!info || info.size > 512 * 1024) continue;
1892
+ const text = await readFile(join5(root2, file), "utf8");
1893
+ const runnable = /^if\s+__name__\s*==\s*["']__main__["']\s*:/m.test(text) || /^(?!def |class |import |from |@|#|\s)[A-Za-z_][\w.]*\s*\(/m.test(text) || /^[A-Za-z_]\w*\s*=\s*[\w.]+\.\w+\(/m.test(text);
1894
+ if (!runnable) continue;
1895
+ const bound = /* @__PURE__ */ new Map();
1896
+ for (const m of text.matchAll(/^\s*import\s+([\w.]+)(?:\s+as\s+(\w+))?/gm)) {
1897
+ const mod = m[1].split(".")[0], service = MODULES[mod] ?? pypi.get(mod);
1898
+ if (service) bound.set(m[2] ?? mod, service);
1899
+ }
1900
+ for (const m of text.matchAll(/^\s*from\s+([\w.]+)\s+import\s+([^\n#]+)/gm)) {
1901
+ const mod = m[1].split(".")[0], service = MODULES[mod] ?? pypi.get(mod);
1902
+ if (!service) continue;
1903
+ for (const name of m[2].replace(/[()]/g, "").split(",")) {
1904
+ const [n, alias] = name.trim().split(/\s+as\s+/);
1905
+ if (n) bound.set(alias ?? n, service);
1906
+ }
1907
+ }
1908
+ for (const m of text.matchAll(/^\s*([A-Za-z_]\w*)\s*=\s*([A-Za-z_][\w.]*)\s*\(/gm)) {
1909
+ const service = bound.get(m[2].split(".")[0]);
1910
+ if (service) bound.set(m[1], service);
1911
+ }
1912
+ const calls = [];
1913
+ const lines = text.split("\n");
1914
+ const constants = new Map([...text.matchAll(/^([A-Z_][A-Z0-9_]*)\s*=\s*["']([^"']+)["']/gm)].map((m) => [m[1], m[2]]));
1915
+ const enclosing = (at) => {
1916
+ let start = at;
1917
+ while (start > 0 && !/^(?:async\s+)?def\s/.test(lines[start])) start--;
1918
+ if (!/^(?:async\s+)?def\s/.test(lines[start])) return lines.slice(at, at + 8).join("\n");
1919
+ let end = start + 1;
1920
+ while (end < lines.length && (!lines[end] || /^\s/.test(lines[end]))) end++;
1921
+ return lines.slice(start, end).join("\n");
1922
+ };
1923
+ lines.forEach((line, i) => {
1924
+ for (const m of line.matchAll(/\b([A-Za-z_]\w*)((?:\.[A-Za-z_]\w*)+)\s*\(/g)) {
1925
+ const service = bound.get(m[1]);
1926
+ if (!service) continue;
1927
+ const chain3 = m[2].slice(1).split(".");
1928
+ if (chain3.length === 1 && /^[A-Z]/.test(chain3[0])) continue;
1929
+ const operation = jsOperation(service.replace(/^pack:/, ""), chain3);
1930
+ const args = literals(lines.slice(i, i + 12).join("\n").slice(line.indexOf(m[0]) + m[0].length));
1931
+ const provider = service;
1932
+ const write = WRITE.test(chain3.at(-1)) || (service === "openai" || service === "anthropic") && /create$/.test(chain3.at(-1));
1933
+ calls.push({ provider, operation, file, line: i + 1, column: line.indexOf(m[0]) + 1, argKeys: Object.keys(args), literals: Object.fromEntries(Object.entries(args).filter(([, v]) => typeof v !== "object")), args, write });
1934
+ }
1935
+ const http = /\b(?:requests|httpx|session|client|urllib\.request)?\.?(get|post|put|patch|delete|request|Request|urlopen)\s*\(\s*(?:["']([^"']+)["']|([A-Za-z_]\w*)\b)/.exec(line);
1936
+ const url = http ? http[2] ?? constants.get(http[3] ?? "") : void 0;
1937
+ if (http && url && /^https:\/\//.test(url)) {
1938
+ const provider = fetchHosts().find(([re]) => re.test(url))?.[1];
1939
+ if (provider) {
1940
+ const statement = lines.slice(i, i + 8).join("\n");
1941
+ const verb = http[1].toLowerCase();
1942
+ const method = /^(post|put|patch|delete)$/.test(verb) ? verb.toUpperCase() : /method\s*=\s*["'](POST|PUT|PATCH|DELETE)["']/i.exec(statement)?.[1]?.toUpperCase() ?? (/\bdata\s*=/.test(statement) ? "POST" : "GET");
1943
+ const parsed = new URL(url), path = parsed.pathname;
1944
+ const body = literals(enclosing(i));
1945
+ calls.push({ provider, operation: provider === "slack" ? path.replace(/^\/api\//, "") : provider === "stripe" ? jsOperation("stripe", [path.split("/").filter(Boolean).slice(1, 2)[0] ?? "", "create"]) : `${method} ${path}`, file, line: i + 1, argKeys: Object.keys(body), literals: Object.fromEntries(Object.entries(body).filter(([, v]) => typeof v !== "object")), args: body, host: parsed.hostname, path, method, write: method !== "GET" });
1946
+ }
1947
+ }
1948
+ });
1949
+ if (!calls.length) continue;
1950
+ const providers = new Set(calls.map((c) => c.provider));
1951
+ const score = calls.filter((c) => c.write).length * 3 + (providers.has("stripe") ? 5 : 0) + (providers.has("openai") || providers.has("anthropic") ? 3 : 0) + providers.size;
1952
+ candidates.push({ id: `python:${file}`, title: `python ${file}`, file, exportName: "__main__", entrypoint: `${file}#__main__`, input: null, calls, tools: [], triggers: [], envVars: [...new Set([...text.matchAll(/os\.(?:environ(?:\.get)?\(?\[?|getenv\()["']([A-Z][A-Z0-9_]+)["']/g)].map((m) => m[1]))], channelHints: [...new Set([...text.matchAll(/["']((?:#[a-z0-9][a-z0-9_-]{0,79})|[CG][A-Z0-9]{8,12})["']/g)].map((m) => m[1]))], score, files: [file], script: true, python: true });
1953
+ }
1954
+ return candidates;
1955
+ }
1956
+
1957
+ // src/inventory/entrypoints.ts
1958
+ import { parse as parse3 } from "@babel/parser";
1959
+
1960
+ // src/inventory/ast.ts
1961
+ import { parse as parse2 } from "@babel/parser";
1962
+ import { posix as posix2 } from "path";
1963
+ function unwrap(node) {
1964
+ while (node && ["TSAsExpression", "TSNonNullExpression", "TSSatisfiesExpression", "TSTypeAssertion", "ParenthesizedExpression", "AwaitExpression", "TSInstantiationExpression"].includes(node.type)) node = node.expression ?? node.argument;
1965
+ return node;
1966
+ }
1967
+
1968
+ // src/inventory/entrypoints.ts
1969
+ var NOT_HANDLER_WRAPPERS = /* @__PURE__ */ new Set(["memo", "forwardRef", "lazy", "observer", "useCallback", "useMemo", "createContext", "styled"]);
1970
+ function wrappedHandler(init) {
1971
+ const call = unwrap(init);
1972
+ if (call?.type !== "CallExpression") return void 0;
1973
+ const callee = call.callee, name = callee?.type === "Identifier" ? callee.name : callee?.type === "MemberExpression" && !callee.computed ? callee.property?.name : void 0;
1974
+ if (name && NOT_HANDLER_WRAPPERS.has(name)) return void 0;
1975
+ for (const argument of [...call.arguments ?? []].reverse()) {
1976
+ if ((argument.type === "ArrowFunctionExpression" || argument.type === "FunctionExpression") && argument.body?.type === "BlockStatement" && argument.body.loc) return argument;
1977
+ }
1978
+ return void 0;
1979
+ }
1980
+
1981
+ // src/flow/analyze.ts
1982
+ var WHOLE_INPUT = "$input";
1983
+ var PROVIDER_MODULES = { "@octokit/rest": "github", octokit: "github", "@octokit/core": "github", "@notionhq/client": "notion", "@linear/sdk": "linear", openai: "openai", "groq-sdk": "openai", "@mistralai/mistralai": "openai", "together-ai": "openai", "@anthropic-ai/sdk": "anthropic", stripe: "stripe", "@slack/web-api": "slack", pg: "postgres", postgres: "postgres", "@neondatabase/serverless": "postgres", googleapis: "gmail", "@googleapis/gmail": "gmail", twilio: "twilio", "@hubspot/api-client": "hubspot", ioredis: "redis", redis: "redis", "@aws-sdk/client-s3": "aws", "@aws-sdk/client-dynamodb": "aws", "@aws-sdk/client-sqs": "aws", "@aws-sdk/client-sns": "aws", "@aws-sdk/lib-dynamodb": "aws" };
1984
+ var FETCH_HOSTS = [[/^https:\/\/slack\.com\/api\//, "slack"], [/^https:\/\/api\.openai\.com\//, "openai"], [/^https:\/\/api\.anthropic\.com\//, "anthropic"], [/^https:\/\/api\.stripe\.com\//, "stripe"], [/^https:\/\/gmail\.googleapis\.com\//, "gmail"], [/^https:\/\/api\.hubapi\.com\//, "hubspot"], [/^https:\/\/api\.twilio\.com\//, "twilio"], [/^https:\/\/[a-z0-9-]+\.zendesk\.com\//, "zendesk"], [/^https:\/\/[a-z0-9-]+\.atlassian\.net\//, "jira"], [/^https:\/\/[a-z0-9-]+\.myshopify\.com\//, "shopify"], [/^https:\/\/gitlab\.com\/api\//, "gitlab"], [/^https:\/\/api\.(?:us5\.)?datadoghq\.(?:com|eu)\//, "datadog"]];
1985
+ var KNOWN_PROVIDERS = /* @__PURE__ */ new Set([...FETCH_HOSTS.map(([, provider]) => provider), ...Object.values(PROVIDER_MODULES)]);
1986
+ var escapeHost = (h) => h.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1987
+ var packHosts;
1988
+ var fetchHosts = () => [...FETCH_HOSTS, ...packHosts ??= Object.values(packCatalog()?.packs ?? {}).flatMap((p) => p.hosts.filter((h) => !h.host || !FETCH_HOSTS.some(([re]) => re.test(`https://${h.host}/`))).map((h) => [h.host ? new RegExp(`^https://${h.suffix ? "(?:[a-z0-9-]+\\.)*" : ""}${escapeHost(h.host)}(?:[:/]|$)`, "i") : new RegExp(`^https://(?:${h.hostPattern.replace(/^\^|\$$/g, "")})(?:[:/]|$)`, "i"), `pack:${p.name}`]))];
1989
+ var READ_OPS = /(^|\.)(retrieve|list|get|search|history|info)$/;
1990
+ var SOURCE = /\.(?:[cm]?[jt]s|tsx|jsx)$/;
1991
+ var SKIP2 = /(^|\/)(node_modules|dist|build|coverage|\.git|\.agenttwin|\.next|out|generated|__generated__|__mocks__|storybook-static)(\/|$)|\.(test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)(test|tests|__tests__|e2e|e2e-tests|cypress|cypress-tests|playwright|mock-server|mock-servers)\//;
1992
+ var SETTINGS_MODULE_SIZE = 15;
1993
+ var SOURCE_FILE_LIMIT = 2e4;
1994
+ var ROUTE_FILE = /(^|\/)app\/(?:.*\/)?route\.[cm]?[jt]sx?$/;
1995
+ var SVELTE_ROUTE_FILE = /(^|\/)(?:src\/)?routes\/(?:.*\/)?\+server\.[cm]?[jt]s$/;
1996
+ var FUNCTION_FILE = /(?:^|\/)api\/(?:[^/]+\/)*[^/.]+\.[cm]?[jt]s$/;
1997
+ var PAGES_API_FILE = /(^|\/)(?:src\/)?pages\/api\/.+\.[cm]?[jt]sx?$/;
1998
+ var REQUEST_TARGET_KEYS = /* @__PURE__ */ new Set(["uri", "url", "baseURL", "baseUrl"]);
1999
+ function walk(node, visit, parent) {
2000
+ if (!node || typeof node !== "object") return;
2001
+ if (Array.isArray(node)) {
2002
+ for (const item of node) walk(item, visit, parent);
2003
+ return;
2004
+ }
2005
+ const value2 = node;
2006
+ if (typeof value2.type === "string" && visit(value2, parent) === false) return;
2007
+ for (const [key2, child] of Object.entries(value2)) if (!["loc", "start", "end", "leadingComments", "trailingComments", "extra"].includes(key2) && child && typeof child === "object") walk(child, visit, typeof value2.type === "string" ? value2 : parent);
2008
+ }
2009
+ var chain2 = (node) => {
2010
+ if (node.type === "Identifier") return [node.name];
2011
+ if (node.type === "ThisExpression") return ["this"];
2012
+ if (node.type === "NewExpression") return chain2(node.callee);
2013
+ if ((node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && !node.computed && node.property.type === "Identifier") {
2014
+ const head = chain2(node.object);
2015
+ return head && [...head, node.property.name];
2016
+ }
2017
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression") {
2018
+ const head = chain2(node.callee);
2019
+ return head;
2020
+ }
2021
+ return void 0;
2022
+ };
2023
+ var literal2 = (node) => !node ? void 0 : node.type === "StringLiteral" ? node.value : node.type === "NumericLiteral" ? node.value : node.type === "BooleanLiteral" ? node.value : node.type === "NullLiteral" ? null : node.type === "TemplateLiteral" && !node.expressions.length ? node.quasis[0].value.cooked : void 0;
2024
+ var objectLiteral = (node) => !node ? void 0 : node.type === "ObjectExpression" ? Object.fromEntries(node.properties.filter((p) => p.type === "ObjectProperty" && !p.computed).map((p) => [String(p.key.name ?? p.key.value), objectLiteral(p.value)])) : node.type === "ArrayExpression" ? node.elements.map(objectLiteral) : literal2(node) ?? null;
2025
+ var templateSql = (node) => node.quasis.map((q, i) => q.value.cooked + (i < node.expressions.length ? `$${i + 1}` : "")).join("");
2026
+ function facts(source, file, projectRoot) {
2027
+ const result = { constants: /* @__PURE__ */ new Map(), imports: /* @__PURE__ */ new Map(), clients: /* @__PURE__ */ new Map(), exportedClients: /* @__PURE__ */ new Map(), functions: /* @__PURE__ */ new Map(), exports: /* @__PURE__ */ new Map(), routes: [], inlineRoutes: [], boltListeners: [], boltInstances: /* @__PURE__ */ new Set(), boltExports: /* @__PURE__ */ new Map(), tools: [], mounts: [], trpcRouters: /* @__PURE__ */ new Map(), startsServer: /\.listen\s*\(|\bserve\s*\(\s*\{|NestFactory\s*\.\s*create\s*[(<]|createServer\s*\(/.test(source) };
2028
+ let ast;
2029
+ try {
2030
+ ast = parse4(source, { sourceType: "unambiguous", plugins: ["typescript", "jsx", "decorators-legacy"], errorRecovery: true });
2031
+ } catch {
2032
+ try {
2033
+ ast = parse4(source, { sourceType: "unambiguous", plugins: ["typescript", "jsx"], errorRecovery: true });
2034
+ } catch {
2035
+ return result;
2036
+ }
2037
+ }
2038
+ const body = ast.program.body;
2039
+ for (const top of body) {
2040
+ const decl = top.type === "ExportNamedDeclaration" && top.declaration ? top.declaration : top;
2041
+ if (decl.type === "TSEnumDeclaration") for (const m of decl.members ?? decl.body?.members ?? []) {
2042
+ const v = literal2(m.initializer);
2043
+ const k = m.id?.name ?? m.id?.value;
2044
+ if (typeof v === "string" && k) result.constants.set(`${decl.id.name}.${k}`, v);
2045
+ }
2046
+ if (decl.type === "VariableDeclaration" && decl.kind === "const") for (const d of decl.declarations) {
2047
+ let init = d.init;
2048
+ while (init && (init.type === "TSAsExpression" || init.type === "TSSatisfiesExpression")) init = init.expression;
2049
+ if (d.id.type === "Identifier" && init?.type === "ObjectExpression") {
2050
+ for (const p of init.properties) if (p.type === "ObjectProperty" && !p.computed) {
2051
+ const v = literal2(p.value);
2052
+ if (typeof v === "string") result.constants.set(`${d.id.name}.${p.key.name ?? p.key.value}`, v);
2053
+ }
2054
+ }
2055
+ if (d.id.type === "Identifier" && init?.type === "MemberExpression") {
2056
+ const names = chain2(init);
2057
+ if (names?.[0] === "process" && names[1] === "env" && names[2] && names.length === 3) result.constants.set(`$env:${d.id.name}`, names[2]);
2058
+ }
2059
+ }
2060
+ }
2061
+ for (const node of body) {
2062
+ if (node.type === "ImportDeclaration") for (const spec of node.specifiers) result.imports.set(spec.local.name, { source: node.source.value, imported: spec.type === "ImportDefaultSpecifier" ? "default" : spec.type === "ImportNamespaceSpecifier" ? "*" : spec.imported.name ?? spec.imported.value });
2063
+ }
2064
+ walk(ast, (node) => {
2065
+ if (node.type === "VariableDeclarator" && node.init?.type === "CallExpression" && node.init.callee.name === "require" && node.init.arguments[0]?.type === "StringLiteral") {
2066
+ const source2 = node.init.arguments[0].value;
2067
+ if (node.id.type === "Identifier") result.imports.set(node.id.name, { source: source2, imported: "default" });
2068
+ else if (node.id.type === "ObjectPattern") {
2069
+ for (const p of node.id.properties) if (p.type === "ObjectProperty" && p.value.type === "Identifier") result.imports.set(p.value.name, { source: source2, imported: p.key.name ?? p.key.value });
2070
+ }
2071
+ }
2072
+ });
2073
+ walk(ast, (node) => {
2074
+ const target = node.type === "VariableDeclarator" ? node.id : node.type === "AssignmentExpression" ? node.left : void 0;
2075
+ const init = node.type === "VariableDeclarator" ? node.init : node.type === "AssignmentExpression" ? node.right : void 0;
2076
+ if (!target || init?.type !== "NewExpression") return;
2077
+ const ctor = chain2(init.callee), imp = ctor && result.imports.get(ctor[0]);
2078
+ if (imp?.source === "@slack/bolt" && (imp.imported === "App" || ctor?.at(-1) === "App")) {
2079
+ const receiver = chain2(target);
2080
+ if (receiver) result.boltInstances.add(receiver.join("."));
2081
+ }
2082
+ });
2083
+ if (/@trpc\/server|createTRPCRouter|\.mutation\(|\.query\(/.test(source)) {
2084
+ const ROUTER = /^(createTRPCRouter|router|createRouter|mergeRouters)$/;
2085
+ const schemas = /* @__PURE__ */ new Map();
2086
+ walk(ast, (node) => {
2087
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) schemas.set(node.id.name, node.init);
2088
+ });
2089
+ const zodKeys = (raw, depth = 0) => {
2090
+ let n = raw;
2091
+ if (!n || depth > 3) return void 0;
2092
+ if (n.type === "Identifier") return zodKeys(schemas.get(n.name), depth + 1);
2093
+ for (; n?.type === "CallExpression" && n.callee?.type === "MemberExpression"; n = n.callee.object)
2094
+ if (n.callee.property?.name === "object" && n.arguments[0]?.type === "ObjectExpression") return n.arguments[0].properties.filter((p) => p.type === "ObjectProperty" && !p.computed).map((p) => String(p.key.name ?? p.key.value));
2095
+ return void 0;
2096
+ };
2097
+ const entries = (obj, router, prefix = "") => obj.properties.flatMap((p) => {
2098
+ if (p.type !== "ObjectProperty" || p.computed) return [];
2099
+ const key2 = prefix + String(p.key.name ?? p.key.value), v = p.value;
2100
+ if (v.type === "Identifier") return [{ key: key2, ref: v.name }];
2101
+ if (v.type !== "CallExpression") return [];
2102
+ const head = chain2(v.callee)?.at(-1);
2103
+ if (head && ROUTER.test(head) && v.arguments[0]?.type === "ObjectExpression") return entries(v.arguments[0], router, key2 + ".");
2104
+ let kind, fn, fields;
2105
+ for (let n = v; n?.type === "CallExpression" && n.callee?.type === "MemberExpression"; n = n.callee.object) {
2106
+ const prop = n.callee.property?.name;
2107
+ if ((prop === "mutation" || prop === "query") && !kind) {
2108
+ kind = prop;
2109
+ fn = n.arguments[0];
2110
+ }
2111
+ if (prop === "input" && !fields) fields = zodKeys(n.arguments[0]);
2112
+ }
2113
+ if (!kind || !fn) return [];
2114
+ if (fn.type === "Identifier") return [{ key: key2, kind, fn: fn.name, ...fields ? { fields } : {} }];
2115
+ if (fn.type !== "ArrowFunctionExpression" && fn.type !== "FunctionExpression") return [];
2116
+ const name = `trpc:${router}.${key2}`;
2117
+ result.functions.set(name, fn);
2118
+ return [{ key: key2, kind, fn: name, ...fields ? { fields } : {} }];
2119
+ });
2120
+ walk(ast, (node) => {
2121
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init?.type === "CallExpression" && node.init.arguments[0]?.type === "ObjectExpression") {
2122
+ const last = chain2(node.init.callee)?.at(-1) ?? (node.init.callee.type === "Identifier" ? node.init.callee.name : void 0);
2123
+ if (last && ROUTER.test(last)) result.trpcRouters.set(node.id.name, entries(node.init.arguments[0], node.id.name));
2124
+ }
2125
+ if (node.type === "CallExpression" && node.arguments[0]?.type === "ObjectExpression") {
2126
+ const last = chain2(node.callee)?.at(-1);
2127
+ if (last && /^(fetchRequestHandler|createNextApiHandler|nodeHTTPRequestHandler)$/.test(last)) {
2128
+ const r = node.arguments[0].properties.find((p) => p.type === "ObjectProperty" && String(p.key?.name ?? p.key?.value) === "router");
2129
+ if (r?.value?.type === "Identifier") result.trpcHandler = { router: r.value.name };
2130
+ }
2131
+ }
2132
+ });
2133
+ }
2134
+ const providerOf = (node) => {
2135
+ const callee = node.type === "NewExpression" || node.type === "CallExpression" ? node.callee : void 0;
2136
+ if (callee?.type === "CallExpression" && callee.callee?.type === "Identifier" && callee.callee.name === "require" && callee.arguments?.[0]?.type === "StringLiteral") {
2137
+ const source2 = callee.arguments[0].value;
2138
+ if (PROVIDER_MODULES[source2]) return PROVIDER_MODULES[source2];
2139
+ const sdk = sdkInfo(projectRoot, source2);
2140
+ if (sdk) return `sdk:${sdk.pkg}`;
2141
+ }
2142
+ const names = callee && chain2(callee);
2143
+ const root2 = names?.[0];
2144
+ if (root2 && result.clients.get(root2) === "sdk:kafkajs" && names?.length === 2 && ["producer", "consumer"].includes(names[1])) return "sdk:kafkajs";
2145
+ if (root2 && result.clients.get(root2) === "sdk:amqplib" && names?.length === 2 && ["createChannel", "createConfirmChannel"].includes(names[1])) return "sdk:amqplib";
2146
+ const imported = root2 ? result.imports.get(root2) : void 0;
2147
+ if (imported && PROVIDER_MODULES[imported.source]) return PROVIDER_MODULES[imported.source];
2148
+ if (imported) {
2149
+ const sdk = sdkInfo(projectRoot, imported.source);
2150
+ if (sdk) return `sdk:${sdk.pkg}`;
2151
+ }
2152
+ return void 0;
2153
+ };
2154
+ const wrapped = [];
2155
+ const declare = (name, init, exported) => {
2156
+ if (exported && /^(GET|POST|PUT|PATCH|DELETE)$/.test(name) && ROUTE_FILE.test(file) && init.type === "CallExpression") {
2157
+ const handler = [...init.arguments].reverse().find((a) => a.type === "ArrowFunctionExpression" || a.type === "FunctionExpression");
2158
+ if (handler) {
2159
+ result.functions.set(name, handler);
2160
+ result.exports.set(name, name);
2161
+ return;
2162
+ }
2163
+ const named = [...init.arguments].reverse().find((a) => a.type === "Identifier");
2164
+ if (named) {
2165
+ wrapped.push({ name, local: named.name });
2166
+ return;
2167
+ }
2168
+ }
2169
+ if (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression") {
2170
+ result.functions.set(name, init);
2171
+ if (exported) result.exports.set(name, name);
2172
+ return;
2173
+ }
2174
+ const unwrapped = init.type === "AwaitExpression" ? init.argument : init;
2175
+ const provider = providerOf(unwrapped);
2176
+ if (provider) {
2177
+ result.clients.set(name, provider);
2178
+ if (exported) result.exportedClients.set(name, provider);
2179
+ } else if (exported && !/^use[A-Z]/.test(name)) {
2180
+ const handler = wrappedHandler(init);
2181
+ if (handler) {
2182
+ result.functions.set(name, handler);
2183
+ result.exports.set(name, name);
2184
+ }
2185
+ }
2186
+ };
2187
+ for (const node of body) {
2188
+ const exported = node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration";
2189
+ const declaration2 = exported ? node.declaration : node;
2190
+ if (!declaration2) continue;
2191
+ if (declaration2.type === "FunctionDeclaration" && declaration2.id) {
2192
+ result.functions.set(declaration2.id.name, declaration2);
2193
+ if (exported) result.exports.set(node.type === "ExportDefaultDeclaration" ? "default" : declaration2.id.name, declaration2.id.name);
2194
+ } else if (declaration2.type === "VariableDeclaration") {
2195
+ for (const d of declaration2.declarations) if (d.id.type === "Identifier" && d.init) {
2196
+ declare(d.id.name, d.init, exported);
2197
+ if (declaration2.kind === "const" && literal2(d.init) !== void 0) result.constants.set(d.id.name, literal2(d.init));
2198
+ }
2199
+ } else if (node.type === "ExportDefaultDeclaration") {
2200
+ const provider = providerOf(declaration2);
2201
+ if (provider) result.exportedClients.set("default", provider);
2202
+ }
2203
+ }
2204
+ for (const w of wrapped) {
2205
+ const fn = result.functions.get(w.local);
2206
+ if (fn) {
2207
+ result.functions.set(w.name, fn);
2208
+ result.exports.set(w.name, w.name);
2209
+ }
2210
+ }
2211
+ for (const node of body)
2212
+ if (node.type === "ExportNamedDeclaration" && !node.declaration) for (const spec of node.specifiers ?? []) {
2213
+ const local = spec.local?.name, name = spec.exported?.name;
2214
+ if (local && name) {
2215
+ if (result.functions.has(local)) result.exports.set(name, local);
2216
+ if (result.clients.has(local)) result.exportedClients.set(name, result.clients.get(local));
2217
+ }
2218
+ }
2219
+ for (const node of body) {
2220
+ if (node.type === "ExportNamedDeclaration" && node.declaration?.type === "VariableDeclaration") {
2221
+ for (const d of node.declaration.declarations) if (d.id.type === "Identifier") result.boltExports.set(d.id.name, d.id.name);
2222
+ }
2223
+ if (node.type === "ExportDefaultDeclaration" && node.declaration?.type === "Identifier") result.boltExports.set("default", node.declaration.name);
2224
+ if (node.type === "ExportNamedDeclaration" && !node.declaration && !node.source) {
2225
+ for (const spec of node.specifiers ?? []) if (spec.local?.name && spec.exported?.name) result.boltExports.set(spec.exported.name, spec.local.name);
2226
+ }
2227
+ }
2228
+ walk(ast, (node) => {
2229
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init && !result.clients.has(node.id.name)) {
2230
+ const init = node.init.type === "AwaitExpression" ? node.init.argument : node.init;
2231
+ const provider = init && (init.type === "NewExpression" || init.type === "CallExpression") ? providerOf(init) : void 0;
2232
+ if (provider) result.clients.set(node.id.name, provider);
2233
+ }
2234
+ });
2235
+ walk(ast, (node) => {
2236
+ if (node.type !== "AssignmentExpression") return;
2237
+ const target = chain2(node.left);
2238
+ if (target?.[0] === "module" && target[1] === "exports" && node.right.type === "ObjectExpression") for (const p of node.right.properties) {
2239
+ if (p.type === "ObjectProperty" && p.value.type === "Identifier") {
2240
+ const name = p.key.name ?? p.key.value;
2241
+ if (result.functions.has(p.value.name)) result.exports.set(name, p.value.name);
2242
+ if (result.clients.has(p.value.name)) result.exportedClients.set(name, result.clients.get(p.value.name));
2243
+ }
2244
+ }
2245
+ if (target?.[0] === "exports" && target.length === 2 && node.right.type === "Identifier" && result.functions.has(node.right.name)) result.exports.set(target[1], node.right.name);
2246
+ });
2247
+ walk(ast, (node) => {
2248
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed && ["get", "post", "put", "patch", "delete", "all"].includes(node.callee.property.name) && node.arguments[0]?.type === "StringLiteral" && node.arguments[0].value.startsWith("/")) {
2249
+ const calls = [];
2250
+ for (const arg of node.arguments.slice(1)) {
2251
+ if (arg.type === "Identifier") calls.push(arg.name);
2252
+ else walk(arg, (inner) => {
2253
+ if (inner.type === "CallExpression" && inner.callee.type === "Identifier") calls.push(inner.callee.name);
2254
+ });
2255
+ }
2256
+ result.routes.push({ method: node.callee.property.name.toUpperCase(), path: node.arguments[0].value, line: node.loc.start.line, calls });
2257
+ for (const arg of node.arguments.slice(1)) if (arg.type === "ArrowFunctionExpression" || arg.type === "FunctionExpression") {
2258
+ const method = node.callee.property.name === "all" ? "POST" : node.callee.property.name.toUpperCase();
2259
+ const name = `route:${method.toLowerCase()}:${node.arguments[0].value}@${node.loc.start.line}`;
2260
+ result.functions.set(name, arg);
2261
+ result.inlineRoutes.push({ name, method, path: node.arguments[0].value, line: node.loc.start.line, on: chain2(node.callee.object)?.[0] });
2262
+ }
2263
+ }
2264
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed) {
2265
+ const method = node.callee.property.name, args = node.arguments;
2266
+ const target = (arg) => {
2267
+ if (!arg) return void 0;
2268
+ if (arg.type === "Identifier") return { name: arg.name };
2269
+ if (arg.type === "CallExpression" && arg.callee.type === "Identifier" && arg.callee.name === "require" && arg.arguments[0]?.type === "StringLiteral") return { source: arg.arguments[0].value };
2270
+ if (arg.type === "CallExpression" && arg.callee.type === "Identifier") return { name: arg.callee.name };
2271
+ if (arg.type === "CallExpression" && arg.callee.type === "MemberExpression") {
2272
+ const names = chain2(arg.callee);
2273
+ if (names) return { name: names[0], ...names.length > 2 ? { member: names[1] } : {} };
2274
+ }
2275
+ if (arg.type === "MemberExpression") {
2276
+ const names = chain2(arg);
2277
+ if (names) return { name: names[0], ...names.length > 1 ? { member: names[1] } : {} };
2278
+ }
2279
+ if (arg.type === "AwaitExpression" || arg.type === "ImportExpression") return target(arg.argument ?? arg.source);
2280
+ if (arg.type === "StringLiteral") return { source: arg.value };
2281
+ return void 0;
2282
+ };
2283
+ if ((method === "use" || method === "route" || method === "basePath") && args[0]?.type === "StringLiteral" && args[0].value.startsWith("/"))
2284
+ for (const arg of args.slice(1)) {
2285
+ const t = target(arg);
2286
+ if (t) result.mounts.push({ prefix: args[0].value, ...t });
2287
+ }
2288
+ if (method === "register" && args[1]?.type === "ObjectExpression") {
2289
+ const prefix = literal2(args[1].properties.find((p) => p.type === "ObjectProperty" && (p.key.name ?? p.key.value) === "prefix")?.value);
2290
+ const t = target(args[0]);
2291
+ if (typeof prefix === "string" && t) result.mounts.push({ prefix, ...t });
2292
+ }
2293
+ if (method === "setGlobalPrefix" && args[0]?.type === "StringLiteral") result.globalPrefix = args[0].value;
2294
+ }
2295
+ if ((node.type === "ClassDeclaration" || node.type === "ClassExpression") && node.decorators?.length) {
2296
+ const decoratorArg = (d) => {
2297
+ const call = d.expression;
2298
+ if (call?.type !== "CallExpression") return void 0;
2299
+ const arg = call.arguments[0];
2300
+ if (!arg) return "";
2301
+ if (arg.type === "StringLiteral") return arg.value;
2302
+ if (arg.type === "ObjectExpression") {
2303
+ const v = literal2(arg.properties.find((p) => (p.key?.name ?? p.key?.value) === "path")?.value);
2304
+ return typeof v === "string" ? v : "";
2305
+ }
2306
+ if (arg.type === "ArrayExpression") {
2307
+ const v = literal2(arg.elements[0]);
2308
+ return typeof v === "string" ? v : "";
2309
+ }
2310
+ const ref = arg.type === "Identifier" || arg.type === "MemberExpression" ? chain2(arg) : void 0;
2311
+ return ref && ref.length <= 2 ? `~${ref.join(".")}~` : "";
2312
+ };
2313
+ const name = (d) => d.expression?.type === "CallExpression" && d.expression.callee.type === "Identifier" ? d.expression.callee.name : void 0;
2314
+ const controller = node.decorators.find((d) => /^(Rest)?Controller$/.test(name(d) ?? ""));
2315
+ if (controller) {
2316
+ const prefix = decoratorArg(controller) ?? "";
2317
+ for (const member of node.body.body ?? []) {
2318
+ if (member.type !== "ClassMethod" || !member.decorators?.length) continue;
2319
+ const route = member.decorators.find((d) => /^(Get|Post|Put|Patch|Delete|All)$/.test(name(d) ?? ""));
2320
+ if (!route) continue;
2321
+ const verb = name(route) === "All" ? "POST" : name(route).toUpperCase();
2322
+ const path = ("/" + [prefix, decoratorArg(route) ?? ""].filter(Boolean).join("/")).replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
2323
+ const fn = `route:${verb.toLowerCase()}:${path}@${member.loc.start.line}`;
2324
+ result.functions.set(fn, member);
2325
+ result.inlineRoutes.push({ name: fn, method: verb, path, line: member.loc.start.line });
2326
+ result.routes.push({ method: verb, path, line: member.loc.start.line, calls: [] });
2327
+ }
2328
+ }
2329
+ }
2330
+ if (node.type === "CallExpression" && node.callee.type === "MemberExpression" && !node.callee.computed && ["event", "message", "command", "action", "shortcut", "view", "options"].includes(node.callee.property.name) && node.arguments.length >= 2 && (node.arguments[0].type === "StringLiteral" || node.arguments[0].type === "ObjectExpression" || node.arguments[0].type === "RegExpLiteral")) {
2331
+ const fnArg = node.arguments.slice(1).find((a) => a.type === "ArrowFunctionExpression" || a.type === "FunctionExpression");
2332
+ const inline = fnArg ? `slack:${node.callee.property.name}@${node.loc.start.line}` : void 0;
2333
+ if (inline) result.functions.set(inline, fnArg);
2334
+ result.boltListeners.push({ receiver: chain2(node.callee.object)?.join("."), ...inline ? { inline } : {}, kind: node.callee.property.name, name: node.arguments[0].type === "StringLiteral" ? node.arguments[0].value : node.arguments[0].type === "RegExpLiteral" ? node.arguments[0].pattern : String(literal2(node.arguments[0].properties?.find((p) => ["action_id", "callback_id", "type"].includes(p.key?.name))?.value) ?? ""), handlers: node.arguments.slice(1).filter((a) => a.type === "Identifier").map((a) => a.name), line: node.loc.start.line });
2335
+ }
2336
+ if (node.type === "ObjectExpression") {
2337
+ const props = new Map(node.properties.filter((p) => p.type === "ObjectProperty" && !p.computed).map((p) => [p.key.name ?? p.key.value, p.value]));
2338
+ const name = literal2(props.get("name"));
2339
+ const schema = props.get("parameters") ?? props.get("input_schema") ?? props.get("inputSchema");
2340
+ if (typeof name === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(name) && schema?.type === "ObjectExpression") {
2341
+ const schemaProps = new Map(schema.properties.filter((p) => p.type === "ObjectProperty").map((p) => [p.key.name ?? p.key.value, p.value]));
2342
+ const properties = schemaProps.get("properties");
2343
+ const parameters = properties?.type === "ObjectExpression" ? properties.properties.filter((p) => p.type === "ObjectProperty").map((p) => String(p.key.name ?? p.key.value)) : [];
2344
+ const required = schemaProps.get("required")?.type === "ArrayExpression" ? schemaProps.get("required").elements.map(literal2).filter((v) => typeof v === "string") : [];
2345
+ result.tools.push({ name, parameters, required, file, line: node.loc.start.line });
2346
+ }
2347
+ }
2348
+ });
2349
+ const declarationTypes = /* @__PURE__ */ new Set(["ImportDeclaration", "FunctionDeclaration", "ClassDeclaration", "ExportNamedDeclaration", "ExportDefaultDeclaration", "ExportAllDeclaration", "TSInterfaceDeclaration", "TSTypeAliasDeclaration", "TSEnumDeclaration", "TSModuleDeclaration"]);
2350
+ const statements = body.filter((node) => !declarationTypes.has(node.type) && !(node.type === "VariableDeclaration" && node.declarations.every((d) => d.init && (d.init.type === "ArrowFunctionExpression" || d.init.type === "FunctionExpression"))));
2351
+ const bootstrap = result.routes.length > 0 || result.inlineRoutes.length > 0 || /\.listen\s*\(|\.on\s*\(\s*['"`]/.test(source);
2352
+ if (statements.length && !bootstrap && !result.exports.size && !body.some((node) => node.type.startsWith("Export"))) {
2353
+ const name = `script:${posix3.basename(file)}`;
2354
+ result.functions.set(name, { type: "ArrowFunctionExpression", params: [], body: { type: "BlockStatement", body: statements } });
2355
+ result.script = name;
2356
+ }
2357
+ return result;
2358
+ }
2359
+ var ENTRY_NAME = /^(main|server|app)\.[cm]?[jt]sx?$/;
2360
+ async function sourceFiles2(root2, limit = SOURCE_FILE_LIMIT) {
2361
+ const files = [], entries = [];
2362
+ let full = false;
2363
+ const visit = async (dir) => {
2364
+ let list;
2365
+ try {
2366
+ list = await readdir2(dir, { withFileTypes: true });
2367
+ } catch {
2368
+ return;
2369
+ }
2370
+ for (const entry of list) {
2371
+ const path = join6(dir, entry.name), rel = relative3(root2, path).split(sep3).join("/");
2372
+ if (entry.name.startsWith(".") || SKIP2.test(rel + (entry.isDirectory() ? "/" : ""))) continue;
2373
+ if (entry.isDirectory()) {
2374
+ if (!full || entries.length < 1e3) await visit(path);
2375
+ } else if (entry.isFile() && SOURCE.test(entry.name) && !entry.name.endsWith(".d.ts")) {
2376
+ if (!full) files.push(rel);
2377
+ else if (ENTRY_NAME.test(entry.name) && entries.length < 1e3) entries.push(rel);
2378
+ if (files.length >= limit) full = true;
2379
+ }
2380
+ }
2381
+ };
2382
+ await visit(root2);
2383
+ return [...files, ...entries];
2384
+ }
2385
+ var nextApps = /* @__PURE__ */ new Map();
2386
+ function nextBasePath(root2, appDir) {
2387
+ if (appDir === void 0) return "";
2388
+ for (const ext of ["js", "mjs", "ts", "cjs", "mts"]) try {
2389
+ const m = /\bbasePath\s*:\s*['"`](\/[^'"`$]*)['"`]/.exec(readFileSync5(join6(root2, appDir, `next.config.${ext}`), "utf8"));
2390
+ if (m) return m[1].replace(/\/$/, "");
2391
+ } catch {
2392
+ }
2393
+ return "";
2394
+ }
2395
+ function nextAppDir(root2, file) {
2396
+ for (let dir = posix3.dirname(file); ; dir = posix3.dirname(dir)) {
2397
+ const key2 = root2 + "\0" + dir;
2398
+ if (!nextApps.has(key2)) {
2399
+ let found;
2400
+ try {
2401
+ const pkg = JSON.parse(readFileSync5(join6(root2, dir, "package.json"), "utf8"));
2402
+ if (pkg.dependencies?.next || pkg.devDependencies?.next) found = dir === "." ? "" : dir;
2403
+ } catch {
2404
+ }
2405
+ nextApps.set(key2, found);
2406
+ }
2407
+ const hit = nextApps.get(key2);
2408
+ if (hit !== void 0) return hit;
2409
+ if (dir === "." || dir === "/") return void 0;
2410
+ }
2411
+ }
2412
+ var LazyFunctions = class extends Map {
2413
+ constructor(names, tree) {
2414
+ super();
2415
+ this.tree = tree;
2416
+ this.names = new Set(names);
2417
+ }
2418
+ tree;
2419
+ names;
2420
+ has(name) {
2421
+ return this.names.has(name);
2422
+ }
2423
+ get(name) {
2424
+ return this.names.has(name) ? this.tree(name) : void 0;
2425
+ }
2426
+ keys() {
2427
+ return this.names.values();
2428
+ }
2429
+ get size() {
2430
+ return this.names.size;
2431
+ }
2432
+ };
2433
+ async function analyzeWorkflows(root2, opts = {}) {
2434
+ const files = await sourceFiles2(root2);
2435
+ const bolt = await readFile2(join6(root2, "package.json"), "utf8").then((t) => {
2436
+ const p = JSON.parse(t);
2437
+ return !!(p.dependencies?.["@slack/bolt"] ?? p.devDependencies?.["@slack/bolt"]);
2438
+ }).catch(() => false);
2439
+ const byFile = /* @__PURE__ */ new Map();
2440
+ const reparsed = /* @__PURE__ */ new Map();
2441
+ const treeOf = (file, text) => {
2442
+ let map = reparsed.get(file);
2443
+ if (map) {
2444
+ reparsed.delete(file);
2445
+ reparsed.set(file, map);
2446
+ return map;
2447
+ }
2448
+ map = facts(text, file, root2).functions;
2449
+ reparsed.set(file, map);
2450
+ if (reparsed.size > 64) reparsed.delete(reparsed.keys().next().value);
2451
+ return map;
2452
+ };
2453
+ for (const file of files) {
2454
+ const info = await stat2(join6(root2, file)).catch(() => void 0);
2455
+ if (!info || info.size > 1024 * 1024) continue;
2456
+ const text = await readFile2(join6(root2, file), "utf8");
2457
+ const found = facts(text, file, root2);
2458
+ found.functions = new LazyFunctions(found.functions.keys(), (name) => treeOf(file, text).get(name));
2459
+ byFile.set(file, { facts: found, text });
2460
+ }
2461
+ const aliases = tsconfigAliases(root2);
2462
+ const workspace = /* @__PURE__ */ new Map();
2463
+ {
2464
+ const seen = /* @__PURE__ */ new Set();
2465
+ for (const file of byFile.keys()) for (let dir = posix3.dirname(file); dir !== "." && dir !== "/" && !seen.has(dir); dir = posix3.dirname(dir)) {
2466
+ seen.add(dir);
2467
+ try {
2468
+ const pkg = JSON.parse(readFileSync5(join6(root2, dir, "package.json"), "utf8"));
2469
+ if (typeof pkg.name !== "string" || workspace.has(pkg.name)) continue;
2470
+ const exports = {};
2471
+ const ex = pkg.exports;
2472
+ if (typeof ex === "string") exports["."] = ex;
2473
+ else if (ex && typeof ex === "object") for (const [k, v] of Object.entries(ex)) {
2474
+ const target = typeof v === "string" ? v : v?.import ?? v?.default ?? v?.types;
2475
+ if (typeof target === "string") exports[k] = target;
2476
+ }
2477
+ if (!exports["."]) exports["."] = typeof pkg.main === "string" ? pkg.main : "./src/index.ts";
2478
+ workspace.set(pkg.name, { dir, exports });
2479
+ } catch {
2480
+ }
2481
+ }
2482
+ }
2483
+ const workspaceBases = (source) => {
2484
+ for (const [name, { dir, exports }] of workspace) {
2485
+ if (source !== name && !source.startsWith(name + "/")) continue;
2486
+ const sub = source === name ? "." : "./" + source.slice(name.length + 1);
2487
+ const direct2 = exports[sub], star = Object.entries(exports).find(([k]) => k.endsWith("/*") && sub.startsWith(k.slice(0, -1)));
2488
+ const target = direct2 ?? (star ? star[1].replace("*", sub.slice(star[0].length - 1)) : sub === "." ? "./src/index.ts" : "./src/" + sub.slice(2));
2489
+ return [posix3.normalize(posix3.join(dir, target)), posix3.normalize(posix3.join(dir, target.replace(/^\.\/dist\//, "./src/")))];
2490
+ }
2491
+ return [];
2492
+ };
2493
+ const resolveModule = (from, source) => {
2494
+ const bases = source.startsWith(".") ? [posix3.normalize(posix3.join(posix3.dirname(from), source))] : [...aliases.resolve(from, source), ...workspaceBases(source)];
2495
+ for (const base of bases) {
2496
+ const stem = base.replace(/\.[cm]?js$/, "");
2497
+ for (const candidate of [base, stem + ".ts", stem + ".tsx", stem + ".mts", stem + ".js", stem + ".mjs", stem + ".cjs", stem + ".jsx", base + "/index.ts", base + "/index.tsx", base + "/index.js"]) if (byFile.has(candidate)) return candidate;
2498
+ }
2499
+ return void 0;
2500
+ };
2501
+ const boltInstance = (file, receiver, seen = /* @__PURE__ */ new Set()) => {
2502
+ const key2 = file + "#" + receiver;
2503
+ if (seen.has(key2)) return;
2504
+ seen.add(key2);
2505
+ const facts2 = byFile.get(file)?.facts;
2506
+ if (!facts2) return;
2507
+ if (facts2.boltInstances.has(receiver)) return file;
2508
+ const [head, ...members] = receiver.split("."), binding = facts2.imports.get(head);
2509
+ if (!binding) return;
2510
+ const target = resolveModule(file, binding.source);
2511
+ if (!target) return;
2512
+ const exported = binding.imported === "*" ? members.shift() : binding.imported;
2513
+ const local = exported && byFile.get(target)?.facts.boltExports.get(exported);
2514
+ return local ? boltInstance(target, [local, ...members].join("."), seen) : void 0;
2515
+ };
2516
+ const clientProvider = (file, name) => {
2517
+ const f = byFile.get(file).facts;
2518
+ if (f.clients.has(name)) return f.clients.get(name);
2519
+ const imported = f.imports.get(name);
2520
+ if (!imported) return void 0;
2521
+ if (PROVIDER_MODULES[imported.source]) return PROVIDER_MODULES[imported.source];
2522
+ const sdk = sdkInfo(root2, imported.source);
2523
+ if (sdk) return `sdk:${sdk.pkg}`;
2524
+ const target = resolveModule(file, imported.source);
2525
+ return target ? byFile.get(target).facts.exportedClients.get(imported.imported) : void 0;
2526
+ };
2527
+ const functionRef = (file, name) => {
2528
+ const f = byFile.get(file).facts;
2529
+ if (f.functions.has(name)) return [file, name];
2530
+ const imported = f.imports.get(name);
2531
+ if (!imported) return void 0;
2532
+ const target = resolveModule(file, imported.source);
2533
+ if (!target) return void 0;
2534
+ const local = byFile.get(target).facts.exports.get(imported.imported);
2535
+ return local ? [target, local] : void 0;
2536
+ };
2537
+ const mountTarget = (file, m) => {
2538
+ if (m.source) return resolveModule(file, m.source);
2539
+ if (!m.name) return void 0;
2540
+ const imported = byFile.get(file).facts.imports.get(m.name);
2541
+ const module = imported ? resolveModule(file, imported.source) : void 0;
2542
+ if (!module || !m.member) return module;
2543
+ const inner = byFile.get(module)?.facts.imports.get(m.member);
2544
+ return inner && resolveModule(module, inner.source) || resolveModule(file, `${imported.source.replace(/\/$/, "")}/${m.member}`) || module;
2545
+ };
2546
+ const mountedBy = (file) => {
2547
+ const found = [];
2548
+ for (const [other, { facts: o }] of byFile) for (const m of o.mounts) if (other !== file && mountTarget(other, m) === file) found.push({ file: other, prefix: m.prefix });
2549
+ return found;
2550
+ };
2551
+ const outerPrefix = (file, depth = 0) => {
2552
+ if (depth > 4) return { prefix: "", top: file };
2553
+ const parent = mountedBy(file)[0];
2554
+ if (!parent) return { prefix: "", top: file };
2555
+ const outer = outerPrefix(parent.file, depth + 1);
2556
+ return { prefix: outer.prefix + parent.prefix, top: outer.top };
2557
+ };
2558
+ const globalPrefix = [...byFile.values()].map((v) => v.facts.globalPrefix).find(Boolean);
2559
+ const join22 = (...parts) => "/" + parts.map((p) => p.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
2560
+ const constantPath = (file, path) => path.replace(/~([\w$.]+)~/g, (_, key2) => {
2561
+ const f = byFile.get(file).facts;
2562
+ if (typeof f.constants.get(key2) === "string") return f.constants.get(key2);
2563
+ const [head, ...rest] = key2.split("."), imported = f.imports.get(head), target = imported ? resolveModule(file, imported.source) : void 0;
2564
+ const value2 = target ? byFile.get(target).facts.constants.get([imported.imported && imported.imported !== "*" && imported.imported !== "default" ? imported.imported : head, ...rest].join(".")) : void 0;
2565
+ if (typeof value2 === "string") return value2;
2566
+ const found = new Set([...byFile.values()].map((v) => v.facts.constants.get(key2)).filter((v) => typeof v === "string"));
2567
+ return found.size === 1 ? [...found][0] : "";
2568
+ });
2569
+ const routePath = (file, route) => {
2570
+ const f = byFile.get(file).facts;
2571
+ const local = route.on ? f.mounts.find((m) => m.name === route.on && !f.imports.has(route.on))?.prefix ?? "" : "";
2572
+ return join22(globalPrefix ?? "", outerPrefix(file).prefix, local, constantPath(file, route.path)) || "/";
2573
+ };
2574
+ const importCache = /* @__PURE__ */ new Map();
2575
+ const importsOf = (file) => {
2576
+ const cached2 = importCache.get(file);
2577
+ if (cached2) return cached2;
2578
+ const out = [];
2579
+ for (const imported of byFile.get(file).facts.imports.values()) {
2580
+ const t = resolveModule(file, imported.source);
2581
+ if (t) out.push(t);
2582
+ }
2583
+ for (const m of byFile.get(file).facts.mounts) {
2584
+ const t = mountTarget(file, m);
2585
+ if (t) out.push(t);
2586
+ }
2587
+ importCache.set(file, out);
2588
+ return out;
2589
+ };
2590
+ const reaches = (from, to) => {
2591
+ const seen = /* @__PURE__ */ new Set([from]), queue = [from];
2592
+ while (queue.length && seen.size < 5e3) {
2593
+ const f = queue.shift();
2594
+ if (f === to) return true;
2595
+ for (const n of importsOf(f)) if (!seen.has(n)) {
2596
+ seen.add(n);
2597
+ queue.push(n);
2598
+ }
2599
+ }
2600
+ return false;
2601
+ };
2602
+ const serverEntry = (file) => {
2603
+ if (byFile.get(file).facts.startsServer) return file;
2604
+ const top = outerPrefix(file).top;
2605
+ const starters = [...byFile.keys()].filter((f) => byFile.get(f).facts.startsServer && !/(^|\/)(test|tests|__tests__|e2e|scripts?|examples?)\//.test(f));
2606
+ const pkgDir = (f) => {
2607
+ for (let d = posix3.dirname(f); ; d = posix3.dirname(d)) {
2608
+ if (existsSync5(join6(root2, d, "package.json"))) return d;
2609
+ if (d === "." || d === "/") return ".";
2610
+ }
2611
+ };
2612
+ let reaching = [.../* @__PURE__ */ new Set([...byFile.get(top).facts.startsServer ? [top] : [], ...starters.filter((f) => reaches(f, top) || reaches(f, file))])];
2613
+ if (reaching.length) {
2614
+ const scripts2 = (f) => [.../* @__PURE__ */ new Set([".", pkgDir(f)])].flatMap((d) => {
2615
+ try {
2616
+ return Object.values(JSON.parse(readFileSync5(join6(root2, d, "package.json"), "utf8")).scripts ?? {});
2617
+ } catch {
2618
+ return [];
2619
+ }
2620
+ });
2621
+ const started = (f) => {
2622
+ const rel = [f, posix3.relative(pkgDir(f), f)].map((x) => x.replace(/\.[cm]?[jt]sx?$/, ""));
2623
+ return scripts2(f).some((cmd) => rel.some((r) => new RegExp(`(^|[\\s/'"])${r.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\.[cm]?[jt]sx?)?(\\s|$|['"])`).test(cmd)));
2624
+ };
2625
+ const conventional = (f) => /(^|\/)(main|server|index|app)\.[cm]?[jt]s$/.test(f);
2626
+ if (!reaching.some((f) => started(f) || conventional(f))) {
2627
+ const entries = starters.filter((f) => pkgDir(f) === pkgDir(file) && (started(f) || conventional(f)));
2628
+ if (entries.length) reaching = entries;
2629
+ }
2630
+ return [...reaching].sort((a, b) => Number(started(b)) - Number(started(a)) || Number(conventional(b)) - Number(conventional(a)))[0];
2631
+ }
2632
+ const same = starters.filter((f) => pkgDir(f) === pkgDir(file));
2633
+ return same.sort((a, b) => Number(/(main|server|index|app)\.[cm]?[jt]s$/.test(b)) - Number(/(main|server|index|app)\.[cm]?[jt]s$/.test(a)))[0] ?? (top !== file ? top : void 0);
2634
+ };
2635
+ const startScript = (entry) => {
2636
+ for (let dir = posix3.dirname(entry); ; dir = posix3.dirname(dir)) {
2637
+ let pkg;
2638
+ try {
2639
+ pkg = JSON.parse(readFileSync5(join6(root2, dir, "package.json"), "utf8"));
2640
+ } catch {
2641
+ }
2642
+ if (pkg) {
2643
+ const stem = posix3.basename(entry).replace(/\.[cm]?[jt]sx?$/, "");
2644
+ for (const name of ["dev", "start:dev", "dev:server", "devserver", "dev:api", "dev:backend", "server", "serve", "start:server", "api", "backend", "start"]) {
2645
+ const command = pkg.scripts?.[name];
2646
+ if (!command) continue;
2647
+ if (/concurrently|npm-run-all|run-p|turbo|docker|\bvite\b(?!-node)|\bnext\b|\bbun\b|\bdeno\b|(^|[^&])&([^&]|$)/.test(command)) continue;
2648
+ if (!/\b(node|tsx|ts-node|ts-node-dev|tsnd|nodemon|nest|vite-node|babel-node|ts-node-esm)\b/.test(command)) continue;
2649
+ if (/\bts-node-esm\b|\bts-node\b[^&|;]*--esm\b/.test(command)) continue;
2650
+ const runs = [...command.matchAll(/(?:^|\s)(\.?\/?[\w@./-]+\.[cm]?[jt]sx?)\b/g)].map((m) => posix3.normalize(posix3.join(dir === "." ? "" : dir, m[1]))).filter((f) => byFile.has(f));
2651
+ if (!(command.includes(stem) || /\bnest\s+start\b/.test(command) || runs.some((f) => f === entry || reaches(f, entry)))) continue;
2652
+ const dist = /\bdist\/|\bbuild\//.exec(command);
2653
+ if (dist && !/\bnest\b/.test(command) && !existsSync5(join6(root2, dir, dist[0]))) continue;
2654
+ return { name, command, dir: dir === "." ? "" : dir };
2655
+ }
2656
+ return void 0;
2657
+ }
2658
+ if (dir === "." || dir === "/") return void 0;
2659
+ }
2660
+ };
2661
+ const direct = /* @__PURE__ */ new Map();
2662
+ const analyze = (file, name) => {
2663
+ const key2 = file + "#" + name;
2664
+ if (direct.has(key2)) return direct.get(key2);
2665
+ const entry = { calls: [], edges: [], env: [], channels: [] };
2666
+ direct.set(key2, entry);
2667
+ const fn = byFile.get(file).facts.functions.get(name);
2668
+ if (!fn) return entry;
2669
+ const inputName = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : void 0;
2670
+ const stripeBindings = /* @__PURE__ */ new Map();
2671
+ if (fn.params?.[0]?.type === "ObjectPattern") {
2672
+ for (const p of fn.params[0].properties) {
2673
+ if (p.type === "ObjectProperty" && !p.computed && p.value.type === "Identifier") {
2674
+ stripeBindings.set(p.value.name, { kind: "field", base: { kind: "input" }, key: p.key.name ?? p.key.value });
2675
+ }
2676
+ }
2677
+ }
2678
+ const branches = [], uncertainSql = [], exits = [];
2679
+ walk(fn.body, (node) => {
2680
+ if (["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"].includes(node.type)) return false;
2681
+ if (node.type === "ReturnStatement" || node.type === "ThrowStatement") exits.push(node);
2682
+ if (node.type === "IfStatement") {
2683
+ branches.push(node.consequent);
2684
+ if (node.alternate) branches.push(node.alternate);
2685
+ } else if (node.type === "ConditionalExpression") branches.push(node.consequent, node.alternate);
2686
+ else if (node.type === "LogicalExpression") branches.push(node.right);
2687
+ else if (node.type === "SwitchCase") branches.push(...node.consequent);
2688
+ if (["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement"].includes(node.type)) uncertainSql.push(node);
2689
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && node.callee.object?.name === "Promise" && ["all", "allSettled", "race", "any"].includes(node.callee.property?.name)) uncertainSql.push(node);
2690
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && ["map", "flatMap", "forEach", "reduce"].includes(node.callee.property?.name)) uncertainSql.push(node);
2691
+ });
2692
+ const before = (a, b) => a.line < b.line || a.line === b.line && a.column <= b.column;
2693
+ const loops = [];
2694
+ walk(fn.body, (node) => {
2695
+ if (["ForStatement", "ForInStatement", "ForOfStatement", "WhileStatement", "DoWhileStatement"].includes(node.type) || node.type === "CallExpression" && node.callee?.type === "MemberExpression" && (["map", "flatMap", "forEach", "reduce"].includes(node.callee.property?.name) || node.callee.object?.name === "Promise" && ["all", "allSettled"].includes(node.callee.property?.name))) loops.push(node);
2696
+ });
2697
+ const inBranch = (line, column = 1) => branches.some((b) => b?.loc && before(b.loc.start, { line, column: column - 1 }) && before({ line, column: column - 1 }, b.loc.end));
2698
+ const boltNames = /* @__PURE__ */ new Map();
2699
+ if (bolt && fn.params?.[0]?.type === "ObjectPattern") {
2700
+ for (const p of fn.params[0].properties) if (p.type === "ObjectProperty" && !p.computed && p.value?.type === "Identifier" && ["client", "say", "respond"].includes(String(p.key.name ?? p.key.value))) boltNames.set(p.value.name, String(p.key.name ?? p.key.value));
2701
+ }
2702
+ const firstCall = entry.calls.length;
2703
+ walk(fn.body, (node, parent) => {
2704
+ if (node.type === "StringLiteral" && /^(?:#[a-z0-9][a-z0-9_-]{0,79}|[CG][A-Z0-9]{8,12})$/.test(node.value)) entry.channels.push(node.value);
2705
+ if (node.type === "MemberExpression") {
2706
+ const names2 = chain2(node);
2707
+ if (names2?.[0] === "process" && names2[1] === "env" && names2[2]) entry.env.push(names2[2]);
2708
+ }
2709
+ if (node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier") {
2710
+ const provider2 = clientProvider(file, node.tag.name);
2711
+ if (provider2 === "postgres") {
2712
+ const sql2 = templateSql(node.quasi);
2713
+ entry.calls.push({ provider: provider2, operation: "sql", file, line: node.loc.start.line, argKeys: [], literals: {}, sql: sql2, sqlParams: node.quasi.expressions.map((e) => literal2(e)), write: !/^\s*select\b/i.test(sql2) });
2714
+ }
2715
+ }
2716
+ if (node.type === "ObjectProperty" && !node.computed && REQUEST_TARGET_KEYS.has(String(node.key?.name ?? node.key?.value))) {
2717
+ let v = node.value;
2718
+ if (v?.type === "TaggedTemplateExpression") v = v.quasi;
2719
+ if (v?.type === "BinaryExpression" && v.operator === "+") v = v.left;
2720
+ const prefix = v?.type === "StringLiteral" ? String(v.value) : v?.type === "TemplateLiteral" ? String(v.quasis?.[0]?.value?.cooked ?? "") : "";
2721
+ const hit = /^https?:\/\/[^/\s]+/.test(prefix) ? fetchHosts().find(([pattern]) => pattern.test(prefix)) : void 0;
2722
+ const holder = parent;
2723
+ const methodProp = holder?.type === "ObjectExpression" ? holder.properties.find((q) => q.type === "ObjectProperty" && !q.computed && String(q.key?.name ?? q.key?.value) === "method") : void 0;
2724
+ const methodLiteral = literal2(methodProp?.value), method = typeof methodLiteral === "string" ? methodLiteral.toUpperCase() : methodProp ? "ANY" : "GET";
2725
+ if (hit && !entry.calls.some((c) => c.file === file && c.line === node.loc.start.line && c.provider === hit[1]))
2726
+ entry.calls.push({ provider: hit[1], operation: prefix.replace(/^https?:\/\/[^/]+\/(?:api\/|v\d+\/)?/, "").replaceAll("/", ".") || "request", file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: [], literals: {}, method, write: !["GET", "HEAD", "OPTIONS"].includes(method) });
2727
+ }
2728
+ if (node.type !== "CallExpression") return;
2729
+ if (node.callee.type === "Identifier") {
2730
+ if (node.callee.name === "fetch") {
2731
+ let target = node.arguments[0];
2732
+ const options = node.arguments[1];
2733
+ const props = new Map(options?.type === "ObjectExpression" ? options.properties.filter((p) => p.type === "ObjectProperty" && !p.computed).map((p) => [String(p.key.name ?? p.key.value), p.value]) : []);
2734
+ const method = String(literal2(props.get("method")) ?? "GET").toUpperCase();
2735
+ const bodyNode = props.get("body");
2736
+ const body = bodyNode?.type === "CallExpression" && chain2(bodyNode.callee)?.join(".") === "JSON.stringify" ? objectLiteral(bodyNode.arguments[0]) : bodyNode?.type === "NewExpression" && bodyNode.callee.type === "Identifier" && bodyNode.callee.name === "URLSearchParams" && bodyNode.arguments[0]?.type === "ObjectExpression" ? objectLiteral(bodyNode.arguments[0]) : void 0;
2737
+ const write2 = !["GET", "HEAD", "OPTIONS"].includes(method);
2738
+ const envName = (n) => {
2739
+ if (!n) return void 0;
2740
+ const names2 = chain2(n);
2741
+ if (names2?.[0] === "process" && names2[1] === "env" && names2[2] && names2.length === 3) return names2[2];
2742
+ if (n.type === "Identifier") {
2743
+ const alias = byFile.get(file)?.facts.constants.get(`$env:${n.name}`);
2744
+ return typeof alias === "string" ? alias : void 0;
2745
+ }
2746
+ return void 0;
2747
+ };
2748
+ const asTemplate = (n) => {
2749
+ if (!n) return n;
2750
+ if (n.type === "TemplateLiteral") return n;
2751
+ const synth = (name2, tail, quasis) => ({ type: "TemplateLiteral", expressions: [{ type: "MemberExpression", object: { type: "MemberExpression", object: { type: "Identifier", name: "process" }, property: { type: "Identifier", name: "env" }, computed: false }, property: { type: "Identifier", name: name2 }, computed: false }, ...tail], quasis: [{ value: { cooked: "" } }, ...quasis.map((q) => ({ value: { cooked: q } }))] });
2752
+ if (n.type === "BinaryExpression" && n.operator === "+") {
2753
+ const name2 = envName(n.left);
2754
+ if (name2 && n.right.type === "StringLiteral") return synth(name2, [], [n.right.value]);
2755
+ if (name2 && n.right.type === "TemplateLiteral") return synth(name2, n.right.expressions, n.right.quasis.map((q) => q.value.cooked));
2756
+ }
2757
+ return n;
2758
+ };
2759
+ target = asTemplate(target);
2760
+ if (target?.type === "TemplateLiteral" && target.expressions.length && target.quasis[0].value.cooked === "") {
2761
+ const env = chain2(target.expressions[0]);
2762
+ if (env?.[0] === "process" && env[1] === "env" && env[2]) {
2763
+ const own = /^AGENTTWIN_([A-Z0-9]+)_URL$/.exec(env[2])?.[1].toLowerCase();
2764
+ if (own && KNOWN_PROVIDERS.has(own)) {
2765
+ const path2 = ("/" + target.quasis.slice(1).map((q, i) => q.value.cooked + (i + 1 < target.expressions.length ? "{id}" : "")).join("")).replace(/\/+/g, "/");
2766
+ const operation2 = path2.replace(/^\/(?:api\/|v1\/)?/, "").replaceAll("/", ".");
2767
+ const args = body && typeof body === "object" && !Array.isArray(body) ? { ...body } : void 0;
2768
+ const argsNode = bodyNode?.type === "NewExpression" || bodyNode?.type === "CallExpression" ? bodyNode.arguments[0] : void 0;
2769
+ const constants = byFile.get(file).facts.constants;
2770
+ if (args && argsNode?.type === "ObjectExpression") {
2771
+ for (const p of argsNode.properties) if (p.type === "ObjectProperty" && !p.computed && p.value.type === "Identifier" && constants.has(p.value.name)) args[String(p.key.name ?? p.key.value)] = constants.get(p.value.name);
2772
+ }
2773
+ const literals3 = args ? Object.fromEntries(Object.entries(args).filter(([, v]) => v !== null && typeof v !== "object")) : {};
2774
+ entry.calls.push({ provider: own, operation: operation2, file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: Object.keys(args ?? {}), literals: literals3, method, path: path2, ...args ? { args, body } : {}, write: write2 });
2775
+ return;
2776
+ }
2777
+ const path = ("/" + target.quasis.slice(1).map((q, i) => q.value.cooked + (i + 1 < target.expressions.length ? "{id}" : "")).join("")).replace(/\/+/g, "/").replace(/\/$/, "") || "/";
2778
+ entry.calls.push({ provider: "internal", operation: `${method} ${path}`, file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: [], literals: {}, envUrl: env[2], method, path, ...body !== void 0 ? { body } : {}, write: write2 });
2779
+ return;
2780
+ }
2781
+ }
2782
+ const url = literal2(target) ?? (target?.type === "TemplateLiteral" ? target.quasis.map((q, i) => q.value.cooked + (i < target.expressions.length ? "{id}" : "")).join("") : void 0);
2783
+ const hit = typeof url === "string" ? fetchHosts().find(([pattern]) => pattern.test(url)) : void 0;
2784
+ if (hit) {
2785
+ const parsed = new URL(String(url).replaceAll("{id}", "x"));
2786
+ const operation2 = String(url).replace(/^https:\/\/[^/]+\/(?:api\/|v1\/)?/, "").replaceAll("/", ".");
2787
+ const args = body && typeof body === "object" && !Array.isArray(body) ? { ...body } : void 0;
2788
+ entry.calls.push({ provider: hit[1], operation: operation2, file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: Object.keys(args ?? {}), literals: args ? Object.fromEntries(Object.entries(args).filter(([, v]) => v !== null && typeof v !== "object")) : {}, ...args ? { args } : {}, method, path: String(url).replace(/^https:\/\/[^/]+/, ""), host: parsed.hostname, ...body !== void 0 ? { body } : {}, write: hit[1] === "slack" ? !READ_OPS.test(operation2) : write2 });
2789
+ }
2790
+ return;
2791
+ }
2792
+ const helper = boltNames.get(node.callee.name);
2793
+ if (helper === "say" || helper === "respond") {
2794
+ const arg0 = node.arguments[0], args = arg0?.type === "ObjectExpression" ? objectLiteral(arg0) : typeof literal2(arg0) === "string" ? { text: literal2(arg0) } : void 0;
2795
+ entry.calls.push({ provider: "slack", operation: helper === "say" ? "chat.postMessage" : "respond", file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: Object.keys(args ?? {}), literals: Object.fromEntries(Object.entries(args ?? {}).filter(([, v]) => v === null || typeof v !== "object")), ...args ? { args } : {}, write: true });
2796
+ return;
2797
+ }
2798
+ const ref = functionRef(file, node.callee.name);
2799
+ if (ref) {
2800
+ entry.edges.push([...ref, inputBinding(node.arguments[0], inputName, stripeBindings), inBranch(node.loc.start.line, node.loc.start.column + 1) || exits.some((e) => e.end < node.start), node.loc.start.line, node.loc.start.column + 1]);
2801
+ return;
2802
+ }
2803
+ const imported = byFile.get(file).facts.imports.get(node.callee.name);
2804
+ const sdk = imported && !PROVIDER_MODULES[imported.source] ? sdkInfo(root2, imported.source) : null;
2805
+ if (sdk) {
2806
+ const url = literal2(node.arguments[0]);
2807
+ let urlHost2, urlPath2;
2808
+ if (typeof url === "string" && /^https?:\/\//.test(url)) {
2809
+ try {
2810
+ const parsed = new URL(url);
2811
+ urlHost2 = parsed.hostname;
2812
+ urlPath2 = parsed.pathname;
2813
+ } catch {
2814
+ }
2815
+ }
2816
+ const options = node.arguments[1], method = options?.type === "ObjectExpression" ? String(literal2(options.properties.find((p) => p.type === "ObjectProperty" && (p.key.name ?? p.key.value) === "method")?.value) ?? "GET").toUpperCase() : "POST";
2817
+ entry.calls.push({ provider: `sdk:${sdk.pkg}`, operation: imported.imported === "default" ? node.callee.name : imported.imported, file, line: node.loc.start.line, column: node.loc.start.column + 1, argKeys: [], literals: {}, ...urlHost2 ? { host: urlHost2, path: urlPath2, method } : {}, ...sdk.hosts.length ? { hosts: sdk.hosts } : {}, write: method !== "GET" });
2818
+ }
2819
+ return;
2820
+ }
2821
+ const names = chain2(node.callee);
2822
+ if (!names || names.length < 2) return;
2823
+ const provider = clientProvider(file, names[0]) ?? (boltNames.get(names[0]) === "client" ? "slack" : void 0);
2824
+ if (!provider) return;
2825
+ const command = names.at(-1) === "send" && node.arguments[0]?.type === "NewExpression" && node.arguments[0].callee.type === "Identifier" ? node.arguments[0] : void 0;
2826
+ const operation = command ? command.callee.name.replace(/Command$/, "") : names.slice(1).join(".");
2827
+ const stripeItem = provider === "stripe" && /^subscriptionItems\.(retrieve|update)$/.test(operation);
2828
+ const positional = {};
2829
+ let objectAt = 0;
2830
+ if (!command) for (const [i, a] of node.arguments.slice(0, 3).entries()) {
2831
+ if (a.type === "StringLiteral") {
2832
+ positional["$" + i] = a.value;
2833
+ objectAt = i + 1;
2834
+ } else break;
2835
+ }
2836
+ const first = stripeItem ? node.arguments[1] : command ? command.arguments[0] : node.arguments[objectAt]?.type === "ObjectExpression" ? node.arguments[objectAt] : node.arguments[0];
2837
+ const quantity = stripeItem && first?.type === "ObjectExpression" ? first.properties.find((p) => p.type === "ObjectProperty" && !p.computed && (p.key.name ?? p.key.value) === "quantity")?.value : void 0;
2838
+ const argKeys = [], literals2 = {}, inputArgs = {};
2839
+ if (first?.type === "ObjectExpression") {
2840
+ for (const p of first.properties) if (p.type === "ObjectProperty" && !p.computed) {
2841
+ const key3 = String(p.key.name ?? p.key.value);
2842
+ argKeys.push(key3);
2843
+ const v = literal2(p.value);
2844
+ if (v !== void 0) literals2[key3] = v;
2845
+ const member = p.value.type === "MemberExpression" && !p.value.computed && p.value.object.type === "Identifier" && inputName && p.value.object.name === inputName ? p.value.property.name : void 0;
2846
+ if (member) inputArgs[key3] = member;
2847
+ else if (inputName && p.value.type === "Identifier" && p.value.name === inputName) inputArgs[key3] = WHOLE_INPUT;
2848
+ }
2849
+ }
2850
+ if (provider === "redis" && typeof literal2(node.arguments[1]) === "string") literals2.value = literal2(node.arguments[1]);
2851
+ let sql, sqlParams;
2852
+ const sqlInputParams = {};
2853
+ const mysqlProvider = provider === "sdk:mysql" || provider === "sdk:mysql2";
2854
+ if (provider === "postgres" && /(^|\.)query$/.test(operation) || mysqlProvider && /(^|\.)(query|execute)$/.test(operation)) {
2855
+ sql = typeof literal2(first) === "string" ? String(literal2(first)) : first?.type === "TemplateLiteral" && !mysqlProvider ? templateSql(first) : first?.type === "ObjectExpression" && typeof literals2.text === "string" ? String(literals2.text) : void 0;
2856
+ const values = node.arguments[1];
2857
+ if (values?.type === "ArrayExpression") {
2858
+ sqlParams = values.elements.map((e) => literal2(e));
2859
+ if (mysqlProvider) values.elements.forEach((e, index) => {
2860
+ if (e?.type === "MemberExpression" && !e.computed && e.object.type === "Identifier" && e.object.name === inputName) sqlInputParams[index] = e.property.name;
2861
+ });
2862
+ }
2863
+ }
2864
+ const write = provider === "postgres" ? !!sql && !/^\s*select\b/i.test(sql) : provider === "openai" || provider === "anthropic" ? false : provider === "redis" ? !/^(get|mget|hget|hgetall|exists|ttl|keys|scan|smembers|lrange|zrange)$/i.test(operation) : provider === "aws" ? /^(Put|Create|Update|Delete|Send|Publish|Write|Copy|Batch)/.test(operation) : !READ_OPS.test(operation);
2865
+ let sdkHosts, urlHost, urlPath;
2866
+ if (provider.startsWith("sdk:")) {
2867
+ sdkHosts = sdkInfo(root2, provider.slice(4))?.hosts;
2868
+ const url = literal2(node.arguments[0]);
2869
+ if (typeof url === "string" && /^https?:\/\//.test(url)) {
2870
+ try {
2871
+ const parsed = new URL(url);
2872
+ urlHost = parsed.hostname;
2873
+ urlPath = parsed.pathname;
2874
+ } catch {
2875
+ }
2876
+ }
2877
+ }
2878
+ Object.assign(literals2, positional);
2879
+ entry.calls.push({
2880
+ provider,
2881
+ operation,
2882
+ file,
2883
+ line: node.loc.start.line,
2884
+ column: node.loc.start.column + 1,
2885
+ argKeys,
2886
+ literals: literals2,
2887
+ ...Object.keys(inputArgs).length ? { inputArgs } : {},
2888
+ ...sql ? { sql } : {},
2889
+ ...sqlParams ? { sqlParams } : {},
2890
+ ...Object.keys(sqlInputParams).length ? { sqlInputParams } : {},
2891
+ ...stripeItem ? { stripeItem: { id: inputBinding(node.arguments[0], inputName, stripeBindings), quantity: inputBinding(quantity, inputName, stripeBindings) } } : {},
2892
+ ...provider === "sdk:amqplib" && /(^|\.)(sendToQueue|publish)$/.test(operation) ? { rabbitmqSend: rabbitmqSendFromAst(operation, node.arguments, inputName) } : {},
2893
+ ...provider === "sdk:kafkajs" && /(^|\.)send$/.test(operation) ? { kafkaSend: kafkaSendFromAst(first, inputName) } : {},
2894
+ ...mysqlProvider || provider === "sdk:kafkajs" || provider === "sdk:amqplib" ? { sqlScope: key2, ...uncertainSql.some((b) => b.loc && before(b.loc.start, node.loc.start) && before(node.loc.end, b.loc.end)) ? { conditional: true } : {} } : {},
2895
+ ...urlHost ? { host: urlHost, path: urlPath, method: names.at(-1).toUpperCase() } : {},
2896
+ ...sdkHosts?.length ? { hosts: sdkHosts } : {},
2897
+ ...first?.type === "ObjectExpression" ? { args: objectLiteral(first) } : {},
2898
+ write
2899
+ });
2900
+ });
2901
+ for (const call of entry.calls.slice(firstCall)) {
2902
+ const at = { line: call.line, column: (call.column ?? 1) - 1 };
2903
+ if (loops.some((node) => node.loc && before(node.loc.start, at) && before(at, node.loc.end))) call.repeats = true;
2904
+ if (loops.some((node) => node.type !== "ForStatement" && node.type !== "WhileStatement" && node.type !== "DoWhileStatement" && node.loc && before(node.loc.start, at) && before(at, node.loc.end))) call.iterates = true;
2905
+ if (inBranch(call.line, call.column) || (call.stripeItem || /^sdk:(mysql2?|kafkajs|amqplib)$/.test(call.provider)) && (exits.some((e) => e.loc && before(e.loc.end, at)) || !!call.stripeItem && uncertainSql.some((node) => node.loc && before(node.loc.start, at) && before(at, node.loc.end)))) call.conditional = true;
2906
+ }
2907
+ return entry;
2908
+ };
2909
+ const closure = (file, name) => {
2910
+ const seen = /* @__PURE__ */ new Set(), calls = [], stripeItems = [], env = /* @__PURE__ */ new Set(), touched = /* @__PURE__ */ new Set(), channels = /* @__PURE__ */ new Set();
2911
+ const visit = (f, n, bindings = [], conditional = false, ancestors = /* @__PURE__ */ new Set()) => {
2912
+ const key2 = f + "#" + n;
2913
+ if (ancestors.has(key2) || seen.size > 200) return;
2914
+ seen.add(key2);
2915
+ touched.add(f);
2916
+ const entry = analyze(f, n);
2917
+ const repeated = (c) => /^sdk:(mysql2?|kafkajs|amqplib)$/.test(c.provider);
2918
+ calls.push(...entry.calls.filter((c) => !c.stripeItem && (repeated(c) || !calls.some((prev) => prev.file === c.file && prev.line === c.line && prev.column === c.column && prev.provider === c.provider && prev.operation === c.operation))).map((c) => ({ ...c, inputBindings: bindings, conditional: repeated(c) && conditional || c.conditional })));
2919
+ entry.env.forEach((v) => env.add(v));
2920
+ entry.channels.forEach((v) => channels.add(v));
2921
+ const next = new Set(ancestors).add(key2);
2922
+ const sites2 = [
2923
+ ...entry.calls.filter((call) => call.stripeItem).map((call) => ({ line: call.line, column: call.column ?? 1, run: () => stripeItems.push({ ...call, inputBindings: bindings, conditional: conditional || call.conditional }) })),
2924
+ ...entry.edges.map(([ef, en, b, branch, line, column]) => ({ line, column, run: () => visit(ef, en, [...bindings, b], conditional || branch, next) }))
2925
+ ];
2926
+ sites2.sort((a, b) => a.line - b.line || a.column - b.column).forEach((site) => site.run());
2927
+ };
2928
+ visit(file, name);
2929
+ const settingsOf = (f) => {
2930
+ const names = new Set([...byFile.get(f).text.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g)].map((m) => m[1]));
2931
+ return names.size > SETTINGS_MODULE_SIZE ? [] : [...names];
2932
+ };
2933
+ for (const f of [...touched]) for (const name2 of settingsOf(f)) env.add(name2);
2934
+ for (const m of byFile.get(file).text.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g)) env.add(m[1]);
2935
+ for (const f of [...touched]) for (const imported of byFile.get(f).facts.imports.values()) {
2936
+ const target = resolveModule(f, imported.source);
2937
+ if (target) {
2938
+ touched.add(target);
2939
+ for (const name2 of settingsOf(target)) env.add(name2);
2940
+ }
2941
+ }
2942
+ return { calls: [...calls, ...stripeItems], env: [...env], files: [...touched], channels: [...channels] };
2943
+ };
2944
+ const importers = /* @__PURE__ */ new Map();
2945
+ for (const [file, { facts: facts2 }] of byFile) {
2946
+ if (/\.[jt]sx$/.test(file)) continue;
2947
+ for (const imported of facts2.imports.values()) {
2948
+ if (imported.imported === "*") continue;
2949
+ const target = resolveModule(file, imported.source);
2950
+ if (target && target !== file) (importers.get(`${target}#${imported.imported}`) ?? importers.set(`${target}#${imported.imported}`, /* @__PURE__ */ new Set()).get(`${target}#${imported.imported}`)).add(file);
2951
+ }
2952
+ }
2953
+ const candidates = [];
2954
+ for (const [file, { facts: f }] of byFile) {
2955
+ for (const [exportName, local] of f.exports) {
2956
+ const { calls: reached, env, files: touched, channels } = closure(file, local);
2957
+ const calls = reached.filter((c) => !/^use[A-Z]/.test(c.operation));
2958
+ if ((/\.[jt]sx$/.test(file) && /^[A-Z]/.test(exportName) || /^use[A-Z]/.test(exportName)) && !ROUTE_FILE.test(file)) continue;
2959
+ const verifiesWebhook = (ROUTE_FILE.test(file) || PAGES_API_FILE.test(file) || SVELTE_ROUTE_FILE.test(file)) && /\.webhooks\.constructEvent(Async)?\(|verifyWebhook|webhooks?\.verify\(|new Webhook\(|validateRequest\(|stripe-signature|x-hub-signature|svix-signature|x-slack-signature/i.test(byFile.get(file).text);
2960
+ if (!calls.length && !opts.all && !verifiesWebhook && !f.trpcHandler) continue;
2961
+ const fn = f.functions.get(local);
2962
+ const param = fn.params?.[0];
2963
+ let input = null;
2964
+ const usage = (name) => {
2965
+ const fields = /* @__PURE__ */ new Set(), methods = /* @__PURE__ */ new Set();
2966
+ let list = false, called = false;
2967
+ walk(fn.body, (node) => {
2968
+ if (node.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === name || node.type === "TaggedTemplateExpression" && node.tag?.type === "Identifier" && node.tag.name === name) called = true;
2969
+ if ((node.type === "MemberExpression" || node.type === "OptionalMemberExpression") && node.object.type === "Identifier" && node.object.name === name && !node.computed) {
2970
+ if (/^(push|map|filter|forEach|slice|concat|length|at|find|some|every|reduce|unshift|pop|shift)$/.test(node.property.name)) list = true;
2971
+ else fields.add(node.property.name);
2972
+ }
2973
+ if (node.type === "CallExpression" && node.callee?.type === "MemberExpression" && !node.callee.computed && node.callee.object?.type === "Identifier" && node.callee.object.name === name && !/^(push|map|filter|forEach|slice|concat|at|find|some|every|reduce|unshift|pop|shift)$/.test(node.callee.property.name)) methods.add(node.callee.property.name);
2974
+ if (node.type === "VariableDeclarator" && node.id?.type === "ObjectPattern") {
2975
+ const init = node.init?.type === "LogicalExpression" ? node.init.left : node.init?.type === "TSAsExpression" || node.init?.type === "TSNonNullExpression" ? node.init.expression : node.init;
2976
+ if (init?.type === "Identifier" && init.name === name) {
2977
+ for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
2978
+ }
2979
+ }
2980
+ if ((node.type === "ForOfStatement" || node.type === "SpreadElement") && (node.right ?? node.argument)?.type === "Identifier" && (node.right ?? node.argument).name === name) list = true;
2981
+ });
2982
+ return { fields: [...fields].filter((f2) => !methods.has(f2)), methods: [...methods], list, called };
2983
+ };
2984
+ if (param?.type === "Identifier") {
2985
+ const u = usage(param.name);
2986
+ input = { name: param.name, fields: u.fields, ...u.methods.length ? { methods: u.methods } : {}, ...u.called ? { called: true } : {} };
2987
+ } else if (param?.type === "ObjectPattern") input = { name: "input", fields: param.properties.filter((p) => p.type === "ObjectProperty").map((p) => String(p.key.name ?? p.key.value)) };
2988
+ const moreInputs = (fn.params ?? []).slice(1).filter((p) => p?.type === "Identifier").map((p) => ({ name: p.name, ...usage(p.name) }));
2989
+ let web;
2990
+ if (SVELTE_ROUTE_FILE.test(file) && /^(GET|POST|PUT|PATCH|DELETE)$/.test(exportName)) {
2991
+ const params = {};
2992
+ const path = "/" + file.replace(/^.*?(?:src\/)?routes\//, "").replace(/\/?\+server\.[cm]?[jt]s$/, "").split("/").filter((seg) => seg && !/^\(.*\)$/.test(seg)).map((seg) => {
2993
+ const m = /^\[(?:\.\.\.)?([A-Za-z_]\w*)\]$/.exec(seg);
2994
+ if (m) {
2995
+ params[m[1]] = "1";
2996
+ return "1";
2997
+ }
2998
+ return seg;
2999
+ }).join("/");
3000
+ web = { method: exportName, path, params, framework: "sveltekit" };
3001
+ input = { name: "request.json()", fields: [] };
3002
+ } else if (!ROUTE_FILE.test(file) && FUNCTION_FILE.test(file) && /^(GET|POST|PUT|PATCH|DELETE)$/.test(exportName)) {
3003
+ const at = file.search(FUNCTION_FILE);
3004
+ const path = "/" + file.slice(at).replace(/^\//, "").replace(/\.[cm]?[jt]sx?$/, "").replace(/\/index$/, "");
3005
+ web = { method: exportName, path, params: {} };
3006
+ } else if (ROUTE_FILE.test(file) && /^(GET|POST|PUT|PATCH|DELETE)$/.test(exportName)) {
3007
+ const params = {};
3008
+ const appDir = nextAppDir(root2, file), inApp = appDir ? file.slice(appDir.length + 1) : file;
3009
+ const path = "/" + inApp.replace(/^src\//, "").replace(/^app\//, "").replace(/\/?route\.[cm]?[jt]sx?$/, "").split("/").filter((seg) => seg && !/^\(.*\)$/.test(seg)).map((seg) => {
3010
+ const m = /^\[(?:\[\.{3}([A-Za-z_]\w*)\]|(?:\.{3})?([A-Za-z_]\w*))\]$/.exec(seg);
3011
+ if (m) {
3012
+ params[m[1] ?? m[2]] = "1";
3013
+ return "1";
3014
+ }
3015
+ return seg;
3016
+ }).join("/");
3017
+ web = { method: exportName, path: (nextBasePath(root2, appDir) + path).replace(/\/+/g, "/") || "/", params, ...appDir !== void 0 ? { appDir } : {} };
3018
+ const requestName = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "request", fields = /* @__PURE__ */ new Set(), aliases2 = /* @__PURE__ */ new Set();
3019
+ const unwrap2 = (n) => n && (n.type === "TSAsExpression" || n.type === "TSNonNullExpression" || n.type === "TSSatisfiesExpression" || n.type === "ParenthesizedExpression") ? unwrap2(n.expression) : n;
3020
+ const isJson = (raw) => {
3021
+ const n = unwrap2(raw);
3022
+ return n?.type === "AwaitExpression" && n.argument?.type === "CallExpression" && n.argument.callee?.type === "MemberExpression" && n.argument.callee.property?.name === "json" && n.argument.callee.object?.type === "Identifier" && n.argument.callee.object.name === requestName;
3023
+ };
3024
+ walk(fn.body, (node) => {
3025
+ if (node.type === "VariableDeclarator" && isJson(node.init)) {
3026
+ if (node.id.type === "ObjectPattern") {
3027
+ for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
3028
+ } else if (node.id.type === "Identifier") aliases2.add(node.id.name);
3029
+ }
3030
+ });
3031
+ walk(fn.body, (node) => {
3032
+ if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && aliases2.has(node.object.name)) fields.add(node.property.name);
3033
+ });
3034
+ const locals = /* @__PURE__ */ new Map(), nested = /* @__PURE__ */ new Map();
3035
+ const addLocal = (pattern) => {
3036
+ if (pattern?.type === "ObjectPattern") {
3037
+ for (const p of pattern.properties) if (p.type === "ObjectProperty" && !p.computed) {
3038
+ const key2 = String(p.key.name ?? p.key.value);
3039
+ fields.add(key2);
3040
+ if (p.value?.type === "Identifier") locals.set(p.value.name, key2);
3041
+ else if (p.value?.type === "AssignmentPattern" && p.value.left?.type === "Identifier") locals.set(p.value.left.name, key2);
3042
+ }
3043
+ }
3044
+ };
3045
+ walk(fn.body, (node) => {
3046
+ if (node.type === "VariableDeclarator") {
3047
+ const init = unwrap2(node.init);
3048
+ if (isJson(node.init)) addLocal(node.id);
3049
+ else if (init?.type === "Identifier" && aliases2.has(init.name)) addLocal(node.id);
3050
+ }
3051
+ });
3052
+ walk(fn.body, (node) => {
3053
+ if (node.type !== "MemberExpression" || node.computed || node.property?.type !== "Identifier") return;
3054
+ const holder = node.object;
3055
+ const key2 = holder?.type === "Identifier" ? locals.get(holder.name) : holder?.type === "MemberExpression" && !holder.computed && holder.object?.type === "Identifier" && aliases2.has(holder.object.name) ? holder.property?.name : void 0;
3056
+ if (key2 && !["length", "map", "filter", "forEach", "push", "slice", "find", "some", "every", "reduce", "at", "includes", "join", "toString"].includes(node.property.name)) nested.set(key2, (nested.get(key2) ?? /* @__PURE__ */ new Set()).add(node.property.name));
3057
+ });
3058
+ const query = /* @__PURE__ */ new Set(), fnText = byFile.get(file)?.text.slice(fn.start, fn.end) ?? "";
3059
+ walk(fn.body, (node, parent) => {
3060
+ if (node.type !== "CallExpression" || node.callee?.type !== "MemberExpression" || !["get", "getAll", "has"].includes(node.callee.property?.name)) return;
3061
+ const holder = node.callee.object, named = holder?.type === "Identifier" ? holder.name : holder?.type === "MemberExpression" ? holder.property?.name : void 0;
3062
+ const key2 = node.arguments?.[0];
3063
+ if (named !== "searchParams" || key2?.type !== "StringLiteral") return;
3064
+ const local2 = parent?.type === "VariableDeclarator" && parent.id?.type === "Identifier" ? parent.id.name : void 0;
3065
+ const guarded = parent?.type === "UnaryExpression" && parent.operator === "!" || local2 && new RegExp(`!\\s*${local2}\\b|\\b${local2}\\s*(?:===?|!==?)\\s*(?:null|undefined)`).test(fnText);
3066
+ if (guarded) query.add(key2.value);
3067
+ });
3068
+ if (web && query.size) web.query = [...query];
3069
+ const bodyText = byFile.get(file)?.text;
3070
+ const sample2 = bodyText && fn.start !== void 0 && fn.end !== void 0 ? zodBodySample(root2, file, bodyText.slice(fn.start, fn.end)) : void 0;
3071
+ input = { name: "request.json()", fields: [.../* @__PURE__ */ new Set([...fields, ...query, ...sample2 && typeof sample2 === "object" ? Object.keys(sample2) : []])], ...sample2 !== void 0 ? { sample: sample2 } : {}, ...nested.size ? { nested: Object.fromEntries([...nested].map(([k, v]) => [k, [...v]])) } : {} };
3072
+ } else if (PAGES_API_FILE.test(file) && exportName === "default" && (fn.params?.length ?? 0) >= 1) {
3073
+ const appDir = nextAppDir(root2, file);
3074
+ if (appDir !== void 0) {
3075
+ const inApp = appDir ? file.slice(appDir.length + 1) : file, params = {};
3076
+ const path = "/" + inApp.replace(/^src\//, "").replace(/^pages\//, "").replace(/\.[cm]?[jt]sx?$/, "").replace(/\/index$/, "").split("/").map((seg) => {
3077
+ const m = /^\[(?:\[\.{3}([A-Za-z_]\w*)\]|(?:\.{3})?([A-Za-z_]\w*))\]$/.exec(seg);
3078
+ if (m) {
3079
+ params[m[1] ?? m[2]] = "1";
3080
+ return "1";
3081
+ }
3082
+ return seg;
3083
+ }).join("/");
3084
+ const text = byFile.get(file).text, named = [...text.matchAll(/\.method\s*={2,3}\s*['"](GET|POST|PUT|PATCH|DELETE)['"]|case\s*['"](GET|POST|PUT|PATCH|DELETE)['"]/g)].map((m) => m[1] ?? m[2]);
3085
+ const method = named.find((m) => m !== "GET") ?? (named.length ? "GET" : /\breq\.body\b|rawBody|getRawBody|signature|buffer\(req\)/.test(text) ? "POST" : "GET");
3086
+ web = { method, path: (nextBasePath(root2, appDir) + path).replace(/\/+/g, "/"), params, appDir };
3087
+ input = { name: "req.body", fields: [] };
3088
+ }
3089
+ }
3090
+ if (web?.appDir !== void 0) {
3091
+ const base = web.appDir ? web.appDir + "/" : "";
3092
+ const mw = ["middleware", "src/middleware"].flatMap((b) => [".ts", ".js", ".mjs", ".tsx"].map((e) => base + b + e)).find((f2) => byFile.get(f2)?.facts.exports.has("middleware"));
3093
+ if (mw) {
3094
+ const extra = closure(mw, byFile.get(mw).facts.exports.get("middleware"));
3095
+ for (const c of extra.calls) if (!calls.some((x) => x.file === c.file && x.line === c.line && x.operation === c.operation)) calls.push({ ...c, write: false, conditional: true });
3096
+ for (const e of extra.env) if (!env.includes(e)) env.push(e);
3097
+ for (const t of extra.files) if (!touched.includes(t)) touched.push(t);
3098
+ }
3099
+ }
3100
+ const tools = touched.flatMap((t) => byFile.get(t).facts.tools);
3101
+ const providers = new Set(calls.map((c) => c.provider));
3102
+ const inNext = nextAppDir(root2, file) !== void 0;
3103
+ const score = calls.filter((c) => c.write).length * 3 + (providers.has("stripe") ? 5 : 0) + (providers.has("openai") || providers.has("anthropic") ? 3 : 0) + providers.size + (tools.length ? 2 : 0) + (web ? 4 : inNext ? -4 : 0) - (calls.length && calls.every((c) => c.provider.startsWith("sdk:") && !c.hosts?.length) ? 12 : 0);
3104
+ candidates.push({ id: `fn:${file}#${exportName}`, title: web ? `${web.method} ${web.path}` : exportName, file, exportName, entrypoint: `${file}#${exportName}`, input, ...moreInputs.length && !web ? { moreInputs } : {}, calls, tools, triggers: [], envVars: env, channelHints: channels, score, files: touched, ...importers.get(`${file}#${exportName}`)?.size ? { callers: importers.get(`${file}#${exportName}`).size } : {}, ...web ? { web } : {} });
3105
+ }
3106
+ }
3107
+ {
3108
+ const superjson = [...byFile.values()].some(({ text }) => /initTRPC/.test(text) && /transformer\s*:\s*superjson\b/.test(text)) || [...byFile.values()].some(({ text }) => /initTRPC/.test(text) && /\btransformer\b/.test(text)) && [...byFile.values()].some(({ facts: facts2 }) => [...facts2.imports.values()].some((i) => i.source === "superjson"));
3109
+ const findRouter = (f, name, depth = 0) => {
3110
+ const ff = byFile.get(f)?.facts;
3111
+ if (!ff || depth > 8) return void 0;
3112
+ if (ff.trpcRouters.has(name)) return { file: f, name };
3113
+ const local = ff.exports.get(name);
3114
+ if (local && local !== name && ff.trpcRouters.has(local)) return { file: f, name: local };
3115
+ const imp = ff.imports.get(name);
3116
+ if (!imp) return void 0;
3117
+ const target = resolveModule(f, imp.source);
3118
+ if (!target) return void 0;
3119
+ const tf = byFile.get(target)?.facts;
3120
+ const tname = tf?.exports.get(imp.imported) ?? imp.imported;
3121
+ return findRouter(target, tname, depth + 1);
3122
+ };
3123
+ const procedures = (r, prefix = "", seen = /* @__PURE__ */ new Set()) => {
3124
+ const key2 = r.file + "#" + r.name;
3125
+ if (seen.has(key2) || seen.size > 100) return [];
3126
+ seen.add(key2);
3127
+ return (byFile.get(r.file).facts.trpcRouters.get(r.name) ?? []).flatMap((e) => {
3128
+ if (e.ref) {
3129
+ const sub = findRouter(r.file, e.ref);
3130
+ return sub ? procedures(sub, prefix + e.key + ".", seen) : [];
3131
+ }
3132
+ return e.fn && e.kind ? [{ path: prefix + e.key, file: r.file, fn: e.fn, kind: e.kind, ...e.fields ? { fields: e.fields } : {} }] : [];
3133
+ });
3134
+ };
3135
+ const expandedFiles = /* @__PURE__ */ new Set();
3136
+ for (const c of [...candidates]) {
3137
+ const handler = byFile.get(c.file)?.facts.trpcHandler;
3138
+ if (!c.web || !handler) continue;
3139
+ if (expandedFiles.has(c.file)) {
3140
+ candidates.splice(candidates.indexOf(c), 1);
3141
+ continue;
3142
+ }
3143
+ const router = findRouter(c.file, handler.router);
3144
+ if (!router) continue;
3145
+ const procs = procedures(router);
3146
+ if (!procs.length) continue;
3147
+ expandedFiles.add(c.file);
3148
+ const param = Object.keys(c.web.params).at(-1);
3149
+ if (!param) continue;
3150
+ const base = c.web.path.replace(/\/1$/, "");
3151
+ const expanded = [];
3152
+ for (const proc of procs) {
3153
+ if (!byFile.get(proc.file).facts.functions.has(proc.fn)) continue;
3154
+ const { calls: reached, env, files: touched, channels } = closure(proc.file, proc.fn);
3155
+ const calls = reached.filter((x) => !/^use[A-Z]/.test(x.operation));
3156
+ if (!calls.length && !opts.all) continue;
3157
+ const method = proc.kind === "query" ? "GET" : "POST", path = `${base}/${proc.path}`;
3158
+ const providers = new Set(calls.map((x) => x.provider));
3159
+ const score = calls.filter((x) => x.write).length * 3 + (providers.has("stripe") ? 5 : 0) + (providers.has("openai") || providers.has("anthropic") ? 3 : 0) + providers.size + 4 + (proc.kind === "mutation" ? 1 : 0) - (calls.length && calls.every((x) => x.provider.startsWith("sdk:") && !x.hosts?.length) ? 12 : 0);
3160
+ expanded.push({
3161
+ ...c,
3162
+ id: `${c.id}:${proc.path}`,
3163
+ title: `${method} ${path}`,
3164
+ calls,
3165
+ envVars: [.../* @__PURE__ */ new Set([...c.envVars, ...env])],
3166
+ channelHints: channels,
3167
+ files: [.../* @__PURE__ */ new Set([...c.files, ...touched])],
3168
+ score,
3169
+ input: { name: "input", fields: proc.fields ?? [] },
3170
+ web: { ...c.web, method, path, params: { ...c.web.params, [param]: proc.path }, trpc: { procedure: proc.path, kind: proc.kind, ...superjson ? { transformer: "superjson" } : {} } }
3171
+ });
3172
+ }
3173
+ candidates.splice(candidates.indexOf(c), 1, ...expanded);
3174
+ }
3175
+ }
3176
+ const scripts = [];
3177
+ for (const [file, { facts: f }] of byFile) {
3178
+ if (!f.script) continue;
3179
+ const { calls, env, files: touched, channels } = closure(file, f.script);
3180
+ if (!calls.length) continue;
3181
+ const tools = touched.flatMap((t) => byFile.get(t).facts.tools);
3182
+ const providers = new Set(calls.map((c) => c.provider));
3183
+ const score = calls.filter((c) => c.write).length * 3 + (providers.has("stripe") ? 5 : 0) + (providers.has("openai") || providers.has("anthropic") ? 3 : 0) + providers.size + (tools.length ? 2 : 0);
3184
+ scripts.push({ id: `script:${file}`, title: `node ${posix3.basename(file)}`, file, exportName: f.script, entrypoint: `${file}#${f.script}`, input: null, calls, tools, triggers: [], envVars: env, channelHints: channels, score, files: touched, script: true });
3185
+ }
3186
+ for (const [file, { facts: f }] of byFile) for (const route of f.inlineRoutes) {
3187
+ const { calls, env, files: touched, channels } = closure(file, route.name);
3188
+ if (!calls.length && !opts.all) continue;
3189
+ const fn = f.functions.get(route.name);
3190
+ const req = fn.params?.[0]?.type === "Identifier" ? fn.params[0].name : "req";
3191
+ const fields = /* @__PURE__ */ new Set();
3192
+ const aliases2 = /* @__PURE__ */ new Set();
3193
+ walk(fn.body, (node) => {
3194
+ if (node.type === "VariableDeclarator" && node.id.type === "Identifier" && node.init) {
3195
+ const init = node.init.type === "TSAsExpression" || node.init.type === "TSSatisfiesExpression" ? node.init.expression : node.init;
3196
+ const names = chain2(init);
3197
+ if (names && names[0] === req && names[1] === "body" && names.length === 2) aliases2.add(node.id.name);
3198
+ }
3199
+ });
3200
+ walk(fn.body, (node) => {
3201
+ if (node.type === "MemberExpression" && !node.computed && node.object.type === "Identifier" && aliases2.has(node.object.name) && node.property.type === "Identifier") fields.add(node.property.name);
3202
+ if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && node.init?.type === "Identifier" && aliases2.has(node.init.name)) {
3203
+ for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
3204
+ }
3205
+ if (node.type === "MemberExpression" && !node.computed) {
3206
+ const names = chain2(node);
3207
+ if (names && names[0] === req && names[1] === "body" && names[2]) fields.add(names[2]);
3208
+ }
3209
+ if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && node.init) {
3210
+ const names = chain2(node.init);
3211
+ if (names && names[0] === req && names[1] === "body" && names.length === 2) {
3212
+ for (const p of node.id.properties) if (p.type === "ObjectProperty" && !p.computed) fields.add(String(p.key.name ?? p.key.value));
3213
+ }
3214
+ }
3215
+ });
3216
+ const tools = touched.flatMap((t) => byFile.get(t).facts.tools);
3217
+ const providers = new Set(calls.map((c) => c.provider));
3218
+ const score = calls.filter((c) => c.write).length * 3 + (providers.has("stripe") ? 5 : 0) + (providers.has("openai") || providers.has("anthropic") ? 3 : 0) + providers.size + (tools.length ? 2 : 0);
3219
+ const path = routePath(file, route), entry = serverEntry(file), script = entry ? startScript(entry) : void 0;
3220
+ const title = `${route.method} ${path}`;
3221
+ const listenPort = [...touched, ...entry ? [entry] : []].map((t) => /\.listen\(\s*(?:process\.env\.[A-Z_]+\s*(?:\|\||\?\?)\s*)?(\d{2,5})/.exec(byFile.get(t).text)?.[1] ?? /\bport\s*[:=]\s*(?:Number\()?(?:process\.env\.[A-Z_]+\s*(?:\|\||\?\?)\s*)?['"]?(\d{4,5})/i.exec(byFile.get(t).text)?.[1]).find(Boolean);
3222
+ candidates.push({
3223
+ id: `route:${file}#${route.name}`,
3224
+ title,
3225
+ file,
3226
+ exportName: title,
3227
+ entrypoint: `${file}#${route.name}`,
3228
+ input: { name: "req.body", fields: [...fields] },
3229
+ calls,
3230
+ tools,
3231
+ triggers: [{ method: route.method, path, file, line: route.line }],
3232
+ envVars: env,
3233
+ channelHints: channels,
3234
+ score: score + 2,
3235
+ files: touched,
3236
+ serve: { method: route.method, path: path.replace(/:([A-Za-z_]\w*)\??/g, "1").replace(/\{[^}]+\}/g, "1").replace(/\/\*{1,2}(?=\/|$)/g, "/file-1"), line: route.line, ...listenPort ? { listenPort: Number(listenPort) } : {}, ...entry ? { entry } : {}, ...script ? { script } : {} }
3237
+ });
3238
+ }
3239
+ if (bolt) for (const [file, { facts: f }] of byFile) for (const listener of f.boltListeners) {
3240
+ const appFile = boltInstance(file, listener.receiver ?? "");
3241
+ if (!listener.inline || !appFile || !["message", "event", "action", "command"].includes(listener.kind)) continue;
3242
+ const { calls, env, files: touched, channels } = closure(file, listener.inline);
3243
+ if (!calls.length && !opts.all) continue;
3244
+ const tools = touched.flatMap((t) => byFile.get(t).facts.tools);
3245
+ const providers = new Set(calls.map((c) => c.provider));
3246
+ const score = calls.filter((c) => c.write).length * 3 + providers.size + (tools.length ? 2 : 0) + 2;
3247
+ const title = `Slack ${listener.kind} ${listener.name || "(any)"}`;
3248
+ const text = byFile.get(appFile).text, socket = /socketMode\s*:\s*true/.test(text);
3249
+ for (const operation of ["auth.test", ...socket ? ["apps.connections.open"] : []]) calls.push({ provider: "slack", operation, file, line: listener.line, argKeys: [], literals: {}, write: false });
3250
+ candidates.push({
3251
+ id: `slack:${file}#${listener.inline}`,
3252
+ title,
3253
+ file,
3254
+ exportName: title,
3255
+ entrypoint: `${file}#${listener.inline}`,
3256
+ input: null,
3257
+ calls,
3258
+ tools,
3259
+ triggers: [{ method: `slack:${listener.kind}`, path: listener.name, file, line: listener.line }],
3260
+ envVars: env,
3261
+ channelHints: channels,
3262
+ score,
3263
+ files: touched,
3264
+ bolt: { kind: listener.kind, name: listener.name },
3265
+ boltApp: { line: listener.line }
3266
+ });
3267
+ }
3268
+ for (const [file, { facts: f }] of byFile) for (const listener of f.boltListeners) for (const name of listener.handlers) {
3269
+ const ref = functionRef(file, name);
3270
+ if (!ref) continue;
3271
+ const exportName = [...byFile.get(ref[0]).facts.exports].find(([, local]) => local === ref[1])?.[0];
3272
+ const candidate = candidates.find((c) => c.file === ref[0] && c.exportName === exportName);
3273
+ if (!candidate) continue;
3274
+ candidate.bolt ??= { kind: listener.kind, name: listener.name };
3275
+ if (!candidate.triggers.some((t) => t.file === file && t.line === listener.line)) candidate.triggers.push({ method: `slack:${listener.kind}`, path: listener.name, file, line: listener.line });
3276
+ if (candidate.title === exportName) candidate.title = `Slack ${listener.kind} ${listener.name} (${exportName})`;
3277
+ }
3278
+ for (const [file, { facts: f }] of byFile) for (const route of f.routes) for (const name of route.calls) {
3279
+ const ref = functionRef(file, name);
3280
+ if (!ref) continue;
3281
+ const exportName = [...byFile.get(ref[0]).facts.exports].find(([, local]) => local === ref[1])?.[0];
3282
+ const candidate = candidates.find((c) => c.file === ref[0] && c.exportName === exportName);
3283
+ if (candidate && !candidate.triggers.some((t) => t.file === file && t.line === route.line)) candidate.triggers.push({ method: route.method, path: route.path, file, line: route.line });
3284
+ }
3285
+ const signature = (c) => c.calls.length ? c.calls.map((call) => `${call.file}:${call.line}`).sort().join("|") : c.id;
3286
+ const unique = /* @__PURE__ */ new Map();
3287
+ for (const c of candidates.sort((a, b) => Number(!!b.web) - Number(!!a.web) || a.files.length - b.files.length)) {
3288
+ const key2 = c.web ? c.id : signature(c);
3289
+ const kept = unique.get(key2);
3290
+ if (kept) {
3291
+ kept.triggers.push(...c.triggers.filter((t) => !kept.triggers.some((k) => k.file === t.file && k.line === t.line)));
3292
+ continue;
3293
+ }
3294
+ unique.set(key2, c);
3295
+ }
3296
+ const sites = (c) => new Set(c.calls.map((call) => `${call.file}:${call.line}`));
3297
+ for (const helper of [...unique.values()]) {
3298
+ const own = sites(helper);
3299
+ if (!own.size || helper.web) continue;
3300
+ const parent = [...unique.values()].find((c) => c !== helper && c.files.includes(helper.file) && c.calls.length > helper.calls.length && [...own].every((site) => sites(c).has(site)));
3301
+ if (parent) {
3302
+ unique.delete(helper.web ? helper.id : signature(helper));
3303
+ parent.triggers.push(...helper.triggers.filter((t) => !parent.triggers.some((k) => k.file === t.file && k.line === t.line)));
3304
+ }
3305
+ }
3306
+ const python = await analyzePythonWorkflows(root2);
3307
+ return [...unique.values(), ...scripts, ...python].map((c) => ({ ...c, score: c.score + (c.triggers.length ? 2 : 0) })).sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
3308
+ }
3309
+
3310
+ // src/flow/scan-worker.ts
3311
+ var { root, all } = workerData;
3312
+ analyzeWorkflows(root, { all }).then((candidates) => parentPort.postMessage({ candidates }), (error) => parentPort.postMessage({ error: error instanceof Error ? error.message : String(error) }));