@botbotgo/agent-harness 0.0.102 → 0.0.103

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.
@@ -1 +1 @@
1
- export declare const AGENT_HARNESS_VERSION = "0.0.101";
1
+ export declare const AGENT_HARNESS_VERSION = "0.0.102";
@@ -1 +1 @@
1
- export const AGENT_HARNESS_VERSION = "0.0.101";
1
+ export const AGENT_HARNESS_VERSION = "0.0.102";
@@ -0,0 +1,75 @@
1
+ import { FilesystemBackend } from "deepagents";
2
+ import type { CompiledAgentBinding, CompiledModel, CompiledSubAgent, DeepAgentParams, RuntimeAdapterOptions } from "../../contracts/types.js";
3
+ import type { ExecutableTool } from "./invoke-runtime.js";
4
+ export declare function resolveBuiltinMiddlewareBackend(input: {
5
+ binding: CompiledAgentBinding;
6
+ runtimeAdapterOptions: RuntimeAdapterOptions;
7
+ resolveFilesystemBackend: (binding: CompiledAgentBinding) => FilesystemBackend;
8
+ options?: {
9
+ state?: Record<string, unknown>;
10
+ files?: Record<string, unknown>;
11
+ };
12
+ }): unknown;
13
+ export declare function resolveSubagents(input: {
14
+ subagents: CompiledSubAgent[];
15
+ binding?: CompiledAgentBinding;
16
+ resolveModel: (model: CompiledModel) => Promise<unknown>;
17
+ resolveTools: (tools: Parameters<DeepAgentParams["tools"]["slice"]>[0] extends never ? never : any, binding?: CompiledAgentBinding) => unknown[];
18
+ createDeclaredMiddlewareResolverOptions: (binding?: CompiledAgentBinding) => unknown;
19
+ }): Promise<CompiledSubAgent[]>;
20
+ export declare function invokeBuiltinTaskTool(input: {
21
+ binding: CompiledAgentBinding;
22
+ toolInput: unknown;
23
+ options?: {
24
+ context?: Record<string, unknown>;
25
+ state?: Record<string, unknown>;
26
+ files?: Record<string, unknown>;
27
+ };
28
+ resolveBuiltinMiddlewareBackend: (binding: CompiledAgentBinding, options?: {
29
+ context?: Record<string, unknown>;
30
+ state?: Record<string, unknown>;
31
+ files?: Record<string, unknown>;
32
+ }) => unknown;
33
+ resolveSubagents: (subagents: CompiledSubAgent[], binding?: CompiledAgentBinding) => Promise<CompiledSubAgent[]>;
34
+ resolveModel: (model: CompiledModel) => Promise<unknown>;
35
+ resolveTools: (tools: Parameters<DeepAgentParams["tools"]["slice"]>[0] extends never ? never : any, binding?: CompiledAgentBinding) => unknown[];
36
+ }): Promise<unknown>;
37
+ export declare function resolveBuiltinMiddlewareTools(input: {
38
+ binding: CompiledAgentBinding;
39
+ options?: {
40
+ context?: Record<string, unknown>;
41
+ state?: Record<string, unknown>;
42
+ files?: Record<string, unknown>;
43
+ };
44
+ resolveBuiltinMiddlewareBackend: (binding: CompiledAgentBinding, options?: {
45
+ context?: Record<string, unknown>;
46
+ state?: Record<string, unknown>;
47
+ files?: Record<string, unknown>;
48
+ }) => unknown;
49
+ invokeBuiltinTaskTool: (binding: CompiledAgentBinding, toolInput: unknown, options?: {
50
+ context?: Record<string, unknown>;
51
+ state?: Record<string, unknown>;
52
+ files?: Record<string, unknown>;
53
+ }) => Promise<unknown>;
54
+ }): Promise<Map<string, ExecutableTool>>;
55
+ export declare function resolveAutomaticSummarizationMiddleware(input: {
56
+ binding: CompiledAgentBinding;
57
+ createDeclaredMiddlewareResolverOptions: (binding?: CompiledAgentBinding) => unknown;
58
+ }): Promise<unknown[]>;
59
+ export declare function resolveLangChainAutomaticMiddleware(input: {
60
+ binding: CompiledAgentBinding;
61
+ resolveAutomaticSummarizationMiddleware: (binding: CompiledAgentBinding) => Promise<unknown[]>;
62
+ resolveFilesystemBackend: (binding: CompiledAgentBinding) => FilesystemBackend;
63
+ resolveModel: (model: CompiledModel) => Promise<unknown>;
64
+ resolveTools: (tools: Parameters<DeepAgentParams["tools"]["slice"]>[0] extends never ? never : any, binding?: CompiledAgentBinding) => unknown[];
65
+ resolveSubagents: (subagents: CompiledSubAgent[], binding?: CompiledAgentBinding) => Promise<CompiledSubAgent[]>;
66
+ }): Promise<unknown[]>;
67
+ export declare function resolveMiddleware(input: {
68
+ binding: CompiledAgentBinding;
69
+ interruptOn?: Record<string, {
70
+ allowedDecisions: Array<"approve" | "edit" | "reject">;
71
+ }>;
72
+ runtimeAdapterOptions: RuntimeAdapterOptions;
73
+ createDeclaredMiddlewareResolverOptions: (binding?: CompiledAgentBinding) => unknown;
74
+ resolveLangChainAutomaticMiddleware: (binding: CompiledAgentBinding) => Promise<unknown[]>;
75
+ }): Promise<unknown[]>;
@@ -0,0 +1,175 @@
1
+ import { HumanMessage } from "@langchain/core/messages";
2
+ import { DEFAULT_SUBAGENT_PROMPT, createMemoryMiddleware, createPatchToolCallsMiddleware, createSkillsMiddleware, createSubAgentMiddleware, createSummarizationMiddleware, StateBackend, } from "deepagents";
3
+ import { createAgent, humanInTheLoopMiddleware } from "langchain";
4
+ import { createBuiltinMiddlewareTools } from "./tool/builtin-middleware-tools.js";
5
+ import { compileInterruptOn } from "./tool/interrupt-policy.js";
6
+ import { extractToolFallbackContext, extractVisibleOutput } from "../parsing/output-parsing.js";
7
+ import { hasConfiguredMiddlewareKind, hasConfiguredSubagentSupport, isObject, isRecord } from "./runtime-adapter-support.js";
8
+ import { resolveDeclaredMiddleware } from "./tool/declared-middleware.js";
9
+ import { getBindingDeepAgentParams, getBindingInterruptCompatibilityRules, getBindingLangChainParams, getBindingMiddlewareConfigs, getBindingPrimaryModel, isDeepAgentBinding, isLangChainBinding, } from "../support/compiled-binding.js";
10
+ import { applyDeepAgentDelegationPromptCompatibility, materializeDeepAgentSkillSourcePaths } from "./compat/deepagent-compat.js";
11
+ export function resolveBuiltinMiddlewareBackend(input) {
12
+ const runtimeState = {
13
+ ...(input.options?.state ?? {}),
14
+ ...(isRecord(input.options?.files) ? { files: input.options?.files } : {}),
15
+ };
16
+ const runtimeLike = {
17
+ state: runtimeState,
18
+ store: input.runtimeAdapterOptions.storeResolver?.(input.binding),
19
+ };
20
+ const configuredBackend = isDeepAgentBinding(input.binding)
21
+ ? input.runtimeAdapterOptions.backendResolver?.(input.binding)
22
+ : input.resolveFilesystemBackend(input.binding);
23
+ if (typeof configuredBackend === "function") {
24
+ return configuredBackend(runtimeLike);
25
+ }
26
+ if (configuredBackend) {
27
+ return configuredBackend;
28
+ }
29
+ return new StateBackend(runtimeLike);
30
+ }
31
+ export async function resolveSubagents(input) {
32
+ return Promise.all(input.subagents.map(async (subagent) => ({
33
+ ...subagent,
34
+ ...(subagent.passthrough ?? {}),
35
+ model: subagent.model ? (await input.resolveModel(subagent.model)) : undefined,
36
+ tools: subagent.tools ? input.resolveTools(subagent.tools, input.binding) : undefined,
37
+ skills: await materializeDeepAgentSkillSourcePaths({
38
+ workspaceRoot: input.binding?.harnessRuntime.workspaceRoot,
39
+ runRoot: input.binding?.harnessRuntime.runRoot,
40
+ ownerId: `${input.binding?.agent.id ?? "agent"}-${subagent.name}`,
41
+ skillPaths: subagent.skills,
42
+ }),
43
+ interruptOn: compileInterruptOn(subagent.tools ?? [], subagent.interruptOn),
44
+ responseFormat: subagent.responseFormat,
45
+ contextSchema: subagent.contextSchema,
46
+ middleware: (await resolveDeclaredMiddleware(subagent.middleware, input.createDeclaredMiddlewareResolverOptions(input.binding))),
47
+ })));
48
+ }
49
+ export async function invokeBuiltinTaskTool(input) {
50
+ if (!isDeepAgentBinding(input.binding)) {
51
+ throw new Error("The built-in task tool is only available for deepagent bindings.");
52
+ }
53
+ const params = getBindingDeepAgentParams(input.binding);
54
+ if (!params) {
55
+ throw new Error(`Agent ${input.binding.agent.id} has no deepagent params`);
56
+ }
57
+ const typedInput = isObject(input.toolInput) ? input.toolInput : {};
58
+ const description = typeof typedInput.description === "string" ? typedInput.description : "";
59
+ const subagentType = typeof typedInput.subagent_type === "string" ? typedInput.subagent_type : "";
60
+ const builtinBackend = input.resolveBuiltinMiddlewareBackend(input.binding, input.options);
61
+ const resolvedSubagents = await input.resolveSubagents(params.subagents, input.binding);
62
+ const selectedSubagent = resolvedSubagents.find((subagent) => subagent.name === subagentType);
63
+ if (!selectedSubagent) {
64
+ const allowed = [
65
+ ...resolvedSubagents.map((subagent) => subagent.name),
66
+ ...(params.generalPurposeAgent ? ["general-purpose"] : []),
67
+ ];
68
+ throw new Error(`Error: invoked agent of type ${subagentType}, the only allowed types are ${allowed.map((name) => `\`${name}\``).join(", ")}`);
69
+ }
70
+ const summarizationModel = selectedSubagent.model
71
+ ? await input.resolveModel(selectedSubagent.model)
72
+ : await input.resolveModel(params.model);
73
+ const middleware = [
74
+ ...(selectedSubagent.skills?.length
75
+ ? [createSkillsMiddleware({ backend: builtinBackend, sources: selectedSubagent.skills })]
76
+ : []),
77
+ ...(selectedSubagent.memory?.length
78
+ ? [createMemoryMiddleware({ backend: builtinBackend, sources: selectedSubagent.memory })]
79
+ : []),
80
+ ...(selectedSubagent.middleware ??
81
+ [
82
+ createPatchToolCallsMiddleware(),
83
+ createSummarizationMiddleware({
84
+ model: summarizationModel,
85
+ backend: builtinBackend,
86
+ }),
87
+ ]),
88
+ ...(selectedSubagent.interruptOn
89
+ ? [humanInTheLoopMiddleware({
90
+ interruptOn: compileInterruptOn(selectedSubagent.tools ?? [], selectedSubagent.interruptOn),
91
+ })]
92
+ : []),
93
+ ];
94
+ const runnable = createAgent({
95
+ model: (selectedSubagent.model ?? (await input.resolveModel(params.model))),
96
+ tools: (selectedSubagent.tools ?? input.resolveTools(params.tools, input.binding)),
97
+ systemPrompt: selectedSubagent.systemPrompt ?? DEFAULT_SUBAGENT_PROMPT,
98
+ middleware: middleware,
99
+ responseFormat: selectedSubagent.responseFormat,
100
+ contextSchema: selectedSubagent.contextSchema,
101
+ name: selectedSubagent.name,
102
+ description: selectedSubagent.description,
103
+ });
104
+ const result = await runnable.invoke({ messages: [new HumanMessage({ content: description })] }, { configurable: { thread_id: `${input.binding.agent.id}:builtin-task` }, ...(input.options?.context ? { context: input.options.context } : {}) });
105
+ const visibleOutput = extractVisibleOutput(result);
106
+ const fallbackOutput = extractToolFallbackContext(result);
107
+ return visibleOutput || fallbackOutput || JSON.stringify(result);
108
+ }
109
+ export async function resolveBuiltinMiddlewareTools(input) {
110
+ const backend = input.resolveBuiltinMiddlewareBackend(input.binding, input.options);
111
+ return createBuiltinMiddlewareTools(backend, {
112
+ includeTaskTool: isDeepAgentBinding(input.binding),
113
+ invokeTaskTool: isDeepAgentBinding(input.binding)
114
+ ? async (toolInput) => input.invokeBuiltinTaskTool(input.binding, toolInput, input.options)
115
+ : undefined,
116
+ });
117
+ }
118
+ export async function resolveAutomaticSummarizationMiddleware(input) {
119
+ if (hasConfiguredMiddlewareKind(input.binding, "summarization")) {
120
+ return [];
121
+ }
122
+ const primaryModel = getBindingPrimaryModel(input.binding);
123
+ if (!primaryModel) {
124
+ return [];
125
+ }
126
+ return resolveDeclaredMiddleware([{ kind: "summarization", model: primaryModel }], input.createDeclaredMiddlewareResolverOptions(input.binding));
127
+ }
128
+ export async function resolveLangChainAutomaticMiddleware(input) {
129
+ const params = getBindingLangChainParams(input.binding);
130
+ if (!params) {
131
+ return [];
132
+ }
133
+ const compatibleParams = applyDeepAgentDelegationPromptCompatibility(params.model, params);
134
+ const automaticMiddleware = [];
135
+ automaticMiddleware.push(createPatchToolCallsMiddleware());
136
+ automaticMiddleware.push(...(await input.resolveAutomaticSummarizationMiddleware(input.binding)));
137
+ if ((compatibleParams.skills?.length ?? 0) > 0) {
138
+ automaticMiddleware.push(createSkillsMiddleware({
139
+ backend: input.resolveFilesystemBackend(input.binding),
140
+ sources: compatibleParams.skills,
141
+ }));
142
+ }
143
+ if ((compatibleParams.memory?.length ?? 0) > 0) {
144
+ automaticMiddleware.push(createMemoryMiddleware({
145
+ backend: input.resolveFilesystemBackend(input.binding),
146
+ sources: compatibleParams.memory,
147
+ }));
148
+ }
149
+ if (hasConfiguredSubagentSupport(input.binding)) {
150
+ automaticMiddleware.push(createSubAgentMiddleware({
151
+ defaultModel: (await input.resolveModel(compatibleParams.model)),
152
+ defaultTools: input.resolveTools(compatibleParams.tools, input.binding),
153
+ defaultInterruptOn: getBindingInterruptCompatibilityRules(input.binding),
154
+ subagents: (await input.resolveSubagents(compatibleParams.subagents ?? [], input.binding)),
155
+ generalPurposeAgent: compatibleParams.generalPurposeAgent,
156
+ taskDescription: compatibleParams.taskDescription ?? null,
157
+ }));
158
+ }
159
+ return automaticMiddleware;
160
+ }
161
+ export async function resolveMiddleware(input) {
162
+ const declarativeMiddleware = await resolveDeclaredMiddleware(getBindingMiddlewareConfigs(input.binding), input.createDeclaredMiddlewareResolverOptions(input.binding));
163
+ const automaticMiddleware = isLangChainBinding(input.binding)
164
+ ? await input.resolveLangChainAutomaticMiddleware(input.binding)
165
+ : [];
166
+ const middleware = [
167
+ ...declarativeMiddleware,
168
+ ...automaticMiddleware,
169
+ ...(input.runtimeAdapterOptions.middlewareResolver ? input.runtimeAdapterOptions.middlewareResolver(input.binding) : []),
170
+ ];
171
+ if (input.interruptOn && Object.keys(input.interruptOn).length > 0) {
172
+ middleware.push(humanInTheLoopMiddleware({ interruptOn: input.interruptOn }));
173
+ }
174
+ return middleware;
175
+ }
@@ -0,0 +1,27 @@
1
+ import type { CompiledAgentBinding } from "../../contracts/types.js";
2
+ export declare class RuntimeOperationTimeoutError extends Error {
3
+ readonly operation: string;
4
+ readonly timeoutMs: number;
5
+ readonly stage: "stream" | "invoke";
6
+ constructor(operation: string, timeoutMs: number, stage?: "stream" | "invoke");
7
+ }
8
+ export declare function invokeWithProviderRetry<T>(binding: CompiledAgentBinding, operation: () => Promise<T>): Promise<T>;
9
+ export declare function withRuntimeTimeout<T>(producer: () => T | Promise<T>, timeoutMs: number | undefined, operation: string, stage?: "stream" | "invoke"): Promise<T>;
10
+ export declare function iterateWithTimeout<T>(iterable: AsyncIterable<T>, timeoutMs: number | undefined, operation: string, deadlineAt?: number, deadlineTimeoutMs?: number): AsyncGenerator<T>;
11
+ export declare function materializeModelStream(streamFactory: (input: unknown, config?: Record<string, unknown>) => Promise<AsyncIterable<unknown>>, input: unknown, config?: Record<string, unknown>): Promise<{
12
+ content: string;
13
+ }>;
14
+ export declare function createModelFallbackRunnable(model: {
15
+ invoke?: (input: unknown, config?: Record<string, unknown>) => Promise<unknown>;
16
+ stream?: (input: unknown, config?: Record<string, unknown>) => Promise<AsyncIterable<unknown>>;
17
+ }): {
18
+ invoke: (input: unknown, config?: Record<string, unknown>) => Promise<unknown>;
19
+ stream: (input: unknown, config?: Record<string, unknown>) => Promise<AsyncIterable<unknown>>;
20
+ };
21
+ export declare function applyStrictToolJsonInstruction(binding: CompiledAgentBinding): CompiledAgentBinding;
22
+ export declare function callRuntimeWithToolParseRecovery(input: {
23
+ binding: CompiledAgentBinding;
24
+ request: unknown;
25
+ resumePayload?: unknown;
26
+ callRuntime: (binding: CompiledAgentBinding, request: unknown) => Promise<Record<string, unknown>>;
27
+ }): Promise<Record<string, unknown>>;
@@ -0,0 +1,168 @@
1
+ import { extractVisibleOutput, isToolCallParseFailure, STRICT_TOOL_JSON_INSTRUCTION } from "../parsing/output-parsing.js";
2
+ import { readStreamDelta } from "../parsing/stream-event-parsing.js";
3
+ import { computeRemainingTimeoutMs, isRetryableProviderError, resolveProviderRetryPolicy } from "./resilience.js";
4
+ import { sleep } from "./runtime-adapter-support.js";
5
+ import { getBindingDeepAgentParams, getBindingLangChainParams, isDeepAgentBinding, isLangChainBinding, } from "../support/compiled-binding.js";
6
+ export class RuntimeOperationTimeoutError extends Error {
7
+ operation;
8
+ timeoutMs;
9
+ stage;
10
+ constructor(operation, timeoutMs, stage = operation.includes("stream") ? "stream" : "invoke") {
11
+ super(`${operation} timed out after ${timeoutMs}ms`);
12
+ this.operation = operation;
13
+ this.timeoutMs = timeoutMs;
14
+ this.stage = stage;
15
+ this.name = "RuntimeOperationTimeoutError";
16
+ }
17
+ }
18
+ export async function invokeWithProviderRetry(binding, operation) {
19
+ const retryPolicy = resolveProviderRetryPolicy(binding);
20
+ let lastError;
21
+ for (let attempt = 1; attempt <= retryPolicy.maxAttempts; attempt += 1) {
22
+ try {
23
+ return await operation();
24
+ }
25
+ catch (error) {
26
+ lastError = error;
27
+ if (attempt >= retryPolicy.maxAttempts || !isRetryableProviderError(binding, error)) {
28
+ throw error;
29
+ }
30
+ if (retryPolicy.backoffMs > 0) {
31
+ await sleep(retryPolicy.backoffMs);
32
+ }
33
+ }
34
+ }
35
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
36
+ }
37
+ export async function withRuntimeTimeout(producer, timeoutMs, operation, stage = operation.includes("stream") ? "stream" : "invoke") {
38
+ if (!timeoutMs) {
39
+ return Promise.resolve(producer());
40
+ }
41
+ return new Promise((resolve, reject) => {
42
+ const timer = setTimeout(() => reject(new RuntimeOperationTimeoutError(operation, timeoutMs, stage)), timeoutMs);
43
+ Promise.resolve(producer()).then((value) => {
44
+ clearTimeout(timer);
45
+ resolve(value);
46
+ }, (error) => {
47
+ clearTimeout(timer);
48
+ reject(error);
49
+ });
50
+ });
51
+ }
52
+ export async function* iterateWithTimeout(iterable, timeoutMs, operation, deadlineAt, deadlineTimeoutMs) {
53
+ const iterator = iterable[Symbol.asyncIterator]();
54
+ try {
55
+ for (;;) {
56
+ const effectiveTimeoutMs = computeRemainingTimeoutMs(deadlineAt, timeoutMs);
57
+ if (effectiveTimeoutMs !== undefined && effectiveTimeoutMs <= 0) {
58
+ throw new RuntimeOperationTimeoutError(operation, deadlineTimeoutMs ?? timeoutMs ?? 0, "invoke");
59
+ }
60
+ let next;
61
+ try {
62
+ next = await withRuntimeTimeout(() => iterator.next(), effectiveTimeoutMs, operation, "stream");
63
+ }
64
+ catch (error) {
65
+ if (error instanceof RuntimeOperationTimeoutError &&
66
+ deadlineAt &&
67
+ deadlineTimeoutMs &&
68
+ effectiveTimeoutMs !== timeoutMs) {
69
+ throw new RuntimeOperationTimeoutError(operation, deadlineTimeoutMs, "invoke");
70
+ }
71
+ throw error;
72
+ }
73
+ if (next.done) {
74
+ return;
75
+ }
76
+ yield next.value;
77
+ }
78
+ }
79
+ finally {
80
+ if (typeof iterator.return === "function") {
81
+ const returnResult = iterator.return();
82
+ if (returnResult && typeof returnResult.then === "function") {
83
+ void returnResult.catch(() => undefined);
84
+ }
85
+ }
86
+ }
87
+ }
88
+ export async function materializeModelStream(streamFactory, input, config) {
89
+ const stream = await streamFactory(input, config);
90
+ let content = "";
91
+ for await (const chunk of stream) {
92
+ const delta = readStreamDelta(chunk) || extractVisibleOutput(chunk);
93
+ if (delta) {
94
+ content += delta;
95
+ }
96
+ }
97
+ return { content };
98
+ }
99
+ export function createModelFallbackRunnable(model) {
100
+ return {
101
+ invoke: async (input, config) => {
102
+ const request = typeof input === "object" && input !== null && "messages" in input
103
+ ? input.messages
104
+ : input;
105
+ if (typeof model.invoke === "function") {
106
+ return model.invoke(request, config);
107
+ }
108
+ if (typeof model.stream === "function") {
109
+ return materializeModelStream(model.stream.bind(model), request, config);
110
+ }
111
+ throw new Error("Resolved model must define invoke or stream.");
112
+ },
113
+ stream: async (input, config) => {
114
+ if (typeof model.stream === "function") {
115
+ const request = typeof input === "object" && input !== null && "messages" in input
116
+ ? input.messages
117
+ : input;
118
+ return model.stream(request, config);
119
+ }
120
+ if (typeof model.invoke === "function") {
121
+ const request = typeof input === "object" && input !== null && "messages" in input
122
+ ? input.messages
123
+ : input;
124
+ const result = await model.invoke(request, config);
125
+ const text = extractVisibleOutput(result);
126
+ async function* singleChunk() {
127
+ yield { content: text };
128
+ }
129
+ return singleChunk();
130
+ }
131
+ throw new Error("Resolved model must define invoke or stream.");
132
+ },
133
+ };
134
+ }
135
+ export function applyStrictToolJsonInstruction(binding) {
136
+ if (isLangChainBinding(binding)) {
137
+ const params = getBindingLangChainParams(binding);
138
+ return {
139
+ ...binding,
140
+ langchainAgentParams: {
141
+ ...params,
142
+ systemPrompt: [params.systemPrompt, STRICT_TOOL_JSON_INSTRUCTION].filter(Boolean).join("\n\n"),
143
+ },
144
+ };
145
+ }
146
+ if (isDeepAgentBinding(binding)) {
147
+ const params = getBindingDeepAgentParams(binding);
148
+ return {
149
+ ...binding,
150
+ deepAgentParams: {
151
+ ...params,
152
+ systemPrompt: [params.systemPrompt, STRICT_TOOL_JSON_INSTRUCTION].filter(Boolean).join("\n\n"),
153
+ },
154
+ };
155
+ }
156
+ return binding;
157
+ }
158
+ export async function callRuntimeWithToolParseRecovery(input) {
159
+ try {
160
+ return await input.callRuntime(input.binding, input.request);
161
+ }
162
+ catch (error) {
163
+ if (input.resumePayload !== undefined || !isToolCallParseFailure(error)) {
164
+ throw error;
165
+ }
166
+ return input.callRuntime(applyStrictToolJsonInstruction(input.binding), input.request);
167
+ }
168
+ }
@@ -0,0 +1,14 @@
1
+ import type { CompiledAgentBinding, CompiledTool } from "../../contracts/types.js";
2
+ import { type ToolNameMapping } from "./tool/tool-name-mapping.js";
3
+ import type { ExecutableTool } from "./invoke-runtime.js";
4
+ export declare function resolveAdapterTools(input: {
5
+ tools: Array<CompiledTool>;
6
+ binding?: CompiledAgentBinding;
7
+ resolveToolValues?: (toolIds: string[], binding?: CompiledAgentBinding) => unknown[];
8
+ }): unknown[];
9
+ export declare function buildExecutableToolMap(input: {
10
+ primaryTools: CompiledTool[];
11
+ resolvedTools: unknown[];
12
+ toolNameMapping?: ToolNameMapping;
13
+ context?: Record<string, unknown>;
14
+ }): Map<string, ExecutableTool>;
@@ -0,0 +1,57 @@
1
+ import { instantiateProviderTool } from "./tool/provider-tool.js";
2
+ import { asStructuredExecutableTool, hasCallableToolHandler, normalizeResolvedToolSchema, wrapResolvedToolWithModelFacingName, } from "./tool/resolved-tool.js";
3
+ import { buildToolNameMapping } from "./tool/tool-name-mapping.js";
4
+ import { wrapToolForExecution } from "./tool/tool-hitl.js";
5
+ export function resolveAdapterTools(input) {
6
+ const resolved = input.resolveToolValues ? input.resolveToolValues(input.tools.map((tool) => tool.id), input.binding) : [];
7
+ const toolNameMapping = buildToolNameMapping(input.tools);
8
+ return input.tools.flatMap((compiledTool, index) => {
9
+ const resolvedTool = resolved[index] ?? (compiledTool.type === "provider" ? instantiateProviderTool(compiledTool) : undefined);
10
+ if (resolvedTool === undefined) {
11
+ return [];
12
+ }
13
+ const wrappedTool = wrapToolForExecution(resolvedTool, compiledTool, input.binding);
14
+ const modelFacingName = toolNameMapping.originalToModelFacing.get(compiledTool.name) ?? compiledTool.name;
15
+ const structuredTool = asStructuredExecutableTool(wrappedTool, modelFacingName, compiledTool.description);
16
+ if (structuredTool !== wrappedTool) {
17
+ return structuredTool;
18
+ }
19
+ return modelFacingName === compiledTool.name ? wrappedTool : wrapResolvedToolWithModelFacingName(wrappedTool, modelFacingName);
20
+ });
21
+ }
22
+ export function buildExecutableToolMap(input) {
23
+ const executableTools = new Map();
24
+ const toolNameMapping = input.toolNameMapping ?? buildToolNameMapping(input.primaryTools);
25
+ for (let index = 0; index < input.primaryTools.length; index += 1) {
26
+ const compiledTool = input.primaryTools[index];
27
+ const resolvedTool = input.resolvedTools[index];
28
+ if (!compiledTool || !resolvedTool || !hasCallableToolHandler(resolvedTool)) {
29
+ continue;
30
+ }
31
+ const callableTool = resolvedTool;
32
+ const handler = async (toolInput) => {
33
+ const callable = typeof callableTool.invoke === "function"
34
+ ? callableTool.invoke
35
+ : typeof callableTool.call === "function"
36
+ ? callableTool.call
37
+ : callableTool.func;
38
+ if (!callable) {
39
+ throw new Error(`Tool ${compiledTool.name} has no callable handler.`);
40
+ }
41
+ return Promise.resolve(callable.call(callableTool, toolInput, input.context ? { context: input.context } : undefined));
42
+ };
43
+ const modelFacingName = toolNameMapping.originalToModelFacing.get(compiledTool.name) ?? compiledTool.name;
44
+ const schema = normalizeResolvedToolSchema(callableTool);
45
+ executableTools.set(modelFacingName, {
46
+ name: compiledTool.name,
47
+ schema,
48
+ invoke: handler,
49
+ });
50
+ executableTools.set(compiledTool.name, {
51
+ name: compiledTool.name,
52
+ schema,
53
+ invoke: handler,
54
+ });
55
+ }
56
+ return executableTools;
57
+ }
@@ -1,5 +1,6 @@
1
1
  import type { CompiledAgentBinding, MessageContent, RunResult, RuntimeAdapterOptions, TranscriptMessage } from "../contracts/types.js";
2
2
  import { type RuntimeStreamChunk } from "./parsing/stream-event-parsing.js";
3
+ import { RuntimeOperationTimeoutError } from "./adapter/runtime-shell.js";
3
4
  export { applyDeepAgentDelegationPromptCompatibility, materializeDeepAgentSkillSourcePaths, relativizeDeepAgentSkillSourcePaths, shouldRelaxDeepAgentDelegationPrompt, } from "./adapter/compat/deepagent-compat.js";
4
5
  export { buildAuthOmittingFetch, normalizeOpenAICompatibleInit } from "./adapter/compat/openai-compatible.js";
5
6
  export { buildToolNameMapping, createModelFacingToolNameCandidates, createModelFacingToolNameLookupCandidates, resolveModelFacingToolName, sanitizeToolNameForModel, } from "./adapter/tool/tool-name-mapping.js";
@@ -10,12 +11,6 @@ type RunnableLike = {
10
11
  streamEvents?: (input: unknown, config?: Record<string, unknown>) => Promise<AsyncIterable<unknown>>;
11
12
  };
12
13
  declare const AGENT_INTERRUPT_SENTINEL_PREFIX = "__agent_harness_interrupt__:";
13
- declare class RuntimeOperationTimeoutError extends Error {
14
- readonly operation: string;
15
- readonly timeoutMs: number;
16
- readonly stage: "stream" | "invoke";
17
- constructor(operation: string, timeoutMs: number, stage?: "stream" | "invoke");
18
- }
19
14
  export declare class AgentRuntimeAdapter {
20
15
  private readonly options;
21
16
  private readonly modelCache;