@easynet/agent-tool 1.0.45 → 1.0.47

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 (40) hide show
  1. package/README.md +31 -105
  2. package/dist/api/extension/groupPrefix.d.ts.map +1 -1
  3. package/dist/api/main.cjs +19 -20
  4. package/dist/api/main.js +2 -3
  5. package/dist/api/runtimeFromConfig.d.ts.map +1 -1
  6. package/dist/{chunk-JH6TWGP4.js → chunk-2ZPDD7ZO.js} +722 -279
  7. package/dist/chunk-2ZPDD7ZO.js.map +1 -0
  8. package/dist/{chunk-ONXFQ6K5.js → chunk-64ZQQV5C.js} +79 -75
  9. package/dist/chunk-64ZQQV5C.js.map +1 -0
  10. package/dist/{chunk-YVL3UMM2.cjs → chunk-A5B6Q6EG.cjs} +733 -317
  11. package/dist/chunk-A5B6Q6EG.cjs.map +1 -0
  12. package/dist/{chunk-5WY557HJ.cjs → chunk-IAEVDXWS.cjs} +15 -16
  13. package/dist/chunk-IAEVDXWS.cjs.map +1 -0
  14. package/dist/{chunk-YUA6KJWF.js → chunk-KYBIKD5R.js} +5 -5
  15. package/dist/chunk-KYBIKD5R.js.map +1 -0
  16. package/dist/{chunk-ETXVT6FE.cjs → chunk-MDPU7EIO.cjs} +83 -87
  17. package/dist/chunk-MDPU7EIO.cjs.map +1 -0
  18. package/dist/index.cjs +195 -413
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.ts +16 -63
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +171 -281
  23. package/dist/index.js.map +1 -1
  24. package/dist/utils/cli/index.cjs +16 -17
  25. package/dist/utils/cli/index.cjs.map +1 -1
  26. package/dist/utils/cli/index.js +3 -4
  27. package/dist/utils/cli/index.js.map +1 -1
  28. package/dist/utils/npmCache.d.ts +1 -1
  29. package/dist/utils/npmCache.d.ts.map +1 -1
  30. package/package.json +1 -1
  31. package/dist/chunk-5WY557HJ.cjs.map +0 -1
  32. package/dist/chunk-CLJCCBXA.js +0 -474
  33. package/dist/chunk-CLJCCBXA.js.map +0 -1
  34. package/dist/chunk-ETXVT6FE.cjs.map +0 -1
  35. package/dist/chunk-H5SPD2O7.cjs +0 -480
  36. package/dist/chunk-H5SPD2O7.cjs.map +0 -1
  37. package/dist/chunk-JH6TWGP4.js.map +0 -1
  38. package/dist/chunk-ONXFQ6K5.js.map +0 -1
  39. package/dist/chunk-YUA6KJWF.js.map +0 -1
  40. package/dist/chunk-YVL3UMM2.cjs.map +0 -1
@@ -2,17 +2,20 @@
2
2
 
3
3
  var chunkTOSPHMYU_cjs = require('./chunk-TOSPHMYU.cjs');
4
4
  var chunkDYDNPIV2_cjs = require('./chunk-DYDNPIV2.cjs');
5
+ var chunkUUNG3GL3_cjs = require('./chunk-UUNG3GL3.cjs');
6
+ var fs = require('fs');
7
+ var path = require('path');
8
+ var agentCommon = require('@easynet/agent-common');
5
9
  var Ajv = require('ajv');
6
10
  var addFormats = require('ajv-formats');
7
11
  var cockatiel = require('cockatiel');
8
12
  var eventemitter3 = require('eventemitter3');
9
13
  var uuid = require('uuid');
10
14
  var pTimeout = require('p-timeout');
11
- var path = require('path');
12
15
  var promises = require('fs/promises');
13
- var fs = require('fs');
14
- var agentCommon = require('@easynet/agent-common');
15
16
  var module$1 = require('module');
17
+ var npm = require('@easynet/agent-common/npm');
18
+ var http = require('http');
16
19
 
17
20
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
18
21
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -21,6 +24,229 @@ var Ajv__default = /*#__PURE__*/_interopDefault(Ajv);
21
24
  var addFormats__default = /*#__PURE__*/_interopDefault(addFormats);
22
25
  var pTimeout__default = /*#__PURE__*/_interopDefault(pTimeout);
23
26
 
27
+ function loadToolConfig(toolYamlPath) {
28
+ const abs = path.resolve(toolYamlPath);
29
+ const raw = fs.readFileSync(abs, "utf8");
30
+ const parsed = agentCommon.parseYamlContent(raw, {
31
+ substituteEnv: false
32
+ });
33
+ if (!parsed || typeof parsed !== "object") return {};
34
+ const toolsBlock = parsed.tools;
35
+ if (toolsBlock != null && typeof toolsBlock === "object" && !Array.isArray(toolsBlock)) {
36
+ const toolDefaults = toolsBlock.defaults != null && typeof toolsBlock.defaults === "object" && !Array.isArray(toolsBlock.defaults) ? toolsBlock.defaults : void 0;
37
+ const packageToolDefaults2 = toolsBlock.packages != null && typeof toolsBlock.packages === "object" && !Array.isArray(toolsBlock.packages) ? toolsBlock.packages : void 0;
38
+ const list2 = Array.isArray(toolsBlock.list) && toolsBlock.list.length > 0 ? toolsBlock.list : void 0;
39
+ return {
40
+ tools: list2 ?? (packageToolDefaults2 ? Object.keys(packageToolDefaults2) : void 0),
41
+ sandboxedPath: typeof toolsBlock.sandboxedPath === "string" ? toolsBlock.sandboxedPath : parsed.sandboxedPath,
42
+ enableSandboxValidation: typeof toolsBlock.enableSandboxValidation === "boolean" ? toolsBlock.enableSandboxValidation : parsed.enableSandboxValidation,
43
+ allowedHosts: Array.isArray(toolsBlock.allowedHosts) ? toolsBlock.allowedHosts : parsed.allowedHosts,
44
+ blockedHosts: Array.isArray(toolsBlock.blockedHosts) ? toolsBlock.blockedHosts : parsed.blockedHosts,
45
+ blockedCidrs: Array.isArray(toolsBlock.blockedCidrs) ? toolsBlock.blockedCidrs : parsed.blockedCidrs,
46
+ toolDefaults,
47
+ packageToolDefaults: packageToolDefaults2
48
+ };
49
+ }
50
+ const packageToolDefaults = typeof parsed.packageToolDefaults === "object" && !Array.isArray(parsed.packageToolDefaults) ? parsed.packageToolDefaults : void 0;
51
+ const list = Array.isArray(parsed.tools) && parsed.tools.length > 0 ? parsed.tools : void 0;
52
+ return {
53
+ tools: list ?? (packageToolDefaults ? Object.keys(packageToolDefaults) : void 0),
54
+ sandboxedPath: parsed.sandboxedPath,
55
+ enableSandboxValidation: typeof parsed.enableSandboxValidation === "boolean" ? parsed.enableSandboxValidation : void 0,
56
+ allowedHosts: Array.isArray(parsed.allowedHosts) ? parsed.allowedHosts : void 0,
57
+ blockedHosts: Array.isArray(parsed.blockedHosts) ? parsed.blockedHosts : void 0,
58
+ blockedCidrs: Array.isArray(parsed.blockedCidrs) ? parsed.blockedCidrs : void 0,
59
+ toolDefaults: typeof parsed.toolDefaults === "object" && !Array.isArray(parsed.toolDefaults) ? parsed.toolDefaults : void 0,
60
+ packageToolDefaults
61
+ };
62
+ }
63
+ function resolveSandboxedPath(toolYamlPath, sandboxedPath) {
64
+ const configDir = path.dirname(path.resolve(toolYamlPath));
65
+ return agentCommon.resolveConfigPath(sandboxedPath, configDir, {
66
+ expandHome: true
67
+ });
68
+ }
69
+ var CACHE_SUBDIR = ".agent/cache";
70
+ function getCacheBaseFromToolConfig(toolYamlPath) {
71
+ const config = loadToolConfig(toolYamlPath);
72
+ if (!config.sandboxedPath || typeof config.sandboxedPath !== "string") return void 0;
73
+ const sandboxRoot = resolveSandboxedPath(toolYamlPath, config.sandboxedPath);
74
+ return path.join(sandboxRoot, CACHE_SUBDIR);
75
+ }
76
+ function findAndLoadToolConfig(dir) {
77
+ const resolvedDir = path.resolve(dir);
78
+ const candidates = [path.join(resolvedDir, "tool.yaml"), path.join(resolvedDir, ".tool.yaml")];
79
+ for (const p of candidates) {
80
+ if (fs.existsSync(p)) {
81
+ const config = loadToolConfig(p);
82
+ return { ...config, configPath: p };
83
+ }
84
+ }
85
+ return {};
86
+ }
87
+
88
+ // src/tools/util/toolDescriptor.ts
89
+ var TOOL_PATH_REGEX = /^([a-z][a-z0-9-]*):([^/]+)\/([^#]+)(#(.+))?$/;
90
+ function isToolPath(descriptor) {
91
+ return TOOL_PATH_REGEX.test(descriptor.trim());
92
+ }
93
+ function isBarePackageDescriptor(descriptor) {
94
+ const parsed = parseToolPath(descriptor.trim());
95
+ return parsed !== null && parsed.toolName === "";
96
+ }
97
+ function parseToolPath(descriptor) {
98
+ const s = descriptor.trim();
99
+ const m = s.match(TOOL_PATH_REGEX);
100
+ if (!m || m[1] === void 0 || m[2] === void 0 || m[3] === void 0) return null;
101
+ return {
102
+ protocol: m[1],
103
+ scope: m[2],
104
+ packageWithVersion: m[3],
105
+ toolName: m[5] ?? ""
106
+ };
107
+ }
108
+ function npmDescriptorToRegistryPrefix(descriptor, resolvedVersion) {
109
+ const s = descriptor.trim();
110
+ if (typeof s !== "string" || !s.startsWith("npm:")) return "";
111
+ const rest = s.slice(4).trim();
112
+ const hashIdx = rest.indexOf("#");
113
+ const beforeHash = hashIdx < 0 ? rest : rest.slice(0, hashIdx);
114
+ const lastAt = beforeHash.lastIndexOf("@");
115
+ const scopeAndPackage = lastAt <= 0 ? beforeHash : beforeHash.slice(0, lastAt);
116
+ let version = lastAt <= 0 ? "latest" : beforeHash.slice(lastAt + 1).trim() || "latest";
117
+ if (version === "latest" || !version) {
118
+ const resolved = (resolvedVersion ?? "").trim();
119
+ if (resolved !== "" && resolved.toLowerCase() !== "latest") {
120
+ version = resolved;
121
+ } else {
122
+ throw new Error(
123
+ `Registry prefix requires a concrete version when descriptor uses latest (${descriptor}). Resolve version from registry (e.g. resolveLatestVersionFromRegistry) and pass as resolvedVersion.`
124
+ );
125
+ }
126
+ }
127
+ if (!version || version.toLowerCase() === "latest") {
128
+ throw new Error(
129
+ `Registry never uses "latest"; pass resolved concrete version for npm descriptor: ${descriptor}`
130
+ );
131
+ }
132
+ const slashIdx = scopeAndPackage.indexOf("/");
133
+ const scope = slashIdx < 0 ? scopeAndPackage : scopeAndPackage.slice(0, slashIdx).replace(/^@/, "");
134
+ const pkg = slashIdx < 0 ? "" : scopeAndPackage.slice(slashIdx + 1);
135
+ const segment = [scope, pkg, version].filter(Boolean).join(".");
136
+ const normalized = chunkDYDNPIV2_cjs.normalizeToolName(segment);
137
+ if (!normalized) return "";
138
+ return "npm." + normalized + ".";
139
+ }
140
+ function npmDescriptorToPackagePrefix(descriptor) {
141
+ const s = descriptor.trim();
142
+ if (typeof s !== "string" || !s.startsWith("npm:")) return "";
143
+ const rest = s.slice(4).trim();
144
+ const hashIdx = rest.indexOf("#");
145
+ const beforeHash = hashIdx < 0 ? rest : rest.slice(0, hashIdx);
146
+ const lastAt = beforeHash.lastIndexOf("@");
147
+ const scopeAndPackage = lastAt <= 0 ? beforeHash : beforeHash.slice(0, lastAt);
148
+ const slashIdx = scopeAndPackage.indexOf("/");
149
+ const scope = slashIdx < 0 ? scopeAndPackage : scopeAndPackage.slice(0, slashIdx).replace(/^@/, "");
150
+ const pkg = slashIdx < 0 ? "" : scopeAndPackage.slice(slashIdx + 1);
151
+ const segment = [scope, pkg].filter(Boolean).join(".");
152
+ const normalized = chunkDYDNPIV2_cjs.normalizeToolName(segment);
153
+ if (!normalized) return "";
154
+ return "npm." + normalized;
155
+ }
156
+ function npmDescriptorToPackagePrefixWithVersion(descriptor) {
157
+ const s = descriptor.trim();
158
+ if (typeof s !== "string" || !s.startsWith("npm:")) return "";
159
+ const rest = s.slice(4).trim();
160
+ const hashIdx = rest.indexOf("#");
161
+ const beforeHash = hashIdx < 0 ? rest : rest.slice(0, hashIdx);
162
+ const lastAt = beforeHash.lastIndexOf("@");
163
+ const scopeAndPackage = lastAt <= 0 ? beforeHash : beforeHash.slice(0, lastAt);
164
+ const version = lastAt <= 0 ? "" : beforeHash.slice(lastAt + 1).trim();
165
+ const slashIdx = scopeAndPackage.indexOf("/");
166
+ const scope = slashIdx < 0 ? scopeAndPackage : scopeAndPackage.slice(0, slashIdx).replace(/^@/, "");
167
+ const pkg = slashIdx < 0 ? "" : scopeAndPackage.slice(slashIdx + 1);
168
+ const segment = [scope, pkg, version].filter(Boolean).join(".");
169
+ const normalized = chunkDYDNPIV2_cjs.normalizeToolName(segment);
170
+ if (!normalized) return "";
171
+ return "npm." + normalized;
172
+ }
173
+ function getDisplayScope(registryName, _kind, _toolVersion) {
174
+ const i = registryName.indexOf(".");
175
+ return i < 0 ? registryName : registryName.slice(0, i);
176
+ }
177
+ function expandToolDescriptorsToRegistryNames(descriptors, registryNames) {
178
+ const out = [];
179
+ const seen = /* @__PURE__ */ new Set();
180
+ function add(name) {
181
+ const key = chunkDYDNPIV2_cjs.normalizeToolName(name);
182
+ if (registryNames.includes(key) && !seen.has(key)) {
183
+ seen.add(key);
184
+ out.push(key);
185
+ return;
186
+ }
187
+ const matched = registryNames.filter((r) => r === key || r.endsWith("." + key));
188
+ for (const m of matched) {
189
+ if (!seen.has(m)) {
190
+ seen.add(m);
191
+ out.push(m);
192
+ }
193
+ }
194
+ }
195
+ for (const d of descriptors) {
196
+ const s = d.trim();
197
+ if (!s) continue;
198
+ if (isToolPath(s)) {
199
+ if (registryNames.includes(s) && !seen.has(s)) {
200
+ seen.add(s);
201
+ out.push(s);
202
+ continue;
203
+ }
204
+ const path = parseToolPath(s);
205
+ if (path) {
206
+ const packagePrefix = path.protocol === "npm" ? npmDescriptorToPackagePrefix(s) : path.protocol === "file" ? fileDescriptorToPackagePrefix(s) : "";
207
+ const prefixWithDot = packagePrefix ? packagePrefix + "." : "";
208
+ if (prefixWithDot) {
209
+ if (path.toolName) {
210
+ const suffix = "." + path.toolName;
211
+ for (const r of registryNames) {
212
+ if (r.startsWith(prefixWithDot) && r.endsWith(suffix) && !seen.has(r)) {
213
+ seen.add(r);
214
+ out.push(r);
215
+ }
216
+ }
217
+ } else {
218
+ for (const r of registryNames) {
219
+ if (r.startsWith(prefixWithDot) && !seen.has(r)) {
220
+ seen.add(r);
221
+ out.push(r);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ }
227
+ continue;
228
+ }
229
+ const name = chunkDYDNPIV2_cjs.normalizeToolName(s);
230
+ add(name);
231
+ }
232
+ return out;
233
+ }
234
+ function resolveToolDescriptor(descriptor) {
235
+ const s = descriptor.trim();
236
+ return s;
237
+ }
238
+ function fileDescriptorToPackagePrefix(descriptor) {
239
+ const path = parseToolPath(descriptor.trim());
240
+ if (!path || path.protocol !== "file") return "";
241
+ const pathPart = `${path.scope}/${path.packageWithVersion}`;
242
+ const normalized = chunkDYDNPIV2_cjs.normalizeToolName(pathPart);
243
+ if (!normalized) return "";
244
+ return "file." + normalized;
245
+ }
246
+ function fileDescriptorToRegistryPrefix(descriptor) {
247
+ const prefix = fileDescriptorToPackagePrefix(descriptor);
248
+ return prefix ? prefix + "." : "";
249
+ }
24
250
  var SchemaValidator = class {
25
251
  ajv;
26
252
  cache = /* @__PURE__ */ new Map();
@@ -1490,7 +1716,7 @@ var sandboxValidationEnabled = false;
1490
1716
  function setSandboxValidationEnabled(enabled) {
1491
1717
  sandboxValidationEnabled = enabled;
1492
1718
  }
1493
- async function resolveSandboxedPath(inputPath, sandboxRoot) {
1719
+ async function resolveSandboxedPath2(inputPath, sandboxRoot) {
1494
1720
  let normalizedRoot;
1495
1721
  try {
1496
1722
  normalizedRoot = await promises.realpath(path.resolve(sandboxRoot));
@@ -1528,278 +1754,30 @@ function isWithinRoot(path$1, root) {
1528
1754
  return normalizedPath === normalizedRoot || normalizedPath.startsWith(normalizedRoot + "/");
1529
1755
  }
1530
1756
 
1531
- // src/tools/util/toolDescriptor.ts
1532
- var TOOL_PATH_REGEX = /^([a-z][a-z0-9-]*):([^/]+)\/([^#]+)(#(.+))?$/;
1533
- function isToolPath(descriptor) {
1534
- return TOOL_PATH_REGEX.test(descriptor.trim());
1757
+ // src/api/runtimeFromConfig.ts
1758
+ var requireFromPackage = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-A5B6Q6EG.cjs', document.baseURI).href)));
1759
+ function getProjectRequire() {
1760
+ const cwd = process.cwd();
1761
+ if (fs.existsSync(path.join(cwd, "package.json"))) return module$1.createRequire(path.join(cwd, "package.json"));
1762
+ if (fs.existsSync(path.join(cwd, "tool.yaml"))) return module$1.createRequire(path.join(cwd, "tool.yaml"));
1763
+ return null;
1535
1764
  }
1536
- function isBarePackageDescriptor(descriptor) {
1537
- const parsed = parseToolPath(descriptor.trim());
1538
- return parsed !== null && parsed.toolName === "";
1539
- }
1540
- function parseToolPath(descriptor) {
1541
- const s = descriptor.trim();
1542
- const m = s.match(TOOL_PATH_REGEX);
1543
- if (!m || m[1] === void 0 || m[2] === void 0 || m[3] === void 0) return null;
1544
- return {
1545
- protocol: m[1],
1546
- scope: m[2],
1547
- packageWithVersion: m[3],
1548
- toolName: m[5] ?? ""
1549
- };
1550
- }
1551
- function npmDescriptorToRegistryPrefix(descriptor, resolvedVersion) {
1552
- const s = descriptor.trim();
1553
- if (typeof s !== "string" || !s.startsWith("npm:")) return "";
1554
- const rest = s.slice(4).trim();
1555
- const hashIdx = rest.indexOf("#");
1556
- const beforeHash = hashIdx < 0 ? rest : rest.slice(0, hashIdx);
1557
- const lastAt = beforeHash.lastIndexOf("@");
1558
- const scopeAndPackage = lastAt <= 0 ? beforeHash : beforeHash.slice(0, lastAt);
1559
- let version = lastAt <= 0 ? "latest" : beforeHash.slice(lastAt + 1).trim() || "latest";
1560
- if (version === "latest" || !version) {
1561
- const resolved = (resolvedVersion ?? "").trim();
1562
- if (resolved !== "" && resolved.toLowerCase() !== "latest") {
1563
- version = resolved;
1564
- } else {
1565
- throw new Error(
1566
- `Registry prefix requires a concrete version when descriptor uses latest (${descriptor}). Resolve version from registry (e.g. resolveLatestVersionFromRegistry) and pass as resolvedVersion.`
1567
- );
1568
- }
1569
- }
1570
- if (!version || version.toLowerCase() === "latest") {
1571
- throw new Error(
1572
- `Registry never uses "latest"; pass resolved concrete version for npm descriptor: ${descriptor}`
1573
- );
1574
- }
1575
- const slashIdx = scopeAndPackage.indexOf("/");
1576
- const scope = slashIdx < 0 ? scopeAndPackage : scopeAndPackage.slice(0, slashIdx).replace(/^@/, "");
1577
- const pkg = slashIdx < 0 ? "" : scopeAndPackage.slice(slashIdx + 1);
1578
- const segment = [scope, pkg, version].filter(Boolean).join(".");
1579
- const normalized = chunkDYDNPIV2_cjs.normalizeToolName(segment);
1580
- if (!normalized) return "";
1581
- return "npm." + normalized + ".";
1582
- }
1583
- function npmDescriptorToPackagePrefix(descriptor) {
1584
- const s = descriptor.trim();
1585
- if (typeof s !== "string" || !s.startsWith("npm:")) return "";
1586
- const rest = s.slice(4).trim();
1587
- const hashIdx = rest.indexOf("#");
1588
- const beforeHash = hashIdx < 0 ? rest : rest.slice(0, hashIdx);
1589
- const lastAt = beforeHash.lastIndexOf("@");
1590
- const scopeAndPackage = lastAt <= 0 ? beforeHash : beforeHash.slice(0, lastAt);
1591
- const slashIdx = scopeAndPackage.indexOf("/");
1592
- const scope = slashIdx < 0 ? scopeAndPackage : scopeAndPackage.slice(0, slashIdx).replace(/^@/, "");
1593
- const pkg = slashIdx < 0 ? "" : scopeAndPackage.slice(slashIdx + 1);
1594
- const segment = [scope, pkg].filter(Boolean).join(".");
1595
- const normalized = chunkDYDNPIV2_cjs.normalizeToolName(segment);
1596
- if (!normalized) return "";
1597
- return "npm." + normalized;
1598
- }
1599
- function npmDescriptorToPackagePrefixWithVersion(descriptor) {
1600
- const s = descriptor.trim();
1601
- if (typeof s !== "string" || !s.startsWith("npm:")) return "";
1602
- const rest = s.slice(4).trim();
1603
- const hashIdx = rest.indexOf("#");
1604
- const beforeHash = hashIdx < 0 ? rest : rest.slice(0, hashIdx);
1605
- const lastAt = beforeHash.lastIndexOf("@");
1606
- const scopeAndPackage = lastAt <= 0 ? beforeHash : beforeHash.slice(0, lastAt);
1607
- const version = lastAt <= 0 ? "" : beforeHash.slice(lastAt + 1).trim();
1608
- const slashIdx = scopeAndPackage.indexOf("/");
1609
- const scope = slashIdx < 0 ? scopeAndPackage : scopeAndPackage.slice(0, slashIdx).replace(/^@/, "");
1610
- const pkg = slashIdx < 0 ? "" : scopeAndPackage.slice(slashIdx + 1);
1611
- const segment = [scope, pkg, version].filter(Boolean).join(".");
1612
- const normalized = chunkDYDNPIV2_cjs.normalizeToolName(segment);
1613
- if (!normalized) return "";
1614
- return "npm." + normalized;
1615
- }
1616
- function isNpmToolDescriptor(descriptor) {
1617
- return isToolPath(descriptor) && parseToolPath(descriptor)?.protocol === "npm";
1618
- }
1619
- function parseNpmToolDescriptor(descriptor) {
1620
- const parsed = parseToolPath(descriptor);
1621
- if (!parsed || parsed.protocol !== "npm") return null;
1622
- return {
1623
- fullPackage: `${parsed.scope}/${parsed.packageWithVersion}`,
1624
- toolPath: parsed.toolName
1625
- };
1626
- }
1627
- function getDisplayScope(registryName, _kind, _toolVersion) {
1628
- const i = registryName.indexOf(".");
1629
- return i < 0 ? registryName : registryName.slice(0, i);
1630
- }
1631
- function resolveNpmToolDescriptor(descriptor) {
1632
- return null;
1633
- }
1634
- function expandToolDescriptorsToRegistryNames(descriptors, registryNames) {
1635
- const out = [];
1636
- const seen = /* @__PURE__ */ new Set();
1637
- function add(name) {
1638
- const key = chunkDYDNPIV2_cjs.normalizeToolName(name);
1639
- if (registryNames.includes(key) && !seen.has(key)) {
1640
- seen.add(key);
1641
- out.push(key);
1642
- return;
1643
- }
1644
- const matched = registryNames.filter((r) => r === key || r.endsWith("." + key));
1645
- for (const m of matched) {
1646
- if (!seen.has(m)) {
1647
- seen.add(m);
1648
- out.push(m);
1649
- }
1650
- }
1651
- }
1652
- for (const d of descriptors) {
1653
- const s = d.trim();
1654
- if (!s) continue;
1655
- if (isToolPath(s)) {
1656
- if (registryNames.includes(s) && !seen.has(s)) {
1657
- seen.add(s);
1658
- out.push(s);
1659
- continue;
1660
- }
1661
- const path = parseToolPath(s);
1662
- if (path) {
1663
- const packagePrefix = path.protocol === "npm" ? npmDescriptorToPackagePrefix(s) : path.protocol === "file" ? fileDescriptorToPackagePrefix(s) : "";
1664
- const prefixWithDot = packagePrefix ? packagePrefix + "." : "";
1665
- if (prefixWithDot) {
1666
- if (path.toolName) {
1667
- const suffix = "." + path.toolName;
1668
- for (const r of registryNames) {
1669
- if (r.startsWith(prefixWithDot) && r.endsWith(suffix) && !seen.has(r)) {
1670
- seen.add(r);
1671
- out.push(r);
1672
- }
1673
- }
1674
- } else {
1675
- for (const r of registryNames) {
1676
- if (r.startsWith(prefixWithDot) && !seen.has(r)) {
1677
- seen.add(r);
1678
- out.push(r);
1679
- }
1680
- }
1681
- }
1682
- }
1683
- }
1684
- continue;
1685
- }
1686
- const name = chunkDYDNPIV2_cjs.normalizeToolName(s);
1687
- add(name);
1688
- }
1689
- return out;
1690
- }
1691
- function resolveToolDescriptor(descriptor) {
1692
- const s = descriptor.trim();
1693
- return s;
1694
- }
1695
- function normalizeToolList(descriptors) {
1696
- const seen = /* @__PURE__ */ new Set();
1697
- const out = [];
1698
- for (const d of descriptors) {
1699
- if (typeof d !== "string" || !d.trim()) continue;
1700
- const name = resolveToolDescriptor(d);
1701
- if (!seen.has(name)) {
1702
- seen.add(name);
1703
- out.push(name);
1704
- }
1705
- }
1706
- return out;
1707
- }
1708
- function fileDescriptorToPackagePrefix(descriptor) {
1709
- const path = parseToolPath(descriptor.trim());
1710
- if (!path || path.protocol !== "file") return "";
1711
- const pathPart = `${path.scope}/${path.packageWithVersion}`;
1712
- const normalized = chunkDYDNPIV2_cjs.normalizeToolName(pathPart);
1713
- if (!normalized) return "";
1714
- return "file." + normalized;
1715
- }
1716
- function fileDescriptorToRegistryPrefix(descriptor) {
1717
- const prefix = fileDescriptorToPackagePrefix(descriptor);
1718
- return prefix ? prefix + "." : "";
1719
- }
1720
- function loadToolConfig(toolYamlPath) {
1721
- const abs = path.resolve(toolYamlPath);
1722
- const raw = fs.readFileSync(abs, "utf8");
1723
- const parsed = agentCommon.parseYamlContent(raw, {
1724
- substituteEnv: false
1725
- });
1726
- if (!parsed || typeof parsed !== "object") return {};
1727
- const toolsBlock = parsed.tools;
1728
- if (toolsBlock != null && typeof toolsBlock === "object" && !Array.isArray(toolsBlock)) {
1729
- const toolDefaults = toolsBlock.defaults != null && typeof toolsBlock.defaults === "object" && !Array.isArray(toolsBlock.defaults) ? toolsBlock.defaults : void 0;
1730
- const packageToolDefaults2 = toolsBlock.packages != null && typeof toolsBlock.packages === "object" && !Array.isArray(toolsBlock.packages) ? toolsBlock.packages : void 0;
1731
- const list2 = Array.isArray(toolsBlock.list) && toolsBlock.list.length > 0 ? toolsBlock.list : void 0;
1732
- return {
1733
- tools: list2 ?? (packageToolDefaults2 ? Object.keys(packageToolDefaults2) : void 0),
1734
- sandboxedPath: typeof toolsBlock.sandboxedPath === "string" ? toolsBlock.sandboxedPath : parsed.sandboxedPath,
1735
- enableSandboxValidation: typeof toolsBlock.enableSandboxValidation === "boolean" ? toolsBlock.enableSandboxValidation : parsed.enableSandboxValidation,
1736
- allowedHosts: Array.isArray(toolsBlock.allowedHosts) ? toolsBlock.allowedHosts : parsed.allowedHosts,
1737
- blockedHosts: Array.isArray(toolsBlock.blockedHosts) ? toolsBlock.blockedHosts : parsed.blockedHosts,
1738
- blockedCidrs: Array.isArray(toolsBlock.blockedCidrs) ? toolsBlock.blockedCidrs : parsed.blockedCidrs,
1739
- toolDefaults,
1740
- packageToolDefaults: packageToolDefaults2
1741
- };
1742
- }
1743
- const packageToolDefaults = typeof parsed.packageToolDefaults === "object" && !Array.isArray(parsed.packageToolDefaults) ? parsed.packageToolDefaults : void 0;
1744
- const list = Array.isArray(parsed.tools) && parsed.tools.length > 0 ? parsed.tools : void 0;
1745
- return {
1746
- tools: list ?? (packageToolDefaults ? Object.keys(packageToolDefaults) : void 0),
1747
- sandboxedPath: parsed.sandboxedPath,
1748
- enableSandboxValidation: typeof parsed.enableSandboxValidation === "boolean" ? parsed.enableSandboxValidation : void 0,
1749
- allowedHosts: Array.isArray(parsed.allowedHosts) ? parsed.allowedHosts : void 0,
1750
- blockedHosts: Array.isArray(parsed.blockedHosts) ? parsed.blockedHosts : void 0,
1751
- blockedCidrs: Array.isArray(parsed.blockedCidrs) ? parsed.blockedCidrs : void 0,
1752
- toolDefaults: typeof parsed.toolDefaults === "object" && !Array.isArray(parsed.toolDefaults) ? parsed.toolDefaults : void 0,
1753
- packageToolDefaults
1754
- };
1755
- }
1756
- function resolveSandboxedPath2(toolYamlPath, sandboxedPath) {
1757
- const configDir = path.dirname(path.resolve(toolYamlPath));
1758
- return agentCommon.resolveConfigPath(sandboxedPath, configDir, {
1759
- expandHome: true
1760
- });
1761
- }
1762
- var CACHE_SUBDIR = ".agent/cache";
1763
- function getCacheBaseFromToolConfig(toolYamlPath) {
1764
- const config = loadToolConfig(toolYamlPath);
1765
- if (!config.sandboxedPath || typeof config.sandboxedPath !== "string") return void 0;
1766
- const sandboxRoot = resolveSandboxedPath2(toolYamlPath, config.sandboxedPath);
1767
- return path.join(sandboxRoot, CACHE_SUBDIR);
1768
- }
1769
- function findAndLoadToolConfig(dir) {
1770
- const resolvedDir = path.resolve(dir);
1771
- const candidates = [path.join(resolvedDir, "tool.yaml"), path.join(resolvedDir, ".tool.yaml")];
1772
- for (const p of candidates) {
1773
- if (fs.existsSync(p)) {
1774
- const config = loadToolConfig(p);
1775
- return { ...config, configPath: p };
1776
- }
1777
- }
1778
- return {};
1779
- }
1780
- var requireFromPackage = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('chunk-YVL3UMM2.cjs', document.baseURI).href)));
1781
- function getProjectRequire() {
1782
- const cwd = process.cwd();
1783
- if (fs.existsSync(path.join(cwd, "package.json"))) return module$1.createRequire(path.join(cwd, "package.json"));
1784
- if (fs.existsSync(path.join(cwd, "tool.yaml"))) return module$1.createRequire(path.join(cwd, "tool.yaml"));
1785
- return null;
1786
- }
1787
- var DEFAULT_EXTENSION_PACKAGES = [];
1788
- function getInstalledPackageVersion(packageName) {
1789
- const projectRequire = getProjectRequire();
1790
- const requirers = [requireFromPackage];
1791
- if (projectRequire) requirers.push(projectRequire);
1792
- for (const req of requirers) {
1793
- try {
1794
- const pkgJsonPath = req.resolve(`${packageName}/package.json`);
1795
- const json = fs.readFileSync(pkgJsonPath, "utf-8");
1796
- const pkg = JSON.parse(json);
1797
- return pkg.version ?? null;
1798
- } catch {
1799
- continue;
1800
- }
1801
- }
1802
- return null;
1765
+ var DEFAULT_EXTENSION_PACKAGES = [];
1766
+ function getInstalledPackageVersion(packageName) {
1767
+ const projectRequire = getProjectRequire();
1768
+ const requirers = [requireFromPackage];
1769
+ if (projectRequire) requirers.push(projectRequire);
1770
+ for (const req of requirers) {
1771
+ try {
1772
+ const pkgJsonPath = req.resolve(`${packageName}/package.json`);
1773
+ const json = fs.readFileSync(pkgJsonPath, "utf-8");
1774
+ const pkg = JSON.parse(json);
1775
+ return pkg.version ?? null;
1776
+ } catch {
1777
+ continue;
1778
+ }
1779
+ }
1780
+ return null;
1803
1781
  }
1804
1782
  function getRegisterFn(mod) {
1805
1783
  return mod?.register ?? mod?.registerCoreTools;
@@ -1874,7 +1852,7 @@ function loadExtensionFromFileDescriptorSync(descriptor, configFilePath, stepLog
1874
1852
  const resolvedPath = path.resolve(configDir, pathPart);
1875
1853
  if (!fs.existsSync(resolvedPath) || !fs.statSync(resolvedPath).isDirectory()) return null;
1876
1854
  try {
1877
- const entryPath = agentCommon.getPackageEntryPath(resolvedPath);
1855
+ const entryPath = npm.getPackageEntryPath(resolvedPath);
1878
1856
  const req = module$1.createRequire(path.join(resolvedPath, "package.json"));
1879
1857
  const mod = req(entryPath);
1880
1858
  const fn = getRegisterFn(mod);
@@ -1902,7 +1880,7 @@ function loadExtensionForDescriptorSync(descriptor, configFilePath, stepLog) {
1902
1880
  if (typeof fn === "function") {
1903
1881
  const installed = getInstalledPackageVersionFromRequire(parsed.packageName, configRequire);
1904
1882
  const requested = parsed.version === "latest" || !parsed.version?.trim() ? null : parsed.version;
1905
- const resolvedVersion = requested === null ? agentCommon.resolveLatestVersionFromRegistry(parsed.packageName) : requested;
1883
+ const resolvedVersion = requested === null ? npm.resolveLatestVersionFromRegistry(parsed.packageName) : requested;
1906
1884
  if (installed === resolvedVersion) {
1907
1885
  if (stepLog) stepLog(`Loaded ${parsed.packageName}@${resolvedVersion} from node_modules`);
1908
1886
  return { register: fn, descriptor: entryStr, resolvedVersion };
@@ -1915,9 +1893,9 @@ function loadExtensionForDescriptorSync(descriptor, configFilePath, stepLog) {
1915
1893
  const cacheOpts = cacheBase ? { cacheBase } : {};
1916
1894
  for (const opts of [cacheOpts, {}]) {
1917
1895
  try {
1918
- const cacheDir = agentCommon.ensurePackageInCache(parsed.packageName, parsed.version, opts);
1896
+ const cacheDir = npm.ensurePackageInCache(parsed.packageName, parsed.version, opts);
1919
1897
  if (stepLog) stepLog(`Loaded ${parsed.packageName} from cache: ${cacheDir}`);
1920
- const entryPath = agentCommon.getPackageEntryPath(cacheDir);
1898
+ const entryPath = npm.getPackageEntryPath(cacheDir);
1921
1899
  const req = module$1.createRequire(path.join(cacheDir, "package.json"));
1922
1900
  const mod = req(entryPath);
1923
1901
  const fn = getRegisterFn(mod);
@@ -1974,9 +1952,9 @@ async function loadExtensionForDescriptorAsync(descriptor, configFilePath, stepL
1974
1952
  const cacheOpts = cacheBase ? { cacheBase } : {};
1975
1953
  for (const opts of [cacheOpts, {}]) {
1976
1954
  try {
1977
- const cacheDir = agentCommon.ensurePackageInCache(parsed.packageName, parsed.version, opts);
1955
+ const cacheDir = npm.ensurePackageInCache(parsed.packageName, parsed.version, opts);
1978
1956
  if (stepLog) stepLog(`Loaded ${parsed.packageName} from cache (async): ${cacheDir}`);
1979
- const mod = await agentCommon.importFromCache(cacheDir);
1957
+ const mod = await npm.importFromCache(cacheDir);
1980
1958
  const fn = getRegisterFn(mod);
1981
1959
  if (typeof fn === "function") {
1982
1960
  const resolvedVersion = path.basename(cacheDir);
@@ -2034,7 +2012,7 @@ function createRuntimeFromConfigSync(options = {}) {
2034
2012
  if (extensionNode) {
2035
2013
  if (stepLog) stepLog("Registered extension from node_modules");
2036
2014
  const descriptor = `npm:${extensionNode.packageName}`;
2037
- const resolvedVersion = getInstalledPackageVersion(extensionNode.packageName) ?? agentCommon.resolveLatestVersionFromRegistry(extensionNode.packageName);
2015
+ const resolvedVersion = getInstalledPackageVersion(extensionNode.packageName) ?? npm.resolveLatestVersionFromRegistry(extensionNode.packageName);
2038
2016
  const prefix = npmDescriptorToRegistryPrefix(descriptor, resolvedVersion);
2039
2017
  const reg = prefix ? createPrefixingRegistry(registry, prefix) : registry;
2040
2018
  const coreAdapter = extensionNode.register(reg, options.coreTools);
@@ -2068,43 +2046,487 @@ async function createRuntimeFromConfig(options = {}) {
2068
2046
  return createRuntimeFromConfigSync(options);
2069
2047
  }
2070
2048
 
2049
+ // src/api/expose/openapi.ts
2050
+ function toolNameToSlug(name) {
2051
+ return name.replace(/\./g, "~");
2052
+ }
2053
+ function slugToToolName(slug) {
2054
+ return slug.replace(/~/g, ".");
2055
+ }
2056
+ function toolSchemaKey(name) {
2057
+ return `Tool_${name.replace(/[^a-zA-Z0-9_]/g, "_")}`;
2058
+ }
2059
+ var resultSchema = {
2060
+ type: "object",
2061
+ properties: {
2062
+ result: { description: "Tool return value", additionalProperties: true }
2063
+ }
2064
+ };
2065
+ var errorSchema = {
2066
+ type: "object",
2067
+ properties: {
2068
+ error: { type: "string" },
2069
+ kind: { type: "string" },
2070
+ details: { type: "object", additionalProperties: true }
2071
+ }
2072
+ };
2073
+ function toolsToOpenAPISpec(registry, options = {}) {
2074
+ const title = options.title ?? "Tool API";
2075
+ const version = options.version ?? "1.0.0";
2076
+ const basePath = (options.basePath ?? "").replace(/\/$/, "");
2077
+ const specs = registry.snapshot().map(chunkUUNG3GL3_cjs.enrichSpecWithCanonicalSchema);
2078
+ const toolNamesSchema = {
2079
+ type: "object",
2080
+ required: ["tools"],
2081
+ properties: {
2082
+ tools: {
2083
+ type: "array",
2084
+ items: {
2085
+ type: "object",
2086
+ properties: {
2087
+ name: { type: "string" },
2088
+ description: { type: "string" },
2089
+ kind: { type: "string" }
2090
+ }
2091
+ }
2092
+ }
2093
+ }
2094
+ };
2095
+ const invokeRequestBody = {
2096
+ type: "object",
2097
+ required: ["tool", "args"],
2098
+ properties: {
2099
+ tool: { type: "string", description: "Tool name (e.g. from GET /tools)" },
2100
+ args: {
2101
+ type: "object",
2102
+ description: "Tool arguments (schema per tool; use per-tool paths for typed schema)",
2103
+ additionalProperties: true
2104
+ }
2105
+ }
2106
+ };
2107
+ const prefix = basePath ? `${basePath}/` : "/";
2108
+ const paths = {
2109
+ [`${prefix}tools`]: {
2110
+ get: {
2111
+ summary: "List tools",
2112
+ description: "Returns all registered tool names and descriptions.",
2113
+ operationId: "listTools",
2114
+ responses: {
2115
+ "200": {
2116
+ description: "List of tools",
2117
+ content: {
2118
+ "application/json": {
2119
+ schema: toolNamesSchema
2120
+ }
2121
+ }
2122
+ }
2123
+ }
2124
+ }
2125
+ },
2126
+ [`${prefix}invoke`]: {
2127
+ post: {
2128
+ summary: "Invoke a tool (generic)",
2129
+ description: "Call any tool by name with body { tool, args }. For typed schemas use POST /invoke/{toolSlug}.",
2130
+ operationId: "invokeTool",
2131
+ requestBody: {
2132
+ required: true,
2133
+ content: {
2134
+ "application/json": {
2135
+ schema: invokeRequestBody
2136
+ }
2137
+ }
2138
+ },
2139
+ responses: {
2140
+ "200": {
2141
+ description: "Tool result",
2142
+ content: { "application/json": { schema: resultSchema } }
2143
+ },
2144
+ "400": {
2145
+ description: "Bad request",
2146
+ content: { "application/json": { schema: errorSchema } }
2147
+ }
2148
+ }
2149
+ }
2150
+ }
2151
+ };
2152
+ const schemaEntries = [];
2153
+ for (const s of specs) {
2154
+ const key = toolSchemaKey(s.name);
2155
+ schemaEntries.push([key, s.inputSchema]);
2156
+ const slug = toolNameToSlug(s.name);
2157
+ paths[`${prefix}invoke/${slug}`] = {
2158
+ post: {
2159
+ summary: s.description ?? s.name,
2160
+ description: `Invoke tool \`${s.name}\`. Request body is the tool's arguments (JSON Schema below).`,
2161
+ operationId: `invoke_${key}`,
2162
+ requestBody: {
2163
+ required: true,
2164
+ content: {
2165
+ "application/json": {
2166
+ schema: { $ref: `#/components/schemas/${key}` }
2167
+ }
2168
+ }
2169
+ },
2170
+ responses: {
2171
+ "200": {
2172
+ description: "Tool result",
2173
+ content: { "application/json": { schema: resultSchema } }
2174
+ },
2175
+ "400": {
2176
+ description: "Bad request (invalid args or tool error)",
2177
+ content: { "application/json": { schema: errorSchema } }
2178
+ }
2179
+ }
2180
+ }
2181
+ };
2182
+ }
2183
+ return {
2184
+ openapi: "3.0.3",
2185
+ info: { title, version },
2186
+ paths,
2187
+ components: {
2188
+ schemas: Object.fromEntries(schemaEntries)
2189
+ }
2190
+ };
2191
+ }
2192
+
2193
+ // src/api/expose/openapiHttp.ts
2194
+ var DEFAULT_CTX = {
2195
+ requestId: `http-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
2196
+ taskId: `task-${Date.now()}`,
2197
+ permissions: [
2198
+ "read:web",
2199
+ "read:fs",
2200
+ "write:fs",
2201
+ "read:db",
2202
+ "write:db",
2203
+ "network",
2204
+ "workflow",
2205
+ "danger:destructive"
2206
+ ]
2207
+ };
2208
+ function parseBody(req) {
2209
+ return new Promise((resolve4, reject) => {
2210
+ const chunks = [];
2211
+ req.on("data", (chunk) => chunks.push(chunk));
2212
+ req.on("end", () => {
2213
+ const raw = Buffer.concat(chunks).toString("utf-8");
2214
+ if (!raw.trim()) {
2215
+ resolve4({});
2216
+ return;
2217
+ }
2218
+ try {
2219
+ resolve4(JSON.parse(raw));
2220
+ } catch {
2221
+ reject(new Error("Invalid JSON body"));
2222
+ }
2223
+ });
2224
+ req.on("error", reject);
2225
+ });
2226
+ }
2227
+ function sendJson(res, status, data) {
2228
+ res.writeHead(status, { "Content-Type": "application/json" });
2229
+ res.end(JSON.stringify(data));
2230
+ }
2231
+ function swaggerUiHtml(specUrl) {
2232
+ const specUrlEscaped = specUrl.replace(/"/g, "&quot;");
2233
+ return `<!DOCTYPE html>
2234
+ <html lang="en">
2235
+ <head>
2236
+ <meta charset="UTF-8">
2237
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2238
+ <title>Tool API \u2013 Swagger UI</title>
2239
+ <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css">
2240
+ </head>
2241
+ <body>
2242
+ <div id="swagger-ui"></div>
2243
+ <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js" crossorigin></script>
2244
+ <script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-standalone-preset.js" crossorigin></script>
2245
+ <script>
2246
+ window.onload = function() {
2247
+ window.ui = SwaggerUIBundle({
2248
+ url: "${specUrlEscaped}",
2249
+ dom_id: "#swagger-ui",
2250
+ deepLinking: true,
2251
+ presets: [
2252
+ SwaggerUIBundle.presets.apis,
2253
+ SwaggerUIStandalonePreset
2254
+ ],
2255
+ layout: "StandaloneLayout"
2256
+ });
2257
+ };
2258
+ </script>
2259
+ </body>
2260
+ </html>`;
2261
+ }
2262
+ function createOpenAPIHttpServer(runtime, options = {}) {
2263
+ const basePath = (options.basePath ?? "").replace(/\/$/, "");
2264
+ const ctxFactory = options.execContextFactory ?? (() => ({ ...DEFAULT_CTX }));
2265
+ const server = http.createServer(async (req, res) => {
2266
+ const url = req.url ?? "/";
2267
+ const path = url.split("?")[0] ?? "/";
2268
+ const norm = basePath ? path === basePath ? "" : path.replace(basePath, "") || "/" : path;
2269
+ try {
2270
+ if (req.method === "GET" && (norm === "/" || norm === "/swagger")) {
2271
+ const specPath = basePath ? `${basePath}/openapi.json` : "/openapi.json";
2272
+ const html = swaggerUiHtml(specPath);
2273
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2274
+ res.end(html);
2275
+ return;
2276
+ }
2277
+ if (req.method === "GET" && (norm === "/openapi.json" || norm === "/spec")) {
2278
+ const spec = toolsToOpenAPISpec(runtime.getRegistry(), {
2279
+ title: "Tool API",
2280
+ version: "1.0.0",
2281
+ basePath: basePath || void 0
2282
+ });
2283
+ sendJson(res, 200, spec);
2284
+ return;
2285
+ }
2286
+ if (req.method === "GET" && norm === "/tools") {
2287
+ const { enrichSpecWithCanonicalSchema: enrichSpecWithCanonicalSchema2 } = await import('./canonicalCoreSchemas-TY7NCWCC.cjs');
2288
+ const specs = runtime.getRegistry().snapshot().map(enrichSpecWithCanonicalSchema2);
2289
+ const tools = specs.map((s) => ({
2290
+ name: s.name,
2291
+ description: s.description,
2292
+ kind: s.kind,
2293
+ inputSchema: s.inputSchema
2294
+ }));
2295
+ sendJson(res, 200, { tools });
2296
+ return;
2297
+ }
2298
+ if (req.method === "POST" && norm === "/invoke") {
2299
+ const body = await parseBody(req);
2300
+ const tool = body?.tool;
2301
+ const args = body?.args ?? {};
2302
+ if (typeof tool !== "string" || !tool.trim()) {
2303
+ sendJson(res, 400, { error: "Missing or invalid 'tool' in body", kind: "BAD_REQUEST" });
2304
+ return;
2305
+ }
2306
+ const ctx = ctxFactory(req);
2307
+ const result = await runtime.invoke(
2308
+ { tool: tool.trim(), args, purpose: "openapi" },
2309
+ ctx
2310
+ );
2311
+ if (result.ok) {
2312
+ sendJson(res, 200, { result: result.result });
2313
+ return;
2314
+ }
2315
+ sendJson(res, 400, {
2316
+ error: result.error?.message ?? "Tool failed",
2317
+ kind: result.error?.kind,
2318
+ details: result.error?.details
2319
+ });
2320
+ return;
2321
+ }
2322
+ if (req.method === "POST" && norm.startsWith("/invoke/") && norm.length > "/invoke/".length) {
2323
+ const slug = norm.slice("/invoke/".length);
2324
+ const toolName = slugToToolName(slug);
2325
+ let args;
2326
+ try {
2327
+ args = await parseBody(req);
2328
+ } catch {
2329
+ sendJson(res, 400, { error: "Invalid JSON body", kind: "BAD_REQUEST" });
2330
+ return;
2331
+ }
2332
+ const ctx = ctxFactory(req);
2333
+ const result = await runtime.invoke(
2334
+ { tool: toolName, args: args ?? {}, purpose: "openapi" },
2335
+ ctx
2336
+ );
2337
+ if (result.ok) {
2338
+ sendJson(res, 200, { result: result.result });
2339
+ return;
2340
+ }
2341
+ sendJson(res, 400, {
2342
+ error: result.error?.message ?? "Tool failed",
2343
+ kind: result.error?.kind,
2344
+ details: result.error?.details
2345
+ });
2346
+ return;
2347
+ }
2348
+ res.writeHead(404, { "Content-Type": "application/json" });
2349
+ res.end(JSON.stringify({ error: "Not found", path: norm }));
2350
+ } catch (err) {
2351
+ const message = err instanceof Error ? err.message : String(err);
2352
+ sendJson(res, 500, { error: message, kind: "INTERNAL_ERROR" });
2353
+ }
2354
+ });
2355
+ return server;
2356
+ }
2357
+ function listenOpenAPIHttpServer(server, options = {}) {
2358
+ return new Promise((resolve4, reject) => {
2359
+ const port = options.port ?? 0;
2360
+ const host = options.host ?? "localhost";
2361
+ server.listen(port, host, () => {
2362
+ const addr = server.address();
2363
+ const actualPort = typeof addr === "object" && addr?.port != null ? addr.port : port;
2364
+ resolve4({ port: actualPort, host });
2365
+ });
2366
+ server.on("error", reject);
2367
+ });
2368
+ }
2369
+ async function createHttpService(runtimeOrConfig, options = {}) {
2370
+ const runtime = "invoke" in runtimeOrConfig && typeof runtimeOrConfig.invoke === "function" ? runtimeOrConfig : (await createRuntimeFromConfig(runtimeOrConfig)).runtime;
2371
+ const server = createOpenAPIHttpServer(runtime, options);
2372
+ const openApiSpec = toolsToOpenAPISpec(runtime.getRegistry(), {
2373
+ title: options.title ?? "Tool API",
2374
+ version: options.version ?? "1.0.0",
2375
+ basePath: options.basePath
2376
+ });
2377
+ return {
2378
+ server,
2379
+ openApiSpec,
2380
+ listen: (listenOpts) => listenOpenAPIHttpServer(server, listenOpts)
2381
+ };
2382
+ }
2383
+
2071
2384
  // src/tools/mcp/types.ts
2072
2385
  var MCP_KIND = "mcp";
2073
2386
 
2387
+ // src/api/expose/mcpServer.ts
2388
+ var DEFAULT_CTX2 = {
2389
+ requestId: `mcp-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
2390
+ taskId: `task-${Date.now()}`,
2391
+ permissions: [
2392
+ "read:web",
2393
+ "read:fs",
2394
+ "write:fs",
2395
+ "read:db",
2396
+ "write:db",
2397
+ "network",
2398
+ "workflow",
2399
+ "danger:destructive"
2400
+ ]
2401
+ };
2402
+ function toMcpToolName(registryName) {
2403
+ return chunkDYDNPIV2_cjs.normalizeToolName(registryName);
2404
+ }
2405
+ async function createMcpServerWithTools(runtime, options) {
2406
+ const { McpServer } = await import('@modelcontextprotocol/sdk/server/mcp.js');
2407
+ const name = options.name ?? "agent-tool";
2408
+ const version = options.version ?? "1.0.0";
2409
+ const ctxFactory = options.execContextFactory ?? (() => ({ ...DEFAULT_CTX2 }));
2410
+ const server = new McpServer({ name, version });
2411
+ const registry = runtime.getRegistry();
2412
+ const specs = registry.snapshot();
2413
+ for (const spec of specs) {
2414
+ const mcpName = toMcpToolName(spec.name);
2415
+ server.registerTool(
2416
+ mcpName,
2417
+ {
2418
+ description: spec.description ?? `Tool: ${spec.name}`,
2419
+ inputSchema: spec.inputSchema,
2420
+ _meta: spec._meta
2421
+ },
2422
+ async (args) => {
2423
+ const ctx = ctxFactory();
2424
+ const result = await runtime.invoke(
2425
+ { tool: spec.name, args: args ?? {}, purpose: MCP_KIND },
2426
+ ctx
2427
+ );
2428
+ if (result.ok) {
2429
+ return { content: [{ type: "text", text: JSON.stringify(result.result) }] };
2430
+ }
2431
+ const err = result.error;
2432
+ return {
2433
+ content: [
2434
+ {
2435
+ type: "text",
2436
+ text: JSON.stringify({ error: err?.message ?? "Tool failed", kind: err?.kind })
2437
+ }
2438
+ ],
2439
+ isError: true
2440
+ };
2441
+ }
2442
+ );
2443
+ }
2444
+ return { server };
2445
+ }
2446
+ async function createMCPServer(runtimeOrConfig, options = {}) {
2447
+ const runtime = "invoke" in runtimeOrConfig && typeof runtimeOrConfig.invoke === "function" ? runtimeOrConfig : (await createRuntimeFromConfig(runtimeOrConfig)).runtime;
2448
+ const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
2449
+ const { server } = await createMcpServerWithTools(runtime, options);
2450
+ return {
2451
+ server,
2452
+ async connectStdio() {
2453
+ const transport = new StdioServerTransport();
2454
+ await server.connect(transport);
2455
+ }
2456
+ };
2457
+ }
2458
+ function createMCPStreamableHttpHandler(runtimeOrConfig, options = {}) {
2459
+ if ("invoke" in runtimeOrConfig && typeof runtimeOrConfig.invoke === "function") {
2460
+ const runtime = runtimeOrConfig;
2461
+ return async function streamableHttpHandler(req, res, parsedBody) {
2462
+ const { StreamableHTTPServerTransport } = await import('@modelcontextprotocol/sdk/server/streamableHttp.js');
2463
+ const { server } = await createMcpServerWithTools(runtime, options);
2464
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
2465
+ await server.connect(transport);
2466
+ const onClose = () => {
2467
+ transport.close().catch(() => {
2468
+ });
2469
+ server.close().catch(() => {
2470
+ });
2471
+ res.removeListener("close", onClose);
2472
+ res.removeListener("finish", onClose);
2473
+ };
2474
+ res.once("close", onClose);
2475
+ res.once("finish", onClose);
2476
+ await transport.handleRequest(
2477
+ req,
2478
+ res,
2479
+ parsedBody
2480
+ );
2481
+ };
2482
+ }
2483
+ return (async () => {
2484
+ const { runtime } = await createRuntimeFromConfig(runtimeOrConfig);
2485
+ return createMCPStreamableHttpHandler(runtime, options);
2486
+ })();
2487
+ }
2488
+ async function createMCPServerStreamableHttp(runtimeOrConfig, options = {}) {
2489
+ const path = options.path ?? "/mcp";
2490
+ const host = options.host ?? "127.0.0.1";
2491
+ const port = options.port ?? 3e3;
2492
+ const { createMcpExpressApp } = await import('@modelcontextprotocol/sdk/server/express.js');
2493
+ const handler = "invoke" in runtimeOrConfig && typeof runtimeOrConfig.invoke === "function" ? createMCPStreamableHttpHandler(runtimeOrConfig, options) : await createMCPStreamableHttpHandler(runtimeOrConfig, options);
2494
+ const app = createMcpExpressApp({ host });
2495
+ app.post(path, handler);
2496
+ return {
2497
+ app,
2498
+ path,
2499
+ async listen(listenPort, listenHost) {
2500
+ const p = listenPort ?? port;
2501
+ const h = listenHost ?? host;
2502
+ return new Promise((resolve4, reject) => {
2503
+ const server = app.listen(p, h, () => {
2504
+ const addr = server.address();
2505
+ const actualPort = typeof addr === "object" && addr !== null && "port" in addr ? addr.port : p;
2506
+ resolve4({ url: `http://${h}:${actualPort}${path}`, port: actualPort });
2507
+ });
2508
+ });
2509
+ }
2510
+ };
2511
+ }
2512
+ async function runMCPServerOverStdio(runtime, options = {}) {
2513
+ const result = await createMCPServer(runtime, options);
2514
+ await result.connectStdio();
2515
+ return result;
2516
+ }
2517
+
2074
2518
  // src/tools/langchain/types.ts
2075
2519
  var LANGCHAIN_KIND = "langchain";
2076
2520
  var LANGCHAIN_DIR_NAME = "langchain";
2077
2521
 
2078
- Object.defineProperty(exports, "ensurePackageInCache", {
2079
- enumerable: true,
2080
- get: function () { return agentCommon.ensurePackageInCache; }
2081
- });
2082
- Object.defineProperty(exports, "getPackageEntryPath", {
2083
- enumerable: true,
2084
- get: function () { return agentCommon.getPackageEntryPath; }
2085
- });
2086
- Object.defineProperty(exports, "importFromCache", {
2087
- enumerable: true,
2088
- get: function () { return agentCommon.importFromCache; }
2089
- });
2090
- Object.defineProperty(exports, "resolveLatestVersionFromRegistry", {
2091
- enumerable: true,
2092
- get: function () { return agentCommon.resolveLatestVersionFromRegistry; }
2093
- });
2094
- exports.BudgetManager = BudgetManager;
2095
- exports.EventLog = EventLog;
2096
2522
  exports.LANGCHAIN_DIR_NAME = LANGCHAIN_DIR_NAME;
2097
2523
  exports.LANGCHAIN_KIND = LANGCHAIN_KIND;
2098
2524
  exports.MCP_KIND = MCP_KIND;
2099
- exports.Metrics = Metrics;
2100
2525
  exports.PTCRuntime = PTCRuntime;
2101
- exports.PolicyDeniedError = PolicyDeniedError;
2102
- exports.PolicyEngine = PolicyEngine;
2103
- exports.SchemaValidationError = SchemaValidationError;
2104
- exports.SchemaValidator = SchemaValidator;
2105
- exports.Tracing = Tracing;
2106
- exports.buildEvidence = buildEvidence;
2107
- exports.createLogger = createLogger;
2526
+ exports.createHttpService = createHttpService;
2527
+ exports.createMCPServer = createMCPServer;
2528
+ exports.createMCPServerStreamableHttp = createMCPServerStreamableHttp;
2529
+ exports.createMCPStreamableHttpHandler = createMCPStreamableHttpHandler;
2108
2530
  exports.createRuntimeFromConfig = createRuntimeFromConfig;
2109
2531
  exports.createRuntimeFromConfigSync = createRuntimeFromConfigSync;
2110
2532
  exports.expandToolDescriptorsToRegistryNames = expandToolDescriptorsToRegistryNames;
@@ -2112,18 +2534,12 @@ exports.fileDescriptorToPackagePrefix = fileDescriptorToPackagePrefix;
2112
2534
  exports.findAndLoadToolConfig = findAndLoadToolConfig;
2113
2535
  exports.getDisplayScope = getDisplayScope;
2114
2536
  exports.isBarePackageDescriptor = isBarePackageDescriptor;
2115
- exports.isNpmToolDescriptor = isNpmToolDescriptor;
2116
2537
  exports.loadToolConfig = loadToolConfig;
2117
- exports.normalizeToolList = normalizeToolList;
2118
2538
  exports.npmDescriptorToPackagePrefixWithVersion = npmDescriptorToPackagePrefixWithVersion;
2119
- exports.npmDescriptorToRegistryPrefix = npmDescriptorToRegistryPrefix;
2120
- exports.parseNpmToolDescriptor = parseNpmToolDescriptor;
2121
- exports.resolveNpmToolDescriptor = resolveNpmToolDescriptor;
2122
2539
  exports.resolveSandboxedPath = resolveSandboxedPath;
2123
2540
  exports.resolveSandboxedPath2 = resolveSandboxedPath2;
2124
2541
  exports.resolveToolDescriptor = resolveToolDescriptor;
2125
- exports.sanitizeForLog = sanitizeForLog;
2542
+ exports.runMCPServerOverStdio = runMCPServerOverStdio;
2126
2543
  exports.setSandboxValidationEnabled = setSandboxValidationEnabled;
2127
- exports.summarizeForLog = summarizeForLog;
2128
- //# sourceMappingURL=chunk-YVL3UMM2.cjs.map
2129
- //# sourceMappingURL=chunk-YVL3UMM2.cjs.map
2544
+ //# sourceMappingURL=chunk-A5B6Q6EG.cjs.map
2545
+ //# sourceMappingURL=chunk-A5B6Q6EG.cjs.map