@botbotgo/agent-harness 0.0.474 → 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 +2 -2
- 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 -411
- 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 -1089
- 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
package/dist/runtime/harness.js
CHANGED
|
@@ -1,1490 +1,3 @@
|
|
|
1
|
-
import path from "node:path";
|
|
2
|
-
|
|
3
|
-
import { createPersistentId } from "../utils/id.js";
|
|
4
|
-
import { extractMessageText } from "../utils/message-content.js";
|
|
5
|
-
import { AgentRuntimeAdapter } from "./agent-runtime-adapter.js";
|
|
6
|
-
import { normalizeRecordedArtifactPath } from "./harness/run/artifact-paths.js";
|
|
7
|
-
import { EventBus } from "./harness/events/event-bus.js";
|
|
8
|
-
import { createBackgroundEventRuntime } from "./harness/background-runtime.js";
|
|
9
|
-
import { PolicyEngine } from "./harness/system/policy-engine.js";
|
|
10
|
-
import { getConcurrencyConfig, getRecoveryConfig, getRoutingDefaultAgentId, getRoutingRules, } from "../workspace/support/workspace-ref-utils.js";
|
|
11
|
-
import { createHarnessEvent, inferRoutingBindings, renderRuntimeFailure, } from "./support/harness-support.js";
|
|
12
|
-
import { SessionMemorySync } from "./harness/system/session-memory-sync.js";
|
|
13
|
-
import { RuntimeMemorySync, readRuntimeMemorySyncConfig } from "./harness/system/runtime-memory-sync.js";
|
|
14
|
-
import { SqliteBackedStore } from "./harness/system/store.js";
|
|
15
|
-
import { HealthMonitor, readHealthMonitorConfig, } from "./harness/system/health-monitor.js";
|
|
16
|
-
import { normalizeInvocationEnvelope, normalizeRequestPriority, resolveRequestListeners, } from "./harness/run/helpers.js";
|
|
17
|
-
import { emitHarnessEvent, } from "./harness/events/events.js";
|
|
18
|
-
import { createRuntimeEventOperations } from "./harness/events/runtime-event-operations.js";
|
|
19
|
-
import { appendAssistantMessage as appendLifecycleAssistantMessage, finalizeCancelledRequest as finalizeLifecycleCancelledRequest, finalizeContinuedRequest as finalizeLifecycleContinuedRequest, } from "./harness/run/run-lifecycle.js";
|
|
20
|
-
import { createListenerDispatchRuntime } from "./harness/events/listener-runtime.js";
|
|
21
|
-
import { buildResumePayload as buildHarnessResumePayload, resolveApprovalRecord as resolveHarnessApprovalRecord, } from "./harness/run/resume.js";
|
|
22
|
-
import { cancelRequestOperation, executeQueuedRequestOperation, resumeRequest } from "./harness/run/run-operations.js";
|
|
23
|
-
import { projectOperatorOverview } from "./harness/run/operator-overview.js";
|
|
24
|
-
import { acquireRequestSlot as acquireHarnessRunSlot } from "./harness/run/run-slot-acquisition.js";
|
|
25
|
-
import { dropPendingRequestSlot, enqueuePendingRequestSlot } from "./harness/run/run-queue.js";
|
|
26
|
-
import { getDefaultRuntimeEntryAgentId, resolveSelectedAgentId, routeAgentId } from "./harness/run/routing.js";
|
|
27
|
-
import { resolveStoreFromConfig, resolveVectorStore, } from "./harness/run/resources.js";
|
|
28
|
-
import { createRuntimeMcpServer, createToolMcpServerFromTools, serveRuntimeMcpOverStdio, serveToolsOverStdioFromHarness, } from "../mcp.js";
|
|
29
|
-
import { closeMcpClientsForWorkspace } from "../resource/mcp/tool-support.js";
|
|
30
|
-
import { getBindingRuntimeExecutionMode, } from "./support/compiled-binding.js";
|
|
31
|
-
import { bindingSupportsRunningReplay, getWorkspaceBinding, resolveWorkspaceAgentTools, } from "./harness/bindings.js";
|
|
32
|
-
import { describeWorkspaceInventory, getAgentInventoryRecord, listAgentSkills as listWorkspaceAgentSkills, } from "./harness/system/inventory.js";
|
|
33
|
-
import { analyzeWorkspaceBoundaries, } from "./harness/system/boundary-analysis.js";
|
|
34
|
-
import { createDefaultHealthSnapshot, isInventoryEnabled, isSessionMemorySyncEnabled, } from "./harness/runtime-defaults.js";
|
|
35
|
-
import { cloneRequestRecord, cloneSessionRecord, deriveRequestInputFromTranscript, mergeMemoryItems, summarizeApprovalEvidence, toPublicHarnessStreamItem, toPublicRequestResultShape, toSessionListSummary, } from "./harness/public-shapes.js";
|
|
36
|
-
import { Mem0IngestionSync, Mem0SemanticRecall, readMem0RuntimeConfig, } from "./harness/system/mem0-ingestion-sync.js";
|
|
37
|
-
import { createRuntimeMemoryManager, RuntimeMemoryFormationSync, readRuntimeMemoryFormationConfig, } from "./harness/system/runtime-memory-manager.js";
|
|
38
|
-
import { readRuntimeMemoryMaintenanceConfig, readRuntimeMemoryPolicyConfig, resolveMemoryNamespace, } from "./harness/system/runtime-memory-policy.js";
|
|
39
|
-
import { resolveRuntimeAdapterOptions } from "./support/runtime-adapter-options.js";
|
|
40
|
-
import { resolveKnowledgeStorePath, resolveProceduralMemoryStorePath } from "./layout/runtime-layout.js";
|
|
41
|
-
import { SystemScheduleManager } from "./scheduling/system-schedule-manager.js";
|
|
42
|
-
import { initializeHarnessRuntime, reclaimExpiredClaimedRequests as reclaimHarnessExpiredClaimedRequests, recoverStartupRequests as recoverHarnessStartupRequests, isStaleRunningRequest as isHarnessStaleRunningRequest, } from "./harness/run/startup-runtime.js";
|
|
43
|
-
import { traceStartupStage } from "./startup-tracing.js";
|
|
44
|
-
import { normalizeProcessExecutablePath } from "./env/runtime-env.js";
|
|
45
|
-
import { streamHarnessRun } from "./harness/run/stream-run.js";
|
|
46
|
-
import { defaultRequestedAgentId, prepareRunStart } from "./harness/run/start-run.js";
|
|
47
|
-
import { buildRequestInspectionRecord, buildSessionInspectionRecord, deleteSessionRecord, getPublicApproval, listPublicApprovals, } from "./harness/run/session-records.js";
|
|
48
|
-
import { createKnowledgeModule } from "../knowledge/index.js";
|
|
49
|
-
import { createProceduralMemoryManager, ProceduralMemoryFormationSync, readProceduralMemoryRuntimeConfig, } from "../knowledge/procedural/index.js";
|
|
50
|
-
const BACKGROUND_TASK_CLOSE_DRAIN_TIMEOUT_MS = 1_000;
|
|
51
|
-
const CLOSE_STAGE_TIMEOUT_MS = 1_000;
|
|
52
|
-
const ACTIVE_REQUEST_STATES = [
|
|
53
|
-
"queued",
|
|
54
|
-
"claimed",
|
|
55
|
-
"running",
|
|
56
|
-
"waiting_for_approval",
|
|
57
|
-
"resuming",
|
|
58
|
-
"cancelling",
|
|
59
|
-
];
|
|
60
|
-
export class AgentHarnessRuntime {
|
|
61
|
-
workspace;
|
|
62
|
-
runtimeAdapterOptions;
|
|
63
|
-
static BACKGROUND_EVENT_TYPES = new Set([
|
|
64
|
-
"request.created",
|
|
65
|
-
"request.queued",
|
|
66
|
-
"request.dequeued",
|
|
67
|
-
"output.delta",
|
|
68
|
-
]);
|
|
69
|
-
eventBus = new EventBus();
|
|
70
|
-
persistence;
|
|
71
|
-
policyEngine = new PolicyEngine();
|
|
72
|
-
runtimeAdapter;
|
|
73
|
-
checkpointers = new Map();
|
|
74
|
-
stores = new Map();
|
|
75
|
-
embeddingModels = new Map();
|
|
76
|
-
vectorStores = new Map();
|
|
77
|
-
runtimeEntryBindings;
|
|
78
|
-
defaultRuntimeEntryBinding;
|
|
79
|
-
defaultRuntimeRootValue;
|
|
80
|
-
defaultStore;
|
|
81
|
-
runtimeMemoryStore;
|
|
82
|
-
runtimeMemoryPolicy;
|
|
83
|
-
runtimeMemoryMaintenanceConfig;
|
|
84
|
-
routingRules;
|
|
85
|
-
routingDefaultAgentId;
|
|
86
|
-
sessionMemorySync;
|
|
87
|
-
unregisterSessionMemorySync;
|
|
88
|
-
runtimeMemorySync;
|
|
89
|
-
unregisterRuntimeMemorySync;
|
|
90
|
-
mem0IngestionSync;
|
|
91
|
-
unregisterMem0IngestionSync;
|
|
92
|
-
mem0SemanticRecall;
|
|
93
|
-
runtimeMemoryFormationConfig;
|
|
94
|
-
runtimeMemoryManager;
|
|
95
|
-
knowledgeModule;
|
|
96
|
-
runtimeMemoryFormationSync;
|
|
97
|
-
unregisterRuntimeMemoryFormationSync;
|
|
98
|
-
proceduralMemoryConfig;
|
|
99
|
-
proceduralMemoryStore;
|
|
100
|
-
proceduralMemoryManager;
|
|
101
|
-
proceduralMemoryModule;
|
|
102
|
-
proceduralMemoryFormationSync;
|
|
103
|
-
unregisterProceduralMemoryFormationSync;
|
|
104
|
-
resolvedRuntimeAdapterOptions;
|
|
105
|
-
scheduleManager;
|
|
106
|
-
healthMonitor;
|
|
107
|
-
recoveryConfig;
|
|
108
|
-
concurrencyConfig;
|
|
109
|
-
backgroundTasks = new Set();
|
|
110
|
-
workerId = `worker-${createPersistentId()}`;
|
|
111
|
-
activeRequestSlots = 0;
|
|
112
|
-
pendingRunInsertionOrder = 0;
|
|
113
|
-
pendingRequestSlots = [];
|
|
114
|
-
runtimeEventSequence = 0;
|
|
115
|
-
initialized = false;
|
|
116
|
-
closed = false;
|
|
117
|
-
backgroundEventRuntime;
|
|
118
|
-
runtimeEventOperations;
|
|
119
|
-
async resolveRuntimeMemoryVectorStore() {
|
|
120
|
-
const vectorStoreConfig = typeof this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.vectorStore === "object" &&
|
|
121
|
-
this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.vectorStore
|
|
122
|
-
? this.defaultRuntimeEntryBinding.harnessRuntime.runtimeMemory.vectorStore
|
|
123
|
-
: undefined;
|
|
124
|
-
const vectorStoreRef = typeof vectorStoreConfig?.ref === "string" && vectorStoreConfig.ref.trim().length > 0 ? vectorStoreConfig.ref : undefined;
|
|
125
|
-
try {
|
|
126
|
-
return await resolveVectorStore(this.workspace, this.vectorStores, vectorStoreRef, this.resolvedRuntimeAdapterOptions);
|
|
127
|
-
}
|
|
128
|
-
catch {
|
|
129
|
-
return null;
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
defaultRuntimeRoot() {
|
|
133
|
-
return this.defaultRuntimeRootValue;
|
|
134
|
-
}
|
|
135
|
-
getDefaultRuntimeEntryAgentId() {
|
|
136
|
-
return getDefaultRuntimeEntryAgentId(this.workspace, this.routingDefaultAgentId);
|
|
137
|
-
}
|
|
138
|
-
async resolveSelectedAgentId(input, requestedAgentId, sessionId) {
|
|
139
|
-
return resolveSelectedAgentId({
|
|
140
|
-
workspace: this.workspace,
|
|
141
|
-
input,
|
|
142
|
-
requestedAgentId,
|
|
143
|
-
sessionId,
|
|
144
|
-
preferredRuntimeEntryAgentId: this.routingDefaultAgentId,
|
|
145
|
-
getSessionSummary: (currentSessionId) => this.getSessionSummaryRecord(currentSessionId),
|
|
146
|
-
});
|
|
147
|
-
}
|
|
148
|
-
createPrepareRunStartRuntime() {
|
|
149
|
-
return {
|
|
150
|
-
workspace: this.workspace,
|
|
151
|
-
policyEngine: this.policyEngine,
|
|
152
|
-
persistence: this.persistence,
|
|
153
|
-
resolveSelectedAgentId: (input, requestedAgentId, sessionId) => this.resolveSelectedAgentId(input, requestedAgentId, sessionId),
|
|
154
|
-
emitRequestCreated: (sessionId, requestId, payload) => this.runtimeEventOperations.emitRequestCreated(sessionId, requestId, payload),
|
|
155
|
-
acquireRequestSlot: (sessionId, requestId, activeState, priority) => this.acquireRequestSlot(sessionId, requestId, activeState, priority),
|
|
156
|
-
};
|
|
157
|
-
}
|
|
158
|
-
buildFunctionToolContext(input) {
|
|
159
|
-
return {
|
|
160
|
-
runtime: {
|
|
161
|
-
sessions: {
|
|
162
|
-
list: (filter) => this.listSessions(filter),
|
|
163
|
-
get: (sessionId) => this.getSession(sessionId),
|
|
164
|
-
},
|
|
165
|
-
requests: {
|
|
166
|
-
list: (filter) => this.listRequests(filter),
|
|
167
|
-
get: (requestId) => this.getRequest(requestId),
|
|
168
|
-
cancel: (options) => this.cancelRequest(options),
|
|
169
|
-
},
|
|
170
|
-
approvals: {
|
|
171
|
-
list: (filter) => this.listApprovals(filter),
|
|
172
|
-
get: (approvalId) => this.getApproval(approvalId),
|
|
173
|
-
},
|
|
174
|
-
events: {
|
|
175
|
-
list: (sessionId, requestId) => this.listRequestEvents(sessionId, requestId),
|
|
176
|
-
},
|
|
177
|
-
artifacts: {
|
|
178
|
-
list: (sessionId, requestId) => this.listRequestArtifacts(sessionId, requestId),
|
|
179
|
-
read: (sessionId, requestId, artifactPath) => this.readRequestArtifact(sessionId, requestId, artifactPath),
|
|
180
|
-
create: (artifact) => this.recordArtifact(artifact),
|
|
181
|
-
},
|
|
182
|
-
schedules: {
|
|
183
|
-
manage: (options) => this.manageSchedule(options),
|
|
184
|
-
},
|
|
185
|
-
current: {
|
|
186
|
-
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
187
|
-
...(input.requestId ? { requestId: input.requestId } : {}),
|
|
188
|
-
...(input.binding ? { agentId: input.binding.agent.id } : {}),
|
|
189
|
-
},
|
|
190
|
-
},
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
constructor(workspace, runtimeAdapterOptions = {}) {
|
|
194
|
-
this.workspace = workspace;
|
|
195
|
-
this.runtimeAdapterOptions = runtimeAdapterOptions;
|
|
196
|
-
normalizeProcessExecutablePath();
|
|
197
|
-
this.runtimeEntryBindings = inferRoutingBindings(this.workspace).runtimeEntryBindings;
|
|
198
|
-
this.defaultRuntimeEntryBinding = this.runtimeEntryBindings[0];
|
|
199
|
-
this.defaultRuntimeRootValue = this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeRoot ?? `${this.workspace.workspaceRoot}/.agent`;
|
|
200
|
-
const runtimeRoot = this.defaultRuntimeRoot();
|
|
201
|
-
this.scheduleManager = new SystemScheduleManager({
|
|
202
|
-
workspaceRoot: this.workspace.workspaceRoot,
|
|
203
|
-
runtimeRoot,
|
|
204
|
-
});
|
|
205
|
-
this.persistence = new SqlitePersistence(runtimeRoot);
|
|
206
|
-
const defaultStoreConfig = this.defaultRuntimeEntryBinding?.harnessRuntime.store;
|
|
207
|
-
this.defaultStore = resolveStoreFromConfig(this.stores, defaultStoreConfig, runtimeRoot) ?? new SqliteBackedStore(resolveKnowledgeStorePath(runtimeRoot));
|
|
208
|
-
const runtimeMemoryStoreConfig = typeof this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.store === "object" &&
|
|
209
|
-
this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.store
|
|
210
|
-
? this.defaultRuntimeEntryBinding.harnessRuntime.runtimeMemory.store
|
|
211
|
-
: undefined;
|
|
212
|
-
this.runtimeMemoryStore = resolveStoreFromConfig(this.stores, runtimeMemoryStoreConfig, runtimeRoot) ?? this.defaultStore;
|
|
213
|
-
this.runtimeMemoryPolicy = readRuntimeMemoryPolicyConfig(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory, this.workspace.workspaceRoot) ?? null;
|
|
214
|
-
this.runtimeMemoryMaintenanceConfig =
|
|
215
|
-
readRuntimeMemoryMaintenanceConfig(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory) ?? null;
|
|
216
|
-
this.resolvedRuntimeAdapterOptions = resolveRuntimeAdapterOptions({
|
|
217
|
-
workspace,
|
|
218
|
-
runtimeAdapterOptions: {
|
|
219
|
-
...runtimeAdapterOptions,
|
|
220
|
-
scheduleManager: runtimeAdapterOptions.scheduleManager ?? this.scheduleManager,
|
|
221
|
-
bindingResolver: runtimeAdapterOptions.bindingResolver ?? ((agentId) => this.workspace.bindings.get(agentId)),
|
|
222
|
-
functionToolContextResolver: runtimeAdapterOptions.functionToolContextResolver ?? ((input) => this.buildFunctionToolContext(input)),
|
|
223
|
-
},
|
|
224
|
-
checkpointers: this.checkpointers,
|
|
225
|
-
stores: this.stores,
|
|
226
|
-
defaultStore: this.defaultStore,
|
|
227
|
-
embeddingModels: this.embeddingModels,
|
|
228
|
-
vectorStores: this.vectorStores,
|
|
229
|
-
getDefaultRuntimeRoot: () => this.defaultRuntimeRoot(),
|
|
230
|
-
});
|
|
231
|
-
this.runtimeAdapter = new AgentRuntimeAdapter(this.resolvedRuntimeAdapterOptions);
|
|
232
|
-
this.backgroundEventRuntime = createBackgroundEventRuntime({
|
|
233
|
-
persistence: this.persistence,
|
|
234
|
-
publishEvent: (event) => this.eventBus.publish(event),
|
|
235
|
-
trackBackgroundTask: (task) => this.trackBackgroundTask(task),
|
|
236
|
-
backgroundEventTypes: AgentHarnessRuntime.BACKGROUND_EVENT_TYPES,
|
|
237
|
-
});
|
|
238
|
-
this.runtimeEventOperations = createRuntimeEventOperations(this.backgroundEventRuntime);
|
|
239
|
-
this.routingRules = getRoutingRules(workspace.refs);
|
|
240
|
-
this.routingDefaultAgentId = getRoutingDefaultAgentId(workspace.refs);
|
|
241
|
-
if (isSessionMemorySyncEnabled(workspace)) {
|
|
242
|
-
this.sessionMemorySync = new SessionMemorySync(this.persistence, this.runtimeMemoryStore, {
|
|
243
|
-
resolveSessionNamespace: (sessionId) => {
|
|
244
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
245
|
-
if (!binding) {
|
|
246
|
-
return ["memories", "sessions", sessionId];
|
|
247
|
-
}
|
|
248
|
-
return this.resolveMemoryNamespace("session", binding, { sessionId });
|
|
249
|
-
},
|
|
250
|
-
});
|
|
251
|
-
this.unregisterSessionMemorySync = this.eventBus.registerProjection(this.sessionMemorySync);
|
|
252
|
-
}
|
|
253
|
-
else {
|
|
254
|
-
this.sessionMemorySync = null;
|
|
255
|
-
this.unregisterSessionMemorySync = () => { };
|
|
256
|
-
}
|
|
257
|
-
const runtimeMemorySyncConfig = readRuntimeMemorySyncConfig(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory);
|
|
258
|
-
if (runtimeMemorySyncConfig) {
|
|
259
|
-
this.runtimeMemorySync = new RuntimeMemorySync(this.persistence, this.runtimeMemoryStore, runtimeMemorySyncConfig, {
|
|
260
|
-
resolveSessionNamespace: (sessionId) => {
|
|
261
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
262
|
-
if (!binding) {
|
|
263
|
-
return ["memories", "sessions", sessionId];
|
|
264
|
-
}
|
|
265
|
-
return this.resolveMemoryNamespace("session", binding, { sessionId });
|
|
266
|
-
},
|
|
267
|
-
resolveRequestNamespace: (sessionId) => ["memories", "requests", sessionId],
|
|
268
|
-
});
|
|
269
|
-
this.unregisterRuntimeMemorySync = this.eventBus.registerProjection(this.runtimeMemorySync);
|
|
270
|
-
}
|
|
271
|
-
else {
|
|
272
|
-
this.runtimeMemorySync = null;
|
|
273
|
-
this.unregisterRuntimeMemorySync = () => { };
|
|
274
|
-
}
|
|
275
|
-
const mem0RuntimeConfig = readMem0RuntimeConfig(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory, this.workspace.workspaceRoot);
|
|
276
|
-
if (mem0RuntimeConfig) {
|
|
277
|
-
this.mem0IngestionSync = new Mem0IngestionSync(this.persistence, mem0RuntimeConfig, runtimeRoot);
|
|
278
|
-
this.unregisterMem0IngestionSync = this.eventBus.registerProjection(this.mem0IngestionSync);
|
|
279
|
-
this.mem0SemanticRecall = new Mem0SemanticRecall(mem0RuntimeConfig);
|
|
280
|
-
}
|
|
281
|
-
else {
|
|
282
|
-
this.mem0IngestionSync = null;
|
|
283
|
-
this.unregisterMem0IngestionSync = () => { };
|
|
284
|
-
this.mem0SemanticRecall = null;
|
|
285
|
-
}
|
|
286
|
-
const runtimeMemoryFormationConfig = readRuntimeMemoryFormationConfig(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory, this.workspace.workspaceRoot);
|
|
287
|
-
this.runtimeMemoryFormationConfig = runtimeMemoryFormationConfig ?? null;
|
|
288
|
-
this.runtimeMemoryManager =
|
|
289
|
-
this.defaultRuntimeEntryBinding && runtimeMemoryFormationConfig
|
|
290
|
-
? createRuntimeMemoryManager({
|
|
291
|
-
workspace: this.workspace,
|
|
292
|
-
binding: this.defaultRuntimeEntryBinding,
|
|
293
|
-
config: runtimeMemoryFormationConfig,
|
|
294
|
-
modelResolver: this.resolvedRuntimeAdapterOptions.modelResolver,
|
|
295
|
-
})
|
|
296
|
-
: null;
|
|
297
|
-
this.knowledgeModule = createKnowledgeModule({
|
|
298
|
-
store: this.runtimeMemoryStore,
|
|
299
|
-
policy: this.runtimeMemoryPolicy,
|
|
300
|
-
maintenanceConfig: this.runtimeMemoryMaintenanceConfig,
|
|
301
|
-
resolveNamespace: (scope, context) => {
|
|
302
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
303
|
-
if (!binding) {
|
|
304
|
-
const identifier = scope === "session"
|
|
305
|
-
? context.sessionId
|
|
306
|
-
: scope === "agent"
|
|
307
|
-
? context.agentId
|
|
308
|
-
: scope === "workspace"
|
|
309
|
-
? context.workspaceId
|
|
310
|
-
: scope === "user"
|
|
311
|
-
? context.userId ?? "default"
|
|
312
|
-
: context.projectId ?? context.workspaceId;
|
|
313
|
-
return ["memories", `${scope}s`, identifier ?? "default"];
|
|
314
|
-
}
|
|
315
|
-
return this.resolveMemoryNamespace(scope, binding, {
|
|
316
|
-
sessionId: context.sessionId,
|
|
317
|
-
agentId: context.agentId,
|
|
318
|
-
userId: context.userId,
|
|
319
|
-
projectId: context.projectId,
|
|
320
|
-
});
|
|
321
|
-
},
|
|
322
|
-
resolveVectorStore: () => this.resolveRuntimeMemoryVectorStore(),
|
|
323
|
-
transformCandidates: this.runtimeMemoryManager && this.defaultRuntimeEntryBinding
|
|
324
|
-
? ({ candidates, context, existingRecords }) => this.runtimeMemoryManager.transform({
|
|
325
|
-
candidates,
|
|
326
|
-
binding: this.defaultRuntimeEntryBinding,
|
|
327
|
-
sessionId: context.sessionId ?? `memory-api-${context.requestId ?? "unknown"}`,
|
|
328
|
-
requestId: context.requestId ?? createPersistentId(new Date(context.recordedAt ?? new Date().toISOString())),
|
|
329
|
-
recordedAt: context.recordedAt ?? new Date().toISOString(),
|
|
330
|
-
existingRecords,
|
|
331
|
-
})
|
|
332
|
-
: undefined,
|
|
333
|
-
getMem0SemanticRecall: () => this.mem0SemanticRecall,
|
|
334
|
-
});
|
|
335
|
-
if (runtimeMemoryFormationConfig) {
|
|
336
|
-
this.runtimeMemoryFormationSync = new RuntimeMemoryFormationSync(this.persistence, runtimeMemoryFormationConfig, (input) => this.knowledgeModule.memorizeCandidates(input.candidates, {
|
|
337
|
-
sessionId: input.sessionId,
|
|
338
|
-
requestId: input.requestId,
|
|
339
|
-
agentId: input.agentId,
|
|
340
|
-
workspaceId: this.getWorkspaceId(this.defaultRuntimeEntryBinding),
|
|
341
|
-
userId: input.userId,
|
|
342
|
-
projectId: input.projectId,
|
|
343
|
-
recordedAt: input.recordedAt,
|
|
344
|
-
}, { storeCandidateLog: false }).then(() => undefined), runtimeRoot);
|
|
345
|
-
this.unregisterRuntimeMemoryFormationSync = this.eventBus.registerProjection(this.runtimeMemoryFormationSync);
|
|
346
|
-
}
|
|
347
|
-
else {
|
|
348
|
-
this.runtimeMemoryFormationSync = null;
|
|
349
|
-
this.unregisterRuntimeMemoryFormationSync = () => { };
|
|
350
|
-
}
|
|
351
|
-
const proceduralMemoryConfig = readProceduralMemoryRuntimeConfig(this.defaultRuntimeEntryBinding?.harnessRuntime.proceduralMemory);
|
|
352
|
-
this.proceduralMemoryConfig = proceduralMemoryConfig?.enabled ? proceduralMemoryConfig : null;
|
|
353
|
-
const proceduralStoreConfig = this.proceduralMemoryConfig?.store && Object.keys(this.proceduralMemoryConfig.store).length > 0
|
|
354
|
-
? this.proceduralMemoryConfig.store
|
|
355
|
-
: {
|
|
356
|
-
kind: "SqliteStore",
|
|
357
|
-
path: resolveProceduralMemoryStorePath(runtimeRoot),
|
|
358
|
-
};
|
|
359
|
-
this.proceduralMemoryStore = this.proceduralMemoryConfig
|
|
360
|
-
? resolveStoreFromConfig(this.stores, proceduralStoreConfig, runtimeRoot) ?? null
|
|
361
|
-
: null;
|
|
362
|
-
this.proceduralMemoryManager =
|
|
363
|
-
this.defaultRuntimeEntryBinding && this.proceduralMemoryConfig
|
|
364
|
-
? createProceduralMemoryManager({
|
|
365
|
-
workspace: this.workspace,
|
|
366
|
-
binding: this.defaultRuntimeEntryBinding,
|
|
367
|
-
config: this.proceduralMemoryConfig,
|
|
368
|
-
modelResolver: this.resolvedRuntimeAdapterOptions.modelResolver,
|
|
369
|
-
})
|
|
370
|
-
: null;
|
|
371
|
-
this.proceduralMemoryModule =
|
|
372
|
-
this.proceduralMemoryConfig && this.proceduralMemoryStore
|
|
373
|
-
? createKnowledgeModule({
|
|
374
|
-
store: this.proceduralMemoryStore,
|
|
375
|
-
policy: null,
|
|
376
|
-
maintenanceConfig: null,
|
|
377
|
-
resolveNamespace: (scope, context) => {
|
|
378
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
379
|
-
if (!binding) {
|
|
380
|
-
const identifier = scope === "session"
|
|
381
|
-
? context.sessionId
|
|
382
|
-
: scope === "agent"
|
|
383
|
-
? context.agentId
|
|
384
|
-
: scope === "workspace"
|
|
385
|
-
? context.workspaceId
|
|
386
|
-
: scope === "user"
|
|
387
|
-
? context.userId ?? "default"
|
|
388
|
-
: context.projectId ?? context.workspaceId;
|
|
389
|
-
return ["procedural", `${scope}s`, identifier ?? "default"];
|
|
390
|
-
}
|
|
391
|
-
return this.resolveMemoryNamespace(scope, binding, {
|
|
392
|
-
sessionId: context.sessionId,
|
|
393
|
-
agentId: context.agentId,
|
|
394
|
-
userId: context.userId,
|
|
395
|
-
projectId: context.projectId,
|
|
396
|
-
});
|
|
397
|
-
},
|
|
398
|
-
resolveVectorStore: async () => null,
|
|
399
|
-
transformCandidates: this.proceduralMemoryManager && this.defaultRuntimeEntryBinding
|
|
400
|
-
? ({ candidates, context, existingRecords }) => this.proceduralMemoryManager.transform({
|
|
401
|
-
candidates,
|
|
402
|
-
binding: this.defaultRuntimeEntryBinding,
|
|
403
|
-
sessionId: context.sessionId ?? `procedural-api-${context.requestId ?? "unknown"}`,
|
|
404
|
-
requestId: context.requestId ?? createPersistentId(new Date(context.recordedAt ?? new Date().toISOString())),
|
|
405
|
-
recordedAt: context.recordedAt ?? new Date().toISOString(),
|
|
406
|
-
existingRecords,
|
|
407
|
-
})
|
|
408
|
-
: undefined,
|
|
409
|
-
})
|
|
410
|
-
: null;
|
|
411
|
-
if (this.proceduralMemoryConfig && this.proceduralMemoryModule) {
|
|
412
|
-
this.proceduralMemoryFormationSync = new ProceduralMemoryFormationSync(this.persistence, this.proceduralMemoryConfig, (input) => this.proceduralMemoryModule.memorizeCandidates(input.candidates, {
|
|
413
|
-
sessionId: input.sessionId,
|
|
414
|
-
requestId: input.requestId,
|
|
415
|
-
agentId: input.agentId,
|
|
416
|
-
workspaceId: this.getWorkspaceId(this.defaultRuntimeEntryBinding),
|
|
417
|
-
userId: input.userId,
|
|
418
|
-
projectId: input.projectId,
|
|
419
|
-
recordedAt: input.recordedAt,
|
|
420
|
-
}, { storeCandidateLog: false }).then(() => undefined), runtimeRoot);
|
|
421
|
-
this.unregisterProceduralMemoryFormationSync = this.eventBus.registerProjection(this.proceduralMemoryFormationSync);
|
|
422
|
-
}
|
|
423
|
-
else {
|
|
424
|
-
this.proceduralMemoryFormationSync = null;
|
|
425
|
-
this.unregisterProceduralMemoryFormationSync = () => { };
|
|
426
|
-
}
|
|
427
|
-
this.recoveryConfig = getRecoveryConfig(workspace.refs);
|
|
428
|
-
this.concurrencyConfig = getConcurrencyConfig(workspace.refs);
|
|
429
|
-
const healthConfig = readHealthMonitorConfig(workspace);
|
|
430
|
-
this.healthMonitor = healthConfig.enabled ? this.createHealthMonitor() : null;
|
|
431
|
-
}
|
|
432
|
-
async manageSchedule(input) {
|
|
433
|
-
return this.scheduleManager.manageSchedule(input);
|
|
434
|
-
}
|
|
435
|
-
async getSchedule(scheduleId) {
|
|
436
|
-
return this.scheduleManager.getSchedule(scheduleId);
|
|
437
|
-
}
|
|
438
|
-
async runScheduledTask(scheduleId) {
|
|
439
|
-
const schedule = await this.scheduleManager.getSchedule(scheduleId);
|
|
440
|
-
if (!schedule) {
|
|
441
|
-
throw new Error(`Unknown schedule '${scheduleId}'.`);
|
|
442
|
-
}
|
|
443
|
-
return this.run({
|
|
444
|
-
...(schedule.agentId ? { agentId: schedule.agentId } : {}),
|
|
445
|
-
input: schedule.instruction,
|
|
446
|
-
});
|
|
447
|
-
}
|
|
448
|
-
createHealthMonitor() {
|
|
449
|
-
return new HealthMonitor({
|
|
450
|
-
workspace: this.workspace,
|
|
451
|
-
persistence: this.persistence,
|
|
452
|
-
getActiveRequestSlots: () => this.activeRequestSlots,
|
|
453
|
-
getPendingRequestSlots: () => this.pendingRequestSlots.length,
|
|
454
|
-
getCheckpointMaintenanceStatus: () => null,
|
|
455
|
-
getRuntimeRecordMaintenanceStatus: () => null,
|
|
456
|
-
publishEvent: async (payload) => {
|
|
457
|
-
this.eventBus.publish(createHarnessEvent("__runtime__", "__runtime__", ++this.runtimeEventSequence, "runtime.health.changed", payload));
|
|
458
|
-
},
|
|
459
|
-
});
|
|
460
|
-
}
|
|
461
|
-
recordLlmSuccess(startedAt) {
|
|
462
|
-
this.healthMonitor?.recordLlmSuccess(Date.now() - startedAt);
|
|
463
|
-
}
|
|
464
|
-
recordLlmFailure(startedAt) {
|
|
465
|
-
this.healthMonitor?.recordLlmFailure(Date.now() - startedAt);
|
|
466
|
-
}
|
|
467
|
-
async initialize() {
|
|
468
|
-
if (this.closed) {
|
|
469
|
-
throw new Error("AgentHarnessRuntime has been closed and cannot be reinitialized");
|
|
470
|
-
}
|
|
471
|
-
if (this.initialized) {
|
|
472
|
-
return;
|
|
473
|
-
}
|
|
474
|
-
await initializeHarnessRuntime({
|
|
475
|
-
persistence: this.persistence,
|
|
476
|
-
healthMonitor: this.healthMonitor,
|
|
477
|
-
scheduleBackgroundTask: (task) => this.scheduleBackgroundStartupTask(task),
|
|
478
|
-
});
|
|
479
|
-
this.scheduleBackgroundStartupTask(traceStartupStage("runtime.initialize.startupRecovery", () => this.recoverStartupRequests()));
|
|
480
|
-
if (this.proceduralMemoryStore) {
|
|
481
|
-
await this.proceduralMemoryStore.listNamespaces();
|
|
482
|
-
}
|
|
483
|
-
this.initialized = true;
|
|
484
|
-
}
|
|
485
|
-
subscribe(listener) {
|
|
486
|
-
return this.eventBus.subscribe(listener);
|
|
487
|
-
}
|
|
488
|
-
async getHealth() {
|
|
489
|
-
if (this.healthMonitor) {
|
|
490
|
-
return this.healthMonitor.getSnapshot();
|
|
491
|
-
}
|
|
492
|
-
return createDefaultHealthSnapshot(this.activeRequestSlots, this.pendingRequestSlots.length);
|
|
493
|
-
}
|
|
494
|
-
async getOperatorOverview(options) {
|
|
495
|
-
const [health, requests, approvals] = await Promise.all([
|
|
496
|
-
this.getHealth(),
|
|
497
|
-
Promise.all(ACTIVE_REQUEST_STATES.map((state) => this.listRequests({ state }))).then((groups) => groups.flat()),
|
|
498
|
-
this.listApprovals({ status: "pending" }),
|
|
499
|
-
]);
|
|
500
|
-
return projectOperatorOverview({
|
|
501
|
-
health,
|
|
502
|
-
requests,
|
|
503
|
-
approvals,
|
|
504
|
-
limit: options?.limit,
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
async listSessions(filter) {
|
|
508
|
-
const sessions = await this.persistence.listSessions(filter);
|
|
509
|
-
return sessions.map((session) => ({
|
|
510
|
-
agentId: session.agentId,
|
|
511
|
-
sessionId: session.sessionId,
|
|
512
|
-
latestRequestId: session.latestRequestId,
|
|
513
|
-
createdAt: session.createdAt,
|
|
514
|
-
updatedAt: session.updatedAt,
|
|
515
|
-
status: session.status,
|
|
516
|
-
currentAgentId: session.currentAgentId,
|
|
517
|
-
}));
|
|
518
|
-
}
|
|
519
|
-
async listSessionSummaries(filter) {
|
|
520
|
-
const sessions = await this.persistence.listSessionSummaries(filter);
|
|
521
|
-
return sessions.map((session) => toSessionListSummary(session));
|
|
522
|
-
}
|
|
523
|
-
async listRequests(filter) {
|
|
524
|
-
const requests = await this.persistence.listRequests({
|
|
525
|
-
agentId: filter?.agentId,
|
|
526
|
-
sessionId: filter?.sessionId,
|
|
527
|
-
state: filter?.state,
|
|
528
|
-
});
|
|
529
|
-
return requests.map((request) => ({
|
|
530
|
-
requestId: request.requestId,
|
|
531
|
-
sessionId: request.sessionId,
|
|
532
|
-
agentId: request.agentId,
|
|
533
|
-
parentRequestId: request.parentRequestId,
|
|
534
|
-
executionMode: request.executionMode,
|
|
535
|
-
adapterKind: request.adapterKind,
|
|
536
|
-
createdAt: request.createdAt,
|
|
537
|
-
updatedAt: request.updatedAt,
|
|
538
|
-
state: request.state,
|
|
539
|
-
checkpointRef: request.checkpointRef,
|
|
540
|
-
resumable: request.resumable,
|
|
541
|
-
startedAt: request.startedAt,
|
|
542
|
-
endedAt: request.endedAt,
|
|
543
|
-
lastActivityAt: request.lastActivityAt,
|
|
544
|
-
currentAgentId: request.currentAgentId,
|
|
545
|
-
delegationChain: request.delegationChain,
|
|
546
|
-
runtimeSnapshot: request.runtimeSnapshot,
|
|
547
|
-
}));
|
|
548
|
-
}
|
|
549
|
-
async memorize(input) {
|
|
550
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
551
|
-
if (!binding) {
|
|
552
|
-
throw new Error("memorize requires a runtime entry binding.");
|
|
553
|
-
}
|
|
554
|
-
return this.knowledgeModule.memorize({
|
|
555
|
-
records: input.records,
|
|
556
|
-
storeCandidateLog: true,
|
|
557
|
-
forceStore: true,
|
|
558
|
-
}, {
|
|
559
|
-
sessionId: input.sessionId,
|
|
560
|
-
requestId: input.requestId,
|
|
561
|
-
agentId: input.agentId ?? binding.agent.id,
|
|
562
|
-
workspaceId: this.getWorkspaceId(binding),
|
|
563
|
-
userId: input.userId,
|
|
564
|
-
projectId: input.projectId,
|
|
565
|
-
recordedAt: input.recordedAt,
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
async recall(input) {
|
|
569
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
570
|
-
if (!binding) {
|
|
571
|
-
throw new Error("recall requires a runtime entry binding.");
|
|
572
|
-
}
|
|
573
|
-
const context = {
|
|
574
|
-
sessionId: input.sessionId,
|
|
575
|
-
agentId: input.agentId ?? binding.agent.id,
|
|
576
|
-
workspaceId: input.workspaceId ?? this.getWorkspaceId(binding),
|
|
577
|
-
userId: input.userId,
|
|
578
|
-
projectId: input.projectId,
|
|
579
|
-
};
|
|
580
|
-
const [knowledge, procedural] = await Promise.all([
|
|
581
|
-
this.knowledgeModule.recall(input, context),
|
|
582
|
-
this.proceduralMemoryModule && this.proceduralMemoryConfig?.retrieval?.enabled !== false
|
|
583
|
-
? this.proceduralMemoryModule.recall(input, context)
|
|
584
|
-
: Promise.resolve({ items: [] }),
|
|
585
|
-
]);
|
|
586
|
-
return {
|
|
587
|
-
items: mergeMemoryItems(knowledge.items, procedural.items),
|
|
588
|
-
};
|
|
589
|
-
}
|
|
590
|
-
async listMemories(input = {}) {
|
|
591
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
592
|
-
if (!binding) {
|
|
593
|
-
throw new Error("listMemories requires a runtime entry binding.");
|
|
594
|
-
}
|
|
595
|
-
const context = {
|
|
596
|
-
sessionId: input.sessionId,
|
|
597
|
-
agentId: input.agentId,
|
|
598
|
-
workspaceId: input.workspaceId ?? this.getWorkspaceId(binding),
|
|
599
|
-
userId: input.userId,
|
|
600
|
-
projectId: input.projectId,
|
|
601
|
-
};
|
|
602
|
-
const [knowledge, procedural] = await Promise.all([
|
|
603
|
-
this.knowledgeModule.list(input, context),
|
|
604
|
-
this.proceduralMemoryModule
|
|
605
|
-
? this.proceduralMemoryModule.list(input, context)
|
|
606
|
-
: Promise.resolve({ items: [] }),
|
|
607
|
-
]);
|
|
608
|
-
return {
|
|
609
|
-
items: mergeMemoryItems(knowledge.items, procedural.items),
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
async updateMemory(input) {
|
|
613
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
614
|
-
if (!binding) {
|
|
615
|
-
throw new Error("updateMemory requires a runtime entry binding.");
|
|
616
|
-
}
|
|
617
|
-
return this.knowledgeModule.update(input, {
|
|
618
|
-
agentId: binding.agent.id,
|
|
619
|
-
workspaceId: this.getWorkspaceId(binding),
|
|
620
|
-
});
|
|
621
|
-
}
|
|
622
|
-
async removeMemory(input) {
|
|
623
|
-
const binding = this.defaultRuntimeEntryBinding;
|
|
624
|
-
if (!binding) {
|
|
625
|
-
throw new Error("removeMemory requires a runtime entry binding.");
|
|
626
|
-
}
|
|
627
|
-
return this.knowledgeModule.remove(input, {
|
|
628
|
-
agentId: binding.agent.id,
|
|
629
|
-
workspaceId: this.getWorkspaceId(binding),
|
|
630
|
-
});
|
|
631
|
-
}
|
|
632
|
-
async getRequest(requestId) {
|
|
633
|
-
const request = await this.persistence.getRequest(requestId);
|
|
634
|
-
return request ? buildRequestInspectionRecord(this.persistence, request) : null;
|
|
635
|
-
}
|
|
636
|
-
async getRequestPlanState(sessionId, requestId) {
|
|
637
|
-
return this.persistence.getRequestPlanState(sessionId, requestId);
|
|
638
|
-
}
|
|
639
|
-
async getSessionSummary(sessionId) {
|
|
640
|
-
const session = await this.persistence.getSession(sessionId);
|
|
641
|
-
return session
|
|
642
|
-
? {
|
|
643
|
-
agentId: session.agentId,
|
|
644
|
-
sessionId: session.sessionId,
|
|
645
|
-
latestRequestId: session.latestRequestId,
|
|
646
|
-
createdAt: session.createdAt,
|
|
647
|
-
updatedAt: session.updatedAt,
|
|
648
|
-
status: session.status,
|
|
649
|
-
currentAgentId: session.currentAgentId,
|
|
650
|
-
}
|
|
651
|
-
: null;
|
|
652
|
-
}
|
|
653
|
-
async getSessionSummaryRecord(sessionId) {
|
|
654
|
-
return this.getSessionSummary(sessionId);
|
|
655
|
-
}
|
|
656
|
-
async getSession(sessionId) {
|
|
657
|
-
return this.getSessionRecord(sessionId);
|
|
658
|
-
}
|
|
659
|
-
async getSessionRecord(sessionId) {
|
|
660
|
-
return buildSessionInspectionRecord({
|
|
661
|
-
persistence: this.persistence,
|
|
662
|
-
getSession: (currentSessionId) => this.getSessionSummary(currentSessionId),
|
|
663
|
-
}, sessionId);
|
|
664
|
-
}
|
|
665
|
-
async listApprovals(filter) {
|
|
666
|
-
const approvals = await listPublicApprovals({
|
|
667
|
-
persistence: this.persistence,
|
|
668
|
-
}, {
|
|
669
|
-
status: filter?.status,
|
|
670
|
-
sessionId: filter?.sessionId,
|
|
671
|
-
requestId: filter?.requestId,
|
|
672
|
-
});
|
|
673
|
-
return approvals;
|
|
674
|
-
}
|
|
675
|
-
async getApproval(approvalId) {
|
|
676
|
-
return getPublicApproval({
|
|
677
|
-
persistence: this.persistence,
|
|
678
|
-
}, approvalId);
|
|
679
|
-
}
|
|
680
|
-
async listRequestArtifacts(sessionId, requestId) {
|
|
681
|
-
const listing = await this.persistence.listRequestArtifacts(sessionId, requestId);
|
|
682
|
-
return {
|
|
683
|
-
sessionId: listing.sessionId,
|
|
684
|
-
requestId: listing.requestId,
|
|
685
|
-
items: listing.items,
|
|
686
|
-
};
|
|
687
|
-
}
|
|
688
|
-
async recordArtifact(input) {
|
|
689
|
-
const session = await this.getSessionRecord(input.sessionId);
|
|
690
|
-
if (!session) {
|
|
691
|
-
throw new Error(`Cannot record artifact for unknown session: ${input.sessionId}`);
|
|
692
|
-
}
|
|
693
|
-
const request = await this.getRequest(input.requestId);
|
|
694
|
-
if (!request || request.sessionId !== input.sessionId) {
|
|
695
|
-
throw new Error(`Cannot record artifact for unknown request: ${input.requestId}`);
|
|
696
|
-
}
|
|
697
|
-
const artifact = {
|
|
698
|
-
artifactId: typeof input.artifactId === "string" && input.artifactId.trim().length > 0
|
|
699
|
-
? input.artifactId.trim()
|
|
700
|
-
: createPersistentId(),
|
|
701
|
-
kind: input.kind.trim(),
|
|
702
|
-
path: normalizeRecordedArtifactPath(input.path),
|
|
703
|
-
createdAt: typeof input.createdAt === "string" && input.createdAt.trim().length > 0
|
|
704
|
-
? input.createdAt.trim()
|
|
705
|
-
: new Date().toISOString(),
|
|
706
|
-
};
|
|
707
|
-
return this.persistence.createRequestArtifact(input.sessionId, input.requestId, artifact, input.content);
|
|
708
|
-
}
|
|
709
|
-
async readRequestArtifact(sessionId, requestId, artifactPath) {
|
|
710
|
-
return this.persistence.readRequestArtifact(sessionId, requestId, artifactPath);
|
|
711
|
-
}
|
|
712
|
-
async listRequestEvents(sessionId, requestId) {
|
|
713
|
-
return this.persistence.listRequestEvents(sessionId, requestId);
|
|
714
|
-
}
|
|
715
|
-
async exportRequestPackage(input) {
|
|
716
|
-
const session = await this.getSessionRecord(input.sessionId);
|
|
717
|
-
const request = await this.getRequest(input.requestId);
|
|
718
|
-
const approvals = await this.listApprovals({ sessionId: input.sessionId, requestId: input.requestId });
|
|
719
|
-
const transcript = await this.persistence.listSessionMessages(input.sessionId, 500);
|
|
720
|
-
const events = await this.listRequestEvents(input.sessionId, input.requestId);
|
|
721
|
-
const artifactsListing = input.includeArtifacts === false
|
|
722
|
-
? { items: [] }
|
|
723
|
-
: await this.persistence.listRequestArtifacts(input.sessionId, input.requestId);
|
|
724
|
-
const artifacts = await Promise.all(artifactsListing.items.map(async (artifact) => ({
|
|
725
|
-
...artifact,
|
|
726
|
-
...(input.includeArtifactContents === true
|
|
727
|
-
? { content: await this.persistence.readRequestArtifact(input.sessionId, input.requestId, artifact.path) }
|
|
728
|
-
: {}),
|
|
729
|
-
})));
|
|
730
|
-
const approvalSummary = summarizeApprovalEvidence(approvals);
|
|
731
|
-
const bundles = request?.runtimeSnapshot?.governance?.bundles ?? [];
|
|
732
|
-
const governanceSummaryParts = [
|
|
733
|
-
`${bundles.length} governance bundle(s)`,
|
|
734
|
-
`${approvalSummary.total} approval record(s)`,
|
|
735
|
-
];
|
|
736
|
-
if (approvalSummary.approvalReasons.length > 0) {
|
|
737
|
-
governanceSummaryParts.push(`reasons=${approvalSummary.approvalReasons.join(",")}`);
|
|
738
|
-
}
|
|
739
|
-
return {
|
|
740
|
-
session,
|
|
741
|
-
request,
|
|
742
|
-
approvals,
|
|
743
|
-
transcript,
|
|
744
|
-
events,
|
|
745
|
-
artifacts,
|
|
746
|
-
governance: {
|
|
747
|
-
bundles,
|
|
748
|
-
approvalSummary,
|
|
749
|
-
summary: governanceSummaryParts.join(" "),
|
|
750
|
-
},
|
|
751
|
-
...(input.includeRuntimeHealth === false ? {} : { runtimeHealth: await this.getHealth() }),
|
|
752
|
-
};
|
|
753
|
-
}
|
|
754
|
-
async exportRunPackage(input) {
|
|
755
|
-
return this.exportRequestPackage(input);
|
|
756
|
-
}
|
|
757
|
-
async exportSessionPackage(input) {
|
|
758
|
-
const session = await this.getSessionRecord(input.sessionId);
|
|
759
|
-
const requestIds = Array.from(new Set((session?.requests ?? []).map((item) => item.requestId)));
|
|
760
|
-
const requestPackages = await Promise.all(requestIds.map((requestId) => this.exportRequestPackage({
|
|
761
|
-
sessionId: input.sessionId,
|
|
762
|
-
requestId,
|
|
763
|
-
includeArtifacts: input.includeArtifacts,
|
|
764
|
-
includeArtifactContents: input.includeArtifactContents,
|
|
765
|
-
includeRuntimeHealth: false,
|
|
766
|
-
})));
|
|
767
|
-
const approvals = await this.listApprovals({ sessionId: input.sessionId });
|
|
768
|
-
const approvalSummary = summarizeApprovalEvidence(approvals);
|
|
769
|
-
const governanceRequests = requestPackages
|
|
770
|
-
.filter((item) => item.request?.requestId)
|
|
771
|
-
.map((item) => ({
|
|
772
|
-
requestId: item.request.requestId,
|
|
773
|
-
evidence: item.governance,
|
|
774
|
-
}));
|
|
775
|
-
return {
|
|
776
|
-
session,
|
|
777
|
-
requests: requestPackages.map((item) => item.request).filter((item) => Boolean(item)),
|
|
778
|
-
approvals,
|
|
779
|
-
transcript: await this.persistence.listSessionMessages(input.sessionId, 500),
|
|
780
|
-
requestsPackages: requestPackages,
|
|
781
|
-
governance: {
|
|
782
|
-
requests: governanceRequests,
|
|
783
|
-
approvalSummary,
|
|
784
|
-
summary: `${governanceRequests.length} request evidence package(s), ${approvalSummary.total} approval record(s)`,
|
|
785
|
-
},
|
|
786
|
-
...(input.includeRuntimeHealth === false ? {} : { runtimeHealth: await this.getHealth() }),
|
|
787
|
-
};
|
|
788
|
-
}
|
|
789
|
-
async exportEvaluationBundle(input) {
|
|
790
|
-
const session = await this.getSessionRecord(input.sessionId);
|
|
791
|
-
const request = await this.getRequest(input.requestId);
|
|
792
|
-
const requestInput = await this.persistence.getRequestInput(input.sessionId, input.requestId);
|
|
793
|
-
const approvals = await this.listApprovals({ sessionId: input.sessionId, requestId: input.requestId });
|
|
794
|
-
const transcript = await this.persistence.listSessionMessages(input.sessionId, 500);
|
|
795
|
-
const events = await this.persistence.listRequestEvents(input.sessionId, input.requestId);
|
|
796
|
-
const runtimeHealth = await this.getHealth();
|
|
797
|
-
const artifactsListing = input.includeArtifacts === false
|
|
798
|
-
? { items: [] }
|
|
799
|
-
: await this.persistence.listRequestArtifacts(input.sessionId, input.requestId);
|
|
800
|
-
const artifacts = await Promise.all(artifactsListing.items.map(async (artifact) => ({
|
|
801
|
-
...artifact,
|
|
802
|
-
...(input.includeArtifactContents === true
|
|
803
|
-
? { content: await this.persistence.readRequestArtifact(input.sessionId, input.requestId, artifact.path) }
|
|
804
|
-
: {}),
|
|
805
|
-
})));
|
|
806
|
-
return {
|
|
807
|
-
session: session ? cloneSessionRecord(session) : null,
|
|
808
|
-
request: request ? cloneRequestRecord(request) : null,
|
|
809
|
-
requestInput: requestInput
|
|
810
|
-
? {
|
|
811
|
-
input: requestInput.input,
|
|
812
|
-
...(requestInput.invocation ? { invocation: requestInput.invocation } : {}),
|
|
813
|
-
...(typeof requestInput.priority === "number" ? { priority: requestInput.priority } : {}),
|
|
814
|
-
}
|
|
815
|
-
: (deriveRequestInputFromTranscript(transcript, input.requestId) ?? null),
|
|
816
|
-
approvals,
|
|
817
|
-
transcript,
|
|
818
|
-
events,
|
|
819
|
-
artifacts,
|
|
820
|
-
runtimeHealth,
|
|
821
|
-
...(typeof input.expectedOutput === "string" && input.expectedOutput.trim().length > 0
|
|
822
|
-
? { expectedOutput: input.expectedOutput.trim() }
|
|
823
|
-
: {}),
|
|
824
|
-
rubric: Array.isArray(input.rubric)
|
|
825
|
-
? input.rubric.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim())
|
|
826
|
-
: [],
|
|
827
|
-
tags: Array.isArray(input.tags)
|
|
828
|
-
? input.tags.filter((item) => typeof item === "string" && item.trim().length > 0).map((item) => item.trim())
|
|
829
|
-
: [],
|
|
830
|
-
...(input.metadata ? { metadata: { ...input.metadata } } : {}),
|
|
831
|
-
};
|
|
832
|
-
}
|
|
833
|
-
async replayEvaluationBundle(input) {
|
|
834
|
-
const replayAgentId = input.agentId ?? input.bundle.request?.agentId ?? input.bundle.session?.entryAgentId;
|
|
835
|
-
if (!replayAgentId) {
|
|
836
|
-
throw new Error("Evaluation replay requires an agentId on the replay input or exported bundle.");
|
|
837
|
-
}
|
|
838
|
-
const replayRequest = input.bundle.requestInput ?? deriveRequestInputFromTranscript(input.bundle.transcript, input.bundle.request?.requestId);
|
|
839
|
-
if (!replayRequest) {
|
|
840
|
-
throw new Error("Evaluation replay requires bundle.requestInput from exportEvaluationBundle.");
|
|
841
|
-
}
|
|
842
|
-
const invocation = input.invocation ?? replayRequest.invocation;
|
|
843
|
-
const result = await this.run({
|
|
844
|
-
agentId: replayAgentId,
|
|
845
|
-
input: replayRequest.input,
|
|
846
|
-
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
847
|
-
...(invocation ? { invocation } : {}),
|
|
848
|
-
});
|
|
849
|
-
const expected = typeof input.bundle.expectedOutput === "string" ? input.bundle.expectedOutput.trim() : "";
|
|
850
|
-
return {
|
|
851
|
-
request: {
|
|
852
|
-
agentId: replayAgentId,
|
|
853
|
-
input: replayRequest.input,
|
|
854
|
-
...(invocation ? { invocation } : {}),
|
|
855
|
-
...(input.sessionId ? { sessionId: input.sessionId } : {}),
|
|
856
|
-
},
|
|
857
|
-
result,
|
|
858
|
-
assertions: {
|
|
859
|
-
...(expected.length > 0 ? { expectedOutputMatched: result.output.includes(expected) } : {}),
|
|
860
|
-
},
|
|
861
|
-
};
|
|
862
|
-
}
|
|
863
|
-
listAgentSkills(agentId, options = {}) {
|
|
864
|
-
return listWorkspaceAgentSkills(this.workspace, agentId, {
|
|
865
|
-
assessRequirements: isInventoryEnabled(this.workspace),
|
|
866
|
-
...options,
|
|
867
|
-
});
|
|
868
|
-
}
|
|
869
|
-
getAgent(agentId, options = {}) {
|
|
870
|
-
return getAgentInventoryRecord(this.workspace, agentId, {
|
|
871
|
-
assessRequirements: isInventoryEnabled(this.workspace),
|
|
872
|
-
...options,
|
|
873
|
-
});
|
|
874
|
-
}
|
|
875
|
-
describeWorkspaceInventory(options = {}) {
|
|
876
|
-
return describeWorkspaceInventory(this.workspace, {
|
|
877
|
-
assessRequirements: isInventoryEnabled(this.workspace),
|
|
878
|
-
...options,
|
|
879
|
-
});
|
|
880
|
-
}
|
|
881
|
-
analyzeWorkspaceBoundaries(options = {}) {
|
|
882
|
-
return analyzeWorkspaceBoundaries(this.workspace, options);
|
|
883
|
-
}
|
|
884
|
-
async deleteSessionCheckpoints(sessionId) {
|
|
885
|
-
const resolver = this.resolvedRuntimeAdapterOptions.checkpointerResolver;
|
|
886
|
-
if (!resolver) {
|
|
887
|
-
return;
|
|
888
|
-
}
|
|
889
|
-
const seen = new Set();
|
|
890
|
-
for (const binding of this.workspace.bindings.values()) {
|
|
891
|
-
const saver = resolver(binding);
|
|
892
|
-
if (!saver || seen.has(saver)) {
|
|
893
|
-
continue;
|
|
894
|
-
}
|
|
895
|
-
seen.add(saver);
|
|
896
|
-
const maybeDeleteSession = saver.deleteSession;
|
|
897
|
-
if (typeof maybeDeleteSession === "function") {
|
|
898
|
-
await maybeDeleteSession.call(saver, sessionId);
|
|
899
|
-
continue;
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
}
|
|
903
|
-
async deleteSession(sessionId) {
|
|
904
|
-
return deleteSessionRecord({
|
|
905
|
-
getSession: (currentSessionId) => this.getSessionRecord(currentSessionId),
|
|
906
|
-
deleteSession: (currentSessionId) => this.persistence.deleteSession(currentSessionId),
|
|
907
|
-
deleteSessionCheckpoints: (currentSessionId) => this.deleteSessionCheckpoints(currentSessionId),
|
|
908
|
-
}, sessionId);
|
|
909
|
-
}
|
|
910
|
-
async createToolMcpServer(options) {
|
|
911
|
-
const tools = this.resolveToolMcpServerTools(options.agentId);
|
|
912
|
-
return createToolMcpServerFromTools(tools, options);
|
|
913
|
-
}
|
|
914
|
-
async serveToolsOverStdio(options) {
|
|
915
|
-
const tools = this.resolveToolMcpServerTools(options.agentId);
|
|
916
|
-
return serveToolsOverStdioFromHarness(tools, options);
|
|
917
|
-
}
|
|
918
|
-
async createRuntimeMcpServer(options = {}) {
|
|
919
|
-
return createRuntimeMcpServer(this, options);
|
|
920
|
-
}
|
|
921
|
-
async serveRuntimeMcpOverStdio(options = {}) {
|
|
922
|
-
return serveRuntimeMcpOverStdio(this, options);
|
|
923
|
-
}
|
|
924
|
-
async serveRuntimeMcpOverStreamableHttp(options = {}) {
|
|
925
|
-
const { serveRuntimeMcpOverStreamableHttp } = await import("../mcp.js");
|
|
926
|
-
return serveRuntimeMcpOverStreamableHttp(this, options);
|
|
927
|
-
}
|
|
928
|
-
async routeAgent(input, options = {}) {
|
|
929
|
-
return routeAgentId({
|
|
930
|
-
workspace: this.workspace,
|
|
931
|
-
input,
|
|
932
|
-
routingRules: this.routingRules,
|
|
933
|
-
routingDefaultAgentId: this.routingDefaultAgentId,
|
|
934
|
-
sessionId: options.sessionId,
|
|
935
|
-
});
|
|
936
|
-
}
|
|
937
|
-
async emit(sessionId, requestId, sequence, eventType, payload, source = "runtime") {
|
|
938
|
-
return emitHarnessEvent({
|
|
939
|
-
persistence: this.persistence,
|
|
940
|
-
publishEvent: (event) => this.eventBus.publish(event),
|
|
941
|
-
trackBackgroundTask: (task) => this.trackBackgroundTask(task),
|
|
942
|
-
backgroundEventTypes: AgentHarnessRuntime.BACKGROUND_EVENT_TYPES,
|
|
943
|
-
}, sessionId, requestId, sequence, eventType, payload, source);
|
|
944
|
-
}
|
|
945
|
-
trackBackgroundTask(task) {
|
|
946
|
-
this.backgroundTasks.add(task);
|
|
947
|
-
void task.finally(() => {
|
|
948
|
-
this.backgroundTasks.delete(task);
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
scheduleBackgroundStartupTask(task) {
|
|
952
|
-
this.trackBackgroundTask(task.then(() => undefined).catch(() => undefined));
|
|
953
|
-
}
|
|
954
|
-
async drainBackgroundTasksForClose() {
|
|
955
|
-
const tasks = Array.from(this.backgroundTasks);
|
|
956
|
-
if (tasks.length === 0) {
|
|
957
|
-
return;
|
|
958
|
-
}
|
|
959
|
-
let timeoutHandle;
|
|
960
|
-
await Promise.race([
|
|
961
|
-
Promise.allSettled(tasks),
|
|
962
|
-
new Promise((resolve) => {
|
|
963
|
-
timeoutHandle = setTimeout(resolve, BACKGROUND_TASK_CLOSE_DRAIN_TIMEOUT_MS);
|
|
964
|
-
timeoutHandle.unref?.();
|
|
965
|
-
}),
|
|
966
|
-
]);
|
|
967
|
-
if (timeoutHandle) {
|
|
968
|
-
clearTimeout(timeoutHandle);
|
|
969
|
-
}
|
|
970
|
-
}
|
|
971
|
-
async closeStageWithTimeout(_label, stage) {
|
|
972
|
-
if (!stage) {
|
|
973
|
-
return;
|
|
974
|
-
}
|
|
975
|
-
let timeoutHandle;
|
|
976
|
-
await Promise.race([
|
|
977
|
-
stage().then(() => undefined).catch(() => undefined),
|
|
978
|
-
new Promise((resolve) => {
|
|
979
|
-
timeoutHandle = setTimeout(resolve, CLOSE_STAGE_TIMEOUT_MS);
|
|
980
|
-
timeoutHandle.unref?.();
|
|
981
|
-
}),
|
|
982
|
-
]);
|
|
983
|
-
if (timeoutHandle) {
|
|
984
|
-
clearTimeout(timeoutHandle);
|
|
985
|
-
}
|
|
986
|
-
}
|
|
987
|
-
resolveToolMcpServerTools(agentId) {
|
|
988
|
-
return resolveWorkspaceAgentTools({
|
|
989
|
-
workspace: this.workspace,
|
|
990
|
-
agentId,
|
|
991
|
-
toolResolver: this.resolvedRuntimeAdapterOptions.toolResolver,
|
|
992
|
-
}).map(({ compiledTool, resolvedTool }) => ({
|
|
993
|
-
compiledTool,
|
|
994
|
-
resolvedTool,
|
|
995
|
-
sourceTool: this.workspace.tools.get(compiledTool.id),
|
|
996
|
-
}));
|
|
997
|
-
}
|
|
998
|
-
async loadPriorHistory(sessionId, requestId) {
|
|
999
|
-
const history = await this.persistence.listSessionMessages(sessionId);
|
|
1000
|
-
return history.filter((message) => message.requestId !== requestId);
|
|
1001
|
-
}
|
|
1002
|
-
async loadRequestInput(sessionId, requestId) {
|
|
1003
|
-
const history = await this.persistence.listSessionMessages(sessionId, 100);
|
|
1004
|
-
const userTurn = history.find((message) => message.requestId === requestId && message.role === "user");
|
|
1005
|
-
return userTurn?.content ?? "";
|
|
1006
|
-
}
|
|
1007
|
-
async getRequestCancellation(requestId) {
|
|
1008
|
-
const control = await this.persistence.getRequestControl(requestId);
|
|
1009
|
-
return {
|
|
1010
|
-
requested: control?.cancelRequested === true,
|
|
1011
|
-
...(control?.cancelReason ? { reason: control.cancelReason } : {}),
|
|
1012
|
-
};
|
|
1013
|
-
}
|
|
1014
|
-
async finalizeCancelledRequest(sessionId, requestId, previousState, reason) {
|
|
1015
|
-
return finalizeLifecycleCancelledRequest({
|
|
1016
|
-
persistence: this.persistence,
|
|
1017
|
-
emit: (currentSessionId, currentRequestId, sequence, eventType, payload, source) => this.emit(currentSessionId, currentRequestId, sequence, eventType, payload, source),
|
|
1018
|
-
setRequestStateAndEmit: (currentSessionId, currentRequestId, sequence, state, options) => this.setRequestStateAndEmit(currentSessionId, currentRequestId, sequence, state, options),
|
|
1019
|
-
}, sessionId, requestId, previousState, reason);
|
|
1020
|
-
}
|
|
1021
|
-
async invokeWithHistory(binding, input, sessionId, requestId, resumePayload, priorHistory, options = {}) {
|
|
1022
|
-
const history = priorHistory ?? await this.loadPriorHistory(sessionId, requestId);
|
|
1023
|
-
const memoryRecall = options.memoryRecall ?? await this.buildRuntimeMemoryContext(binding, sessionId, input);
|
|
1024
|
-
const startedAt = Date.now();
|
|
1025
|
-
try {
|
|
1026
|
-
const result = await this.runtimeAdapter.invoke(binding, input, sessionId, requestId, resumePayload, history, {
|
|
1027
|
-
...options,
|
|
1028
|
-
...(memoryRecall?.prompt ? { memoryContext: memoryRecall.prompt } : {}),
|
|
1029
|
-
});
|
|
1030
|
-
await this.persistRuntimeMemoryCandidates(binding, sessionId, requestId, result.metadata?.memoryCandidates);
|
|
1031
|
-
await this.persistRequestPlanState(sessionId, requestId, result.metadata?.executedToolResults);
|
|
1032
|
-
this.recordLlmSuccess(startedAt);
|
|
1033
|
-
return result;
|
|
1034
|
-
}
|
|
1035
|
-
catch (error) {
|
|
1036
|
-
this.recordLlmFailure(startedAt);
|
|
1037
|
-
throw error;
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
resolveMemoryNamespace(scope, binding, options = {}) {
|
|
1041
|
-
const workspaceId = this.getWorkspaceId(binding);
|
|
1042
|
-
const template = this.runtimeMemoryPolicy?.namespaces[scope] ?? `memories/${scope}s/{${scope}Id}`;
|
|
1043
|
-
return resolveMemoryNamespace(template, {
|
|
1044
|
-
sessionId: options.sessionId,
|
|
1045
|
-
agentId: options.agentId ?? binding.agent.id,
|
|
1046
|
-
workspaceId,
|
|
1047
|
-
userId: options.userId ?? "default",
|
|
1048
|
-
projectId: options.projectId ?? workspaceId,
|
|
1049
|
-
});
|
|
1050
|
-
}
|
|
1051
|
-
getWorkspaceId(binding) {
|
|
1052
|
-
const workspaceRoot = binding.harnessRuntime.workspaceRoot ?? this.workspace.workspaceRoot;
|
|
1053
|
-
return path.basename(workspaceRoot) || "default";
|
|
1054
|
-
}
|
|
1055
|
-
async buildRuntimeMemoryContext(binding, sessionId, input) {
|
|
1056
|
-
if (!this.runtimeMemoryPolicy && !this.proceduralMemoryModule) {
|
|
1057
|
-
return undefined;
|
|
1058
|
-
}
|
|
1059
|
-
const query = extractMessageText(input ?? "").trim();
|
|
1060
|
-
if (!query) {
|
|
1061
|
-
return undefined;
|
|
1062
|
-
}
|
|
1063
|
-
const context = {
|
|
1064
|
-
sessionId,
|
|
1065
|
-
agentId: binding.agent.id,
|
|
1066
|
-
workspaceId: this.getWorkspaceId(binding),
|
|
1067
|
-
};
|
|
1068
|
-
const proceduralTopK = this.proceduralMemoryConfig?.retrieval?.maxPromptItems ?? 4;
|
|
1069
|
-
const [knowledgeRecall, proceduralRecall] = await Promise.all([
|
|
1070
|
-
this.runtimeMemoryPolicy
|
|
1071
|
-
? this.knowledgeModule.buildPromptRecall({
|
|
1072
|
-
query,
|
|
1073
|
-
topK: this.runtimeMemoryPolicy?.retrieval.maxPromptMemories ?? 8,
|
|
1074
|
-
}, context)
|
|
1075
|
-
: Promise.resolve({ items: [], context: undefined }),
|
|
1076
|
-
this.proceduralMemoryModule && this.proceduralMemoryConfig?.retrieval?.enabled !== false
|
|
1077
|
-
? this.proceduralMemoryModule.buildPromptRecall({
|
|
1078
|
-
query,
|
|
1079
|
-
topK: proceduralTopK,
|
|
1080
|
-
}, context)
|
|
1081
|
-
: Promise.resolve({ items: [], context: undefined }),
|
|
1082
|
-
]);
|
|
1083
|
-
const promptParts = [knowledgeRecall.context?.trim(), proceduralRecall.context?.trim()].filter((value) => !!value);
|
|
1084
|
-
if (promptParts.length === 0) {
|
|
1085
|
-
return undefined;
|
|
1086
|
-
}
|
|
1087
|
-
return {
|
|
1088
|
-
prompt: promptParts.join("\n\n"),
|
|
1089
|
-
items: mergeMemoryItems(knowledgeRecall.items, proceduralRecall.items),
|
|
1090
|
-
};
|
|
1091
|
-
}
|
|
1092
|
-
async persistRuntimeMemoryCandidates(binding, sessionId, requestId, value) {
|
|
1093
|
-
if (!Array.isArray(value) || value.length === 0) {
|
|
1094
|
-
return;
|
|
1095
|
-
}
|
|
1096
|
-
if (this.runtimeMemoryFormationConfig?.hotPath.enabled === false) {
|
|
1097
|
-
return;
|
|
1098
|
-
}
|
|
1099
|
-
const candidates = value
|
|
1100
|
-
.filter((candidate) => typeof candidate === "object" && candidate !== null)
|
|
1101
|
-
.filter((candidate) => candidate.noStore !== true && typeof candidate.content === "string" && candidate.content.trim().length > 0);
|
|
1102
|
-
if (candidates.length === 0) {
|
|
1103
|
-
return;
|
|
1104
|
-
}
|
|
1105
|
-
await this.knowledgeModule.memorizeCandidates(candidates, {
|
|
1106
|
-
sessionId,
|
|
1107
|
-
requestId,
|
|
1108
|
-
agentId: binding.agent.id,
|
|
1109
|
-
workspaceId: this.getWorkspaceId(binding),
|
|
1110
|
-
recordedAt: new Date().toISOString(),
|
|
1111
|
-
}, { storeCandidateLog: true });
|
|
1112
|
-
}
|
|
1113
|
-
async persistRequestPlanState(sessionId, requestId, value) {
|
|
1114
|
-
if (!Array.isArray(value) || value.length === 0) {
|
|
1115
|
-
return;
|
|
1116
|
-
}
|
|
1117
|
-
const executedToolResults = value
|
|
1118
|
-
.filter((item) => typeof item === "object" && item !== null);
|
|
1119
|
-
let typedSummary = null;
|
|
1120
|
-
for (const latest of [...executedToolResults].reverse()) {
|
|
1121
|
-
const summary = typeof latest.output === "object" && latest.output !== null
|
|
1122
|
-
? latest.output.summary
|
|
1123
|
-
: undefined;
|
|
1124
|
-
if (typeof summary !== "object" || summary === null) {
|
|
1125
|
-
continue;
|
|
1126
|
-
}
|
|
1127
|
-
const candidate = summary;
|
|
1128
|
-
if (!Array.isArray(candidate.items) || !candidate.summary || typeof candidate.summary !== "object") {
|
|
1129
|
-
continue;
|
|
1130
|
-
}
|
|
1131
|
-
typedSummary = candidate;
|
|
1132
|
-
break;
|
|
1133
|
-
}
|
|
1134
|
-
if (!typedSummary) {
|
|
1135
|
-
return;
|
|
1136
|
-
}
|
|
1137
|
-
const items = typedSummary.items;
|
|
1138
|
-
const summary = typedSummary.summary;
|
|
1139
|
-
const current = await this.persistence.getRequestPlanState(sessionId, requestId);
|
|
1140
|
-
await this.persistence.saveRequestPlanState(sessionId, requestId, {
|
|
1141
|
-
sessionId,
|
|
1142
|
-
requestId,
|
|
1143
|
-
version: (current?.version ?? 0) + 1,
|
|
1144
|
-
updatedAt: new Date().toISOString(),
|
|
1145
|
-
items,
|
|
1146
|
-
summary,
|
|
1147
|
-
});
|
|
1148
|
-
}
|
|
1149
|
-
async resolvePersistedRequestPriority(sessionId, requestId) {
|
|
1150
|
-
const persisted = await this.persistence.getRequestInput(sessionId, requestId);
|
|
1151
|
-
return normalizeRequestPriority(persisted?.priority);
|
|
1152
|
-
}
|
|
1153
|
-
enqueuePendingRequestSlot(entry) {
|
|
1154
|
-
return enqueuePendingRequestSlot(this.pendingRequestSlots, entry, this.pendingRunInsertionOrder++);
|
|
1155
|
-
}
|
|
1156
|
-
async executeQueuedRequest(binding, input, sessionId, requestId, agentId, options = {}) {
|
|
1157
|
-
return executeQueuedRequestOperation({
|
|
1158
|
-
persistence: this.persistence,
|
|
1159
|
-
getRequestCancellation: (currentRequestId) => this.getRequestCancellation(currentRequestId),
|
|
1160
|
-
finalizeCancelledRequest: (currentSessionId, currentRequestId, previousRequestState, reason) => this.finalizeCancelledRequest(currentSessionId, currentRequestId, previousRequestState, reason),
|
|
1161
|
-
emit: (currentSessionId, currentRequestId, sequence, eventType, payload) => {
|
|
1162
|
-
if (eventType === "request.dequeued") {
|
|
1163
|
-
return this.emit(currentSessionId, currentRequestId, sequence, eventType, {
|
|
1164
|
-
...payload,
|
|
1165
|
-
activeRequestCount: this.activeRequestSlots,
|
|
1166
|
-
maxConcurrentRuns: this.concurrencyConfig.maxConcurrentRuns,
|
|
1167
|
-
});
|
|
1168
|
-
}
|
|
1169
|
-
return this.emit(currentSessionId, currentRequestId, sequence, eventType, payload);
|
|
1170
|
-
},
|
|
1171
|
-
setRequestStateAndEmit: (currentSessionId, currentRequestId, sequence, state, stateOptions) => this.setRequestStateAndEmit(currentSessionId, currentRequestId, sequence, state, stateOptions),
|
|
1172
|
-
invokeWithHistory: (activeBinding, activeInput, currentSessionId, currentRequestId, resumePayload, priorHistory, invokeOptions) => this.invokeWithHistory(activeBinding, activeInput, currentSessionId, currentRequestId, resumePayload, priorHistory, invokeOptions),
|
|
1173
|
-
finalizeContinuedRequest: (activeBinding, currentSessionId, currentRequestId, currentInput, actual, finalizeOptions) => this.finalizeContinuedRequest(activeBinding, currentSessionId, currentRequestId, currentInput, actual, finalizeOptions),
|
|
1174
|
-
emitSyntheticFallback: (currentSessionId, currentRequestId, currentAgentId, error) => this.runtimeEventOperations.emitSyntheticFallback(currentSessionId, currentRequestId, currentAgentId, error, 103),
|
|
1175
|
-
renderRuntimeFailure,
|
|
1176
|
-
}, {
|
|
1177
|
-
binding,
|
|
1178
|
-
message: input,
|
|
1179
|
-
sessionId,
|
|
1180
|
-
requestId,
|
|
1181
|
-
agentId,
|
|
1182
|
-
options,
|
|
1183
|
-
});
|
|
1184
|
-
}
|
|
1185
|
-
async finalizeContinuedRequest(binding, sessionId, requestId, input, actual, options) {
|
|
1186
|
-
return finalizeLifecycleContinuedRequest({
|
|
1187
|
-
persistence: this.persistence,
|
|
1188
|
-
emit: (currentSessionId, currentRequestId, sequence, eventType, payload, source) => this.emit(currentSessionId, currentRequestId, sequence, eventType, payload, source),
|
|
1189
|
-
setRequestStateAndEmit: (currentSessionId, currentRequestId, sequence, state, lifecycleOptions) => this.setRequestStateAndEmit(currentSessionId, currentRequestId, sequence, state, lifecycleOptions),
|
|
1190
|
-
requestApprovalAndEmit: (currentSessionId, currentRequestId, lifecycleInput, interruptContent, checkpointRef, sequence) => this.requestApprovalAndEmit(currentSessionId, currentRequestId, lifecycleInput, interruptContent, checkpointRef, sequence),
|
|
1191
|
-
}, binding, sessionId, requestId, input, actual, options);
|
|
1192
|
-
}
|
|
1193
|
-
async setRequestStateAndEmit(sessionId, requestId, sequence, state, options) {
|
|
1194
|
-
return this.runtimeEventOperations.setRequestStateAndEmit(sessionId, requestId, sequence, state, options);
|
|
1195
|
-
}
|
|
1196
|
-
async requestApprovalAndEmit(sessionId, requestId, input, interruptContent, checkpointRef, sequence) {
|
|
1197
|
-
return this.runtimeEventOperations.requestApprovalAndEmit(sessionId, requestId, input, interruptContent, checkpointRef, sequence);
|
|
1198
|
-
}
|
|
1199
|
-
isDecisionRun(options) {
|
|
1200
|
-
return "decision" in options;
|
|
1201
|
-
}
|
|
1202
|
-
async notifyListener(listener, value) {
|
|
1203
|
-
if (!listener) {
|
|
1204
|
-
return;
|
|
1205
|
-
}
|
|
1206
|
-
await listener(value);
|
|
1207
|
-
}
|
|
1208
|
-
async acquireRequestSlot(sessionId, requestId, activeState = "running", priority = 0) {
|
|
1209
|
-
return acquireHarnessRunSlot({
|
|
1210
|
-
persistence: {
|
|
1211
|
-
claimQueuedRequest: ({ sessionId, requestId, workerId, claimedAt, leaseExpiresAt }) => this.persistence.claimQueuedRequest({ sessionId, requestId, workerId, claimedAt, leaseExpiresAt }),
|
|
1212
|
-
renewRequestLease: ({ requestId, workerId, heartbeatAt, leaseExpiresAt }) => this.persistence.renewRequestLease({ requestId, workerId, heartbeatAt, leaseExpiresAt }),
|
|
1213
|
-
releaseRequestClaim: (requestId) => this.persistence.releaseRequestClaim(requestId),
|
|
1214
|
-
enqueueRequest: ({ sessionId, requestId, priority }) => this.persistence.enqueueRequest({ sessionId, requestId, priority }),
|
|
1215
|
-
getRequest: (requestId) => this.persistence.getRequest(requestId),
|
|
1216
|
-
},
|
|
1217
|
-
workerId: this.workerId,
|
|
1218
|
-
concurrencyConfig: this.concurrencyConfig,
|
|
1219
|
-
pendingRequestSlots: this.pendingRequestSlots,
|
|
1220
|
-
getActiveRequestSlots: () => this.activeRequestSlots,
|
|
1221
|
-
setActiveRequestSlots: (count) => {
|
|
1222
|
-
this.activeRequestSlots = count;
|
|
1223
|
-
},
|
|
1224
|
-
enqueuePendingRequestSlot: (entry) => this.enqueuePendingRequestSlot(entry),
|
|
1225
|
-
emit: (currentSessionId, currentRequestId, sequence, eventType, payload) => this.emit(currentSessionId, currentRequestId, sequence, eventType, payload),
|
|
1226
|
-
setRequestStateAndEmit: (currentSessionId, currentRequestId, sequence, state, stateOptions) => this.setRequestStateAndEmit(currentSessionId, currentRequestId, sequence, state, stateOptions),
|
|
1227
|
-
}, {
|
|
1228
|
-
sessionId,
|
|
1229
|
-
requestId,
|
|
1230
|
-
activeState,
|
|
1231
|
-
priority,
|
|
1232
|
-
});
|
|
1233
|
-
}
|
|
1234
|
-
dropPendingRequestSlot(requestId) {
|
|
1235
|
-
return dropPendingRequestSlot(this.pendingRequestSlots, requestId);
|
|
1236
|
-
}
|
|
1237
|
-
async run(options) {
|
|
1238
|
-
if (this.isDecisionRun(options)) {
|
|
1239
|
-
const resumeOptions = {
|
|
1240
|
-
sessionId: options.sessionId,
|
|
1241
|
-
requestId: options.requestId,
|
|
1242
|
-
approvalId: options.approvalId,
|
|
1243
|
-
decision: options.decision,
|
|
1244
|
-
editedInput: options.editedInput,
|
|
1245
|
-
};
|
|
1246
|
-
return this.resume(resumeOptions);
|
|
1247
|
-
}
|
|
1248
|
-
const resolvedListeners = resolveRequestListeners(options);
|
|
1249
|
-
if (resolvedListeners) {
|
|
1250
|
-
const result = await createListenerDispatchRuntime({
|
|
1251
|
-
notifyListener: (listener, value) => this.notifyListener(listener, value),
|
|
1252
|
-
getSession: async (sessionId) => {
|
|
1253
|
-
const session = await this.getSessionRecord(sessionId);
|
|
1254
|
-
return session
|
|
1255
|
-
? {
|
|
1256
|
-
currentState: session.currentState,
|
|
1257
|
-
latestRequestId: session.latestRequestId,
|
|
1258
|
-
entryAgentId: session.entryAgentId,
|
|
1259
|
-
currentAgentId: session.currentAgentId,
|
|
1260
|
-
requests: session.requests.map((request) => ({ agentId: request.agentId })),
|
|
1261
|
-
pendingDecision: session.pendingDecision,
|
|
1262
|
-
}
|
|
1263
|
-
: null;
|
|
1264
|
-
},
|
|
1265
|
-
}).dispatchRequestListeners(this.streamEvents(options), resolvedListeners);
|
|
1266
|
-
return toPublicRequestResultShape(result);
|
|
1267
|
-
}
|
|
1268
|
-
const invocation = normalizeInvocationEnvelope(options);
|
|
1269
|
-
const { binding, selectedAgentId, sessionId, requestId, isNewSession, requestCreatedEventPromise, releaseRequestSlotPromise, } = await prepareRunStart(this.createPrepareRunStartRuntime(), {
|
|
1270
|
-
options,
|
|
1271
|
-
invocation,
|
|
1272
|
-
requestCreatedPayload: (activeBinding, activeSelectedAgentId) => ({
|
|
1273
|
-
agentId: activeBinding.agent.id,
|
|
1274
|
-
requestedAgentId: defaultRequestedAgentId(options.agentId),
|
|
1275
|
-
selectedAgentId: activeSelectedAgentId,
|
|
1276
|
-
executionMode: getBindingRuntimeExecutionMode(activeBinding),
|
|
1277
|
-
}),
|
|
1278
|
-
});
|
|
1279
|
-
await requestCreatedEventPromise;
|
|
1280
|
-
const releaseRequestSlot = await releaseRequestSlotPromise;
|
|
1281
|
-
try {
|
|
1282
|
-
return toPublicRequestResultShape(await this.executeQueuedRequest(binding, options.input, sessionId, requestId, selectedAgentId, {
|
|
1283
|
-
context: invocation.context,
|
|
1284
|
-
state: invocation.state,
|
|
1285
|
-
files: invocation.files,
|
|
1286
|
-
previousState: "running",
|
|
1287
|
-
stateSequence: 6,
|
|
1288
|
-
approvalSequence: 7,
|
|
1289
|
-
priorHistory: isNewSession ? [] : undefined,
|
|
1290
|
-
}));
|
|
1291
|
-
}
|
|
1292
|
-
finally {
|
|
1293
|
-
await releaseRequestSlot();
|
|
1294
|
-
}
|
|
1295
|
-
}
|
|
1296
|
-
async *streamEvents(options) {
|
|
1297
|
-
const invocation = normalizeInvocationEnvelope(options);
|
|
1298
|
-
const selectedAgentId = await this.resolveSelectedAgentId(options.input, options.agentId, options.sessionId);
|
|
1299
|
-
const binding = getWorkspaceBinding(this.workspace, selectedAgentId);
|
|
1300
|
-
if (!binding) {
|
|
1301
|
-
const result = await this.run(options);
|
|
1302
|
-
yield {
|
|
1303
|
-
type: "result",
|
|
1304
|
-
result,
|
|
1305
|
-
};
|
|
1306
|
-
return;
|
|
1307
|
-
}
|
|
1308
|
-
const { sessionId, requestId, isNewSession, requestCreatedEventPromise, releaseRequestSlotPromise, } = await prepareRunStart(this.createPrepareRunStartRuntime(), {
|
|
1309
|
-
options,
|
|
1310
|
-
invocation,
|
|
1311
|
-
requestCreatedPayload: (_binding, activeSelectedAgentId) => ({
|
|
1312
|
-
agentId: activeSelectedAgentId,
|
|
1313
|
-
requestedAgentId: defaultRequestedAgentId(options.agentId),
|
|
1314
|
-
selectedAgentId: activeSelectedAgentId,
|
|
1315
|
-
input: options.input,
|
|
1316
|
-
state: "running",
|
|
1317
|
-
}),
|
|
1318
|
-
});
|
|
1319
|
-
const stream = streamHarnessRun({
|
|
1320
|
-
binding,
|
|
1321
|
-
input: options.input,
|
|
1322
|
-
invocation: {
|
|
1323
|
-
...invocation,
|
|
1324
|
-
memoryRecall: await this.buildRuntimeMemoryContext(binding, sessionId, options.input),
|
|
1325
|
-
},
|
|
1326
|
-
sessionId,
|
|
1327
|
-
requestId,
|
|
1328
|
-
selectedAgentId,
|
|
1329
|
-
isNewSession: isNewSession,
|
|
1330
|
-
requestCreatedEventPromise,
|
|
1331
|
-
releaseRequestSlotPromise,
|
|
1332
|
-
getBinding: (agentId) => getWorkspaceBinding(this.workspace, agentId),
|
|
1333
|
-
loadPriorHistory: (sessionId, requestId) => this.loadPriorHistory(sessionId, requestId),
|
|
1334
|
-
stream: (binding, message, sessionId, priorHistory, streamOptions) => this.runtimeAdapter.stream(binding, message, sessionId, priorHistory, {
|
|
1335
|
-
...streamOptions,
|
|
1336
|
-
profiling: true,
|
|
1337
|
-
}),
|
|
1338
|
-
invokeWithHistory: (binding, input, sessionId, requestId) => this.invokeWithHistory(binding, input, sessionId, requestId),
|
|
1339
|
-
emit: (sessionId, requestId, sequence, eventType, payload) => this.emit(sessionId, requestId, sequence, eventType, payload),
|
|
1340
|
-
setRequestStateAndEmit: (sessionId, requestId, sequence, state, stateOptions) => this.setRequestStateAndEmit(sessionId, requestId, sequence, state, stateOptions),
|
|
1341
|
-
requestApprovalAndEmit: (sessionId, requestId, input, interruptContent, checkpointRef, sequence) => this.requestApprovalAndEmit(sessionId, requestId, input, interruptContent, checkpointRef, sequence),
|
|
1342
|
-
appendAssistantMessage: (sessionId, requestId, content) => appendLifecycleAssistantMessage(this.persistence, sessionId, requestId, content),
|
|
1343
|
-
clearRequestInput: (sessionId, requestId) => this.persistence.clearRequestInput(sessionId, requestId),
|
|
1344
|
-
updateRequestInspection: (sessionId, requestId, patch) => this.persistence.updateRequestInspection(sessionId, requestId, patch),
|
|
1345
|
-
appendRequestTraceItem: (sessionId, requestId, item) => this.persistence.appendRequestTraceItem(sessionId, requestId, item),
|
|
1346
|
-
loadRequestPlanState: (sessionId, requestId) => this.persistence.getRequestPlanState(sessionId, requestId),
|
|
1347
|
-
saveRequestPlanState: (sessionId, requestId, planState) => this.persistence.saveRequestPlanState(sessionId, requestId, planState),
|
|
1348
|
-
emitSyntheticFallback: (sessionId, requestId, selectedAgentId, error) => this.runtimeEventOperations.emitSyntheticFallback(sessionId, requestId, selectedAgentId, error),
|
|
1349
|
-
});
|
|
1350
|
-
for await (const item of stream) {
|
|
1351
|
-
yield toPublicHarnessStreamItem(item);
|
|
1352
|
-
}
|
|
1353
|
-
}
|
|
1354
|
-
async resume(options) {
|
|
1355
|
-
return toPublicRequestResultShape(await resumeRequest({
|
|
1356
|
-
getApprovalById: (approvalId) => this.persistence.getApproval(approvalId),
|
|
1357
|
-
getSession: (sessionId) => this.getSession(sessionId),
|
|
1358
|
-
resolveApprovalRecord: (resumeOptions, session) => resolveHarnessApprovalRecord(this.persistence, resumeOptions, session),
|
|
1359
|
-
getBinding: (agentId) => getWorkspaceBinding(this.workspace, agentId),
|
|
1360
|
-
buildResumePayload: (binding, approval, resumeOptions) => buildHarnessResumePayload(binding, approval, resumeOptions),
|
|
1361
|
-
getRequestCancellation: (requestId) => this.getRequestCancellation(requestId),
|
|
1362
|
-
finalizeCancelledRequest: (sessionId, requestId, previousState, reason) => this.finalizeCancelledRequest(sessionId, requestId, previousState, reason),
|
|
1363
|
-
setRequestState: (sessionId, requestId, state, checkpointRef) => this.persistence.setRequestState(sessionId, requestId, state, checkpointRef),
|
|
1364
|
-
acquireRequestSlot: (sessionId, requestId, activeState, priority) => this.acquireRequestSlot(sessionId, requestId, activeState, priority),
|
|
1365
|
-
resolvePersistedRequestPriority: (sessionId, requestId) => this.resolvePersistedRequestPriority(sessionId, requestId),
|
|
1366
|
-
saveRequestRecoveryIntent: (sessionId, requestId, payload) => this.persistence.saveRequestRecoveryIntent(sessionId, requestId, payload),
|
|
1367
|
-
emit: (sessionId, requestId, sequence, eventType, payload) => this.emit(sessionId, requestId, sequence, eventType, payload),
|
|
1368
|
-
resolveApproval: (sessionId, requestId, approvalId, resolution) => this.persistence.resolveApproval(sessionId, requestId, approvalId, resolution),
|
|
1369
|
-
listSessionMessages: (sessionId) => this.persistence.listSessionMessages(sessionId),
|
|
1370
|
-
loadRequestInput: (sessionId, requestId) => this.loadRequestInput(sessionId, requestId),
|
|
1371
|
-
invoke: (binding, input, sessionId, requestId, resumePayload, priorHistory) => this.runtimeAdapter.invoke(binding, input, sessionId, requestId, resumePayload, priorHistory),
|
|
1372
|
-
recordLlmSuccess: (startedAt) => this.recordLlmSuccess(startedAt),
|
|
1373
|
-
recordLlmFailure: (startedAt) => this.recordLlmFailure(startedAt),
|
|
1374
|
-
clearRequestRecoveryIntent: (sessionId, requestId) => this.persistence.clearRequestRecoveryIntent(sessionId, requestId),
|
|
1375
|
-
finalizeContinuedRequest: (binding, sessionId, requestId, input, actual, operationOptions) => this.finalizeContinuedRequest(binding, sessionId, requestId, input, actual, operationOptions),
|
|
1376
|
-
}, {
|
|
1377
|
-
...options,
|
|
1378
|
-
}));
|
|
1379
|
-
}
|
|
1380
|
-
async restartConversation(options) {
|
|
1381
|
-
const session = await this.getSession(options.sessionId);
|
|
1382
|
-
if (!session) {
|
|
1383
|
-
throw new Error(`Unknown session ${options.sessionId}`);
|
|
1384
|
-
}
|
|
1385
|
-
const sourceRequestId = session.latestRequestId;
|
|
1386
|
-
const targetSessionId = options.mode === "restart-new-session" ? createPersistentId() : options.sessionId;
|
|
1387
|
-
const result = await this.run({
|
|
1388
|
-
agentId: session.currentAgentId ?? session.entryAgentId,
|
|
1389
|
-
input: options.input,
|
|
1390
|
-
sessionId: options.mode === "restart-new-session" ? undefined : targetSessionId,
|
|
1391
|
-
});
|
|
1392
|
-
return {
|
|
1393
|
-
...result,
|
|
1394
|
-
restart: {
|
|
1395
|
-
sourceSessionId: options.sessionId,
|
|
1396
|
-
sourceRequestId,
|
|
1397
|
-
restartMode: options.mode,
|
|
1398
|
-
restartedBy: "console",
|
|
1399
|
-
restartedAt: new Date().toISOString(),
|
|
1400
|
-
newSessionId: result.sessionId,
|
|
1401
|
-
newRequestId: result.requestId,
|
|
1402
|
-
},
|
|
1403
|
-
};
|
|
1404
|
-
}
|
|
1405
|
-
async close() {
|
|
1406
|
-
if (this.closed) {
|
|
1407
|
-
return;
|
|
1408
|
-
}
|
|
1409
|
-
this.closed = true;
|
|
1410
|
-
await this.closeStageWithTimeout("healthMonitor.stop", async () => {
|
|
1411
|
-
await this.healthMonitor?.stop();
|
|
1412
|
-
});
|
|
1413
|
-
await this.closeStageWithTimeout("eventBus.drain", () => this.eventBus.drain());
|
|
1414
|
-
this.unregisterSessionMemorySync();
|
|
1415
|
-
this.unregisterRuntimeMemorySync();
|
|
1416
|
-
this.unregisterMem0IngestionSync();
|
|
1417
|
-
this.unregisterRuntimeMemoryFormationSync();
|
|
1418
|
-
this.unregisterProceduralMemoryFormationSync();
|
|
1419
|
-
await this.drainBackgroundTasksForClose();
|
|
1420
|
-
await this.closeStageWithTimeout("sessionMemorySync.close", async () => {
|
|
1421
|
-
await this.sessionMemorySync?.close();
|
|
1422
|
-
});
|
|
1423
|
-
await this.closeStageWithTimeout("runtimeMemorySync.close", async () => {
|
|
1424
|
-
await this.runtimeMemorySync?.close();
|
|
1425
|
-
});
|
|
1426
|
-
await this.closeStageWithTimeout("mem0IngestionSync.close", async () => {
|
|
1427
|
-
await this.mem0IngestionSync?.close();
|
|
1428
|
-
});
|
|
1429
|
-
await this.closeStageWithTimeout("runtimeMemoryFormationSync.close", async () => {
|
|
1430
|
-
await this.runtimeMemoryFormationSync?.close();
|
|
1431
|
-
});
|
|
1432
|
-
await this.closeStageWithTimeout("proceduralMemoryFormationSync.close", async () => {
|
|
1433
|
-
await this.proceduralMemoryFormationSync?.close();
|
|
1434
|
-
});
|
|
1435
|
-
await this.closeStageWithTimeout("closeMcpClientsForWorkspace", () => closeMcpClientsForWorkspace(this.workspace));
|
|
1436
|
-
this.initialized = false;
|
|
1437
|
-
}
|
|
1438
|
-
async stop() {
|
|
1439
|
-
await this.close();
|
|
1440
|
-
}
|
|
1441
|
-
async cancelRequest(options) {
|
|
1442
|
-
return toPublicRequestResultShape(await cancelRequestOperation({
|
|
1443
|
-
getRequest: (requestId) => this.persistence.getRequest(requestId),
|
|
1444
|
-
requestRequestCancel: (requestId, reason) => this.persistence.requestRequestCancel(requestId, reason),
|
|
1445
|
-
dropPendingRequestSlot: (requestId) => this.dropPendingRequestSlot(requestId),
|
|
1446
|
-
finalizeCancelledRequest: (sessionId, requestId, previousState, reason) => this.finalizeCancelledRequest(sessionId, requestId, previousState, reason),
|
|
1447
|
-
setRequestStateAndEmit: (sessionId, requestId, sequence, state, stateOptions) => this.setRequestStateAndEmit(sessionId, requestId, sequence, state, stateOptions),
|
|
1448
|
-
}, options));
|
|
1449
|
-
}
|
|
1450
|
-
async recoverStartupRequests() {
|
|
1451
|
-
await recoverHarnessStartupRequests({
|
|
1452
|
-
recoveryConfig: this.recoveryConfig,
|
|
1453
|
-
persistence: this.persistence,
|
|
1454
|
-
createStartupRecoveryContext: () => ({
|
|
1455
|
-
persistence: this.persistence,
|
|
1456
|
-
workspace: this.workspace,
|
|
1457
|
-
runtimeAdapter: this.runtimeAdapter,
|
|
1458
|
-
recoveryConfig: this.recoveryConfig,
|
|
1459
|
-
concurrencyConfig: this.concurrencyConfig,
|
|
1460
|
-
getBinding: (agentId) => getWorkspaceBinding(this.workspace, agentId),
|
|
1461
|
-
acquireRequestSlot: (sessionId, requestId, activeState, priority) => this.acquireRequestSlot(sessionId, requestId, activeState, priority),
|
|
1462
|
-
executeQueuedRequest: (binding, input, sessionId, requestId, agentId, options) => this.executeQueuedRequest(binding, input, sessionId, requestId, agentId, options),
|
|
1463
|
-
setRequestStateAndEmit: (sessionId, requestId, sequence, state, options) => this.setRequestStateAndEmit(sessionId, requestId, sequence, state, options),
|
|
1464
|
-
emit: (sessionId, requestId, sequence, eventType, payload) => this.emit(sessionId, requestId, sequence, eventType, payload),
|
|
1465
|
-
loadRequestInput: (sessionId, requestId) => this.loadRequestInput(sessionId, requestId),
|
|
1466
|
-
finalizeContinuedRequest: (binding, sessionId, requestId, input, actual, options) => this.finalizeContinuedRequest(binding, sessionId, requestId, input, actual, options),
|
|
1467
|
-
supportsRunningReplay: (binding) => bindingSupportsRunningReplay(binding),
|
|
1468
|
-
isStaleRunningRequest: (session, nowMs) => this.isStaleRunningRequest(session, nowMs),
|
|
1469
|
-
recordLlmSuccess: (startedAt) => this.recordLlmSuccess(startedAt),
|
|
1470
|
-
recordLlmFailure: (startedAt) => this.recordLlmFailure(startedAt),
|
|
1471
|
-
}),
|
|
1472
|
-
reclaimExpiredClaimedRequests: (nowIso) => this.reclaimExpiredClaimedRequests(nowIso),
|
|
1473
|
-
});
|
|
1474
|
-
}
|
|
1475
|
-
async reclaimExpiredClaimedRequests(nowIso = new Date().toISOString()) {
|
|
1476
|
-
await reclaimHarnessExpiredClaimedRequests({
|
|
1477
|
-
persistence: this.persistence,
|
|
1478
|
-
setRequestStateAndEmit: (sessionId, requestId, sequence, state, options) => this.setRequestStateAndEmit(sessionId, requestId, sequence, state, options),
|
|
1479
|
-
emit: (sessionId, requestId, sequence, eventType, payload) => this.emit(sessionId, requestId, sequence, eventType, payload),
|
|
1480
|
-
concurrencyConfig: this.concurrencyConfig,
|
|
1481
|
-
getActiveRequestSlots: () => this.activeRequestSlots,
|
|
1482
|
-
}, nowIso);
|
|
1483
|
-
}
|
|
1484
|
-
async isStaleRunningRequest(session, nowMs = Date.now()) {
|
|
1485
|
-
return isHarnessStaleRunningRequest({
|
|
1486
|
-
persistence: this.persistence,
|
|
1487
|
-
concurrencyConfig: this.concurrencyConfig,
|
|
1488
|
-
}, session, nowMs);
|
|
1489
|
-
}
|
|
1490
|
-
}
|
|
1
|
+
import b from"node:path";import{SqlitePersistence as P}from"../persistence/sqlite-store.js";import{createPersistentId as p}from"../utils/id.js";import{extractMessageText as B}from"../utils/message-content.js";import{AgentRuntimeAdapter as T}from"./agent-runtime-adapter.js";import{normalizeRecordedArtifactPath as O}from"./harness/run/artifact-paths.js";import{EventBus as F}from"./harness/events/event-bus.js";import{createBackgroundEventRuntime as H}from"./harness/background-runtime.js";import{PolicyEngine as z}from"./harness/system/policy-engine.js";import{getConcurrencyConfig as D,getRecoveryConfig as j,getRoutingDefaultAgentId as L,getRoutingRules as W}from"../workspace/support/workspace-ref-utils.js";import{createHarnessEvent as x,inferRoutingBindings as _,renderRuntimeFailure as N}from"./support/harness-support.js";import{SessionMemorySync as $}from"./harness/system/session-memory-sync.js";import{RuntimeMemorySync as K,readRuntimeMemorySyncConfig as V}from"./harness/system/runtime-memory-sync.js";import{SqliteBackedStore as U}from"./harness/system/store.js";import{HealthMonitor as Q,readHealthMonitorConfig as G}from"./harness/system/health-monitor.js";import{normalizeInvocationEnvelope as v,normalizeRequestPriority as Y,resolveRequestListeners as J}from"./harness/run/helpers.js";import{emitHarnessEvent as X}from"./harness/events/events.js";import{createRuntimeEventOperations as Z}from"./harness/events/runtime-event-operations.js";import{appendAssistantMessage as ee,finalizeCancelledRequest as te,finalizeContinuedRequest as se}from"./harness/run/run-lifecycle.js";import{createListenerDispatchRuntime as re}from"./harness/events/listener-runtime.js";import{buildResumePayload as ie,resolveApprovalRecord as ne}from"./harness/run/resume.js";import{cancelRequestOperation as oe,executeQueuedRequestOperation as ae,resumeRequest as ue}from"./harness/run/run-operations.js";import{projectOperatorOverview as ce}from"./harness/run/operator-overview.js";import{acquireRequestSlot as de}from"./harness/run/run-slot-acquisition.js";import{dropPendingRequestSlot as le,enqueuePendingRequestSlot as me}from"./harness/run/run-queue.js";import{getDefaultRuntimeEntryAgentId as he,resolveSelectedAgentId as ge,routeAgentId as pe}from"./harness/run/routing.js";import{resolveStoreFromConfig as f,resolveVectorStore as ye}from"./harness/run/resources.js";import{createRuntimeMcpServer as Re,createToolMcpServerFromTools as fe,serveRuntimeMcpOverStdio as Se,serveToolsOverStdioFromHarness as Ie}from"../mcp.js";import{closeMcpClientsForWorkspace as qe}from"../resource/mcp/tool-support.js";import{getBindingRuntimeExecutionMode as ve}from"./support/compiled-binding.js";import{bindingSupportsRunningReplay as Me,getWorkspaceBinding as y,resolveWorkspaceAgentTools as we}from"./harness/bindings.js";import{describeWorkspaceInventory as Ae,getAgentInventoryRecord as ke,listAgentSkills as Ee}from"./harness/system/inventory.js";import{analyzeWorkspaceBoundaries as Ce}from"./harness/system/boundary-analysis.js";import{createDefaultHealthSnapshot as be,isInventoryEnabled as S,isSessionMemorySyncEnabled as Pe}from"./harness/runtime-defaults.js";import{cloneRequestRecord as Be,cloneSessionRecord as Te,deriveRequestInputFromTranscript as M,mergeMemoryItems as I,summarizeApprovalEvidence as w,toPublicHarnessStreamItem as Oe,toPublicRequestResultShape as R,toSessionListSummary as Fe}from"./harness/public-shapes.js";import{Mem0IngestionSync as He,Mem0SemanticRecall as ze,readMem0RuntimeConfig as De}from"./harness/system/mem0-ingestion-sync.js";import{createRuntimeMemoryManager as je,RuntimeMemoryFormationSync as Le,readRuntimeMemoryFormationConfig as We}from"./harness/system/runtime-memory-manager.js";import{readRuntimeMemoryMaintenanceConfig as xe,readRuntimeMemoryPolicyConfig as _e,resolveMemoryNamespace as Ne}from"./harness/system/runtime-memory-policy.js";import{resolveRuntimeAdapterOptions as $e}from"./support/runtime-adapter-options.js";import{resolveKnowledgeStorePath as Ke,resolveProceduralMemoryStorePath as Ve}from"./layout/runtime-layout.js";import{SystemScheduleManager as Ue}from"./scheduling/system-schedule-manager.js";import{initializeHarnessRuntime as Qe,reclaimExpiredClaimedRequests as Ge,recoverStartupRequests as Ye,isStaleRunningRequest as Je}from"./harness/run/startup-runtime.js";import{traceStartupStage as Xe}from"./startup-tracing.js";import{normalizeProcessExecutablePath as Ze}from"./env/runtime-env.js";import{streamHarnessRun as et}from"./harness/run/stream-run.js";import{defaultRequestedAgentId as A,prepareRunStart as k}from"./harness/run/start-run.js";import{buildRequestInspectionRecord as tt,buildSessionInspectionRecord as st,deleteSessionRecord as rt,getPublicApproval as it,listPublicApprovals as nt}from"./harness/run/session-records.js";import{createKnowledgeModule as E}from"../knowledge/index.js";import{createProceduralMemoryManager as ot,ProceduralMemoryFormationSync as at,readProceduralMemoryRuntimeConfig as ut}from"../knowledge/procedural/index.js";const ct=1e3,dt=1e3,lt=["queued","claimed","running","waiting_for_approval","resuming","cancelling"];class q{workspace;runtimeAdapterOptions;static BACKGROUND_EVENT_TYPES=new Set(["request.created","request.queued","request.dequeued","output.delta"]);eventBus=new F;persistence;policyEngine=new z;runtimeAdapter;checkpointers=new Map;stores=new Map;embeddingModels=new Map;vectorStores=new Map;runtimeEntryBindings;defaultRuntimeEntryBinding;defaultRuntimeRootValue;defaultStore;runtimeMemoryStore;runtimeMemoryPolicy;runtimeMemoryMaintenanceConfig;routingRules;routingDefaultAgentId;sessionMemorySync;unregisterSessionMemorySync;runtimeMemorySync;unregisterRuntimeMemorySync;mem0IngestionSync;unregisterMem0IngestionSync;mem0SemanticRecall;runtimeMemoryFormationConfig;runtimeMemoryManager;knowledgeModule;runtimeMemoryFormationSync;unregisterRuntimeMemoryFormationSync;proceduralMemoryConfig;proceduralMemoryStore;proceduralMemoryManager;proceduralMemoryModule;proceduralMemoryFormationSync;unregisterProceduralMemoryFormationSync;resolvedRuntimeAdapterOptions;scheduleManager;healthMonitor;recoveryConfig;concurrencyConfig;backgroundTasks=new Set;workerId=`worker-${p()}`;activeRequestSlots=0;pendingRunInsertionOrder=0;pendingRequestSlots=[];runtimeEventSequence=0;initialized=!1;closed=!1;backgroundEventRuntime;runtimeEventOperations;async resolveRuntimeMemoryVectorStore(){const e=typeof this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.vectorStore=="object"&&this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.vectorStore?this.defaultRuntimeEntryBinding.harnessRuntime.runtimeMemory.vectorStore:void 0,t=typeof e?.ref=="string"&&e.ref.trim().length>0?e.ref:void 0;try{return await ye(this.workspace,this.vectorStores,t,this.resolvedRuntimeAdapterOptions)}catch{return null}}defaultRuntimeRoot(){return this.defaultRuntimeRootValue}getDefaultRuntimeEntryAgentId(){return he(this.workspace,this.routingDefaultAgentId)}async resolveSelectedAgentId(e,t,s){return ge({workspace:this.workspace,input:e,requestedAgentId:t,sessionId:s,preferredRuntimeEntryAgentId:this.routingDefaultAgentId,getSessionSummary:r=>this.getSessionSummaryRecord(r)})}createPrepareRunStartRuntime(){return{workspace:this.workspace,policyEngine:this.policyEngine,persistence:this.persistence,resolveSelectedAgentId:(e,t,s)=>this.resolveSelectedAgentId(e,t,s),emitRequestCreated:(e,t,s)=>this.runtimeEventOperations.emitRequestCreated(e,t,s),acquireRequestSlot:(e,t,s,r)=>this.acquireRequestSlot(e,t,s,r)}}buildFunctionToolContext(e){return{runtime:{sessions:{list:t=>this.listSessions(t),get:t=>this.getSession(t)},requests:{list:t=>this.listRequests(t),get:t=>this.getRequest(t),cancel:t=>this.cancelRequest(t)},approvals:{list:t=>this.listApprovals(t),get:t=>this.getApproval(t)},events:{list:(t,s)=>this.listRequestEvents(t,s)},artifacts:{list:(t,s)=>this.listRequestArtifacts(t,s),read:(t,s,r)=>this.readRequestArtifact(t,s,r),create:t=>this.recordArtifact(t)},schedules:{manage:t=>this.manageSchedule(t)},current:{...e.sessionId?{sessionId:e.sessionId}:{},...e.requestId?{requestId:e.requestId}:{},...e.binding?{agentId:e.binding.agent.id}:{}}}}}constructor(e,t={}){this.workspace=e,this.runtimeAdapterOptions=t,Ze(),this.runtimeEntryBindings=_(this.workspace).runtimeEntryBindings,this.defaultRuntimeEntryBinding=this.runtimeEntryBindings[0],this.defaultRuntimeRootValue=this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeRoot??`${this.workspace.workspaceRoot}/.agent`;const s=this.defaultRuntimeRoot();this.scheduleManager=new Ue({workspaceRoot:this.workspace.workspaceRoot,runtimeRoot:s}),this.persistence=new P(s);const r=this.defaultRuntimeEntryBinding?.harnessRuntime.store;this.defaultStore=f(this.stores,r,s)??new U(Ke(s));const i=typeof this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.store=="object"&&this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory?.store?this.defaultRuntimeEntryBinding.harnessRuntime.runtimeMemory.store:void 0;this.runtimeMemoryStore=f(this.stores,i,s)??this.defaultStore,this.runtimeMemoryPolicy=_e(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory,this.workspace.workspaceRoot)??null,this.runtimeMemoryMaintenanceConfig=xe(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory)??null,this.resolvedRuntimeAdapterOptions=$e({workspace:e,runtimeAdapterOptions:{...t,scheduleManager:t.scheduleManager??this.scheduleManager,bindingResolver:t.bindingResolver??(n=>this.workspace.bindings.get(n)),functionToolContextResolver:t.functionToolContextResolver??(n=>this.buildFunctionToolContext(n))},checkpointers:this.checkpointers,stores:this.stores,defaultStore:this.defaultStore,embeddingModels:this.embeddingModels,vectorStores:this.vectorStores,getDefaultRuntimeRoot:()=>this.defaultRuntimeRoot()}),this.runtimeAdapter=new T(this.resolvedRuntimeAdapterOptions),this.backgroundEventRuntime=H({persistence:this.persistence,publishEvent:n=>this.eventBus.publish(n),trackBackgroundTask:n=>this.trackBackgroundTask(n),backgroundEventTypes:q.BACKGROUND_EVENT_TYPES}),this.runtimeEventOperations=Z(this.backgroundEventRuntime),this.routingRules=W(e.refs),this.routingDefaultAgentId=L(e.refs),Pe(e)?(this.sessionMemorySync=new $(this.persistence,this.runtimeMemoryStore,{resolveSessionNamespace:n=>{const u=this.defaultRuntimeEntryBinding;return u?this.resolveMemoryNamespace("session",u,{sessionId:n}):["memories","sessions",n]}}),this.unregisterSessionMemorySync=this.eventBus.registerProjection(this.sessionMemorySync)):(this.sessionMemorySync=null,this.unregisterSessionMemorySync=()=>{});const a=V(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory);a?(this.runtimeMemorySync=new K(this.persistence,this.runtimeMemoryStore,a,{resolveSessionNamespace:n=>{const u=this.defaultRuntimeEntryBinding;return u?this.resolveMemoryNamespace("session",u,{sessionId:n}):["memories","sessions",n]},resolveRequestNamespace:n=>["memories","requests",n]}),this.unregisterRuntimeMemorySync=this.eventBus.registerProjection(this.runtimeMemorySync)):(this.runtimeMemorySync=null,this.unregisterRuntimeMemorySync=()=>{});const c=De(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory,this.workspace.workspaceRoot);c?(this.mem0IngestionSync=new He(this.persistence,c,s),this.unregisterMem0IngestionSync=this.eventBus.registerProjection(this.mem0IngestionSync),this.mem0SemanticRecall=new ze(c)):(this.mem0IngestionSync=null,this.unregisterMem0IngestionSync=()=>{},this.mem0SemanticRecall=null);const d=We(this.defaultRuntimeEntryBinding?.harnessRuntime.runtimeMemory,this.workspace.workspaceRoot);this.runtimeMemoryFormationConfig=d??null,this.runtimeMemoryManager=this.defaultRuntimeEntryBinding&&d?je({workspace:this.workspace,binding:this.defaultRuntimeEntryBinding,config:d,modelResolver:this.resolvedRuntimeAdapterOptions.modelResolver}):null,this.knowledgeModule=E({store:this.runtimeMemoryStore,policy:this.runtimeMemoryPolicy,maintenanceConfig:this.runtimeMemoryMaintenanceConfig,resolveNamespace:(n,u)=>{const h=this.defaultRuntimeEntryBinding;if(!h){const g=n==="session"?u.sessionId:n==="agent"?u.agentId:n==="workspace"?u.workspaceId:n==="user"?u.userId??"default":u.projectId??u.workspaceId;return["memories",`${n}s`,g??"default"]}return this.resolveMemoryNamespace(n,h,{sessionId:u.sessionId,agentId:u.agentId,userId:u.userId,projectId:u.projectId})},resolveVectorStore:()=>this.resolveRuntimeMemoryVectorStore(),transformCandidates:this.runtimeMemoryManager&&this.defaultRuntimeEntryBinding?({candidates:n,context:u,existingRecords:h})=>this.runtimeMemoryManager.transform({candidates:n,binding:this.defaultRuntimeEntryBinding,sessionId:u.sessionId??`memory-api-${u.requestId??"unknown"}`,requestId:u.requestId??p(new Date(u.recordedAt??new Date().toISOString())),recordedAt:u.recordedAt??new Date().toISOString(),existingRecords:h}):void 0,getMem0SemanticRecall:()=>this.mem0SemanticRecall}),d?(this.runtimeMemoryFormationSync=new Le(this.persistence,d,n=>this.knowledgeModule.memorizeCandidates(n.candidates,{sessionId:n.sessionId,requestId:n.requestId,agentId:n.agentId,workspaceId:this.getWorkspaceId(this.defaultRuntimeEntryBinding),userId:n.userId,projectId:n.projectId,recordedAt:n.recordedAt},{storeCandidateLog:!1}).then(()=>{}),s),this.unregisterRuntimeMemoryFormationSync=this.eventBus.registerProjection(this.runtimeMemoryFormationSync)):(this.runtimeMemoryFormationSync=null,this.unregisterRuntimeMemoryFormationSync=()=>{});const l=ut(this.defaultRuntimeEntryBinding?.harnessRuntime.proceduralMemory);this.proceduralMemoryConfig=l?.enabled?l:null;const m=this.proceduralMemoryConfig?.store&&Object.keys(this.proceduralMemoryConfig.store).length>0?this.proceduralMemoryConfig.store:{kind:"SqliteStore",path:Ve(s)};this.proceduralMemoryStore=this.proceduralMemoryConfig?f(this.stores,m,s)??null:null,this.proceduralMemoryManager=this.defaultRuntimeEntryBinding&&this.proceduralMemoryConfig?ot({workspace:this.workspace,binding:this.defaultRuntimeEntryBinding,config:this.proceduralMemoryConfig,modelResolver:this.resolvedRuntimeAdapterOptions.modelResolver}):null,this.proceduralMemoryModule=this.proceduralMemoryConfig&&this.proceduralMemoryStore?E({store:this.proceduralMemoryStore,policy:null,maintenanceConfig:null,resolveNamespace:(n,u)=>{const h=this.defaultRuntimeEntryBinding;if(!h){const g=n==="session"?u.sessionId:n==="agent"?u.agentId:n==="workspace"?u.workspaceId:n==="user"?u.userId??"default":u.projectId??u.workspaceId;return["procedural",`${n}s`,g??"default"]}return this.resolveMemoryNamespace(n,h,{sessionId:u.sessionId,agentId:u.agentId,userId:u.userId,projectId:u.projectId})},resolveVectorStore:async()=>null,transformCandidates:this.proceduralMemoryManager&&this.defaultRuntimeEntryBinding?({candidates:n,context:u,existingRecords:h})=>this.proceduralMemoryManager.transform({candidates:n,binding:this.defaultRuntimeEntryBinding,sessionId:u.sessionId??`procedural-api-${u.requestId??"unknown"}`,requestId:u.requestId??p(new Date(u.recordedAt??new Date().toISOString())),recordedAt:u.recordedAt??new Date().toISOString(),existingRecords:h}):void 0}):null,this.proceduralMemoryConfig&&this.proceduralMemoryModule?(this.proceduralMemoryFormationSync=new at(this.persistence,this.proceduralMemoryConfig,n=>this.proceduralMemoryModule.memorizeCandidates(n.candidates,{sessionId:n.sessionId,requestId:n.requestId,agentId:n.agentId,workspaceId:this.getWorkspaceId(this.defaultRuntimeEntryBinding),userId:n.userId,projectId:n.projectId,recordedAt:n.recordedAt},{storeCandidateLog:!1}).then(()=>{}),s),this.unregisterProceduralMemoryFormationSync=this.eventBus.registerProjection(this.proceduralMemoryFormationSync)):(this.proceduralMemoryFormationSync=null,this.unregisterProceduralMemoryFormationSync=()=>{}),this.recoveryConfig=j(e.refs),this.concurrencyConfig=D(e.refs);const o=G(e);this.healthMonitor=o.enabled?this.createHealthMonitor():null}async manageSchedule(e){return this.scheduleManager.manageSchedule(e)}async getSchedule(e){return this.scheduleManager.getSchedule(e)}async runScheduledTask(e){const t=await this.scheduleManager.getSchedule(e);if(!t)throw new Error(`Unknown schedule '${e}'.`);return this.run({...t.agentId?{agentId:t.agentId}:{},input:t.instruction})}createHealthMonitor(){return new Q({workspace:this.workspace,persistence:this.persistence,getActiveRequestSlots:()=>this.activeRequestSlots,getPendingRequestSlots:()=>this.pendingRequestSlots.length,getCheckpointMaintenanceStatus:()=>null,getRuntimeRecordMaintenanceStatus:()=>null,publishEvent:async e=>{this.eventBus.publish(x("__runtime__","__runtime__",++this.runtimeEventSequence,"runtime.health.changed",e))}})}recordLlmSuccess(e){this.healthMonitor?.recordLlmSuccess(Date.now()-e)}recordLlmFailure(e){this.healthMonitor?.recordLlmFailure(Date.now()-e)}async initialize(){if(this.closed)throw new Error("AgentHarnessRuntime has been closed and cannot be reinitialized");this.initialized||(await Qe({persistence:this.persistence,healthMonitor:this.healthMonitor,scheduleBackgroundTask:e=>this.scheduleBackgroundStartupTask(e)}),this.scheduleBackgroundStartupTask(Xe("runtime.initialize.startupRecovery",()=>this.recoverStartupRequests())),this.proceduralMemoryStore&&await this.proceduralMemoryStore.listNamespaces(),this.initialized=!0)}subscribe(e){return this.eventBus.subscribe(e)}async getHealth(){return this.healthMonitor?this.healthMonitor.getSnapshot():be(this.activeRequestSlots,this.pendingRequestSlots.length)}async getOperatorOverview(e){const[t,s,r]=await Promise.all([this.getHealth(),Promise.all(lt.map(i=>this.listRequests({state:i}))).then(i=>i.flat()),this.listApprovals({status:"pending"})]);return ce({health:t,requests:s,approvals:r,limit:e?.limit})}async listSessions(e){return(await this.persistence.listSessions(e)).map(s=>({agentId:s.agentId,sessionId:s.sessionId,latestRequestId:s.latestRequestId,createdAt:s.createdAt,updatedAt:s.updatedAt,status:s.status,currentAgentId:s.currentAgentId}))}async listSessionSummaries(e){return(await this.persistence.listSessionSummaries(e)).map(s=>Fe(s))}async listRequests(e){return(await this.persistence.listRequests({agentId:e?.agentId,sessionId:e?.sessionId,state:e?.state})).map(s=>({requestId:s.requestId,sessionId:s.sessionId,agentId:s.agentId,parentRequestId:s.parentRequestId,executionMode:s.executionMode,adapterKind:s.adapterKind,createdAt:s.createdAt,updatedAt:s.updatedAt,state:s.state,checkpointRef:s.checkpointRef,resumable:s.resumable,startedAt:s.startedAt,endedAt:s.endedAt,lastActivityAt:s.lastActivityAt,currentAgentId:s.currentAgentId,delegationChain:s.delegationChain,runtimeSnapshot:s.runtimeSnapshot}))}async memorize(e){const t=this.defaultRuntimeEntryBinding;if(!t)throw new Error("memorize requires a runtime entry binding.");return this.knowledgeModule.memorize({records:e.records,storeCandidateLog:!0,forceStore:!0},{sessionId:e.sessionId,requestId:e.requestId,agentId:e.agentId??t.agent.id,workspaceId:this.getWorkspaceId(t),userId:e.userId,projectId:e.projectId,recordedAt:e.recordedAt})}async recall(e){const t=this.defaultRuntimeEntryBinding;if(!t)throw new Error("recall requires a runtime entry binding.");const s={sessionId:e.sessionId,agentId:e.agentId??t.agent.id,workspaceId:e.workspaceId??this.getWorkspaceId(t),userId:e.userId,projectId:e.projectId},[r,i]=await Promise.all([this.knowledgeModule.recall(e,s),this.proceduralMemoryModule&&this.proceduralMemoryConfig?.retrieval?.enabled!==!1?this.proceduralMemoryModule.recall(e,s):Promise.resolve({items:[]})]);return{items:I(r.items,i.items)}}async listMemories(e={}){const t=this.defaultRuntimeEntryBinding;if(!t)throw new Error("listMemories requires a runtime entry binding.");const s={sessionId:e.sessionId,agentId:e.agentId,workspaceId:e.workspaceId??this.getWorkspaceId(t),userId:e.userId,projectId:e.projectId},[r,i]=await Promise.all([this.knowledgeModule.list(e,s),this.proceduralMemoryModule?this.proceduralMemoryModule.list(e,s):Promise.resolve({items:[]})]);return{items:I(r.items,i.items)}}async updateMemory(e){const t=this.defaultRuntimeEntryBinding;if(!t)throw new Error("updateMemory requires a runtime entry binding.");return this.knowledgeModule.update(e,{agentId:t.agent.id,workspaceId:this.getWorkspaceId(t)})}async removeMemory(e){const t=this.defaultRuntimeEntryBinding;if(!t)throw new Error("removeMemory requires a runtime entry binding.");return this.knowledgeModule.remove(e,{agentId:t.agent.id,workspaceId:this.getWorkspaceId(t)})}async getRequest(e){const t=await this.persistence.getRequest(e);return t?tt(this.persistence,t):null}async getRequestPlanState(e,t){return this.persistence.getRequestPlanState(e,t)}async getSessionSummary(e){const t=await this.persistence.getSession(e);return t?{agentId:t.agentId,sessionId:t.sessionId,latestRequestId:t.latestRequestId,createdAt:t.createdAt,updatedAt:t.updatedAt,status:t.status,currentAgentId:t.currentAgentId}:null}async getSessionSummaryRecord(e){return this.getSessionSummary(e)}async getSession(e){return this.getSessionRecord(e)}async getSessionRecord(e){return st({persistence:this.persistence,getSession:t=>this.getSessionSummary(t)},e)}async listApprovals(e){return await nt({persistence:this.persistence},{status:e?.status,sessionId:e?.sessionId,requestId:e?.requestId})}async getApproval(e){return it({persistence:this.persistence},e)}async listRequestArtifacts(e,t){const s=await this.persistence.listRequestArtifacts(e,t);return{sessionId:s.sessionId,requestId:s.requestId,items:s.items}}async recordArtifact(e){if(!await this.getSessionRecord(e.sessionId))throw new Error(`Cannot record artifact for unknown session: ${e.sessionId}`);const s=await this.getRequest(e.requestId);if(!s||s.sessionId!==e.sessionId)throw new Error(`Cannot record artifact for unknown request: ${e.requestId}`);const r={artifactId:typeof e.artifactId=="string"&&e.artifactId.trim().length>0?e.artifactId.trim():p(),kind:e.kind.trim(),path:O(e.path),createdAt:typeof e.createdAt=="string"&&e.createdAt.trim().length>0?e.createdAt.trim():new Date().toISOString()};return this.persistence.createRequestArtifact(e.sessionId,e.requestId,r,e.content)}async readRequestArtifact(e,t,s){return this.persistence.readRequestArtifact(e,t,s)}async listRequestEvents(e,t){return this.persistence.listRequestEvents(e,t)}async exportRequestPackage(e){const t=await this.getSessionRecord(e.sessionId),s=await this.getRequest(e.requestId),r=await this.listApprovals({sessionId:e.sessionId,requestId:e.requestId}),i=await this.persistence.listSessionMessages(e.sessionId,500),a=await this.listRequestEvents(e.sessionId,e.requestId),c=e.includeArtifacts===!1?{items:[]}:await this.persistence.listRequestArtifacts(e.sessionId,e.requestId),d=await Promise.all(c.items.map(async n=>({...n,...e.includeArtifactContents===!0?{content:await this.persistence.readRequestArtifact(e.sessionId,e.requestId,n.path)}:{}}))),l=w(r),m=s?.runtimeSnapshot?.governance?.bundles??[],o=[`${m.length} governance bundle(s)`,`${l.total} approval record(s)`];return l.approvalReasons.length>0&&o.push(`reasons=${l.approvalReasons.join(",")}`),{session:t,request:s,approvals:r,transcript:i,events:a,artifacts:d,governance:{bundles:m,approvalSummary:l,summary:o.join(" ")},...e.includeRuntimeHealth===!1?{}:{runtimeHealth:await this.getHealth()}}}async exportRunPackage(e){return this.exportRequestPackage(e)}async exportSessionPackage(e){const t=await this.getSessionRecord(e.sessionId),s=Array.from(new Set((t?.requests??[]).map(d=>d.requestId))),r=await Promise.all(s.map(d=>this.exportRequestPackage({sessionId:e.sessionId,requestId:d,includeArtifacts:e.includeArtifacts,includeArtifactContents:e.includeArtifactContents,includeRuntimeHealth:!1}))),i=await this.listApprovals({sessionId:e.sessionId}),a=w(i),c=r.filter(d=>d.request?.requestId).map(d=>({requestId:d.request.requestId,evidence:d.governance}));return{session:t,requests:r.map(d=>d.request).filter(d=>!!d),approvals:i,transcript:await this.persistence.listSessionMessages(e.sessionId,500),requestsPackages:r,governance:{requests:c,approvalSummary:a,summary:`${c.length} request evidence package(s), ${a.total} approval record(s)`},...e.includeRuntimeHealth===!1?{}:{runtimeHealth:await this.getHealth()}}}async exportEvaluationBundle(e){const t=await this.getSessionRecord(e.sessionId),s=await this.getRequest(e.requestId),r=await this.persistence.getRequestInput(e.sessionId,e.requestId),i=await this.listApprovals({sessionId:e.sessionId,requestId:e.requestId}),a=await this.persistence.listSessionMessages(e.sessionId,500),c=await this.persistence.listRequestEvents(e.sessionId,e.requestId),d=await this.getHealth(),l=e.includeArtifacts===!1?{items:[]}:await this.persistence.listRequestArtifacts(e.sessionId,e.requestId),m=await Promise.all(l.items.map(async o=>({...o,...e.includeArtifactContents===!0?{content:await this.persistence.readRequestArtifact(e.sessionId,e.requestId,o.path)}:{}})));return{session:t?Te(t):null,request:s?Be(s):null,requestInput:r?{input:r.input,...r.invocation?{invocation:r.invocation}:{},...typeof r.priority=="number"?{priority:r.priority}:{}}:M(a,e.requestId)??null,approvals:i,transcript:a,events:c,artifacts:m,runtimeHealth:d,...typeof e.expectedOutput=="string"&&e.expectedOutput.trim().length>0?{expectedOutput:e.expectedOutput.trim()}:{},rubric:Array.isArray(e.rubric)?e.rubric.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[],tags:Array.isArray(e.tags)?e.tags.filter(o=>typeof o=="string"&&o.trim().length>0).map(o=>o.trim()):[],...e.metadata?{metadata:{...e.metadata}}:{}}}async replayEvaluationBundle(e){const t=e.agentId??e.bundle.request?.agentId??e.bundle.session?.entryAgentId;if(!t)throw new Error("Evaluation replay requires an agentId on the replay input or exported bundle.");const s=e.bundle.requestInput??M(e.bundle.transcript,e.bundle.request?.requestId);if(!s)throw new Error("Evaluation replay requires bundle.requestInput from exportEvaluationBundle.");const r=e.invocation??s.invocation,i=await this.run({agentId:t,input:s.input,...e.sessionId?{sessionId:e.sessionId}:{},...r?{invocation:r}:{}}),a=typeof e.bundle.expectedOutput=="string"?e.bundle.expectedOutput.trim():"";return{request:{agentId:t,input:s.input,...r?{invocation:r}:{},...e.sessionId?{sessionId:e.sessionId}:{}},result:i,assertions:{...a.length>0?{expectedOutputMatched:i.output.includes(a)}:{}}}}listAgentSkills(e,t={}){return Ee(this.workspace,e,{assessRequirements:S(this.workspace),...t})}getAgent(e,t={}){return ke(this.workspace,e,{assessRequirements:S(this.workspace),...t})}describeWorkspaceInventory(e={}){return Ae(this.workspace,{assessRequirements:S(this.workspace),...e})}analyzeWorkspaceBoundaries(e={}){return Ce(this.workspace,e)}async deleteSessionCheckpoints(e){const t=this.resolvedRuntimeAdapterOptions.checkpointerResolver;if(!t)return;const s=new Set;for(const r of this.workspace.bindings.values()){const i=t(r);if(!i||s.has(i))continue;s.add(i);const a=i.deleteSession;if(typeof a=="function"){await a.call(i,e);continue}}}async deleteSession(e){return rt({getSession:t=>this.getSessionRecord(t),deleteSession:t=>this.persistence.deleteSession(t),deleteSessionCheckpoints:t=>this.deleteSessionCheckpoints(t)},e)}async createToolMcpServer(e){const t=this.resolveToolMcpServerTools(e.agentId);return fe(t,e)}async serveToolsOverStdio(e){const t=this.resolveToolMcpServerTools(e.agentId);return Ie(t,e)}async createRuntimeMcpServer(e={}){return Re(this,e)}async serveRuntimeMcpOverStdio(e={}){return Se(this,e)}async serveRuntimeMcpOverStreamableHttp(e={}){const{serveRuntimeMcpOverStreamableHttp:t}=await import("../mcp.js");return t(this,e)}async routeAgent(e,t={}){return pe({workspace:this.workspace,input:e,routingRules:this.routingRules,routingDefaultAgentId:this.routingDefaultAgentId,sessionId:t.sessionId})}async emit(e,t,s,r,i,a="runtime"){return X({persistence:this.persistence,publishEvent:c=>this.eventBus.publish(c),trackBackgroundTask:c=>this.trackBackgroundTask(c),backgroundEventTypes:q.BACKGROUND_EVENT_TYPES},e,t,s,r,i,a)}trackBackgroundTask(e){this.backgroundTasks.add(e),e.finally(()=>{this.backgroundTasks.delete(e)})}scheduleBackgroundStartupTask(e){this.trackBackgroundTask(e.then(()=>{}).catch(()=>{}))}async drainBackgroundTasksForClose(){const e=Array.from(this.backgroundTasks);if(e.length===0)return;let t;await Promise.race([Promise.allSettled(e),new Promise(s=>{t=setTimeout(s,ct),t.unref?.()})]),t&&clearTimeout(t)}async closeStageWithTimeout(e,t){if(!t)return;let s;await Promise.race([t().then(()=>{}).catch(()=>{}),new Promise(r=>{s=setTimeout(r,dt),s.unref?.()})]),s&&clearTimeout(s)}resolveToolMcpServerTools(e){return we({workspace:this.workspace,agentId:e,toolResolver:this.resolvedRuntimeAdapterOptions.toolResolver}).map(({compiledTool:t,resolvedTool:s})=>({compiledTool:t,resolvedTool:s,sourceTool:this.workspace.tools.get(t.id)}))}async loadPriorHistory(e,t){return(await this.persistence.listSessionMessages(e)).filter(r=>r.requestId!==t)}async loadRequestInput(e,t){return(await this.persistence.listSessionMessages(e,100)).find(i=>i.requestId===t&&i.role==="user")?.content??""}async getRequestCancellation(e){const t=await this.persistence.getRequestControl(e);return{requested:t?.cancelRequested===!0,...t?.cancelReason?{reason:t.cancelReason}:{}}}async finalizeCancelledRequest(e,t,s,r){return te({persistence:this.persistence,emit:(i,a,c,d,l,m)=>this.emit(i,a,c,d,l,m),setRequestStateAndEmit:(i,a,c,d,l)=>this.setRequestStateAndEmit(i,a,c,d,l)},e,t,s,r)}async invokeWithHistory(e,t,s,r,i,a,c={}){const d=a??await this.loadPriorHistory(s,r),l=c.memoryRecall??await this.buildRuntimeMemoryContext(e,s,t),m=Date.now();try{const o=await this.runtimeAdapter.invoke(e,t,s,r,i,d,{...c,...l?.prompt?{memoryContext:l.prompt}:{}});return await this.persistRuntimeMemoryCandidates(e,s,r,o.metadata?.memoryCandidates),await this.persistRequestPlanState(s,r,o.metadata?.executedToolResults),this.recordLlmSuccess(m),o}catch(o){throw this.recordLlmFailure(m),o}}resolveMemoryNamespace(e,t,s={}){const r=this.getWorkspaceId(t),i=this.runtimeMemoryPolicy?.namespaces[e]??`memories/${e}s/{${e}Id}`;return Ne(i,{sessionId:s.sessionId,agentId:s.agentId??t.agent.id,workspaceId:r,userId:s.userId??"default",projectId:s.projectId??r})}getWorkspaceId(e){const t=e.harnessRuntime.workspaceRoot??this.workspace.workspaceRoot;return b.basename(t)||"default"}async buildRuntimeMemoryContext(e,t,s){if(!this.runtimeMemoryPolicy&&!this.proceduralMemoryModule)return;const r=B(s??"").trim();if(!r)return;const i={sessionId:t,agentId:e.agent.id,workspaceId:this.getWorkspaceId(e)},a=this.proceduralMemoryConfig?.retrieval?.maxPromptItems??4,[c,d]=await Promise.all([this.runtimeMemoryPolicy?this.knowledgeModule.buildPromptRecall({query:r,topK:this.runtimeMemoryPolicy?.retrieval.maxPromptMemories??8},i):Promise.resolve({items:[],context:void 0}),this.proceduralMemoryModule&&this.proceduralMemoryConfig?.retrieval?.enabled!==!1?this.proceduralMemoryModule.buildPromptRecall({query:r,topK:a},i):Promise.resolve({items:[],context:void 0})]),l=[c.context?.trim(),d.context?.trim()].filter(m=>!!m);if(l.length!==0)return{prompt:l.join(`
|
|
2
|
+
|
|
3
|
+
`),items:I(c.items,d.items)}}async persistRuntimeMemoryCandidates(e,t,s,r){if(!Array.isArray(r)||r.length===0||this.runtimeMemoryFormationConfig?.hotPath.enabled===!1)return;const i=r.filter(a=>typeof a=="object"&&a!==null).filter(a=>a.noStore!==!0&&typeof a.content=="string"&&a.content.trim().length>0);i.length!==0&&await this.knowledgeModule.memorizeCandidates(i,{sessionId:t,requestId:s,agentId:e.agent.id,workspaceId:this.getWorkspaceId(e),recordedAt:new Date().toISOString()},{storeCandidateLog:!0})}async persistRequestPlanState(e,t,s){if(!Array.isArray(s)||s.length===0)return;const r=s.filter(l=>typeof l=="object"&&l!==null);let i=null;for(const l of[...r].reverse()){const m=typeof l.output=="object"&&l.output!==null?l.output.summary:void 0;if(typeof m!="object"||m===null)continue;const o=m;if(!(!Array.isArray(o.items)||!o.summary||typeof o.summary!="object")){i=o;break}}if(!i)return;const a=i.items,c=i.summary,d=await this.persistence.getRequestPlanState(e,t);await this.persistence.saveRequestPlanState(e,t,{sessionId:e,requestId:t,version:(d?.version??0)+1,updatedAt:new Date().toISOString(),items:a,summary:c})}async resolvePersistedRequestPriority(e,t){const s=await this.persistence.getRequestInput(e,t);return Y(s?.priority)}enqueuePendingRequestSlot(e){return me(this.pendingRequestSlots,e,this.pendingRunInsertionOrder++)}async executeQueuedRequest(e,t,s,r,i,a={}){return ae({persistence:this.persistence,getRequestCancellation:c=>this.getRequestCancellation(c),finalizeCancelledRequest:(c,d,l,m)=>this.finalizeCancelledRequest(c,d,l,m),emit:(c,d,l,m,o)=>m==="request.dequeued"?this.emit(c,d,l,m,{...o,activeRequestCount:this.activeRequestSlots,maxConcurrentRuns:this.concurrencyConfig.maxConcurrentRuns}):this.emit(c,d,l,m,o),setRequestStateAndEmit:(c,d,l,m,o)=>this.setRequestStateAndEmit(c,d,l,m,o),invokeWithHistory:(c,d,l,m,o,n,u)=>this.invokeWithHistory(c,d,l,m,o,n,u),finalizeContinuedRequest:(c,d,l,m,o,n)=>this.finalizeContinuedRequest(c,d,l,m,o,n),emitSyntheticFallback:(c,d,l,m)=>this.runtimeEventOperations.emitSyntheticFallback(c,d,l,m,103),renderRuntimeFailure:N},{binding:e,message:t,sessionId:s,requestId:r,agentId:i,options:a})}async finalizeContinuedRequest(e,t,s,r,i,a){return se({persistence:this.persistence,emit:(c,d,l,m,o,n)=>this.emit(c,d,l,m,o,n),setRequestStateAndEmit:(c,d,l,m,o)=>this.setRequestStateAndEmit(c,d,l,m,o),requestApprovalAndEmit:(c,d,l,m,o,n)=>this.requestApprovalAndEmit(c,d,l,m,o,n)},e,t,s,r,i,a)}async setRequestStateAndEmit(e,t,s,r,i){return this.runtimeEventOperations.setRequestStateAndEmit(e,t,s,r,i)}async requestApprovalAndEmit(e,t,s,r,i,a){return this.runtimeEventOperations.requestApprovalAndEmit(e,t,s,r,i,a)}isDecisionRun(e){return"decision"in e}async notifyListener(e,t){e&&await e(t)}async acquireRequestSlot(e,t,s="running",r=0){return de({persistence:{claimQueuedRequest:({sessionId:i,requestId:a,workerId:c,claimedAt:d,leaseExpiresAt:l})=>this.persistence.claimQueuedRequest({sessionId:i,requestId:a,workerId:c,claimedAt:d,leaseExpiresAt:l}),renewRequestLease:({requestId:i,workerId:a,heartbeatAt:c,leaseExpiresAt:d})=>this.persistence.renewRequestLease({requestId:i,workerId:a,heartbeatAt:c,leaseExpiresAt:d}),releaseRequestClaim:i=>this.persistence.releaseRequestClaim(i),enqueueRequest:({sessionId:i,requestId:a,priority:c})=>this.persistence.enqueueRequest({sessionId:i,requestId:a,priority:c}),getRequest:i=>this.persistence.getRequest(i)},workerId:this.workerId,concurrencyConfig:this.concurrencyConfig,pendingRequestSlots:this.pendingRequestSlots,getActiveRequestSlots:()=>this.activeRequestSlots,setActiveRequestSlots:i=>{this.activeRequestSlots=i},enqueuePendingRequestSlot:i=>this.enqueuePendingRequestSlot(i),emit:(i,a,c,d,l)=>this.emit(i,a,c,d,l),setRequestStateAndEmit:(i,a,c,d,l)=>this.setRequestStateAndEmit(i,a,c,d,l)},{sessionId:e,requestId:t,activeState:s,priority:r})}dropPendingRequestSlot(e){return le(this.pendingRequestSlots,e)}async run(e){if(this.isDecisionRun(e)){const n={sessionId:e.sessionId,requestId:e.requestId,approvalId:e.approvalId,decision:e.decision,editedInput:e.editedInput};return this.resume(n)}const t=J(e);if(t){const n=await re({notifyListener:(u,h)=>this.notifyListener(u,h),getSession:async u=>{const h=await this.getSessionRecord(u);return h?{currentState:h.currentState,latestRequestId:h.latestRequestId,entryAgentId:h.entryAgentId,currentAgentId:h.currentAgentId,requests:h.requests.map(g=>({agentId:g.agentId})),pendingDecision:h.pendingDecision}:null}}).dispatchRequestListeners(this.streamEvents(e),t);return R(n)}const s=v(e),{binding:r,selectedAgentId:i,sessionId:a,requestId:c,isNewSession:d,requestCreatedEventPromise:l,releaseRequestSlotPromise:m}=await k(this.createPrepareRunStartRuntime(),{options:e,invocation:s,requestCreatedPayload:(n,u)=>({agentId:n.agent.id,requestedAgentId:A(e.agentId),selectedAgentId:u,executionMode:ve(n)})});await l;const o=await m;try{return R(await this.executeQueuedRequest(r,e.input,a,c,i,{context:s.context,state:s.state,files:s.files,previousState:"running",stateSequence:6,approvalSequence:7,priorHistory:d?[]:void 0}))}finally{await o()}}async*streamEvents(e){const t=v(e),s=await this.resolveSelectedAgentId(e.input,e.agentId,e.sessionId),r=y(this.workspace,s);if(!r){yield{type:"result",result:await this.run(e)};return}const{sessionId:i,requestId:a,isNewSession:c,requestCreatedEventPromise:d,releaseRequestSlotPromise:l}=await k(this.createPrepareRunStartRuntime(),{options:e,invocation:t,requestCreatedPayload:(o,n)=>({agentId:n,requestedAgentId:A(e.agentId),selectedAgentId:n,input:e.input,state:"running"})}),m=et({binding:r,input:e.input,invocation:{...t,memoryRecall:await this.buildRuntimeMemoryContext(r,i,e.input)},sessionId:i,requestId:a,selectedAgentId:s,isNewSession:c,requestCreatedEventPromise:d,releaseRequestSlotPromise:l,getBinding:o=>y(this.workspace,o),loadPriorHistory:(o,n)=>this.loadPriorHistory(o,n),stream:(o,n,u,h,g)=>this.runtimeAdapter.stream(o,n,u,h,{...g,profiling:!0}),invokeWithHistory:(o,n,u,h)=>this.invokeWithHistory(o,n,u,h),emit:(o,n,u,h,g)=>this.emit(o,n,u,h,g),setRequestStateAndEmit:(o,n,u,h,g)=>this.setRequestStateAndEmit(o,n,u,h,g),requestApprovalAndEmit:(o,n,u,h,g,C)=>this.requestApprovalAndEmit(o,n,u,h,g,C),appendAssistantMessage:(o,n,u)=>ee(this.persistence,o,n,u),clearRequestInput:(o,n)=>this.persistence.clearRequestInput(o,n),updateRequestInspection:(o,n,u)=>this.persistence.updateRequestInspection(o,n,u),appendRequestTraceItem:(o,n,u)=>this.persistence.appendRequestTraceItem(o,n,u),loadRequestPlanState:(o,n)=>this.persistence.getRequestPlanState(o,n),saveRequestPlanState:(o,n,u)=>this.persistence.saveRequestPlanState(o,n,u),emitSyntheticFallback:(o,n,u,h)=>this.runtimeEventOperations.emitSyntheticFallback(o,n,u,h)});for await(const o of m)yield Oe(o)}async resume(e){return R(await ue({getApprovalById:t=>this.persistence.getApproval(t),getSession:t=>this.getSession(t),resolveApprovalRecord:(t,s)=>ne(this.persistence,t,s),getBinding:t=>y(this.workspace,t),buildResumePayload:(t,s,r)=>ie(t,s,r),getRequestCancellation:t=>this.getRequestCancellation(t),finalizeCancelledRequest:(t,s,r,i)=>this.finalizeCancelledRequest(t,s,r,i),setRequestState:(t,s,r,i)=>this.persistence.setRequestState(t,s,r,i),acquireRequestSlot:(t,s,r,i)=>this.acquireRequestSlot(t,s,r,i),resolvePersistedRequestPriority:(t,s)=>this.resolvePersistedRequestPriority(t,s),saveRequestRecoveryIntent:(t,s,r)=>this.persistence.saveRequestRecoveryIntent(t,s,r),emit:(t,s,r,i,a)=>this.emit(t,s,r,i,a),resolveApproval:(t,s,r,i)=>this.persistence.resolveApproval(t,s,r,i),listSessionMessages:t=>this.persistence.listSessionMessages(t),loadRequestInput:(t,s)=>this.loadRequestInput(t,s),invoke:(t,s,r,i,a,c)=>this.runtimeAdapter.invoke(t,s,r,i,a,c),recordLlmSuccess:t=>this.recordLlmSuccess(t),recordLlmFailure:t=>this.recordLlmFailure(t),clearRequestRecoveryIntent:(t,s)=>this.persistence.clearRequestRecoveryIntent(t,s),finalizeContinuedRequest:(t,s,r,i,a,c)=>this.finalizeContinuedRequest(t,s,r,i,a,c)},{...e}))}async restartConversation(e){const t=await this.getSession(e.sessionId);if(!t)throw new Error(`Unknown session ${e.sessionId}`);const s=t.latestRequestId,r=e.mode==="restart-new-session"?p():e.sessionId,i=await this.run({agentId:t.currentAgentId??t.entryAgentId,input:e.input,sessionId:e.mode==="restart-new-session"?void 0:r});return{...i,restart:{sourceSessionId:e.sessionId,sourceRequestId:s,restartMode:e.mode,restartedBy:"console",restartedAt:new Date().toISOString(),newSessionId:i.sessionId,newRequestId:i.requestId}}}async close(){this.closed||(this.closed=!0,await this.closeStageWithTimeout("healthMonitor.stop",async()=>{await this.healthMonitor?.stop()}),await this.closeStageWithTimeout("eventBus.drain",()=>this.eventBus.drain()),this.unregisterSessionMemorySync(),this.unregisterRuntimeMemorySync(),this.unregisterMem0IngestionSync(),this.unregisterRuntimeMemoryFormationSync(),this.unregisterProceduralMemoryFormationSync(),await this.drainBackgroundTasksForClose(),await this.closeStageWithTimeout("sessionMemorySync.close",async()=>{await this.sessionMemorySync?.close()}),await this.closeStageWithTimeout("runtimeMemorySync.close",async()=>{await this.runtimeMemorySync?.close()}),await this.closeStageWithTimeout("mem0IngestionSync.close",async()=>{await this.mem0IngestionSync?.close()}),await this.closeStageWithTimeout("runtimeMemoryFormationSync.close",async()=>{await this.runtimeMemoryFormationSync?.close()}),await this.closeStageWithTimeout("proceduralMemoryFormationSync.close",async()=>{await this.proceduralMemoryFormationSync?.close()}),await this.closeStageWithTimeout("closeMcpClientsForWorkspace",()=>qe(this.workspace)),this.initialized=!1)}async stop(){await this.close()}async cancelRequest(e){return R(await oe({getRequest:t=>this.persistence.getRequest(t),requestRequestCancel:(t,s)=>this.persistence.requestRequestCancel(t,s),dropPendingRequestSlot:t=>this.dropPendingRequestSlot(t),finalizeCancelledRequest:(t,s,r,i)=>this.finalizeCancelledRequest(t,s,r,i),setRequestStateAndEmit:(t,s,r,i,a)=>this.setRequestStateAndEmit(t,s,r,i,a)},e))}async recoverStartupRequests(){await Ye({recoveryConfig:this.recoveryConfig,persistence:this.persistence,createStartupRecoveryContext:()=>({persistence:this.persistence,workspace:this.workspace,runtimeAdapter:this.runtimeAdapter,recoveryConfig:this.recoveryConfig,concurrencyConfig:this.concurrencyConfig,getBinding:e=>y(this.workspace,e),acquireRequestSlot:(e,t,s,r)=>this.acquireRequestSlot(e,t,s,r),executeQueuedRequest:(e,t,s,r,i,a)=>this.executeQueuedRequest(e,t,s,r,i,a),setRequestStateAndEmit:(e,t,s,r,i)=>this.setRequestStateAndEmit(e,t,s,r,i),emit:(e,t,s,r,i)=>this.emit(e,t,s,r,i),loadRequestInput:(e,t)=>this.loadRequestInput(e,t),finalizeContinuedRequest:(e,t,s,r,i,a)=>this.finalizeContinuedRequest(e,t,s,r,i,a),supportsRunningReplay:e=>Me(e),isStaleRunningRequest:(e,t)=>this.isStaleRunningRequest(e,t),recordLlmSuccess:e=>this.recordLlmSuccess(e),recordLlmFailure:e=>this.recordLlmFailure(e)}),reclaimExpiredClaimedRequests:e=>this.reclaimExpiredClaimedRequests(e)})}async reclaimExpiredClaimedRequests(e=new Date().toISOString()){await Ge({persistence:this.persistence,setRequestStateAndEmit:(t,s,r,i,a)=>this.setRequestStateAndEmit(t,s,r,i,a),emit:(t,s,r,i,a)=>this.emit(t,s,r,i,a),concurrencyConfig:this.concurrencyConfig,getActiveRequestSlots:()=>this.activeRequestSlots},e)}async isStaleRunningRequest(e,t=Date.now()){return Je({persistence:this.persistence,concurrencyConfig:this.concurrencyConfig},e,t)}}export{q as AgentHarnessRuntime};
|