@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.
- package/README.md +3 -1234
- package/README.zh.md +3 -1191
- package/dist/acp.js +1 -1
- package/dist/api.js +1 -404
- package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
- package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
- package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
- package/dist/cli/chat-interactive.js +25 -244
- package/dist/cli/chat-rendering.js +6 -100
- package/dist/cli/chat-stream.js +23 -512
- package/dist/cli/chat-ui.js +21 -199
- package/dist/cli/chat-workspace.js +2 -210
- package/dist/cli/main.js +21 -428
- package/dist/cli/managed-service-commands.js +9 -63
- package/dist/cli/managed-service.js +2 -137
- package/dist/cli/options-init-chat.js +1 -108
- package/dist/cli/options-runtime.js +1 -158
- package/dist/cli/options-serve.js +1 -282
- package/dist/cli/options.js +2 -19
- package/dist/cli/process-guards.js +1 -139
- package/dist/cli/request-tree.js +7 -296
- package/dist/cli/runtime-commands.js +12 -258
- package/dist/cli/runtime-output.js +16 -155
- package/dist/cli/server-commands.js +16 -270
- package/dist/cli/workspace.js +1 -67
- package/dist/cli.js +1 -7
- package/dist/client/acp.js +1 -1
- package/dist/client/in-process.js +1 -67
- package/dist/client/index.js +1 -2
- package/dist/client/types.js +0 -1
- package/dist/client.js +1 -1
- package/dist/contracts/core.js +1 -1
- package/dist/contracts/runtime-evaluation.js +0 -1
- package/dist/contracts/runtime-memory.js +0 -1
- package/dist/contracts/runtime-observability.js +0 -1
- package/dist/contracts/runtime-requests.js +0 -1
- package/dist/contracts/runtime-scheduling.js +0 -1
- package/dist/contracts/runtime.js +1 -27
- package/dist/contracts/types.js +1 -3
- package/dist/contracts/workspace.js +0 -1
- package/dist/flow/build-flow-graph.js +1 -50
- package/dist/flow/export-mermaid.js +2 -464
- package/dist/flow/export-sequence-mermaid.js +2 -325
- package/dist/flow/flow-graph-normalization.js +1 -214
- package/dist/flow/flow-graph-runtime.js +1 -107
- package/dist/flow/flow-graph-upstream.js +1 -494
- package/dist/flow/index.js +1 -3
- package/dist/flow/types.js +0 -1
- package/dist/index.js +1 -5
- package/dist/init-project.js +1 -1
- package/dist/knowledge/config.js +1 -32
- package/dist/knowledge/contracts.js +0 -1
- package/dist/knowledge/index.js +1 -2
- package/dist/knowledge/module.js +12 -909
- package/dist/knowledge/procedural/config.js +1 -125
- package/dist/knowledge/procedural/index.js +1 -2
- package/dist/knowledge/procedural/manager.js +9 -345
- package/dist/mcp.js +1 -2
- package/dist/package-version.d.ts +1 -1
- package/dist/package-version.js +1 -2
- package/dist/persistence/file-store.js +3 -758
- package/dist/persistence/sqlite-request-context-store.js +5 -54
- package/dist/persistence/sqlite-request-queue-store.js +10 -108
- package/dist/persistence/sqlite-runtime.js +1 -86
- package/dist/persistence/sqlite-store.js +62 -810
- package/dist/persistence/types.js +0 -1
- package/dist/projections/presentation.js +37 -206
- package/dist/projections/request-events.js +2 -502
- package/dist/projections/upstream-events.js +1 -201
- package/dist/protocol/a2a/http-discovery.js +1 -178
- package/dist/protocol/a2a/http-rpc.js +6 -622
- package/dist/protocol/a2a/http.js +1 -138
- package/dist/protocol/a2a/task-state.js +3 -317
- package/dist/protocol/acp/client.js +8 -294
- package/dist/protocol/acp/harness-client.js +1 -218
- package/dist/protocol/acp/http.js +5 -130
- package/dist/protocol/acp/server.js +1 -310
- package/dist/protocol/acp/stdio.js +2 -69
- package/dist/protocol/ag-ui/http.js +3 -378
- package/dist/protocol/mcp/server.js +1 -428
- package/dist/resource/backend/workspace-scoped-backend.js +1 -319
- package/dist/resource/isolation.js +1 -237
- package/dist/resource/mcp/tool-support.js +3 -296
- package/dist/resource/mcp-tool-support.js +1 -2
- package/dist/resource/providers/resource-provider.js +1 -215
- package/dist/resource/resource-impl.js +1 -3
- package/dist/resource/resource-types.js +0 -1
- package/dist/resource/resource.js +1 -1
- package/dist/resource/sources.js +1 -247
- package/dist/resource/tools/function-tool-resolver.js +2 -272
- package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
- package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
- package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
- package/dist/runtime/adapter/flow/execution-context.js +1 -71
- package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
- package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
- package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
- package/dist/runtime/adapter/invocation-result.js +2 -473
- package/dist/runtime/adapter/local-tool-invocation.js +6 -638
- package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
- package/dist/runtime/adapter/middleware-assembly.js +5 -477
- package/dist/runtime/adapter/model/invocation-request.js +3 -183
- package/dist/runtime/adapter/model/message-assembly.js +1 -28
- package/dist/runtime/adapter/model/model-providers.js +23 -1115
- package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
- package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
- package/dist/runtime/adapter/resilience.js +1 -104
- package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
- package/dist/runtime/adapter/runtime-shell.js +5 -166
- package/dist/runtime/adapter/stream-event-projection.js +2 -622
- package/dist/runtime/adapter/stream-text-consumption.js +1 -18
- package/dist/runtime/adapter/terminal-status.js +2 -67
- package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
- package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
- package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
- package/dist/runtime/adapter/tool/provider-tool.js +1 -25
- package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
- package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
- package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
- package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
- package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
- package/dist/runtime/adapter/tool/tool-replay.js +1 -37
- package/dist/runtime/adapter/tool-resolution.js +1 -86
- package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
- package/dist/runtime/agent-runtime-adapter.js +60 -2338
- package/dist/runtime/agent-runtime-assembly.js +7 -249
- package/dist/runtime/env/runtime-env.js +1 -62
- package/dist/runtime/harness/background-runtime.js +1 -8
- package/dist/runtime/harness/bindings.js +1 -58
- package/dist/runtime/harness/events/event-bus.js +1 -16
- package/dist/runtime/harness/events/event-sink.js +1 -61
- package/dist/runtime/harness/events/events.js +1 -80
- package/dist/runtime/harness/events/listener-runtime.js +1 -13
- package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
- package/dist/runtime/harness/events/streaming.js +1 -100
- package/dist/runtime/harness/events/timeline.js +1 -52
- package/dist/runtime/harness/public-shapes.js +1 -186
- package/dist/runtime/harness/run/artifact-paths.js +1 -15
- package/dist/runtime/harness/run/governance.js +1 -295
- package/dist/runtime/harness/run/helpers.js +1 -71
- package/dist/runtime/harness/run/inspection.js +1 -409
- package/dist/runtime/harness/run/operator-overview.js +1 -80
- package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
- package/dist/runtime/harness/run/recovery.js +1 -162
- package/dist/runtime/harness/run/resources.js +1 -60
- package/dist/runtime/harness/run/resume.js +1 -56
- package/dist/runtime/harness/run/routing.js +1 -48
- package/dist/runtime/harness/run/run-lifecycle.js +1 -66
- package/dist/runtime/harness/run/run-operations.js +1 -217
- package/dist/runtime/harness/run/run-queue.js +1 -43
- package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
- package/dist/runtime/harness/run/session-records.js +1 -97
- package/dist/runtime/harness/run/start-run.js +1 -120
- package/dist/runtime/harness/run/startup-runtime.js +1 -69
- package/dist/runtime/harness/run/stream-run.js +8 -1418
- package/dist/runtime/harness/run/surface-semantics.js +1 -79
- package/dist/runtime/harness/runtime-defaults.js +1 -39
- package/dist/runtime/harness/system/boundary-analysis.js +1 -234
- package/dist/runtime/harness/system/health-monitor.js +1 -258
- package/dist/runtime/harness/system/inventory.js +1 -129
- package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
- package/dist/runtime/harness/system/policy-engine.js +1 -175
- package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
- package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
- package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
- package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
- package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
- package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
- package/dist/runtime/harness/system/session-memory-sync.js +3 -113
- package/dist/runtime/harness/system/skill-requirements.js +1 -112
- package/dist/runtime/harness/system/store.js +9 -365
- package/dist/runtime/harness/tool-gateway/index.js +1 -2
- package/dist/runtime/harness/tool-gateway/policy.js +1 -45
- package/dist/runtime/harness/tool-gateway/validation.js +1 -176
- package/dist/runtime/harness/tool-schema.js +1 -3
- package/dist/runtime/harness.js +3 -1490
- package/dist/runtime/index.js +1 -3
- package/dist/runtime/layout/runtime-layout.js +1 -31
- package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
- package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
- package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
- package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
- package/dist/runtime/parsing/output-content.js +10 -550
- package/dist/runtime/parsing/output-parsing.js +1 -4
- package/dist/runtime/parsing/output-recovery.js +3 -213
- package/dist/runtime/parsing/output-tool-args.js +7 -663
- package/dist/runtime/parsing/stream-event-parsing.js +3 -362
- package/dist/runtime/prompts/runtime-prompts.js +4 -73
- package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
- package/dist/runtime/skills/skill-metadata.js +1 -197
- package/dist/runtime/startup-tracing.js +2 -37
- package/dist/runtime/support/compiled-binding.js +1 -290
- package/dist/runtime/support/embedding-models.js +1 -118
- package/dist/runtime/support/harness-support.js +5 -137
- package/dist/runtime/support/llamaindex.js +1 -108
- package/dist/runtime/support/runtime-adapter-options.js +1 -29
- package/dist/runtime/support/runtime-factories.js +1 -51
- package/dist/runtime/support/vector-stores.js +9 -270
- package/dist/scaffold/init-project.js +54 -233
- package/dist/tooling/extensions.js +1 -311
- package/dist/tooling/module-loader.js +1 -55
- package/dist/tools.js +1 -176
- package/dist/utils/agent-display.js +1 -18
- package/dist/utils/bundled-text.js +4 -39
- package/dist/utils/compiled-binding.js +1 -33
- package/dist/utils/fs.js +2 -45
- package/dist/utils/id.js +1 -9
- package/dist/utils/message-content.js +1 -30
- package/dist/utils/object.js +1 -6
- package/dist/workspace/agent-binding-compiler.js +3 -613
- package/dist/workspace/compile.js +1 -472
- package/dist/workspace/framework-contract-validation.js +2 -322
- package/dist/workspace/index.js +1 -1
- package/dist/workspace/object-loader-paths.js +1 -71
- package/dist/workspace/object-loader-readers.js +1 -187
- package/dist/workspace/object-loader.js +1 -754
- package/dist/workspace/resource-compilers.js +1 -374
- package/dist/workspace/support/agent-capabilities.js +1 -37
- package/dist/workspace/support/agent-execution-config.js +1 -44
- package/dist/workspace/support/discovery.js +1 -147
- package/dist/workspace/support/source-collectors.js +1 -30
- package/dist/workspace/support/source-protocols.js +2 -192
- package/dist/workspace/support/workspace-ref-utils.js +1 -362
- package/dist/workspace/tool-hydration.js +1 -280
- package/dist/workspace/validate.js +1 -99
- package/dist/workspace/yaml-object-reader.js +1 -285
- package/package.json +7 -3
|
@@ -1,90 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
const
|
|
3
|
-
function parseListingEntry(line) {
|
|
4
|
-
const trimmed = line.trim();
|
|
5
|
-
if (!trimmed || trimmed === "...[truncated]" || trimmed === "... [truncated]") {
|
|
6
|
-
return null;
|
|
7
|
-
}
|
|
8
|
-
const match = trimmed.match(/^(\/.+?)(?:\s+\((\d+)\s+bytes\))?$/);
|
|
9
|
-
if (!match) {
|
|
10
|
-
return null;
|
|
11
|
-
}
|
|
12
|
-
const path = match[1];
|
|
13
|
-
return {
|
|
14
|
-
path,
|
|
15
|
-
isDirectory: path.endsWith("/"),
|
|
16
|
-
...(match[2] ? { sizeBytes: Number(match[2]) } : {}),
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
function parseListingEntries(text) {
|
|
20
|
-
const normalized = text.trim();
|
|
21
|
-
if (!normalized) {
|
|
22
|
-
return [];
|
|
23
|
-
}
|
|
24
|
-
const lines = normalized.split(/\r?\n/);
|
|
25
|
-
const entries = lines
|
|
26
|
-
.map((line) => parseListingEntry(line))
|
|
27
|
-
.filter((entry) => entry !== null);
|
|
28
|
-
if (entries.length < 4) {
|
|
29
|
-
return [];
|
|
30
|
-
}
|
|
31
|
-
return entries.length >= Math.ceil(lines.length * 0.7) ? entries : [];
|
|
32
|
-
}
|
|
33
|
-
function buildListingSummary(entries) {
|
|
34
|
-
const directories = entries.filter((entry) => entry.isDirectory);
|
|
35
|
-
const files = entries.filter((entry) => !entry.isDirectory);
|
|
36
|
-
return {
|
|
37
|
-
totalEntries: entries.length,
|
|
38
|
-
directoryCount: directories.length,
|
|
39
|
-
fileCount: files.length,
|
|
40
|
-
sampleDirectories: directories.slice(0, 8).map((entry) => entry.path),
|
|
41
|
-
sampleFiles: files.slice(0, 8).map((entry) => entry.path),
|
|
42
|
-
};
|
|
43
|
-
}
|
|
44
|
-
function summarizeGenericAssistantResponse(text) {
|
|
45
|
-
const normalized = text.trim();
|
|
46
|
-
if (!normalized) {
|
|
47
|
-
return normalized;
|
|
48
|
-
}
|
|
49
|
-
const summaryLines = normalized
|
|
50
|
-
.split(/\r?\n/)
|
|
51
|
-
.map((line) => line.trim())
|
|
52
|
-
.filter((line) => line.length > 0)
|
|
53
|
-
.filter((line) => line !== "Prior assistant response summary:")
|
|
54
|
-
.map((line) => line.replace(/^(?:[#>*-]+|\d+\.)\s*/u, "").trim())
|
|
55
|
-
.map((line) => line.replace(/^Earlier assistant answer covered:\s*/u, "").trim())
|
|
56
|
-
.filter((line) => line.length > 0);
|
|
57
|
-
const selected = summaryLines
|
|
58
|
-
.filter((line, index, items) => items.indexOf(line) === index)
|
|
59
|
-
.slice(0, GENERIC_ASSISTANT_SUMMARY_MAX_LINES)
|
|
60
|
-
.map((line) => line.length > GENERIC_ASSISTANT_SUMMARY_MAX_CHARS ? `${line.slice(0, GENERIC_ASSISTANT_SUMMARY_MAX_CHARS - 1)}…` : line);
|
|
61
|
-
if (selected.length === 0) {
|
|
62
|
-
return normalized.length > 240 ? `${normalized.slice(0, 239)}…` : normalized;
|
|
63
|
-
}
|
|
64
|
-
return selected.join("; ");
|
|
65
|
-
}
|
|
66
|
-
export function summarizeAssistantText(text) {
|
|
67
|
-
const normalized = text.trim();
|
|
68
|
-
if (!normalized) {
|
|
69
|
-
return normalized;
|
|
70
|
-
}
|
|
71
|
-
if (/^(?:Prior assistant response summary:|Earlier assistant answer covered:)/m.test(normalized)) {
|
|
72
|
-
return summarizeGenericAssistantResponse(normalized);
|
|
73
|
-
}
|
|
74
|
-
const entries = parseListingEntries(normalized);
|
|
75
|
-
if (entries.length > 0) {
|
|
76
|
-
const summary = buildListingSummary(entries);
|
|
77
|
-
return [
|
|
78
|
-
`Prior assistant output listed ${summary.totalEntries} workspace entries.`,
|
|
79
|
-
`Directories: ${summary.directoryCount}`,
|
|
80
|
-
`Files: ${summary.fileCount}`,
|
|
81
|
-
summary.sampleDirectories.length > 0 ? `Sample directories: ${summary.sampleDirectories.join(", ")}` : undefined,
|
|
82
|
-
summary.sampleFiles.length > 0 ? `Sample files: ${summary.sampleFiles.join(", ")}` : undefined,
|
|
83
|
-
].filter((part) => Boolean(part)).join("\n");
|
|
84
|
-
}
|
|
85
|
-
const lineCount = normalized.split(/\r?\n/).length;
|
|
86
|
-
if (normalized.length <= 500 && lineCount <= 8) {
|
|
87
|
-
return normalized;
|
|
88
|
-
}
|
|
89
|
-
return summarizeGenericAssistantResponse(normalized);
|
|
90
|
-
}
|
|
1
|
+
const u=180,p=6;function a(n){const e=n.trim();if(!e||e==="...[truncated]"||e==="... [truncated]")return null;const i=e.match(/^(\/.+?)(?:\s+\((\d+)\s+bytes\))?$/);if(!i)return null;const r=i[1];return{path:r,isDirectory:r.endsWith("/"),...i[2]?{sizeBytes:Number(i[2])}:{}}}function c(n){const e=n.trim();if(!e)return[];const i=e.split(/\r?\n/),r=i.map(t=>a(t)).filter(t=>t!==null);return r.length<4?[]:r.length>=Math.ceil(i.length*.7)?r:[]}function m(n){const e=n.filter(r=>r.isDirectory),i=n.filter(r=>!r.isDirectory);return{totalEntries:n.length,directoryCount:e.length,fileCount:i.length,sampleDirectories:e.slice(0,8).map(r=>r.path),sampleFiles:i.slice(0,8).map(r=>r.path)}}function l(n){const e=n.trim();if(!e)return e;const r=e.split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>t!=="Prior assistant response summary:").map(t=>t.replace(/^(?:[#>*-]+|\d+\.)\s*/u,"").trim()).map(t=>t.replace(/^Earlier assistant answer covered:\s*/u,"").trim()).filter(t=>t.length>0).filter((t,s,o)=>o.indexOf(t)===s).slice(0,6).map(t=>t.length>180?`${t.slice(0,179)}\u2026`:t);return r.length===0?e.length>240?`${e.slice(0,239)}\u2026`:e:r.join("; ")}function f(n){const e=n.trim();if(!e)return e;if(/^(?:Prior assistant response summary:|Earlier assistant answer covered:)/m.test(e))return l(e);const i=c(e);if(i.length>0){const t=m(i);return[`Prior assistant output listed ${t.totalEntries} workspace entries.`,`Directories: ${t.directoryCount}`,`Files: ${t.fileCount}`,t.sampleDirectories.length>0?`Sample directories: ${t.sampleDirectories.join(", ")}`:void 0,t.sampleFiles.length>0?`Sample files: ${t.sampleFiles.join(", ")}`:void 0].filter(s=>!!s).join(`
|
|
2
|
+
`)}const r=e.split(/\r?\n/).length;return e.length<=500&&r<=8?e:l(e)}export{f as summarizeAssistantText};
|
|
@@ -1,71 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { getBindingInteractionMode, getBindingPrimaryModel, getBindingPrimaryTools, isLangChainBinding } from "../../support/compiled-binding.js";
|
|
3
|
-
export function buildBindingToolCatalog(input) {
|
|
4
|
-
const primaryTools = getBindingPrimaryTools(input.binding);
|
|
5
|
-
const toolNameMapping = input.getToolNameMapping(input.binding);
|
|
6
|
-
return {
|
|
7
|
-
primaryTools,
|
|
8
|
-
toolNameMapping,
|
|
9
|
-
};
|
|
10
|
-
}
|
|
11
|
-
export function buildBindingToolExecutionContext(input) {
|
|
12
|
-
const { primaryTools, toolNameMapping } = buildBindingToolCatalog(input);
|
|
13
|
-
const resolvedTools = input.resolveTools(primaryTools, input.binding);
|
|
14
|
-
const executableTools = buildExecutableToolMap({
|
|
15
|
-
primaryTools,
|
|
16
|
-
resolvedTools,
|
|
17
|
-
toolNameMapping,
|
|
18
|
-
toolConfig: input.toolConfig,
|
|
19
|
-
});
|
|
20
|
-
return {
|
|
21
|
-
primaryTools,
|
|
22
|
-
resolvedTools,
|
|
23
|
-
toolNameMapping,
|
|
24
|
-
executableTools,
|
|
25
|
-
defersToUpstreamHitlExecution: primaryTools.some((tool) => tool.hitl?.enabled === true),
|
|
26
|
-
};
|
|
27
|
-
}
|
|
28
|
-
export async function resolveLangChainStreamContext(input) {
|
|
29
|
-
const primaryTools = getBindingPrimaryTools(input.binding);
|
|
30
|
-
const primaryModel = getBindingPrimaryModel(input.binding);
|
|
31
|
-
const resolvedLangChainModel = primaryModel
|
|
32
|
-
? (await input.resolveModel(primaryModel))
|
|
33
|
-
: undefined;
|
|
34
|
-
const resolvedLangChainTools = primaryTools.length > 0 ? input.resolveTools(primaryTools, input.binding) : [];
|
|
35
|
-
const modelSupportsToolBinding = typeof resolvedLangChainModel?.bindTools === "function";
|
|
36
|
-
const forceInvokeFallback = isLangChainBinding(input.binding) &&
|
|
37
|
-
primaryTools.length > 0 &&
|
|
38
|
-
primaryModel?.provider === "openai-compatible";
|
|
39
|
-
const canUseDirectModelStream = !!resolvedLangChainModel &&
|
|
40
|
-
primaryTools.length === 0;
|
|
41
|
-
const langChainStreamModel = resolvedLangChainModel && canUseDirectModelStream
|
|
42
|
-
? resolvedLangChainModel
|
|
43
|
-
: resolvedLangChainModel && modelSupportsToolBinding && resolvedLangChainTools.length > 0
|
|
44
|
-
? resolvedLangChainModel.bindTools(resolvedLangChainTools)
|
|
45
|
-
: undefined;
|
|
46
|
-
return {
|
|
47
|
-
primaryTools,
|
|
48
|
-
forceInvokeFallback,
|
|
49
|
-
canUseDirectModelStream,
|
|
50
|
-
langChainStreamModel,
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
export async function resolveRuntimeStreamExecutionContext(input) {
|
|
54
|
-
const { primaryTools, toolNameMapping } = buildBindingToolCatalog({
|
|
55
|
-
binding: input.binding,
|
|
56
|
-
getToolNameMapping: input.getToolNameMapping,
|
|
57
|
-
});
|
|
58
|
-
const interactionMode = getBindingInteractionMode(input.binding) ?? "stream";
|
|
59
|
-
const { forceInvokeFallback, canUseDirectModelStream, langChainStreamModel, } = await resolveLangChainStreamContext({
|
|
60
|
-
binding: input.binding,
|
|
61
|
-
resolveModel: input.resolveModel,
|
|
62
|
-
resolveTools: input.resolveTools,
|
|
63
|
-
});
|
|
64
|
-
return {
|
|
65
|
-
primaryTools,
|
|
66
|
-
toolNameMapping,
|
|
67
|
-
forceInvokeFallback: interactionMode === "invoke" ? true : forceInvokeFallback,
|
|
68
|
-
canUseDirectModelStream,
|
|
69
|
-
langChainStreamModel,
|
|
70
|
-
};
|
|
71
|
-
}
|
|
1
|
+
import{buildExecutableToolMap as c}from"../tool-resolution.js";import{getBindingInteractionMode as m,getBindingPrimaryModel as b,getBindingPrimaryTools as s,isLangChainBinding as T}from"../../support/compiled-binding.js";function d(o){const e=s(o.binding),i=o.getToolNameMapping(o.binding);return{primaryTools:e,toolNameMapping:i}}function p(o){const{primaryTools:e,toolNameMapping:i}=d(o),n=o.resolveTools(e,o.binding),l=c({primaryTools:e,resolvedTools:n,toolNameMapping:i,toolConfig:o.toolConfig});return{primaryTools:e,resolvedTools:n,toolNameMapping:i,executableTools:l,defersToUpstreamHitlExecution:e.some(t=>t.hitl?.enabled===!0)}}async function M(o){const e=s(o.binding),i=b(o.binding),n=i?await o.resolveModel(i):void 0,l=e.length>0?o.resolveTools(e,o.binding):[],t=typeof n?.bindTools=="function",a=T(o.binding)&&e.length>0&&i?.provider==="openai-compatible",r=!!n&&e.length===0,g=n&&r?n:n&&t&&l.length>0?n.bindTools(l):void 0;return{primaryTools:e,forceInvokeFallback:a,canUseDirectModelStream:r,langChainStreamModel:g}}async function x(o){const{primaryTools:e,toolNameMapping:i}=d({binding:o.binding,getToolNameMapping:o.getToolNameMapping}),n=m(o.binding)??"stream",{forceInvokeFallback:l,canUseDirectModelStream:t,langChainStreamModel:a}=await M({binding:o.binding,resolveModel:o.resolveModel,resolveTools:o.resolveTools});return{primaryTools:e,toolNameMapping:i,forceInvokeFallback:n==="invoke"?!0:l,canUseDirectModelStream:t,langChainStreamModel:a}}export{d as buildBindingToolCatalog,p as buildBindingToolExecutionContext,M as resolveLangChainStreamContext,x as resolveRuntimeStreamExecutionContext};
|
|
@@ -1,425 +1,8 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
import { salvageJsonToolCalls } from "../../parsing/output-tool-args.js";
|
|
10
|
-
import { isEmptyFinalAiMessageError } from "../resilience.js";
|
|
11
|
-
import { REQUIRED_EXECUTION_CONTINUATION_INSTRUCTION, WRITE_TODOS_REQUIRED_PLAN_INSTRUCTION, } from "../../prompts/runtime-prompts.js";
|
|
12
|
-
const CLOSE_REQUIRED_PLAN_RECOVERY_INSTRUCTION = [
|
|
13
|
-
"The current required todo board still has unfinished work.",
|
|
14
|
-
"Do not broaden the task, restart planning, or ask the user what to do next.",
|
|
15
|
-
"Use the existing tool evidence already available in this run.",
|
|
16
|
-
"Your next action must be write_todos: update every remaining pending or in_progress item to completed if evidence was gathered, or failed if it cannot be completed with the available tools.",
|
|
17
|
-
"After that write_todos call, provide the final answer required by the agent response format.",
|
|
18
|
-
].join("\n");
|
|
19
|
-
const INITIAL_REQUIRED_PLAN_INSTRUCTION = [
|
|
20
|
-
"This agent has a required visible planning contract.",
|
|
21
|
-
"Your first action for this request must be write_todos with concrete task steps and statuses.",
|
|
22
|
-
"Do not call any domain/evidence tool and do not provide a final answer before the initial write_todos call succeeds.",
|
|
23
|
-
"After each evidence step, update the todo board. Before the final answer, close every todo as completed or failed.",
|
|
24
|
-
].join("\n");
|
|
25
|
-
function readBindingExecutionParams(binding) {
|
|
26
|
-
const params = binding.execution?.params ?? binding.deepAgentParams ?? binding.langchainAgentParams;
|
|
27
|
-
return {
|
|
28
|
-
tools: Array.isArray(params?.tools) ? params.tools : [],
|
|
29
|
-
subagents: Array.isArray(params?.subagents)
|
|
30
|
-
? (params.subagents ?? [])
|
|
31
|
-
: [],
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
function isDelegationOnlyBinding(binding) {
|
|
35
|
-
const { tools, subagents } = readBindingExecutionParams(binding);
|
|
36
|
-
const agent = binding.agent;
|
|
37
|
-
const configuredSubagents = [
|
|
38
|
-
...subagents,
|
|
39
|
-
...(agent?.subagentRefs ?? []),
|
|
40
|
-
...(agent?.subagentPathRefs ?? []),
|
|
41
|
-
...(agent?.asyncSubagents ?? []),
|
|
42
|
-
];
|
|
43
|
-
const configuredTools = [
|
|
44
|
-
...tools,
|
|
45
|
-
...(agent?.toolRefs ?? []),
|
|
46
|
-
...(agent?.toolBindings ?? []),
|
|
47
|
-
];
|
|
48
|
-
const skillRefs = agent?.skillPathRefs ?? [];
|
|
49
|
-
return configuredSubagents.length > 0 && configuredTools.length === 0 && skillRefs.length === 0;
|
|
50
|
-
}
|
|
51
|
-
function hasTaskDelegationEvidence(executedToolResults) {
|
|
52
|
-
return executedToolResults.some((item) => item.toolName === "task");
|
|
53
|
-
}
|
|
54
|
-
function normalizePlanToolName(toolName) {
|
|
55
|
-
return typeof toolName === "string" ? toolName.trim().toLowerCase().replace(/[\s-]+/gu, "_") : "";
|
|
56
|
-
}
|
|
57
|
-
function isPlanToolName(toolName) {
|
|
58
|
-
const normalized = normalizePlanToolName(toolName);
|
|
59
|
-
return normalized === "write_todos"
|
|
60
|
-
|| normalized === "read_todos"
|
|
61
|
-
|| normalized === "tool_call_write_todos"
|
|
62
|
-
|| normalized === "tool_call_read_todos"
|
|
63
|
-
|| normalized === "call_write_todos"
|
|
64
|
-
|| normalized === "call_read_todos";
|
|
65
|
-
}
|
|
66
|
-
function hasPlanToolEvidence(executedToolResults) {
|
|
67
|
-
return executedToolResults.some((item) => isPlanToolName(item.toolName));
|
|
68
|
-
}
|
|
69
|
-
function hasIncompleteTodos(value) {
|
|
70
|
-
if (!Array.isArray(value)) {
|
|
71
|
-
return false;
|
|
72
|
-
}
|
|
73
|
-
return value.some((todo) => {
|
|
74
|
-
if (typeof todo !== "object" || todo === null) {
|
|
75
|
-
return false;
|
|
76
|
-
}
|
|
77
|
-
const status = typeof todo.status === "string"
|
|
78
|
-
? todo.status.trim().toLowerCase()
|
|
79
|
-
: "";
|
|
80
|
-
return status === "pending" || status === "in_progress";
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
function hasIncompleteUpstreamPlan(value) {
|
|
84
|
-
if (typeof value !== "object" || value === null) {
|
|
85
|
-
return false;
|
|
86
|
-
}
|
|
87
|
-
const typed = value;
|
|
88
|
-
return hasIncompleteTodos(typed.todos)
|
|
89
|
-
|| hasIncompleteTodos(typed.stateSnapshot?.todos)
|
|
90
|
-
|| hasIncompleteTodos(typed.metadata?.stateSnapshot?.todos);
|
|
91
|
-
}
|
|
92
|
-
function hasNativeTaskDelegationIntent(value) {
|
|
93
|
-
if (typeof value !== "object" || value === null) {
|
|
94
|
-
return false;
|
|
95
|
-
}
|
|
96
|
-
if (Array.isArray(value)) {
|
|
97
|
-
return value.some((item) => hasNativeTaskDelegationIntent(item));
|
|
98
|
-
}
|
|
99
|
-
const typed = value;
|
|
100
|
-
if (typed.name === "task") {
|
|
101
|
-
return true;
|
|
102
|
-
}
|
|
103
|
-
return hasNativeTaskDelegationIntent(typed.tool_calls) || hasNativeTaskDelegationIntent(typed.messages);
|
|
104
|
-
}
|
|
105
|
-
function readStructuredToolCall(value) {
|
|
106
|
-
const salvaged = salvageJsonToolCalls(value)[0];
|
|
107
|
-
if (salvaged) {
|
|
108
|
-
return salvaged;
|
|
109
|
-
}
|
|
110
|
-
if (Array.isArray(value)) {
|
|
111
|
-
for (const item of value) {
|
|
112
|
-
const nested = readStructuredToolCall(item);
|
|
113
|
-
if (nested) {
|
|
114
|
-
return nested;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
return null;
|
|
118
|
-
}
|
|
119
|
-
if (typeof value === "object" && value !== null) {
|
|
120
|
-
const typed = value;
|
|
121
|
-
const fromOutput = typed.output !== undefined ? readStructuredToolCall(typed.output) : null;
|
|
122
|
-
if (fromOutput) {
|
|
123
|
-
return fromOutput;
|
|
124
|
-
}
|
|
125
|
-
const fromContent = typed.content !== undefined ? readStructuredToolCall(typed.content) : null;
|
|
126
|
-
if (fromContent) {
|
|
127
|
-
return fromContent;
|
|
128
|
-
}
|
|
129
|
-
const fromMessages = typed.messages !== undefined ? readStructuredToolCall(typed.messages) : null;
|
|
130
|
-
if (fromMessages) {
|
|
131
|
-
return fromMessages;
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
const text = typeof value === "string" ? value.trim() : "";
|
|
135
|
-
const parsed = text ? (tryParseJson(text) ?? extractFirstJsonObject(text)) : value;
|
|
136
|
-
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
137
|
-
return null;
|
|
138
|
-
}
|
|
139
|
-
const typed = parsed;
|
|
140
|
-
if (Array.isArray(typed.tool_calls)) {
|
|
141
|
-
return readStructuredToolCall(typed.tool_calls[0]);
|
|
142
|
-
}
|
|
143
|
-
const functionPayload = typeof typed.function === "object" && typed.function !== null ? typed.function : undefined;
|
|
144
|
-
const nameCandidate = typed.name
|
|
145
|
-
?? typed.tool_name
|
|
146
|
-
?? typed.tool
|
|
147
|
-
?? functionPayload?.name
|
|
148
|
-
?? (typeof typed.function === "string" ? typed.function : undefined);
|
|
149
|
-
const name = typeof nameCandidate === "string" ? nameCandidate.trim() : "";
|
|
150
|
-
if (!name) {
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
const argsCandidate = typed.arguments
|
|
154
|
-
?? typed.args
|
|
155
|
-
?? typed.parameters
|
|
156
|
-
?? functionPayload?.arguments
|
|
157
|
-
?? functionPayload?.args
|
|
158
|
-
?? functionPayload?.parameters
|
|
159
|
-
?? {};
|
|
160
|
-
const args = typeof argsCandidate === "object" && argsCandidate !== null && !Array.isArray(argsCandidate)
|
|
161
|
-
? argsCandidate
|
|
162
|
-
: {};
|
|
163
|
-
return { name, args };
|
|
164
|
-
}
|
|
165
|
-
function extractFirstJsonObject(text) {
|
|
166
|
-
let start = -1;
|
|
167
|
-
let depth = 0;
|
|
168
|
-
let inString = false;
|
|
169
|
-
let escaped = false;
|
|
170
|
-
for (let index = 0; index < text.length; index += 1) {
|
|
171
|
-
const char = text[index];
|
|
172
|
-
if (start < 0) {
|
|
173
|
-
if (char === "{") {
|
|
174
|
-
start = index;
|
|
175
|
-
depth = 1;
|
|
176
|
-
}
|
|
177
|
-
continue;
|
|
178
|
-
}
|
|
179
|
-
if (escaped) {
|
|
180
|
-
escaped = false;
|
|
181
|
-
continue;
|
|
182
|
-
}
|
|
183
|
-
if (char === "\\") {
|
|
184
|
-
escaped = inString;
|
|
185
|
-
continue;
|
|
186
|
-
}
|
|
187
|
-
if (char === "\"") {
|
|
188
|
-
inString = !inString;
|
|
189
|
-
continue;
|
|
190
|
-
}
|
|
191
|
-
if (inString) {
|
|
192
|
-
continue;
|
|
193
|
-
}
|
|
194
|
-
if (char === "{") {
|
|
195
|
-
depth += 1;
|
|
196
|
-
continue;
|
|
197
|
-
}
|
|
198
|
-
if (char === "}") {
|
|
199
|
-
depth -= 1;
|
|
200
|
-
if (depth === 0) {
|
|
201
|
-
const parsed = tryParseJson(text.slice(start, index + 1));
|
|
202
|
-
if (parsed) {
|
|
203
|
-
return parsed;
|
|
204
|
-
}
|
|
205
|
-
start = -1;
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
return null;
|
|
210
|
-
}
|
|
211
|
-
async function replayStructuredTaskToolCall(input) {
|
|
212
|
-
if (hasTaskDelegationEvidence(input.invocation.executedToolResults)) {
|
|
213
|
-
return input.invocation;
|
|
214
|
-
}
|
|
215
|
-
const visibleOutput = extractVisibleOutput(input.invocation.result);
|
|
216
|
-
const toolCall = readStructuredToolCall(visibleOutput) ?? readStructuredToolCall(input.invocation.result);
|
|
217
|
-
if (toolCall?.name !== "task") {
|
|
218
|
-
return input.invocation;
|
|
219
|
-
}
|
|
220
|
-
const taskTool = input.builtinExecutableTools.get("task");
|
|
221
|
-
if (!taskTool) {
|
|
222
|
-
return input.invocation;
|
|
223
|
-
}
|
|
224
|
-
try {
|
|
225
|
-
const output = await taskTool.invoke(toolCall.args, input.toolRuntimeContext);
|
|
226
|
-
return {
|
|
227
|
-
result: { output },
|
|
228
|
-
executedToolResults: [
|
|
229
|
-
...input.invocation.executedToolResults,
|
|
230
|
-
{ toolName: "task", output },
|
|
231
|
-
],
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
catch (error) {
|
|
235
|
-
const output = error instanceof Error ? error.message : String(error);
|
|
236
|
-
return {
|
|
237
|
-
result: { output },
|
|
238
|
-
executedToolResults: [
|
|
239
|
-
...input.invocation.executedToolResults,
|
|
240
|
-
{ toolName: "task", output, isError: true },
|
|
241
|
-
],
|
|
242
|
-
};
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
function formatDelegationSubagentCatalog(binding) {
|
|
246
|
-
const { subagents } = readBindingExecutionParams(binding);
|
|
247
|
-
return subagents
|
|
248
|
-
.map((subagent) => {
|
|
249
|
-
if (typeof subagent !== "object" || subagent === null) {
|
|
250
|
-
return "";
|
|
251
|
-
}
|
|
252
|
-
const typed = subagent;
|
|
253
|
-
const name = typeof typed.name === "string" ? typed.name.trim() : "";
|
|
254
|
-
if (!name) {
|
|
255
|
-
return "";
|
|
256
|
-
}
|
|
257
|
-
const description = typeof typed.description === "string" ? typed.description.trim() : "";
|
|
258
|
-
return description ? `- ${name}: ${description}` : `- ${name}`;
|
|
259
|
-
})
|
|
260
|
-
.filter(Boolean)
|
|
261
|
-
.join("\n");
|
|
262
|
-
}
|
|
263
|
-
function buildDelegationOnlyRecoveryInstruction(binding, input) {
|
|
264
|
-
const subagentCatalog = formatDelegationSubagentCatalog(binding) || "(none)";
|
|
265
|
-
return [
|
|
266
|
-
"/no_think",
|
|
267
|
-
"Runtime correction: this agent is delegation-only.",
|
|
268
|
-
"Return exactly one JSON object and no prose.",
|
|
269
|
-
"Use this shape when a listed subagent fits:",
|
|
270
|
-
"{\"name\":\"task\",\"arguments\":{\"subagent_type\":\"<listed name>\",\"description\":\"<original request>\"}}",
|
|
271
|
-
"Use this shape only when no listed subagent fits:",
|
|
272
|
-
"{\"status\":\"refused\",\"reason\":\"No configured subagent can handle the request.\"}",
|
|
273
|
-
"Listed subagents:",
|
|
274
|
-
subagentCatalog,
|
|
275
|
-
"Original request:",
|
|
276
|
-
JSON.stringify(input),
|
|
277
|
-
].join("\n");
|
|
278
|
-
}
|
|
279
|
-
function buildEmptyAssistantRecoveryInstruction() {
|
|
280
|
-
return [
|
|
281
|
-
"/no_think",
|
|
282
|
-
"Runtime correction: your previous assistant response was empty.",
|
|
283
|
-
"Continue the original request now.",
|
|
284
|
-
"If an available tool is needed, call exactly one valid tool with complete arguments.",
|
|
285
|
-
"If no tool is needed, return a non-empty final answer.",
|
|
286
|
-
"Do not return empty content.",
|
|
287
|
-
].join("\n");
|
|
288
|
-
}
|
|
289
|
-
function isEmptyAssistantOutputError(error) {
|
|
290
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
291
|
-
return isEmptyFinalAiMessageError(error) || message === "empty_final_output";
|
|
292
|
-
}
|
|
293
|
-
function appendUserRecoveryInstruction(input, instruction) {
|
|
294
|
-
const content = [
|
|
295
|
-
"Runtime correction:",
|
|
296
|
-
instruction,
|
|
297
|
-
].join("\n\n");
|
|
298
|
-
if (Array.isArray(input)) {
|
|
299
|
-
return [...input, { role: "user", content }];
|
|
300
|
-
}
|
|
301
|
-
if (typeof input === "object" && input && Array.isArray(input.messages)) {
|
|
302
|
-
return {
|
|
303
|
-
...input,
|
|
304
|
-
messages: [...(input.messages), { role: "user", content }],
|
|
305
|
-
};
|
|
306
|
-
}
|
|
307
|
-
return input;
|
|
308
|
-
}
|
|
309
|
-
export async function executeRequestInvocation(options) {
|
|
310
|
-
const history = options.history ?? [];
|
|
311
|
-
const invokeOptions = options.invokeOptions ?? {};
|
|
312
|
-
let request = options.resumePayload === undefined
|
|
313
|
-
? buildInvocationRequest(options.binding, history, options.input, invokeOptions)
|
|
314
|
-
: new Command({ resume: options.resumePayload });
|
|
315
|
-
if (options.resumePayload === undefined
|
|
316
|
-
&& options.binding.harnessRuntime.executionContract?.requiresPlan === true
|
|
317
|
-
&& invokeOptions.suppressInitialRequiredPlanInstruction !== true) {
|
|
318
|
-
request = withPromptedJsonToolPolicy(appendToolRecoveryInstruction(request, INITIAL_REQUIRED_PLAN_INSTRUCTION), "planning");
|
|
319
|
-
}
|
|
320
|
-
const { primaryTools, toolNameMapping, executableTools, defersToUpstreamHitlExecution, } = buildBindingToolExecutionContext({
|
|
321
|
-
binding: options.binding,
|
|
322
|
-
resolveTools: options.resolveTools,
|
|
323
|
-
getToolNameMapping: options.getToolNameMapping,
|
|
324
|
-
toolConfig: {
|
|
325
|
-
...(invokeOptions.context ? { context: invokeOptions.context } : {}),
|
|
326
|
-
configurable: {
|
|
327
|
-
[UPSTREAM_SESSION_CONFIG_KEY]: options.sessionId,
|
|
328
|
-
[UPSTREAM_REQUEST_CONFIG_KEY]: options.requestId,
|
|
329
|
-
},
|
|
330
|
-
...(options.invokeOptions?.toolRuntimeContext ? { toolRuntimeContext: options.invokeOptions.toolRuntimeContext } : {}),
|
|
331
|
-
},
|
|
332
|
-
});
|
|
333
|
-
const builtinExecutableTools = await options.resolveBuiltinMiddlewareTools(options.binding, invokeOptions);
|
|
334
|
-
const invokeOnce = (activeRequest) => invokeRuntimeWithLocalTools({
|
|
335
|
-
binding: options.binding,
|
|
336
|
-
request: activeRequest,
|
|
337
|
-
resumePayload: options.resumePayload,
|
|
338
|
-
primaryTools,
|
|
339
|
-
defersToUpstreamHitlExecution,
|
|
340
|
-
toolNameMapping,
|
|
341
|
-
executableTools,
|
|
342
|
-
builtinExecutableTools: builtinExecutableTools,
|
|
343
|
-
callRuntimeWithToolParseRecovery: options.callRuntimeWithToolParseRecovery,
|
|
344
|
-
toolRuntimeContext: invokeOptions.toolRuntimeContext,
|
|
345
|
-
externalPlanEvidence: invokeOptions.externalPlanEvidence,
|
|
346
|
-
});
|
|
347
|
-
let localOrUpstreamInvocation = await invokeOnce(request);
|
|
348
|
-
if (options.resumePayload === undefined
|
|
349
|
-
&& isDelegationOnlyBinding(options.binding)
|
|
350
|
-
&& !hasTaskDelegationEvidence(localOrUpstreamInvocation.executedToolResults)
|
|
351
|
-
&& !hasNativeTaskDelegationIntent(localOrUpstreamInvocation.result)) {
|
|
352
|
-
const delegationRecoveryInstruction = buildDelegationOnlyRecoveryInstruction(options.binding, options.input);
|
|
353
|
-
const recoveredRequest = appendUserRecoveryInstruction(request, delegationRecoveryInstruction);
|
|
354
|
-
const recoveredInvocation = await invokeOnce(recoveredRequest);
|
|
355
|
-
localOrUpstreamInvocation = await replayStructuredTaskToolCall({
|
|
356
|
-
invocation: recoveredInvocation,
|
|
357
|
-
builtinExecutableTools: builtinExecutableTools,
|
|
358
|
-
toolRuntimeContext: invokeOptions.toolRuntimeContext,
|
|
359
|
-
});
|
|
360
|
-
}
|
|
361
|
-
let result = localOrUpstreamInvocation.result;
|
|
362
|
-
const executedToolResults = [...localOrUpstreamInvocation.executedToolResults];
|
|
363
|
-
if (!result) {
|
|
364
|
-
throw new Error("Agent invocation returned no result");
|
|
365
|
-
}
|
|
366
|
-
if (options.resumePayload === undefined
|
|
367
|
-
&& options.binding.harnessRuntime.executionContract?.requiresPlan === true
|
|
368
|
-
&& !hasPlanToolEvidence(executedToolResults)) {
|
|
369
|
-
const messages = Array.isArray(result.messages)
|
|
370
|
-
? result.messages
|
|
371
|
-
: undefined;
|
|
372
|
-
const recoveryBase = messages ? { messages } : request;
|
|
373
|
-
const recoveredRequest = withPromptedJsonToolPolicy(appendToolRecoveryInstruction(recoveryBase, WRITE_TODOS_REQUIRED_PLAN_INSTRUCTION), "planning");
|
|
374
|
-
const recoveredInvocation = await invokeOnce(recoveredRequest);
|
|
375
|
-
result = recoveredInvocation.result;
|
|
376
|
-
executedToolResults.splice(0, executedToolResults.length, ...recoveredInvocation.executedToolResults);
|
|
377
|
-
}
|
|
378
|
-
if (options.resumePayload === undefined
|
|
379
|
-
&& options.binding.harnessRuntime.executionContract?.requiresPlan === true
|
|
380
|
-
&& hasIncompleteUpstreamPlan(result)) {
|
|
381
|
-
const messages = Array.isArray(result.messages)
|
|
382
|
-
? result.messages
|
|
383
|
-
: undefined;
|
|
384
|
-
const recoveryBase = messages ? { messages } : request;
|
|
385
|
-
const recoveredRequest = appendToolRecoveryInstruction(recoveryBase, REQUIRED_EXECUTION_CONTINUATION_INSTRUCTION);
|
|
386
|
-
const recoveredInvocation = await invokeOnce(recoveredRequest);
|
|
387
|
-
result = recoveredInvocation.result;
|
|
388
|
-
executedToolResults.splice(0, executedToolResults.length, ...recoveredInvocation.executedToolResults);
|
|
389
|
-
}
|
|
390
|
-
try {
|
|
391
|
-
return finalizeRequestResult({
|
|
392
|
-
bindingAgentId: options.binding.agent.id,
|
|
393
|
-
sessionId: options.sessionId,
|
|
394
|
-
requestId: options.requestId,
|
|
395
|
-
binding: options.binding,
|
|
396
|
-
result,
|
|
397
|
-
executedToolResults,
|
|
398
|
-
});
|
|
399
|
-
}
|
|
400
|
-
catch (error) {
|
|
401
|
-
if (options.resumePayload !== undefined || !isEmptyAssistantOutputError(error)) {
|
|
402
|
-
throw error;
|
|
403
|
-
}
|
|
404
|
-
const shouldUseDelegationRecovery = isDelegationOnlyBinding(options.binding)
|
|
405
|
-
&& !hasTaskDelegationEvidence(executedToolResults)
|
|
406
|
-
&& !hasNativeTaskDelegationIntent(result);
|
|
407
|
-
const recoveredRequest = appendUserRecoveryInstruction(request, shouldUseDelegationRecovery
|
|
408
|
-
? buildDelegationOnlyRecoveryInstruction(options.binding, options.input)
|
|
409
|
-
: buildEmptyAssistantRecoveryInstruction());
|
|
410
|
-
const recoveredInvocation = await replayStructuredTaskToolCall({
|
|
411
|
-
invocation: await invokeOnce(recoveredRequest),
|
|
412
|
-
builtinExecutableTools: builtinExecutableTools,
|
|
413
|
-
toolRuntimeContext: invokeOptions.toolRuntimeContext,
|
|
414
|
-
});
|
|
415
|
-
return finalizeRequestResult({
|
|
416
|
-
bindingAgentId: options.binding.agent.id,
|
|
417
|
-
sessionId: options.sessionId,
|
|
418
|
-
requestId: options.requestId,
|
|
419
|
-
binding: options.binding,
|
|
420
|
-
result: recoveredInvocation.result,
|
|
421
|
-
executedToolResults: recoveredInvocation.executedToolResults,
|
|
422
|
-
});
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
export const executeRuntimeInvocation = executeRequestInvocation;
|
|
1
|
+
import{Command as N}from"@langchain/langgraph";import{buildBindingToolExecutionContext as O}from"./execution-context.js";import{finalizeRequestResult as I}from"../invocation-result.js";import{invokeRuntimeWithLocalTools as k}from"./invoke-runtime.js";import{buildInvocationRequest as q}from"../model/invocation-request.js";import{withPromptedJsonToolPolicy as x}from"../model/prompted-json-tool-policy.js";import{UPSTREAM_REQUEST_CONFIG_KEY as S,UPSTREAM_SESSION_CONFIG_KEY as U}from"../upstream-configurable-keys.js";import{appendToolRecoveryInstruction as p,extractVisibleOutput as j,tryParseJson as _}from"../../parsing/output-parsing.js";import{salvageJsonToolCalls as D}from"../../parsing/output-tool-args.js";import{isEmptyFinalAiMessageError as B}from"../resilience.js";import{REQUIRED_EXECUTION_CONTINUATION_INSTRUCTION as L,WRITE_TODOS_REQUIRED_PLAN_INSTRUCTION as M}from"../../prompts/runtime-prompts.js";const le=["The current required todo board still has unfinished work.","Do not broaden the task, restart planning, or ask the user what to do next.","Use the existing tool evidence already available in this run.","Your next action must be write_todos: update every remaining pending or in_progress item to completed if evidence was gathered, or failed if it cannot be completed with the available tools.","After that write_todos call, provide the final answer required by the agent response format."].join(`
|
|
2
|
+
`),J=["This agent has a required visible planning contract.","Your first action for this request must be write_todos with concrete task steps and statuses.","Do not call any domain/evidence tool and do not provide a final answer before the initial write_todos call succeeds.","After each evidence step, update the todo board. Before the final answer, close every todo as completed or failed."].join(`
|
|
3
|
+
`);function E(e){const t=e.execution?.params??e.deepAgentParams??e.langchainAgentParams;return{tools:Array.isArray(t?.tools)?t.tools:[],subagents:Array.isArray(t?.subagents)?t.subagents??[]:[]}}function A(e){const{tools:t,subagents:n}=E(e),o=e.agent,r=[...n,...o?.subagentRefs??[],...o?.subagentPathRefs??[],...o?.asyncSubagents??[]],s=[...t,...o?.toolRefs??[],...o?.toolBindings??[]],u=o?.skillPathRefs??[];return r.length>0&&s.length===0&&u.length===0}function T(e){return e.some(t=>t.toolName==="task")}function Q(e){return typeof e=="string"?e.trim().toLowerCase().replace(/[\s-]+/gu,"_"):""}function Y(e){const t=Q(e);return t==="write_todos"||t==="read_todos"||t==="tool_call_write_todos"||t==="tool_call_read_todos"||t==="call_write_todos"||t==="call_read_todos"}function F(e){return e.some(t=>Y(t.toolName))}function v(e){return Array.isArray(e)?e.some(t=>{if(typeof t!="object"||t===null)return!1;const n=typeof t.status=="string"?t.status.trim().toLowerCase():"";return n==="pending"||n==="in_progress"}):!1}function W(e){if(typeof e!="object"||e===null)return!1;const t=e;return v(t.todos)||v(t.stateSnapshot?.todos)||v(t.metadata?.stateSnapshot?.todos)}function h(e){if(typeof e!="object"||e===null)return!1;if(Array.isArray(e))return e.some(n=>h(n));const t=e;return t.name==="task"?!0:h(t.tool_calls)||h(t.messages)}function b(e){const t=D(e)[0];if(t)return t;if(Array.isArray(e)){for(const l of e){const i=b(l);if(i)return i}return null}if(typeof e=="object"&&e!==null){const l=e,i=l.output!==void 0?b(l.output):null;if(i)return i;const c=l.content!==void 0?b(l.content):null;if(c)return c;const a=l.messages!==void 0?b(l.messages):null;if(a)return a}const n=typeof e=="string"?e.trim():"",o=n?_(n)??z(n):e;if(typeof o!="object"||o===null||Array.isArray(o))return null;const r=o;if(Array.isArray(r.tool_calls))return b(r.tool_calls[0]);const s=typeof r.function=="object"&&r.function!==null?r.function:void 0,u=r.name??r.tool_name??r.tool??s?.name??(typeof r.function=="string"?r.function:void 0),m=typeof u=="string"?u.trim():"";if(!m)return null;const d=r.arguments??r.args??r.parameters??s?.arguments??s?.args??s?.parameters??{},g=typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{};return{name:m,args:g}}function z(e){let t=-1,n=0,o=!1,r=!1;for(let s=0;s<e.length;s+=1){const u=e[s];if(t<0){u==="{"&&(t=s,n=1);continue}if(r){r=!1;continue}if(u==="\\"){r=o;continue}if(u==='"'){o=!o;continue}if(!o){if(u==="{"){n+=1;continue}if(u==="}"&&(n-=1,n===0)){const m=_(e.slice(t,s+1));if(m)return m;t=-1}}}return null}async function C(e){if(T(e.invocation.executedToolResults))return e.invocation;const t=j(e.invocation.result),n=b(t)??b(e.invocation.result);if(n?.name!=="task")return e.invocation;const o=e.builtinExecutableTools.get("task");if(!o)return e.invocation;try{const r=await o.invoke(n.args,e.toolRuntimeContext);return{result:{output:r},executedToolResults:[...e.invocation.executedToolResults,{toolName:"task",output:r}]}}catch(r){const s=r instanceof Error?r.message:String(r);return{result:{output:s},executedToolResults:[...e.invocation.executedToolResults,{toolName:"task",output:s,isError:!0}]}}}function $(e){const{subagents:t}=E(e);return t.map(n=>{if(typeof n!="object"||n===null)return"";const o=n,r=typeof o.name=="string"?o.name.trim():"";if(!r)return"";const s=typeof o.description=="string"?o.description.trim():"";return s?`- ${r}: ${s}`:`- ${r}`}).filter(Boolean).join(`
|
|
4
|
+
`)}function w(e,t){return["/no_think","Runtime correction: this agent is delegation-only.","Return exactly one JSON object and no prose.","Use this shape when a listed subagent fits:",'{"name":"task","arguments":{"subagent_type":"<listed name>","description":"<original request>"}}',"Use this shape only when no listed subagent fits:",'{"status":"refused","reason":"No configured subagent can handle the request."}',"Listed subagents:",$(e)||"(none)","Original request:",JSON.stringify(t)].join(`
|
|
5
|
+
`)}function G(){return["/no_think","Runtime correction: your previous assistant response was empty.","Continue the original request now.","If an available tool is needed, call exactly one valid tool with complete arguments.","If no tool is needed, return a non-empty final answer.","Do not return empty content."].join(`
|
|
6
|
+
`)}function K(e){const t=e instanceof Error?e.message:String(e);return B(e)||t==="empty_final_output"}function P(e,t){const n=["Runtime correction:",t].join(`
|
|
7
|
+
|
|
8
|
+
`);return Array.isArray(e)?[...e,{role:"user",content:n}]:typeof e=="object"&&e&&Array.isArray(e.messages)?{...e,messages:[...e.messages,{role:"user",content:n}]}:e}async function V(e){const t=e.history??[],n=e.invokeOptions??{};let o=e.resumePayload===void 0?q(e.binding,t,e.input,n):new N({resume:e.resumePayload});e.resumePayload===void 0&&e.binding.harnessRuntime.executionContract?.requiresPlan===!0&&n.suppressInitialRequiredPlanInstruction!==!0&&(o=x(p(o,J),"planning"));const{primaryTools:r,toolNameMapping:s,executableTools:u,defersToUpstreamHitlExecution:m}=O({binding:e.binding,resolveTools:e.resolveTools,getToolNameMapping:e.getToolNameMapping,toolConfig:{...n.context?{context:n.context}:{},configurable:{[U]:e.sessionId,[S]:e.requestId},...e.invokeOptions?.toolRuntimeContext?{toolRuntimeContext:e.invokeOptions.toolRuntimeContext}:{}}}),d=await e.resolveBuiltinMiddlewareTools(e.binding,n),g=a=>k({binding:e.binding,request:a,resumePayload:e.resumePayload,primaryTools:r,defersToUpstreamHitlExecution:m,toolNameMapping:s,executableTools:u,builtinExecutableTools:d,callRuntimeWithToolParseRecovery:e.callRuntimeWithToolParseRecovery,toolRuntimeContext:n.toolRuntimeContext,externalPlanEvidence:n.externalPlanEvidence});let l=await g(o);if(e.resumePayload===void 0&&A(e.binding)&&!T(l.executedToolResults)&&!h(l.result)){const a=w(e.binding,e.input),R=P(o,a),y=await g(R);l=await C({invocation:y,builtinExecutableTools:d,toolRuntimeContext:n.toolRuntimeContext})}let i=l.result;const c=[...l.executedToolResults];if(!i)throw new Error("Agent invocation returned no result");if(e.resumePayload===void 0&&e.binding.harnessRuntime.executionContract?.requiresPlan===!0&&!F(c)){const a=Array.isArray(i.messages)?i.messages:void 0,y=x(p(a?{messages:a}:o,M),"planning"),f=await g(y);i=f.result,c.splice(0,c.length,...f.executedToolResults)}if(e.resumePayload===void 0&&e.binding.harnessRuntime.executionContract?.requiresPlan===!0&&W(i)){const a=Array.isArray(i.messages)?i.messages:void 0,y=p(a?{messages:a}:o,L),f=await g(y);i=f.result,c.splice(0,c.length,...f.executedToolResults)}try{return I({bindingAgentId:e.binding.agent.id,sessionId:e.sessionId,requestId:e.requestId,binding:e.binding,result:i,executedToolResults:c})}catch(a){if(e.resumePayload!==void 0||!K(a))throw a;const R=A(e.binding)&&!T(c)&&!h(i),y=P(o,R?w(e.binding,e.input):G()),f=await C({invocation:await g(y),builtinExecutableTools:d,toolRuntimeContext:n.toolRuntimeContext});return I({bindingAgentId:e.binding.agent.id,sessionId:e.sessionId,requestId:e.requestId,binding:e.binding,result:f.result,executedToolResults:f.executedToolResults})}}const ue=V;export{V as executeRequestInvocation,ue as executeRuntimeInvocation};
|
|
@@ -1,20 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
export async function invokeRuntimeWithLocalTools(options) {
|
|
3
|
-
if (options.resumePayload !== undefined || options.defersToUpstreamHitlExecution) {
|
|
4
|
-
return {
|
|
5
|
-
result: await options.callRuntimeWithToolParseRecovery(options.request),
|
|
6
|
-
executedToolResults: [],
|
|
7
|
-
};
|
|
8
|
-
}
|
|
9
|
-
return runLocalToolInvocationLoop({
|
|
10
|
-
binding: options.binding,
|
|
11
|
-
request: options.request,
|
|
12
|
-
primaryTools: options.primaryTools,
|
|
13
|
-
toolNameMapping: options.toolNameMapping,
|
|
14
|
-
executableTools: options.executableTools,
|
|
15
|
-
builtinExecutableTools: options.builtinExecutableTools,
|
|
16
|
-
callRuntimeWithToolParseRecovery: options.callRuntimeWithToolParseRecovery,
|
|
17
|
-
toolRuntimeContext: options.toolRuntimeContext,
|
|
18
|
-
externalPlanEvidence: options.externalPlanEvidence,
|
|
19
|
-
});
|
|
20
|
-
}
|
|
1
|
+
import{runLocalToolInvocationLoop as l}from"../local-tool-invocation.js";async function a(e){return e.resumePayload!==void 0||e.defersToUpstreamHitlExecution?{result:await e.callRuntimeWithToolParseRecovery(e.request),executedToolResults:[]}:l({binding:e.binding,request:e.request,primaryTools:e.primaryTools,toolNameMapping:e.toolNameMapping,executableTools:e.executableTools,builtinExecutableTools:e.builtinExecutableTools,callRuntimeWithToolParseRecovery:e.callRuntimeWithToolParseRecovery,toolRuntimeContext:e.toolRuntimeContext,externalPlanEvidence:e.externalPlanEvidence})}export{a as invokeRuntimeWithLocalTools};
|