@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,428 +1 @@
1
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
3
- import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { randomUUID } from "node:crypto";
5
- import { createServer } from "node:http";
6
- import { pathToFileURL } from "node:url";
7
- import { z } from "zod";
8
- import { AGENT_HARNESS_VERSION } from "../../package-version.js";
9
- import { loadToolModuleDefinition } from "../../tooling/module-loader.js";
10
- function asResolvedTool(value) {
11
- return typeof value === "object" && value !== null ? value : null;
12
- }
13
- async function buildRawShapeForTool(sourceTool, resolvedTool) {
14
- if (!sourceTool) {
15
- return undefined;
16
- }
17
- if (sourceTool.type === "function") {
18
- const imported = await import(pathToFileURL(sourceTool.sourcePath).href);
19
- const definition = loadToolModuleDefinition(imported, sourceTool.implementationName ?? sourceTool.id);
20
- return typeof definition.schema.shape === "object" && definition.schema.shape !== null
21
- ? definition.schema.shape
22
- : undefined;
23
- }
24
- const typedResolvedTool = asResolvedTool(resolvedTool);
25
- if (!typedResolvedTool?.inputSchemaPromise) {
26
- return undefined;
27
- }
28
- return jsonSchemaObjectToRawShape(await typedResolvedTool.inputSchemaPromise);
29
- }
30
- async function invokeResolvedTool(resolvedTool, input) {
31
- const typed = asResolvedTool(resolvedTool);
32
- if (!typed) {
33
- throw new Error("Resolved tool is not invokable.");
34
- }
35
- if (typeof typed.invoke === "function") {
36
- return typed.invoke(input);
37
- }
38
- if (typeof typed.call === "function") {
39
- return typed.call(input);
40
- }
41
- if (typeof typed.func === "function") {
42
- return typed.func(input);
43
- }
44
- throw new Error("Resolved tool does not expose invoke, call, or func.");
45
- }
46
- function renderToolOutput(output) {
47
- if (typeof output === "string") {
48
- return output;
49
- }
50
- return JSON.stringify(output, null, 2);
51
- }
52
- function normalizePath(value, fallback) {
53
- const source = typeof value === "string" && value.trim().length > 0 ? value.trim() : fallback;
54
- return source.startsWith("/") ? source : `/${source}`;
55
- }
56
- function writeJson(response, statusCode, payload) {
57
- response.statusCode = statusCode;
58
- response.setHeader("content-type", "application/json; charset=utf-8");
59
- response.end(JSON.stringify(payload));
60
- }
61
- function readRequestBody(request) {
62
- return new Promise((resolve, reject) => {
63
- const chunks = [];
64
- request.on("data", (chunk) => {
65
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
66
- });
67
- request.on("end", () => {
68
- resolve(Buffer.concat(chunks).toString("utf8"));
69
- });
70
- request.on("error", reject);
71
- });
72
- }
73
- function isInitializeRequest(payload) {
74
- return typeof payload === "object"
75
- && payload !== null
76
- && !Array.isArray(payload)
77
- && payload.method === "initialize";
78
- }
79
- function jsonSchemaObjectToRawShape(schema) {
80
- if (!schema || schema.type !== "object") {
81
- return undefined;
82
- }
83
- const properties = typeof schema.properties === "object" && schema.properties
84
- ? schema.properties
85
- : {};
86
- const required = Array.isArray(schema.required)
87
- ? new Set(schema.required.filter((item) => typeof item === "string"))
88
- : new Set();
89
- const shape = {};
90
- for (const [key, propertySchema] of Object.entries(properties)) {
91
- const built = jsonSchemaToZod(propertySchema);
92
- shape[key] = required.has(key) ? built : built.optional();
93
- }
94
- return shape;
95
- }
96
- function jsonSchemaToZod(schema) {
97
- switch (schema?.type) {
98
- case "string":
99
- return z.string();
100
- case "number":
101
- return z.number();
102
- case "integer":
103
- return z.number().int();
104
- case "boolean":
105
- return z.boolean();
106
- case "array":
107
- return z.array(jsonSchemaToZod(typeof schema.items === "object" && schema.items ? schema.items : undefined));
108
- case "object": {
109
- const shape = jsonSchemaObjectToRawShape(schema);
110
- return z.object(shape ?? {}).passthrough();
111
- }
112
- default:
113
- return z.any();
114
- }
115
- }
116
- export async function createToolMcpServerFromTools(tools, options) {
117
- const server = new McpServer({
118
- name: options.serverInfo?.name ?? `agent-harness-${options.agentId}`,
119
- version: options.serverInfo?.version ?? AGENT_HARNESS_VERSION,
120
- });
121
- const allowedNames = options.includeToolNames ? new Set(options.includeToolNames) : null;
122
- for (const { compiledTool, resolvedTool, sourceTool } of tools) {
123
- if (allowedNames && !allowedNames.has(compiledTool.name)) {
124
- continue;
125
- }
126
- const rawShape = await buildRawShapeForTool(sourceTool, resolvedTool);
127
- server.tool(compiledTool.name, compiledTool.description, rawShape ?? {}, async (input) => ({
128
- content: [
129
- {
130
- type: "text",
131
- text: renderToolOutput(await invokeResolvedTool(resolvedTool, input)),
132
- },
133
- ],
134
- }));
135
- }
136
- return server;
137
- }
138
- export async function serveToolsOverStdioFromHarness(tools, options) {
139
- const server = await createToolMcpServerFromTools(tools, options);
140
- await server.connect(new StdioServerTransport());
141
- return server;
142
- }
143
- export async function createRuntimeMcpServer(runtime, options = {}) {
144
- const server = new McpServer({
145
- name: options.serverInfo?.name ?? "agent-harness-runtime",
146
- version: options.serverInfo?.version ?? AGENT_HARNESS_VERSION,
147
- });
148
- server.tool("list_sessions", "List persisted runtime sessions.", {
149
- agentId: z.string().optional(),
150
- }, async (input) => ({
151
- content: [{
152
- type: "text",
153
- text: renderToolOutput(await runtime.listSessions(input.agentId ? { agentId: input.agentId } : undefined)),
154
- }],
155
- }));
156
- server.tool("get_session", "Get one persisted runtime session by id.", {
157
- sessionId: z.string(),
158
- }, async (input) => ({
159
- content: [{
160
- type: "text",
161
- text: renderToolOutput(await runtime.getSessionRecord(input.sessionId)),
162
- }],
163
- }));
164
- server.tool("list_requests", "List persisted runtime requests.", {
165
- agentId: z.string().optional(),
166
- sessionId: z.string().optional(),
167
- state: z.enum(["queued", "running", "waiting_for_approval", "completed", "failed", "cancelled"]).optional(),
168
- }, async (input) => ({
169
- content: [{
170
- type: "text",
171
- text: renderToolOutput(await runtime.listRequests({
172
- ...(input.agentId ? { agentId: input.agentId } : {}),
173
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
174
- ...(input.state ? { state: input.state } : {}),
175
- })),
176
- }],
177
- }));
178
- server.tool("get_request", "Get one persisted runtime request by id.", {
179
- requestId: z.string(),
180
- }, async (input) => ({
181
- content: [{
182
- type: "text",
183
- text: renderToolOutput(await runtime.getRequest(input.requestId)),
184
- }],
185
- }));
186
- server.tool("list_approvals", "List runtime approvals.", {
187
- status: z.enum(["pending", "approved", "edited", "rejected", "expired"]).optional(),
188
- sessionId: z.string().optional(),
189
- requestId: z.string().optional(),
190
- }, async (input) => ({
191
- content: [{
192
- type: "text",
193
- text: renderToolOutput(await runtime.listApprovals({
194
- ...(input.status ? { status: input.status } : {}),
195
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
196
- ...(input.requestId ? { requestId: input.requestId } : {}),
197
- })),
198
- }],
199
- }));
200
- server.tool("get_approval", "Get one runtime approval by id.", {
201
- approvalId: z.string(),
202
- }, async (input) => ({
203
- content: [{
204
- type: "text",
205
- text: renderToolOutput(await runtime.getApproval(input.approvalId)),
206
- }],
207
- }));
208
- server.tool("resolve_approval", "Resolve one runtime approval.", {
209
- approvalId: z.string(),
210
- decision: z.enum(["approve", "edit", "reject"]),
211
- sessionId: z.string().optional(),
212
- requestId: z.string().optional(),
213
- editedInput: z.record(z.string(), z.any()).optional(),
214
- }, async (input) => ({
215
- content: [{
216
- type: "text",
217
- text: renderToolOutput(await runtime.resume({
218
- approvalId: input.approvalId,
219
- decision: input.decision,
220
- ...(input.sessionId ? { sessionId: input.sessionId } : {}),
221
- ...(input.requestId ? { requestId: input.requestId } : {}),
222
- ...(input.editedInput ? { editedInput: input.editedInput } : {}),
223
- })),
224
- }],
225
- }));
226
- server.tool("list_artifacts", "List artifacts for one runtime request.", {
227
- sessionId: z.string(),
228
- requestId: z.string(),
229
- }, async (input) => ({
230
- content: [{
231
- type: "text",
232
- text: renderToolOutput(await runtime.listRequestArtifacts(input.sessionId, input.requestId)),
233
- }],
234
- }));
235
- server.tool("read_artifact", "Read one runtime artifact.", {
236
- sessionId: z.string(),
237
- requestId: z.string(),
238
- artifactPath: z.string(),
239
- }, async (input) => ({
240
- content: [{
241
- type: "text",
242
- text: renderToolOutput(await runtime.readRequestArtifact(input.sessionId, input.requestId, input.artifactPath)),
243
- }],
244
- }));
245
- server.tool("list_request_events", "List persisted runtime events for one request.", {
246
- sessionId: z.string(),
247
- requestId: z.string(),
248
- }, async (input) => ({
249
- content: [{
250
- type: "text",
251
- text: renderToolOutput(await runtime.listRequestEvents(input.sessionId, input.requestId)),
252
- }],
253
- }));
254
- server.tool("export_request_package", "Export a stable runtime request package for one request.", {
255
- sessionId: z.string(),
256
- requestId: z.string(),
257
- includeArtifacts: z.boolean().optional(),
258
- includeArtifactContents: z.boolean().optional(),
259
- includeRuntimeHealth: z.boolean().optional(),
260
- }, async (input) => ({
261
- content: [{
262
- type: "text",
263
- text: renderToolOutput(await runtime.exportRequestPackage(input)),
264
- }],
265
- }));
266
- server.tool("export_session_package", "Export a stable runtime session package.", {
267
- sessionId: z.string(),
268
- includeArtifacts: z.boolean().optional(),
269
- includeArtifactContents: z.boolean().optional(),
270
- includeRuntimeHealth: z.boolean().optional(),
271
- }, async (input) => ({
272
- content: [{
273
- type: "text",
274
- text: renderToolOutput(await runtime.exportSessionPackage(input)),
275
- }],
276
- }));
277
- return server;
278
- }
279
- export async function serveRuntimeMcpOverStdio(runtime, options = {}) {
280
- const server = await createRuntimeMcpServer(runtime, options);
281
- await server.connect(new StdioServerTransport());
282
- return server;
283
- }
284
- export async function serveRuntimeMcpOverStreamableHttp(runtime, options = {}) {
285
- const hostname = options.hostname?.trim() || "127.0.0.1";
286
- const port = typeof options.port === "number" && Number.isFinite(options.port) ? options.port : 0;
287
- const mcpPath = normalizePath(options.path, "/mcp");
288
- const sessions = new Map();
289
- const closeSession = async (sessionId) => {
290
- const session = sessions.get(sessionId);
291
- if (!session) {
292
- return;
293
- }
294
- sessions.delete(sessionId);
295
- await Promise.allSettled([
296
- session.transport.close(),
297
- session.server.close(),
298
- ]);
299
- };
300
- const httpServer = createServer(async (request, response) => {
301
- try {
302
- const requestUrl = new URL(request.url ?? "/", `http://${hostname}`);
303
- if (requestUrl.pathname !== mcpPath) {
304
- writeJson(response, 404, {
305
- error: "Not Found",
306
- path: mcpPath,
307
- });
308
- return;
309
- }
310
- const headerValue = request.headers["mcp-session-id"];
311
- const sessionId = Array.isArray(headerValue) ? headerValue[0] : headerValue;
312
- if (request.method === "POST") {
313
- const body = await readRequestBody(request);
314
- let payload;
315
- try {
316
- payload = JSON.parse(body);
317
- }
318
- catch {
319
- writeJson(response, 400, {
320
- jsonrpc: "2.0",
321
- id: null,
322
- error: {
323
- code: -32700,
324
- message: "Invalid JSON payload.",
325
- },
326
- });
327
- return;
328
- }
329
- const existingSession = sessionId ? sessions.get(sessionId) : undefined;
330
- if (existingSession) {
331
- await existingSession.transport.handleRequest(request, response, payload);
332
- return;
333
- }
334
- if (sessionId || !isInitializeRequest(payload)) {
335
- writeJson(response, 400, {
336
- jsonrpc: "2.0",
337
- id: null,
338
- error: {
339
- code: -32000,
340
- message: "Bad Request: No valid MCP session was provided.",
341
- },
342
- });
343
- return;
344
- }
345
- let createdTransport;
346
- const server = await createRuntimeMcpServer(runtime, options);
347
- const transport = new StreamableHTTPServerTransport({
348
- sessionIdGenerator: () => randomUUID(),
349
- onsessioninitialized: (initializedSessionId) => {
350
- sessions.set(initializedSessionId, { transport, server });
351
- },
352
- });
353
- createdTransport = transport;
354
- transport.onclose = () => {
355
- const activeSessionId = createdTransport?.sessionId;
356
- if (activeSessionId) {
357
- const active = sessions.get(activeSessionId);
358
- if (active?.transport === createdTransport) {
359
- sessions.delete(activeSessionId);
360
- }
361
- }
362
- };
363
- await server.connect(transport);
364
- await transport.handleRequest(request, response, payload);
365
- return;
366
- }
367
- if (request.method === "GET" || request.method === "DELETE") {
368
- if (!sessionId || !sessions.has(sessionId)) {
369
- writeJson(response, 400, {
370
- jsonrpc: "2.0",
371
- id: null,
372
- error: {
373
- code: -32000,
374
- message: "Bad Request: No valid MCP session was provided.",
375
- },
376
- });
377
- return;
378
- }
379
- const session = sessions.get(sessionId);
380
- await session.transport.handleRequest(request, response);
381
- if (request.method === "DELETE") {
382
- await closeSession(sessionId);
383
- }
384
- return;
385
- }
386
- response.statusCode = 405;
387
- response.setHeader("allow", "GET, POST, DELETE");
388
- response.end();
389
- }
390
- catch (error) {
391
- writeJson(response, 500, {
392
- error: error instanceof Error ? error.message : "Runtime MCP Streamable HTTP transport failed.",
393
- });
394
- }
395
- });
396
- const completed = new Promise((resolve, reject) => {
397
- httpServer.once("close", resolve);
398
- httpServer.once("error", reject);
399
- });
400
- await new Promise((resolve, reject) => {
401
- httpServer.listen(port, hostname, () => resolve());
402
- httpServer.once("error", reject);
403
- });
404
- const address = httpServer.address();
405
- const resolvedPort = typeof address === "object" && address ? address.port : port;
406
- return {
407
- hostname,
408
- port: resolvedPort,
409
- path: mcpPath,
410
- url: `http://${hostname}:${resolvedPort}${mcpPath}`,
411
- completed,
412
- close: async () => {
413
- const sessionIds = Array.from(sessions.keys());
414
- for (const sessionId of sessionIds) {
415
- await closeSession(sessionId);
416
- }
417
- await new Promise((resolve, reject) => {
418
- httpServer.close((error) => {
419
- if (error) {
420
- reject(error);
421
- return;
422
- }
423
- resolve();
424
- });
425
- });
426
- },
427
- };
428
- }
1
+ import{McpServer as T}from"@modelcontextprotocol/sdk/server/mcp.js";import{StreamableHTTPServerTransport as O}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{StdioServerTransport as P}from"@modelcontextprotocol/sdk/server/stdio.js";import{randomUUID as k}from"node:crypto";import{createServer as L}from"node:http";import{pathToFileURL as M}from"node:url";import{z as n}from"zod";import{AGENT_HARNESS_VERSION as E}from"../../package-version.js";import{loadToolModuleDefinition as H}from"../../tooling/module-loader.js";function j(e){return typeof e=="object"&&e!==null?e:null}async function B(e,s){if(!e)return;if(e.type==="function"){const t=await import(M(e.sourcePath).href),a=H(t,e.implementationName??e.id);return typeof a.schema.shape=="object"&&a.schema.shape!==null?a.schema.shape:void 0}const o=j(s);if(o?.inputSchemaPromise)return _(await o.inputSchemaPromise)}async function C(e,s){const o=j(e);if(!o)throw new Error("Resolved tool is not invokable.");if(typeof o.invoke=="function")return o.invoke(s);if(typeof o.call=="function")return o.call(s);if(typeof o.func=="function")return o.func(s);throw new Error("Resolved tool does not expose invoke, call, or func.")}function d(e){return typeof e=="string"?e:JSON.stringify(e,null,2)}function G(e,s){const o=typeof e=="string"&&e.trim().length>0?e.trim():s;return o.startsWith("/")?o:`/${o}`}function g(e,s,o){e.statusCode=s,e.setHeader("content-type","application/json; charset=utf-8"),e.end(JSON.stringify(o))}function F(e){return new Promise((s,o)=>{const t=[];e.on("data",a=>{t.push(Buffer.isBuffer(a)?a:Buffer.from(a))}),e.on("end",()=>{s(Buffer.concat(t).toString("utf8"))}),e.on("error",o)})}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e.method==="initialize"}function _(e){if(!e||e.type!=="object")return;const s=typeof e.properties=="object"&&e.properties?e.properties:{},o=Array.isArray(e.required)?new Set(e.required.filter(a=>typeof a=="string")):new Set,t={};for(const[a,c]of Object.entries(s)){const p=A(c);t[a]=o.has(a)?p:p.optional()}return t}function A(e){switch(e?.type){case"string":return n.string();case"number":return n.number();case"integer":return n.number().int();case"boolean":return n.boolean();case"array":return n.array(A(typeof e.items=="object"&&e.items?e.items:void 0));case"object":{const s=_(e);return n.object(s??{}).passthrough()}default:return n.any()}}async function $(e,s){const o=new T({name:s.serverInfo?.name??`agent-harness-${s.agentId}`,version:s.serverInfo?.version??E}),t=s.includeToolNames?new Set(s.includeToolNames):null;for(const{compiledTool:a,resolvedTool:c,sourceTool:p}of e){if(t&&!t.has(a.name))continue;const l=await B(p,c);o.tool(a.name,a.description,l??{},async w=>({content:[{type:"text",text:d(await C(c,w))}]}))}return o}async function ee(e,s){const o=await $(e,s);return await o.connect(new P),o}async function N(e,s={}){const o=new T({name:s.serverInfo?.name??"agent-harness-runtime",version:s.serverInfo?.version??E});return o.tool("list_sessions","List persisted runtime sessions.",{agentId:n.string().optional()},async t=>({content:[{type:"text",text:d(await e.listSessions(t.agentId?{agentId:t.agentId}:void 0))}]})),o.tool("get_session","Get one persisted runtime session by id.",{sessionId:n.string()},async t=>({content:[{type:"text",text:d(await e.getSessionRecord(t.sessionId))}]})),o.tool("list_requests","List persisted runtime requests.",{agentId:n.string().optional(),sessionId:n.string().optional(),state:n.enum(["queued","running","waiting_for_approval","completed","failed","cancelled"]).optional()},async t=>({content:[{type:"text",text:d(await e.listRequests({...t.agentId?{agentId:t.agentId}:{},...t.sessionId?{sessionId:t.sessionId}:{},...t.state?{state:t.state}:{}}))}]})),o.tool("get_request","Get one persisted runtime request by id.",{requestId:n.string()},async t=>({content:[{type:"text",text:d(await e.getRequest(t.requestId))}]})),o.tool("list_approvals","List runtime approvals.",{status:n.enum(["pending","approved","edited","rejected","expired"]).optional(),sessionId:n.string().optional(),requestId:n.string().optional()},async t=>({content:[{type:"text",text:d(await e.listApprovals({...t.status?{status:t.status}:{},...t.sessionId?{sessionId:t.sessionId}:{},...t.requestId?{requestId:t.requestId}:{}}))}]})),o.tool("get_approval","Get one runtime approval by id.",{approvalId:n.string()},async t=>({content:[{type:"text",text:d(await e.getApproval(t.approvalId))}]})),o.tool("resolve_approval","Resolve one runtime approval.",{approvalId:n.string(),decision:n.enum(["approve","edit","reject"]),sessionId:n.string().optional(),requestId:n.string().optional(),editedInput:n.record(n.string(),n.any()).optional()},async t=>({content:[{type:"text",text:d(await e.resume({approvalId:t.approvalId,decision:t.decision,...t.sessionId?{sessionId:t.sessionId}:{},...t.requestId?{requestId:t.requestId}:{},...t.editedInput?{editedInput:t.editedInput}:{}}))}]})),o.tool("list_artifacts","List artifacts for one runtime request.",{sessionId:n.string(),requestId:n.string()},async t=>({content:[{type:"text",text:d(await e.listRequestArtifacts(t.sessionId,t.requestId))}]})),o.tool("read_artifact","Read one runtime artifact.",{sessionId:n.string(),requestId:n.string(),artifactPath:n.string()},async t=>({content:[{type:"text",text:d(await e.readRequestArtifact(t.sessionId,t.requestId,t.artifactPath))}]})),o.tool("list_request_events","List persisted runtime events for one request.",{sessionId:n.string(),requestId:n.string()},async t=>({content:[{type:"text",text:d(await e.listRequestEvents(t.sessionId,t.requestId))}]})),o.tool("export_request_package","Export a stable runtime request package for one request.",{sessionId:n.string(),requestId:n.string(),includeArtifacts:n.boolean().optional(),includeArtifactContents:n.boolean().optional(),includeRuntimeHealth:n.boolean().optional()},async t=>({content:[{type:"text",text:d(await e.exportRequestPackage(t))}]})),o.tool("export_session_package","Export a stable runtime session package.",{sessionId:n.string(),includeArtifacts:n.boolean().optional(),includeArtifactContents:n.boolean().optional(),includeRuntimeHealth:n.boolean().optional()},async t=>({content:[{type:"text",text:d(await e.exportSessionPackage(t))}]})),o}async function te(e,s={}){const o=await N(e,s);return await o.connect(new P),o}async function oe(e,s={}){const o=s.hostname?.trim()||"127.0.0.1",t=typeof s.port=="number"&&Number.isFinite(s.port)?s.port:0,a=G(s.path,"/mcp"),c=new Map,p=async i=>{const r=c.get(i);r&&(c.delete(i),await Promise.allSettled([r.transport.close(),r.server.close()]))},l=L(async(i,r)=>{try{if(new URL(i.url??"/",`http://${o}`).pathname!==a){g(r,404,{error:"Not Found",path:a});return}const f=i.headers["mcp-session-id"],u=Array.isArray(f)?f[0]:f;if(i.method==="POST"){const b=await F(i);let v;try{v=JSON.parse(b)}catch{g(r,400,{jsonrpc:"2.0",id:null,error:{code:-32700,message:"Invalid JSON payload."}});return}const q=u?c.get(u):void 0;if(q){await q.transport.handleRequest(i,r,v);return}if(u||!U(v)){g(r,400,{jsonrpc:"2.0",id:null,error:{code:-32e3,message:"Bad Request: No valid MCP session was provided."}});return}let S;const R=await N(e,s),y=new O({sessionIdGenerator:()=>k(),onsessioninitialized:I=>{c.set(I,{transport:y,server:R})}});S=y,y.onclose=()=>{const I=S?.sessionId;I&&c.get(I)?.transport===S&&c.delete(I)},await R.connect(y),await y.handleRequest(i,r,v);return}if(i.method==="GET"||i.method==="DELETE"){if(!u||!c.has(u)){g(r,400,{jsonrpc:"2.0",id:null,error:{code:-32e3,message:"Bad Request: No valid MCP session was provided."}});return}await c.get(u).transport.handleRequest(i,r),i.method==="DELETE"&&await p(u);return}r.statusCode=405,r.setHeader("allow","GET, POST, DELETE"),r.end()}catch(m){g(r,500,{error:m instanceof Error?m.message:"Runtime MCP Streamable HTTP transport failed."})}}),w=new Promise((i,r)=>{l.once("close",i),l.once("error",r)});await new Promise((i,r)=>{l.listen(t,o,()=>i()),l.once("error",r)});const h=l.address(),x=typeof h=="object"&&h?h.port:t;return{hostname:o,port:x,path:a,url:`http://${o}:${x}${a}`,completed:w,close:async()=>{const i=Array.from(c.keys());for(const r of i)await p(r);await new Promise((r,m)=>{l.close(f=>{if(f){m(f);return}r()})})}}}export{N as createRuntimeMcpServer,$ as createToolMcpServerFromTools,te as serveRuntimeMcpOverStdio,oe as serveRuntimeMcpOverStreamableHttp,ee as serveToolsOverStdioFromHarness};