@botbotgo/agent-harness 0.0.475 → 0.0.476

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 (227) hide show
  1. package/README.md +3 -1234
  2. package/README.zh.md +3 -1191
  3. package/dist/acp.js +1 -1
  4. package/dist/api.js +1 -404
  5. package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
  6. package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
  7. package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
  8. package/dist/cli/chat-interactive.js +25 -244
  9. package/dist/cli/chat-rendering.js +6 -100
  10. package/dist/cli/chat-stream.js +23 -512
  11. package/dist/cli/chat-ui.js +21 -199
  12. package/dist/cli/chat-workspace.js +2 -210
  13. package/dist/cli/main.js +21 -428
  14. package/dist/cli/managed-service-commands.js +9 -63
  15. package/dist/cli/managed-service.js +2 -137
  16. package/dist/cli/options-init-chat.js +1 -108
  17. package/dist/cli/options-runtime.js +1 -158
  18. package/dist/cli/options-serve.js +1 -282
  19. package/dist/cli/options.js +2 -19
  20. package/dist/cli/process-guards.js +1 -139
  21. package/dist/cli/request-tree.js +7 -296
  22. package/dist/cli/runtime-commands.js +12 -258
  23. package/dist/cli/runtime-output.js +16 -155
  24. package/dist/cli/server-commands.js +16 -270
  25. package/dist/cli/workspace.js +1 -67
  26. package/dist/cli.js +1 -7
  27. package/dist/client/acp.js +1 -1
  28. package/dist/client/in-process.js +1 -67
  29. package/dist/client/index.js +1 -2
  30. package/dist/client/types.js +0 -1
  31. package/dist/client.js +1 -1
  32. package/dist/contracts/core.js +1 -1
  33. package/dist/contracts/runtime-evaluation.js +0 -1
  34. package/dist/contracts/runtime-memory.js +0 -1
  35. package/dist/contracts/runtime-observability.js +0 -1
  36. package/dist/contracts/runtime-requests.js +0 -1
  37. package/dist/contracts/runtime-scheduling.js +0 -1
  38. package/dist/contracts/runtime.js +1 -27
  39. package/dist/contracts/types.js +1 -3
  40. package/dist/contracts/workspace.js +0 -1
  41. package/dist/flow/build-flow-graph.js +1 -50
  42. package/dist/flow/export-mermaid.js +2 -464
  43. package/dist/flow/export-sequence-mermaid.js +2 -325
  44. package/dist/flow/flow-graph-normalization.js +1 -214
  45. package/dist/flow/flow-graph-runtime.js +1 -107
  46. package/dist/flow/flow-graph-upstream.js +1 -494
  47. package/dist/flow/index.js +1 -3
  48. package/dist/flow/types.js +0 -1
  49. package/dist/index.js +1 -5
  50. package/dist/init-project.js +1 -1
  51. package/dist/knowledge/config.js +1 -32
  52. package/dist/knowledge/contracts.js +0 -1
  53. package/dist/knowledge/index.js +1 -2
  54. package/dist/knowledge/module.js +12 -909
  55. package/dist/knowledge/procedural/config.js +1 -125
  56. package/dist/knowledge/procedural/index.js +1 -2
  57. package/dist/knowledge/procedural/manager.js +9 -345
  58. package/dist/mcp.js +1 -2
  59. package/dist/package-version.d.ts +1 -1
  60. package/dist/package-version.js +1 -2
  61. package/dist/persistence/file-store.js +3 -758
  62. package/dist/persistence/sqlite-request-context-store.js +5 -54
  63. package/dist/persistence/sqlite-request-queue-store.js +10 -108
  64. package/dist/persistence/sqlite-runtime.js +1 -86
  65. package/dist/persistence/sqlite-store.js +62 -810
  66. package/dist/persistence/types.js +0 -1
  67. package/dist/projections/presentation.js +37 -206
  68. package/dist/projections/request-events.js +2 -502
  69. package/dist/projections/upstream-events.js +1 -201
  70. package/dist/protocol/a2a/http-discovery.js +1 -178
  71. package/dist/protocol/a2a/http-rpc.js +6 -622
  72. package/dist/protocol/a2a/http.js +1 -138
  73. package/dist/protocol/a2a/task-state.js +3 -317
  74. package/dist/protocol/acp/client.js +8 -294
  75. package/dist/protocol/acp/harness-client.js +1 -218
  76. package/dist/protocol/acp/http.js +5 -130
  77. package/dist/protocol/acp/server.js +1 -310
  78. package/dist/protocol/acp/stdio.js +2 -69
  79. package/dist/protocol/ag-ui/http.js +3 -378
  80. package/dist/protocol/mcp/server.js +1 -428
  81. package/dist/resource/backend/workspace-scoped-backend.js +1 -319
  82. package/dist/resource/isolation.js +1 -237
  83. package/dist/resource/mcp/tool-support.js +3 -296
  84. package/dist/resource/mcp-tool-support.js +1 -2
  85. package/dist/resource/providers/resource-provider.js +1 -215
  86. package/dist/resource/resource-impl.js +1 -3
  87. package/dist/resource/resource-types.js +0 -1
  88. package/dist/resource/resource.js +1 -1
  89. package/dist/resource/sources.js +1 -247
  90. package/dist/resource/tools/function-tool-resolver.js +2 -272
  91. package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
  92. package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
  93. package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
  94. package/dist/runtime/adapter/flow/execution-context.js +1 -71
  95. package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
  96. package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
  97. package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
  98. package/dist/runtime/adapter/invocation-result.js +2 -473
  99. package/dist/runtime/adapter/local-tool-invocation.js +6 -638
  100. package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
  101. package/dist/runtime/adapter/middleware-assembly.js +5 -477
  102. package/dist/runtime/adapter/model/invocation-request.js +3 -183
  103. package/dist/runtime/adapter/model/message-assembly.js +1 -28
  104. package/dist/runtime/adapter/model/model-providers.js +23 -1115
  105. package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
  106. package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
  107. package/dist/runtime/adapter/resilience.js +1 -104
  108. package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
  109. package/dist/runtime/adapter/runtime-shell.js +5 -166
  110. package/dist/runtime/adapter/stream-event-projection.js +2 -622
  111. package/dist/runtime/adapter/stream-text-consumption.js +1 -18
  112. package/dist/runtime/adapter/terminal-status.js +2 -67
  113. package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
  114. package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
  115. package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
  116. package/dist/runtime/adapter/tool/provider-tool.js +1 -25
  117. package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
  118. package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
  119. package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
  120. package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
  121. package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
  122. package/dist/runtime/adapter/tool/tool-replay.js +1 -37
  123. package/dist/runtime/adapter/tool-resolution.js +1 -86
  124. package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
  125. package/dist/runtime/agent-runtime-adapter.js +60 -2338
  126. package/dist/runtime/agent-runtime-assembly.js +7 -249
  127. package/dist/runtime/env/runtime-env.js +1 -62
  128. package/dist/runtime/harness/background-runtime.js +1 -8
  129. package/dist/runtime/harness/bindings.js +1 -58
  130. package/dist/runtime/harness/events/event-bus.js +1 -16
  131. package/dist/runtime/harness/events/event-sink.js +1 -61
  132. package/dist/runtime/harness/events/events.js +1 -80
  133. package/dist/runtime/harness/events/listener-runtime.js +1 -13
  134. package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
  135. package/dist/runtime/harness/events/streaming.js +1 -100
  136. package/dist/runtime/harness/events/timeline.js +1 -52
  137. package/dist/runtime/harness/public-shapes.js +1 -186
  138. package/dist/runtime/harness/run/artifact-paths.js +1 -15
  139. package/dist/runtime/harness/run/governance.js +1 -295
  140. package/dist/runtime/harness/run/helpers.js +1 -71
  141. package/dist/runtime/harness/run/inspection.js +1 -409
  142. package/dist/runtime/harness/run/operator-overview.js +1 -80
  143. package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
  144. package/dist/runtime/harness/run/recovery.js +1 -162
  145. package/dist/runtime/harness/run/resources.js +1 -60
  146. package/dist/runtime/harness/run/resume.js +1 -56
  147. package/dist/runtime/harness/run/routing.js +1 -48
  148. package/dist/runtime/harness/run/run-lifecycle.js +1 -66
  149. package/dist/runtime/harness/run/run-operations.js +1 -217
  150. package/dist/runtime/harness/run/run-queue.js +1 -43
  151. package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
  152. package/dist/runtime/harness/run/session-records.js +1 -97
  153. package/dist/runtime/harness/run/start-run.js +1 -120
  154. package/dist/runtime/harness/run/startup-runtime.js +1 -69
  155. package/dist/runtime/harness/run/stream-run.js +8 -1418
  156. package/dist/runtime/harness/run/surface-semantics.js +1 -79
  157. package/dist/runtime/harness/runtime-defaults.js +1 -39
  158. package/dist/runtime/harness/system/boundary-analysis.js +1 -234
  159. package/dist/runtime/harness/system/health-monitor.js +1 -258
  160. package/dist/runtime/harness/system/inventory.js +1 -129
  161. package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
  162. package/dist/runtime/harness/system/policy-engine.js +1 -175
  163. package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
  164. package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
  165. package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
  166. package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
  167. package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
  168. package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
  169. package/dist/runtime/harness/system/session-memory-sync.js +3 -113
  170. package/dist/runtime/harness/system/skill-requirements.js +1 -112
  171. package/dist/runtime/harness/system/store.js +9 -365
  172. package/dist/runtime/harness/tool-gateway/index.js +1 -2
  173. package/dist/runtime/harness/tool-gateway/policy.js +1 -45
  174. package/dist/runtime/harness/tool-gateway/validation.js +1 -176
  175. package/dist/runtime/harness/tool-schema.js +1 -3
  176. package/dist/runtime/harness.js +3 -1490
  177. package/dist/runtime/index.js +1 -3
  178. package/dist/runtime/layout/runtime-layout.js +1 -31
  179. package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
  180. package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
  181. package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
  182. package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
  183. package/dist/runtime/parsing/output-content.js +10 -550
  184. package/dist/runtime/parsing/output-parsing.js +1 -4
  185. package/dist/runtime/parsing/output-recovery.js +3 -213
  186. package/dist/runtime/parsing/output-tool-args.js +7 -663
  187. package/dist/runtime/parsing/stream-event-parsing.js +3 -362
  188. package/dist/runtime/prompts/runtime-prompts.js +4 -73
  189. package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
  190. package/dist/runtime/skills/skill-metadata.js +1 -197
  191. package/dist/runtime/startup-tracing.js +2 -37
  192. package/dist/runtime/support/compiled-binding.js +1 -290
  193. package/dist/runtime/support/embedding-models.js +1 -118
  194. package/dist/runtime/support/harness-support.js +5 -137
  195. package/dist/runtime/support/llamaindex.js +1 -108
  196. package/dist/runtime/support/runtime-adapter-options.js +1 -29
  197. package/dist/runtime/support/runtime-factories.js +1 -51
  198. package/dist/runtime/support/vector-stores.js +9 -270
  199. package/dist/scaffold/init-project.js +54 -233
  200. package/dist/tooling/extensions.js +1 -311
  201. package/dist/tooling/module-loader.js +1 -55
  202. package/dist/tools.js +1 -176
  203. package/dist/utils/agent-display.js +1 -18
  204. package/dist/utils/bundled-text.js +4 -39
  205. package/dist/utils/compiled-binding.js +1 -33
  206. package/dist/utils/fs.js +2 -45
  207. package/dist/utils/id.js +1 -9
  208. package/dist/utils/message-content.js +1 -30
  209. package/dist/utils/object.js +1 -6
  210. package/dist/workspace/agent-binding-compiler.js +3 -613
  211. package/dist/workspace/compile.js +1 -472
  212. package/dist/workspace/framework-contract-validation.js +2 -322
  213. package/dist/workspace/index.js +1 -1
  214. package/dist/workspace/object-loader-paths.js +1 -71
  215. package/dist/workspace/object-loader-readers.js +1 -187
  216. package/dist/workspace/object-loader.js +1 -754
  217. package/dist/workspace/resource-compilers.js +1 -374
  218. package/dist/workspace/support/agent-capabilities.js +1 -37
  219. package/dist/workspace/support/agent-execution-config.js +1 -44
  220. package/dist/workspace/support/discovery.js +1 -147
  221. package/dist/workspace/support/source-collectors.js +1 -30
  222. package/dist/workspace/support/source-protocols.js +2 -192
  223. package/dist/workspace/support/workspace-ref-utils.js +1 -362
  224. package/dist/workspace/tool-hydration.js +1 -280
  225. package/dist/workspace/validate.js +1 -99
  226. package/dist/workspace/yaml-object-reader.js +1 -285
  227. package/package.json +7 -3
@@ -1,247 +1 @@
1
- import { execFile } from "node:child_process";
2
- import { existsSync, statSync } from "node:fs";
3
- import { mkdir, readFile, writeFile } from "node:fs/promises";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { createHash, createPublicKey, verify } from "node:crypto";
7
- import { promisify } from "node:util";
8
- const execFileAsync = promisify(execFile);
9
- const sourceCache = new Map();
10
- function cacheRoot() {
11
- return path.join(os.tmpdir(), "agent-harness-external-sources");
12
- }
13
- function sourceCacheDir(locator) {
14
- const digest = createHash("sha256").update(locator).digest("hex").slice(0, 16);
15
- return path.join(cacheRoot(), digest);
16
- }
17
- export function resolveResourcePackageRoot(root) {
18
- const candidates = path.basename(root) === "resources" ? [root] : [path.join(root, "resources")];
19
- for (const candidate of candidates) {
20
- if (!existsSync(candidate)) {
21
- continue;
22
- }
23
- if (!statSync(candidate).isDirectory()) {
24
- continue;
25
- }
26
- const packageJsonPath = path.join(candidate, "package.json");
27
- if (!existsSync(packageJsonPath)) {
28
- throw new Error(`Resource package ${candidate} is missing package.json.`);
29
- }
30
- return candidate;
31
- }
32
- return null;
33
- }
34
- function resolveExplicitResourceRoot(root) {
35
- if (isDirectoryPath(root)) {
36
- const packageJsonPath = path.join(root, "package.json");
37
- if (existsSync(packageJsonPath)) {
38
- return root;
39
- }
40
- }
41
- return resolveResourcePackageRoot(root);
42
- }
43
- export function isExternalSourceLocator(value) {
44
- return typeof value === "string" && /^(npm|tgz|file):/.test(value);
45
- }
46
- export function parseExternalSourceLocator(locator) {
47
- const separator = locator.indexOf("::");
48
- const rawBase = separator >= 0 ? locator.slice(0, separator) : locator;
49
- const subpath = separator >= 0 ? locator.slice(separator + 2) : undefined;
50
- const [baseWithoutQuery, rawQuery = ""] = rawBase.split("?", 2);
51
- const query = new URLSearchParams(rawQuery);
52
- const shared = {
53
- subpath,
54
- integrity: query.get("integrity") ?? undefined,
55
- signature: query.get("signature") ?? undefined,
56
- publicKey: query.get("publicKey") ?? query.get("key") ?? undefined,
57
- };
58
- if (baseWithoutQuery.startsWith("npm:")) {
59
- return { kind: "npm", spec: baseWithoutQuery.slice(4), ...shared };
60
- }
61
- if (baseWithoutQuery.startsWith("tgz:")) {
62
- return { kind: "tgz", spec: baseWithoutQuery.slice(4), ...shared };
63
- }
64
- if (baseWithoutQuery.startsWith("file:")) {
65
- return { kind: "file", spec: baseWithoutQuery.slice(5), ...shared };
66
- }
67
- throw new Error(`Unsupported external source locator ${locator}. Use npm:, tgz:, or file:.`);
68
- }
69
- function resolveFileSpec(spec, workspaceRoot) {
70
- if (path.isAbsolute(spec)) {
71
- return spec;
72
- }
73
- return path.resolve(workspaceRoot, spec);
74
- }
75
- async function packAndExtract(packageSpec, cacheKey) {
76
- const root = sourceCacheDir(cacheKey);
77
- const extractRoot = path.join(root, "extract");
78
- const packageRoot = path.join(extractRoot, "package");
79
- const npmCacheRoot = path.join(root, ".npm-cache");
80
- const tarballMarker = path.join(root, ".tarball-path");
81
- if (existsSync(path.join(packageRoot, "package.json"))) {
82
- const tarballPath = existsSync(tarballMarker) ? (await readFile(tarballMarker, "utf8")).trim() : undefined;
83
- return {
84
- basePath: packageRoot,
85
- tarballPath: tarballPath || undefined,
86
- };
87
- }
88
- await mkdir(root, { recursive: true });
89
- await mkdir(extractRoot, { recursive: true });
90
- await mkdir(npmCacheRoot, { recursive: true });
91
- const packed = await execFileAsync("npm", ["pack", packageSpec, "--silent"], {
92
- cwd: root,
93
- maxBuffer: 1024 * 1024 * 10,
94
- env: {
95
- ...process.env,
96
- NPM_CONFIG_CACHE: npmCacheRoot,
97
- },
98
- });
99
- const tarballName = packed.stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);
100
- if (!tarballName) {
101
- throw new Error(`Failed to pack external source ${cacheKey}`);
102
- }
103
- const tarballPath = path.join(root, tarballName);
104
- await execFileAsync("tar", ["-xzf", tarballName, "-C", extractRoot], {
105
- cwd: root,
106
- maxBuffer: 1024 * 1024 * 10,
107
- });
108
- await writeFile(tarballMarker, tarballPath, "utf8");
109
- return {
110
- basePath: packageRoot,
111
- tarballPath,
112
- };
113
- }
114
- function decodeIntegrity(integrity) {
115
- const trimmed = integrity.trim();
116
- if (!trimmed) {
117
- throw new Error("External source integrity must not be empty.");
118
- }
119
- const [algorithm, encoded] = trimmed.includes("-")
120
- ? trimmed.split("-", 2)
121
- : trimmed.includes(":")
122
- ? trimmed.split(":", 2)
123
- : [trimmed, ""];
124
- if (!encoded) {
125
- throw new Error(`External source integrity ${integrity} must use <algorithm>-<digest> or <algorithm>:<digest>.`);
126
- }
127
- const normalizedAlgorithm = algorithm.toLowerCase();
128
- const encoding = /^[a-f0-9]+$/i.test(encoded) ? "hex" : "base64";
129
- return {
130
- algorithm: normalizedAlgorithm,
131
- expected: Buffer.from(encoded, encoding),
132
- };
133
- }
134
- async function readVerificationPublicKey(publicKey, workspaceRoot) {
135
- const trimmed = publicKey.trim();
136
- if (trimmed.startsWith("-----BEGIN")) {
137
- return trimmed;
138
- }
139
- const resolved = trimmed.startsWith("file:")
140
- ? resolveFileSpec(trimmed.slice("file:".length), workspaceRoot)
141
- : resolveFileSpec(trimmed, workspaceRoot);
142
- return readFile(resolved);
143
- }
144
- async function verifyExternalSource(locator, parsed, cached, workspaceRoot) {
145
- if (!parsed.integrity && !parsed.signature) {
146
- return;
147
- }
148
- if (!cached.tarballPath) {
149
- throw new Error(`External source ${locator} does not provide a tarball to verify.`);
150
- }
151
- const tarball = await readFile(cached.tarballPath);
152
- if (parsed.integrity) {
153
- const { algorithm, expected } = decodeIntegrity(parsed.integrity);
154
- const actual = createHash(algorithm).update(tarball).digest();
155
- if (!actual.equals(expected)) {
156
- throw new Error(`External source ${locator} failed integrity verification.`);
157
- }
158
- }
159
- if (parsed.signature) {
160
- if (!parsed.publicKey) {
161
- throw new Error(`External source ${locator} signature verification requires publicKey=.`);
162
- }
163
- const key = createPublicKey(await readVerificationPublicKey(parsed.publicKey, workspaceRoot));
164
- const signature = Buffer.from(parsed.signature, "base64");
165
- const verified = verify(null, tarball, key, signature) ||
166
- verify("sha256", tarball, key, signature);
167
- if (!verified) {
168
- throw new Error(`External source ${locator} failed signature verification.`);
169
- }
170
- }
171
- }
172
- export async function ensureExternalSource(locator, workspaceRoot) {
173
- const parsed = parseExternalSourceLocator(locator);
174
- const cacheKey = `${parsed.kind}:${parsed.spec}`;
175
- const cached = sourceCache.get(cacheKey);
176
- if (cached) {
177
- await verifyExternalSource(locator, parsed, cached, workspaceRoot);
178
- return parsed.subpath ? path.join(cached.basePath, parsed.subpath) : cached.basePath;
179
- }
180
- let resolved;
181
- if (parsed.kind === "npm") {
182
- resolved = await packAndExtract(parsed.spec, cacheKey);
183
- }
184
- else if (parsed.kind === "tgz") {
185
- const tgzPath = resolveFileSpec(parsed.spec, workspaceRoot);
186
- resolved = await packAndExtract(tgzPath, cacheKey);
187
- resolved.tarballPath ??= tgzPath;
188
- }
189
- else {
190
- const filePath = resolveFileSpec(parsed.spec, workspaceRoot);
191
- if (!existsSync(filePath)) {
192
- throw new Error(`External file source ${locator} does not exist`);
193
- }
194
- if (filePath.endsWith(".tgz") || filePath.endsWith(".tar.gz")) {
195
- resolved = await packAndExtract(filePath, cacheKey);
196
- resolved.tarballPath ??= filePath;
197
- }
198
- else {
199
- resolved = { basePath: filePath };
200
- }
201
- }
202
- sourceCache.set(cacheKey, resolved);
203
- await verifyExternalSource(locator, parsed, resolved, workspaceRoot);
204
- return parsed.subpath ? path.join(resolved.basePath, parsed.subpath) : resolved.basePath;
205
- }
206
- export async function ensureExternalResourceSource(locator, workspaceRoot) {
207
- const parsed = parseExternalSourceLocator(locator);
208
- const baseLocator = `${parsed.kind}:${parsed.spec}`;
209
- const packageRoot = await ensureExternalSource(baseLocator, workspaceRoot);
210
- const resourcePackageRoot = resolveExplicitResourceRoot(packageRoot);
211
- if (!resourcePackageRoot) {
212
- throw new Error(`External source ${baseLocator} is missing a resource package root or resources/package.json.`);
213
- }
214
- return parsed.subpath ? path.join(resourcePackageRoot, parsed.subpath) : resourcePackageRoot;
215
- }
216
- export async function ensureExternalSources(locators, workspaceRoot) {
217
- await Promise.all(Array.from(new Set(locators)).map((locator) => ensureExternalSource(locator, workspaceRoot)));
218
- }
219
- export function resolveExternalSourcePath(locator, workspaceRoot) {
220
- const parsed = parseExternalSourceLocator(locator);
221
- const cacheKey = `${parsed.kind}:${parsed.spec}`;
222
- const cached = sourceCache.get(cacheKey);
223
- if (cached) {
224
- return parsed.subpath ? path.join(cached.basePath, parsed.subpath) : cached.basePath;
225
- }
226
- if (parsed.kind === "file") {
227
- const resolved = resolveFileSpec(parsed.spec, workspaceRoot);
228
- if (resolved.endsWith(".tgz") || resolved.endsWith(".tar.gz")) {
229
- throw new Error(`External source ${locator} must be preloaded before synchronous resolution`);
230
- }
231
- return parsed.subpath ? path.join(resolved, parsed.subpath) : resolved;
232
- }
233
- throw new Error(`External source ${locator} must be preloaded before synchronous resolution`);
234
- }
235
- export function resolveExternalResourcePath(locator, workspaceRoot) {
236
- const parsed = parseExternalSourceLocator(locator);
237
- const baseLocator = `${parsed.kind}:${parsed.spec}`;
238
- const packageRoot = resolveExternalSourcePath(baseLocator, workspaceRoot);
239
- const resourcePackageRoot = resolveExplicitResourceRoot(packageRoot);
240
- if (!resourcePackageRoot) {
241
- throw new Error(`External source ${baseLocator} is missing a resource package root or resources/package.json.`);
242
- }
243
- return parsed.subpath ? path.join(resourcePackageRoot, parsed.subpath) : resourcePackageRoot;
244
- }
245
- export function isDirectoryPath(candidate) {
246
- return existsSync(candidate) && statSync(candidate).isDirectory();
247
- }
1
+ import{execFile as $}from"node:child_process";import{existsSync as c,statSync as w}from"node:fs";import{mkdir as h,readFile as d,writeFile as z}from"node:fs/promises";import R from"node:os";import o from"node:path";import{createHash as x,createPublicKey as S,verify as y}from"node:crypto";import{promisify as W}from"node:util";const E=W($),g=new Map;function C(){return o.join(R.tmpdir(),"agent-harness-external-sources")}function K(t){const r=x("sha256").update(t).digest("hex").slice(0,16);return o.join(C(),r)}function B(t){const r=o.basename(t)==="resources"?[t]:[o.join(t,"resources")];for(const e of r){if(!c(e)||!w(e).isDirectory())continue;const i=o.join(e,"package.json");if(!c(i))throw new Error(`Resource package ${e} is missing package.json.`);return e}return null}function k(t){if(D(t)){const r=o.join(t,"package.json");if(c(r))return t}return B(t)}function J(t){return typeof t=="string"&&/^(npm|tgz|file):/.test(t)}function f(t){const r=t.indexOf("::"),e=r>=0?t.slice(0,r):t,i=r>=0?t.slice(r+2):void 0,[a,n=""]=e.split("?",2),s=new URLSearchParams(n),u={subpath:i,integrity:s.get("integrity")??void 0,signature:s.get("signature")??void 0,publicKey:s.get("publicKey")??s.get("key")??void 0};if(a.startsWith("npm:"))return{kind:"npm",spec:a.slice(4),...u};if(a.startsWith("tgz:"))return{kind:"tgz",spec:a.slice(4),...u};if(a.startsWith("file:"))return{kind:"file",spec:a.slice(5),...u};throw new Error(`Unsupported external source locator ${t}. Use npm:, tgz:, or file:.`)}function l(t,r){return o.isAbsolute(t)?t:o.resolve(r,t)}async function m(t,r){const e=K(r),i=o.join(e,"extract"),a=o.join(i,"package"),n=o.join(e,".npm-cache"),s=o.join(e,".tarball-path");if(c(o.join(a,"package.json"))){const v=c(s)?(await d(s,"utf8")).trim():void 0;return{basePath:a,tarballPath:v||void 0}}await h(e,{recursive:!0}),await h(i,{recursive:!0}),await h(n,{recursive:!0});const p=(await E("npm",["pack",t,"--silent"],{cwd:e,maxBuffer:1024*1024*10,env:{...process.env,NPM_CONFIG_CACHE:n}})).stdout.trim().split(/\r?\n/).filter(Boolean).at(-1);if(!p)throw new Error(`Failed to pack external source ${r}`);const b=o.join(e,p);return await E("tar",["-xzf",p,"-C",i],{cwd:e,maxBuffer:1024*1024*10}),await z(s,b,"utf8"),{basePath:a,tarballPath:b}}function F(t){const r=t.trim();if(!r)throw new Error("External source integrity must not be empty.");const[e,i]=r.includes("-")?r.split("-",2):r.includes(":")?r.split(":",2):[r,""];if(!i)throw new Error(`External source integrity ${t} must use <algorithm>-<digest> or <algorithm>:<digest>.`);const a=e.toLowerCase(),n=/^[a-f0-9]+$/i.test(i)?"hex":"base64";return{algorithm:a,expected:Buffer.from(i,n)}}async function A(t,r){const e=t.trim();if(e.startsWith("-----BEGIN"))return e;const i=e.startsWith("file:")?l(e.slice(5),r):l(e,r);return d(i)}async function P(t,r,e,i){if(!r.integrity&&!r.signature)return;if(!e.tarballPath)throw new Error(`External source ${t} does not provide a tarball to verify.`);const a=await d(e.tarballPath);if(r.integrity){const{algorithm:n,expected:s}=F(r.integrity);if(!x(n).update(a).digest().equals(s))throw new Error(`External source ${t} failed integrity verification.`)}if(r.signature){if(!r.publicKey)throw new Error(`External source ${t} signature verification requires publicKey=.`);const n=S(await A(r.publicKey,i)),s=Buffer.from(r.signature,"base64");if(!(y(null,a,n,s)||y("sha256",a,n,s)))throw new Error(`External source ${t} failed signature verification.`)}}async function j(t,r){const e=f(t),i=`${e.kind}:${e.spec}`,a=g.get(i);if(a)return await P(t,e,a,r),e.subpath?o.join(a.basePath,e.subpath):a.basePath;let n;if(e.kind==="npm")n=await m(e.spec,i);else if(e.kind==="tgz"){const s=l(e.spec,r);n=await m(s,i),n.tarballPath??=s}else{const s=l(e.spec,r);if(!c(s))throw new Error(`External file source ${t} does not exist`);s.endsWith(".tgz")||s.endsWith(".tar.gz")?(n=await m(s,i),n.tarballPath??=s):n={basePath:s}}return g.set(i,n),await P(t,e,n,r),e.subpath?o.join(n.basePath,e.subpath):n.basePath}async function O(t,r){const e=f(t),i=`${e.kind}:${e.spec}`,a=await j(i,r),n=k(a);if(!n)throw new Error(`External source ${i} is missing a resource package root or resources/package.json.`);return e.subpath?o.join(n,e.subpath):n}async function Q(t,r){await Promise.all(Array.from(new Set(t)).map(e=>j(e,r)))}function L(t,r){const e=f(t),i=`${e.kind}:${e.spec}`,a=g.get(i);if(a)return e.subpath?o.join(a.basePath,e.subpath):a.basePath;if(e.kind==="file"){const n=l(e.spec,r);if(n.endsWith(".tgz")||n.endsWith(".tar.gz"))throw new Error(`External source ${t} must be preloaded before synchronous resolution`);return e.subpath?o.join(n,e.subpath):n}throw new Error(`External source ${t} must be preloaded before synchronous resolution`)}function _(t,r){const e=f(t),i=`${e.kind}:${e.spec}`,a=L(i,r),n=k(a);if(!n)throw new Error(`External source ${i} is missing a resource package root or resources/package.json.`);return e.subpath?o.join(n,e.subpath):n}function D(t){return c(t)&&w(t).isDirectory()}export{O as ensureExternalResourceSource,j as ensureExternalSource,Q as ensureExternalSources,D as isDirectoryPath,J as isExternalSourceLocator,f as parseExternalSourceLocator,_ as resolveExternalResourcePath,L as resolveExternalSourcePath,B as resolveResourcePackageRoot};
@@ -1,65 +1,4 @@
1
- import { spawn } from "node:child_process";
2
- import path from "node:path";
3
- import { stat } from "node:fs/promises";
4
- import { pathToFileURL } from "node:url";
5
- import { UPSTREAM_REQUEST_CONFIG_KEY, UPSTREAM_SESSION_CONFIG_KEY } from "../../runtime/adapter/upstream-configurable-keys.js";
6
- import { getBindingExecutionView, getBindingPrimaryModel } from "../../runtime/support/compiled-binding.js";
7
- import { resolveCompiledEmbeddingModelRef } from "../../runtime/support/embedding-models.js";
8
- import { createRuntimeEnv } from "../../runtime/env/runtime-env.js";
9
- import { isSupportedToolModulePath, loadToolModuleDefinition } from "../../tooling/module-loader.js";
10
- import { resolveIsolatedResourceModulePath } from "../isolation.js";
11
- import { resolveResourcePackageRoot } from "../sources.js";
12
- function findEnclosingResourcePackageRoot(startPath) {
13
- let current = path.dirname(startPath);
14
- for (;;) {
15
- const resourcePackageRoot = resolveResourcePackageRoot(current);
16
- if (resourcePackageRoot && isPathWithinRoot(startPath, resourcePackageRoot)) {
17
- return resourcePackageRoot;
18
- }
19
- const parent = path.dirname(current);
20
- if (parent === current) {
21
- return null;
22
- }
23
- current = parent;
24
- }
25
- }
26
- function isPathWithinRoot(targetPath, rootPath) {
27
- const relative = path.relative(rootPath, targetPath);
28
- return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
29
- }
30
- async function findPackageRoot(startPath) {
31
- const resourcePackageRoot = findEnclosingResourcePackageRoot(startPath);
32
- if (resourcePackageRoot) {
33
- return resourcePackageRoot;
34
- }
35
- let current = path.dirname(startPath);
36
- for (;;) {
37
- try {
38
- await stat(path.join(current, "package.json"));
39
- return current;
40
- }
41
- catch { }
42
- const parent = path.dirname(current);
43
- if (parent === current) {
44
- return path.dirname(startPath);
45
- }
46
- current = parent;
47
- }
48
- }
49
- function asObject(value) {
50
- return typeof value === "object" && value !== null ? value : undefined;
51
- }
52
- function asStringRecord(value) {
53
- const record = asObject(value);
54
- if (!record) {
55
- return undefined;
56
- }
57
- return Object.fromEntries(Object.entries(record).filter((entry) => typeof entry[1] === "string"));
58
- }
59
- function asStringArray(value) {
60
- return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
61
- }
62
- const FUNCTION_TOOL_SUBPROCESS_RUNNER_SOURCE = `
1
+ import{spawn as _}from"node:child_process";import m from"node:path";import{stat as I}from"node:fs/promises";import{pathToFileURL as k}from"node:url";import{UPSTREAM_REQUEST_CONFIG_KEY as M,UPSTREAM_SESSION_CONFIG_KEY as N}from"../../runtime/adapter/upstream-configurable-keys.js";import{getBindingExecutionView as C,getBindingPrimaryModel as F}from"../../runtime/support/compiled-binding.js";import{resolveCompiledEmbeddingModelRef as j}from"../../runtime/support/embedding-models.js";import{createRuntimeEnv as U}from"../../runtime/env/runtime-env.js";import{isSupportedToolModulePath as A,loadToolModuleDefinition as $}from"../../tooling/module-loader.js";import{resolveIsolatedResourceModulePath as D}from"../isolation.js";import{resolveResourcePackageRoot as L}from"../sources.js";function K(e){let n=m.dirname(e);for(;;){const o=L(n);if(o&&B(e,o))return o;const r=m.dirname(n);if(r===n)return null;n=r}}function B(e,n){const o=m.relative(n,e);return o===""||!o.startsWith("..")&&!m.isAbsolute(o)}async function w(e){const n=K(e);if(n)return n;let o=m.dirname(e);for(;;){try{return await I(m.join(o,"package.json")),o}catch{}const r=m.dirname(o);if(r===o)return m.dirname(e);o=r}}function E(e){return typeof e=="object"&&e!==null?e:void 0}function G(e){const n=E(e);if(n)return Object.fromEntries(Object.entries(n).filter(o=>typeof o[1]=="string"))}function J(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}const q=`
63
2
  import { pathToFileURL } from "node:url";
64
3
 
65
4
  const TOOL_DEFINITION_MARKER = "__agent_harness_tool_definition__";
@@ -94,213 +33,4 @@ const input = tool.schema && typeof tool.schema.parse === "function"
94
33
  : (payload.input ?? {});
95
34
  const result = await tool.invoke(input, payload.context ?? {});
96
35
  process.stdout.write(typeof result === "string" ? result : JSON.stringify(result));
97
- `;
98
- function resolveFunctionToolSubprocessConfig(tool, workspaceRoot, isolatedSourcePath) {
99
- const execution = asObject(tool.config?.execution);
100
- if (tool.subprocess !== true) {
101
- return null;
102
- }
103
- const resolvedExecution = execution ?? {};
104
- const entry = typeof resolvedExecution.entry === "string" && resolvedExecution.entry.trim()
105
- ? path.resolve(workspaceRoot, resolvedExecution.entry)
106
- : undefined;
107
- const command = typeof resolvedExecution.command === "string" && resolvedExecution.command.trim()
108
- ? resolvedExecution.command
109
- : entry
110
- ? process.execPath
111
- : process.execPath;
112
- if (!command) {
113
- throw new Error(`Tool ${tool.id} subprocess execution requires config.execution.command or config.execution.entry`);
114
- }
115
- const args = [
116
- ...(entry ? [entry] : ["--input-type=module", "--eval", FUNCTION_TOOL_SUBPROCESS_RUNNER_SOURCE, isolatedSourcePath, tool.implementationName ?? tool.id]),
117
- ...asStringArray(resolvedExecution.args),
118
- ];
119
- const cwd = typeof resolvedExecution.cwd === "string" && resolvedExecution.cwd.trim()
120
- ? path.resolve(workspaceRoot, resolvedExecution.cwd)
121
- : workspaceRoot;
122
- const timeoutMs = Number.isFinite(resolvedExecution.timeoutMs) ? Number(resolvedExecution.timeoutMs) : undefined;
123
- return {
124
- command,
125
- args,
126
- cwd,
127
- env: asStringRecord(resolvedExecution.env),
128
- timeoutMs,
129
- };
130
- }
131
- async function runFunctionToolInSubprocess(config, input, context) {
132
- return await new Promise((resolve, reject) => {
133
- const child = spawn(config.command, config.args, {
134
- cwd: config.cwd,
135
- env: createRuntimeEnv(config.env, process.env),
136
- stdio: ["pipe", "pipe", "pipe"],
137
- });
138
- let stdout = "";
139
- let stderr = "";
140
- let settled = false;
141
- let timeout;
142
- const finish = (fn) => {
143
- if (settled) {
144
- return;
145
- }
146
- settled = true;
147
- if (timeout) {
148
- clearTimeout(timeout);
149
- }
150
- fn();
151
- };
152
- if (config.timeoutMs && config.timeoutMs > 0) {
153
- timeout = setTimeout(() => {
154
- child.kill("SIGTERM");
155
- finish(() => reject(new Error(`Subprocess tool timed out after ${config.timeoutMs}ms`)));
156
- }, config.timeoutMs);
157
- }
158
- child.stdout.setEncoding("utf8");
159
- child.stderr.setEncoding("utf8");
160
- child.stdout.on("data", (chunk) => {
161
- stdout += chunk;
162
- });
163
- child.stderr.on("data", (chunk) => {
164
- stderr += chunk;
165
- });
166
- child.on("error", (error) => {
167
- finish(() => reject(error));
168
- });
169
- child.on("close", (code, signal) => {
170
- finish(() => {
171
- if (code === 0) {
172
- resolve(stdout.trim());
173
- return;
174
- }
175
- const message = stderr.trim() || stdout.trim() || `Subprocess tool exited with code ${code ?? "unknown"}${signal ? ` (${signal})` : ""}`;
176
- reject(new Error(message));
177
- });
178
- });
179
- child.stdin.end(JSON.stringify({ input, context }));
180
- });
181
- }
182
- const functionToolModuleCache = new Map();
183
- async function loadFunctionToolModule(tool) {
184
- const cacheKey = `${tool.sourcePath}:${tool.implementationName ?? tool.id}`;
185
- const cached = functionToolModuleCache.get(cacheKey);
186
- if (cached) {
187
- return cached;
188
- }
189
- const loading = (async () => {
190
- const packageRoot = await findPackageRoot(tool.sourcePath);
191
- const isolatedSourcePath = await resolveIsolatedResourceModulePath(packageRoot, tool.sourcePath);
192
- const imported = await import(pathToFileURL(isolatedSourcePath).href);
193
- const implementationName = tool.implementationName ?? tool.id;
194
- const loaded = loadToolModuleDefinition(imported, implementationName);
195
- return {
196
- invoke: loaded.invoke,
197
- schema: loaded.schema,
198
- modelSchema: loaded.modelSchema,
199
- description: loaded.description,
200
- isolatedSourcePath,
201
- implementationName,
202
- };
203
- })();
204
- functionToolModuleCache.set(cacheKey, loading);
205
- return loading;
206
- }
207
- export function createFunctionToolResolver(workspace) {
208
- const functionTools = new Map(Array.from(workspace.tools.values())
209
- .filter((tool) => tool.type === "function" && isSupportedToolModulePath(tool.sourcePath))
210
- .map((tool) => [tool.id, tool]));
211
- return (toolIds, binding) => toolIds.flatMap((toolId) => {
212
- const tool = functionTools.get(toolId);
213
- if (!tool) {
214
- return [];
215
- }
216
- return [
217
- {
218
- name: tool.name,
219
- description: tool.description,
220
- schema: tool.modelSchema,
221
- modelSchema: tool.modelSchema,
222
- async invoke(input, config) {
223
- const loaded = await loadFunctionToolModule(tool);
224
- const parsedInput = loaded.schema.parse(input ?? {});
225
- const toolPackageRoot = await findPackageRoot(tool.sourcePath);
226
- const bindingTool = binding
227
- ? getBindingExecutionView(binding).primaryTools.find((candidate) => candidate.id === tool.id || candidate.name === tool.name)
228
- : undefined;
229
- const effectiveEmbeddingModelRef = bindingTool?.embeddingModelRef ?? tool.embeddingModelRef;
230
- const effectiveSubprocess = bindingTool?.subprocess ?? tool.subprocess;
231
- const effectiveConfig = bindingTool?.config ?? tool.config;
232
- const effectiveHitl = bindingTool?.hitl ?? tool.hitl;
233
- const effectiveRetryable = bindingTool?.retryable ?? tool.retryable;
234
- const embeddingModel = effectiveEmbeddingModelRef
235
- ? resolveCompiledEmbeddingModelRef(workspace, effectiveEmbeddingModelRef)
236
- : undefined;
237
- const model = binding ? getBindingPrimaryModel(binding) : undefined;
238
- const configurable = typeof config?.configurable === "object" && config.configurable !== null
239
- ? config.configurable
240
- : {};
241
- const dynamicToolRuntimeContext = typeof config?.toolRuntimeContext === "object" && config.toolRuntimeContext !== null
242
- ? config.toolRuntimeContext
243
- : {};
244
- const baseToolContext = {
245
- appRoot: workspace.workspaceRoot,
246
- toolId: tool.id,
247
- toolPath: tool.sourcePath,
248
- toolPackageRoot,
249
- embeddingModel,
250
- model,
251
- runtime: {
252
- workspaceRoot: workspace.workspaceRoot,
253
- runtimeRoot: binding?.harnessRuntime.runtimeRoot,
254
- ...(typeof configurable[UPSTREAM_SESSION_CONFIG_KEY] === "string"
255
- ? { sessionId: configurable[UPSTREAM_SESSION_CONFIG_KEY] }
256
- : {}),
257
- ...(typeof configurable[UPSTREAM_REQUEST_CONFIG_KEY] === "string"
258
- ? { requestId: configurable[UPSTREAM_REQUEST_CONFIG_KEY] }
259
- : {}),
260
- },
261
- agent: binding
262
- ? {
263
- id: binding.agent.id,
264
- executionMode: binding.agent.executionMode,
265
- description: binding.agent.description,
266
- sourcePath: binding.agent.sourcePath,
267
- }
268
- : undefined,
269
- tool: {
270
- id: tool.id,
271
- name: tool.name,
272
- type: tool.type,
273
- description: tool.description,
274
- sourcePath: tool.sourcePath,
275
- packageRoot: toolPackageRoot,
276
- config: effectiveConfig,
277
- embeddingModelRef: effectiveEmbeddingModelRef,
278
- inputSchemaRef: tool.inputSchemaRef,
279
- retryable: effectiveRetryable,
280
- hitl: effectiveHitl,
281
- },
282
- };
283
- const subprocessConfig = resolveFunctionToolSubprocessConfig({
284
- ...tool,
285
- config: effectiveConfig,
286
- embeddingModelRef: effectiveEmbeddingModelRef,
287
- hitl: effectiveHitl,
288
- retryable: effectiveRetryable,
289
- subprocess: effectiveSubprocess,
290
- }, workspace.workspaceRoot, loaded.isolatedSourcePath);
291
- if (subprocessConfig) {
292
- return runFunctionToolInSubprocess(subprocessConfig, parsedInput, baseToolContext);
293
- }
294
- return loaded.invoke(parsedInput, {
295
- ...baseToolContext,
296
- ...dynamicToolRuntimeContext,
297
- runtime: {
298
- ...(typeof baseToolContext.runtime === "object" && baseToolContext.runtime ? baseToolContext.runtime : {}),
299
- ...(typeof dynamicToolRuntimeContext.runtime === "object" && dynamicToolRuntimeContext.runtime ? dynamicToolRuntimeContext.runtime : {}),
300
- },
301
- });
302
- },
303
- },
304
- ];
305
- });
306
- }
36
+ `;function W(e,n,o){const r=E(e.config?.execution);if(e.subprocess!==!0)return null;const i=r??{},t=typeof i.entry=="string"&&i.entry.trim()?m.resolve(n,i.entry):void 0,u=typeof i.command=="string"&&i.command.trim()?i.command:process.execPath;if(!u)throw new Error(`Tool ${e.id} subprocess execution requires config.execution.command or config.execution.entry`);const a=[...t?[t]:["--input-type=module","--eval",q,o,e.implementationName??e.id],...J(i.args)],c=typeof i.cwd=="string"&&i.cwd.trim()?m.resolve(n,i.cwd):n,d=Number.isFinite(i.timeoutMs)?Number(i.timeoutMs):void 0;return{command:u,args:a,cwd:c,env:G(i.env),timeoutMs:d}}async function Y(e,n,o){return await new Promise((r,i)=>{const t=_(e.command,e.args,{cwd:e.cwd,env:U(e.env,process.env),stdio:["pipe","pipe","pipe"]});let u="",a="",c=!1,d;const f=s=>{c||(c=!0,d&&clearTimeout(d),s())};e.timeoutMs&&e.timeoutMs>0&&(d=setTimeout(()=>{t.kill("SIGTERM"),f(()=>i(new Error(`Subprocess tool timed out after ${e.timeoutMs}ms`)))},e.timeoutMs)),t.stdout.setEncoding("utf8"),t.stderr.setEncoding("utf8"),t.stdout.on("data",s=>{u+=s}),t.stderr.on("data",s=>{a+=s}),t.on("error",s=>{f(()=>i(s))}),t.on("close",(s,l)=>{f(()=>{if(s===0){r(u.trim());return}const R=a.trim()||u.trim()||`Subprocess tool exited with code ${s??"unknown"}${l?` (${l})`:""}`;i(new Error(R))})}),t.stdin.end(JSON.stringify({input:n,context:o}))})}const P=new Map;async function H(e){const n=`${e.sourcePath}:${e.implementationName??e.id}`,o=P.get(n);if(o)return o;const r=(async()=>{const i=await w(e.sourcePath),t=await D(i,e.sourcePath),u=await import(k(t).href),a=e.implementationName??e.id,c=$(u,a);return{invoke:c.invoke,schema:c.schema,modelSchema:c.modelSchema,description:c.description,isolatedSourcePath:t,implementationName:a}})();return P.set(n,r),r}function se(e){const n=new Map(Array.from(e.tools.values()).filter(o=>o.type==="function"&&A(o.sourcePath)).map(o=>[o.id,o]));return(o,r)=>o.flatMap(i=>{const t=n.get(i);return t?[{name:t.name,description:t.description,schema:t.modelSchema,modelSchema:t.modelSchema,async invoke(u,a){const c=await H(t),d=c.schema.parse(u??{}),f=await w(t.sourcePath),s=r?C(r).primaryTools.find(S=>S.id===t.id||S.name===t.name):void 0,l=s?.embeddingModelRef??t.embeddingModelRef,R=s?.subprocess??t.subprocess,g=s?.config??t.config,v=s?.hitl??t.hitl,b=s?.retryable??t.retryable,x=l?j(e,l):void 0,O=r?F(r):void 0,h=typeof a?.configurable=="object"&&a.configurable!==null?a.configurable:{},y=typeof a?.toolRuntimeContext=="object"&&a.toolRuntimeContext!==null?a.toolRuntimeContext:{},p={appRoot:e.workspaceRoot,toolId:t.id,toolPath:t.sourcePath,toolPackageRoot:f,embeddingModel:x,model:O,runtime:{workspaceRoot:e.workspaceRoot,runtimeRoot:r?.harnessRuntime.runtimeRoot,...typeof h[N]=="string"?{sessionId:h[N]}:{},...typeof h[M]=="string"?{requestId:h[M]}:{}},agent:r?{id:r.agent.id,executionMode:r.agent.executionMode,description:r.agent.description,sourcePath:r.agent.sourcePath}:void 0,tool:{id:t.id,name:t.name,type:t.type,description:t.description,sourcePath:t.sourcePath,packageRoot:f,config:g,embeddingModelRef:l,inputSchemaRef:t.inputSchemaRef,retryable:b,hitl:v}},T=W({...t,config:g,embeddingModelRef:l,hitl:v,retryable:b,subprocess:R},e.workspaceRoot,c.isolatedSourcePath);return T?Y(T,d,p):c.invoke(d,{...p,...y,runtime:{...typeof p.runtime=="object"&&p.runtime?p.runtime:{},...typeof y.runtime=="object"&&y.runtime?y.runtime:{}}})}}]:[]})}export{se as createFunctionToolResolver};
@@ -1,29 +1 @@
1
- import path from "node:path";
2
- export function relativizeDeepAgentSkillSourcePaths(workspaceRoot, skillPaths) {
3
- if (!workspaceRoot || !skillPaths) {
4
- return skillPaths;
5
- }
6
- return skillPaths.map((skillPath) => {
7
- if (!path.isAbsolute(skillPath)) {
8
- return skillPath;
9
- }
10
- const relative = path.relative(workspaceRoot, skillPath);
11
- if (!relative || relative.startsWith("..")) {
12
- return skillPath;
13
- }
14
- return relative.split(path.sep).join("/");
15
- });
16
- }
17
- export async function materializeDeepAgentSkillSourcePaths(options) {
18
- return Promise.resolve(resolveDeepAgentSkillSourcePaths(options));
19
- }
20
- export function resolveDeepAgentSkillSourcePaths(options) {
21
- const { workspaceRoot, skillPaths } = options;
22
- if (!skillPaths) {
23
- return skillPaths;
24
- }
25
- return relativizeDeepAgentSkillSourcePaths(workspaceRoot, skillPaths) ?? skillPaths;
26
- }
27
- export function resolveDeepAgentSkillSourceRootPaths(options) {
28
- return resolveDeepAgentSkillSourcePaths(options);
29
- }
1
+ import o from"node:path";function u(r,t){return!r||!t?t:t.map(e=>{if(!o.isAbsolute(e))return e;const n=o.relative(r,e);return!n||n.startsWith("..")?e:n.split(o.sep).join("/")})}async function s(r){return Promise.resolve(i(r))}function i(r){const{workspaceRoot:t,skillPaths:e}=r;return e&&(u(t,e)??e)}function c(r){return i(r)}export{s as materializeDeepAgentSkillSourcePaths,u as relativizeDeepAgentSkillSourcePaths,i as resolveDeepAgentSkillSourcePaths,c as resolveDeepAgentSkillSourceRootPaths};
@@ -1,55 +1 @@
1
- function asObject(value) {
2
- return typeof value === "object" && value ? value : undefined;
3
- }
4
- function isPlaceholderApiKey(value) {
5
- return typeof value === "string" && value.trim().toLowerCase() === "dummy";
6
- }
7
- export function buildAuthOmittingFetch(baseFetch = fetch) {
8
- return async (input, init) => {
9
- const sanitizedHeaders = new Headers(input instanceof Request ? input.headers : undefined);
10
- const initHeaders = new Headers(init?.headers);
11
- initHeaders.forEach((value, key) => {
12
- sanitizedHeaders.set(key, value);
13
- });
14
- sanitizedHeaders.delete("authorization");
15
- if (input instanceof Request) {
16
- return baseFetch(new Request(input, {
17
- ...init,
18
- headers: sanitizedHeaders,
19
- }));
20
- }
21
- return baseFetch(input, {
22
- ...init,
23
- headers: sanitizedHeaders,
24
- });
25
- };
26
- }
27
- export function normalizeOpenAICompatibleInit(init) {
28
- const normalized = { ...init };
29
- const configuration = asObject(init.configuration) ?? {};
30
- const modelKwargs = asObject(init.modelKwargs) ?? {};
31
- const baseUrl = typeof init.baseUrl === "string" && init.baseUrl.trim() ? init.baseUrl.trim() : undefined;
32
- const omitAuthHeader = init.omitAuthHeader === true || isPlaceholderApiKey(init.apiKey);
33
- const nextConfiguration = { ...configuration };
34
- if (baseUrl && typeof nextConfiguration.baseURL !== "string") {
35
- nextConfiguration.baseURL = baseUrl;
36
- }
37
- if (omitAuthHeader) {
38
- nextConfiguration.fetch = buildAuthOmittingFetch(typeof configuration.fetch === "function" ? configuration.fetch : fetch);
39
- }
40
- if (typeof init.numPredict === "number" && typeof normalized.maxTokens !== "number") {
41
- normalized.maxTokens = init.numPredict;
42
- }
43
- if (typeof init.numCtx === "number" && typeof modelKwargs.num_ctx !== "number") {
44
- normalized.modelKwargs = {
45
- ...modelKwargs,
46
- num_ctx: init.numCtx,
47
- };
48
- }
49
- normalized.configuration = nextConfiguration;
50
- delete normalized.baseUrl;
51
- delete normalized.omitAuthHeader;
52
- delete normalized.numPredict;
53
- delete normalized.numCtx;
54
- return normalized;
55
- }
1
+ function d(e){return typeof e=="object"&&e?e:void 0}function f(e){return typeof e=="string"&&e.trim().toLowerCase()==="dummy"}function u(e=fetch){return async(t,r)=>{const n=new Headers(t instanceof Request?t.headers:void 0);return new Headers(r?.headers).forEach((a,o)=>{n.set(o,a)}),n.delete("authorization"),t instanceof Request?e(new Request(t,{...r,headers:n})):e(t,{...r,headers:n})}}function c(e){const t={...e},r=d(e.configuration)??{},n=d(e.modelKwargs)??{},s=typeof e.baseUrl=="string"&&e.baseUrl.trim()?e.baseUrl.trim():void 0,a=e.omitAuthHeader===!0||f(e.apiKey),o={...r};return s&&typeof o.baseURL!="string"&&(o.baseURL=s),a&&(o.fetch=u(typeof r.fetch=="function"?r.fetch:fetch)),typeof e.numPredict=="number"&&typeof t.maxTokens!="number"&&(t.maxTokens=e.numPredict),typeof e.numCtx=="number"&&typeof n.num_ctx!="number"&&(t.modelKwargs={...n,num_ctx:e.numCtx}),t.configuration=o,delete t.baseUrl,delete t.omitAuthHeader,delete t.numPredict,delete t.numCtx,t}export{u as buildAuthOmittingFetch,c as normalizeOpenAICompatibleInit};