@tencent-ai/agent-harness 0.2.0-beta.1 → 0.2.0-beta.3
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/CHANGELOG.md +44 -0
- package/README.md +1 -1
- package/cli/CHANGELOG.md +135 -0
- package/cli/dist-server/shared.cjs +455 -387
- package/cli/dist-server/types/node/acp/acp-protocol.d.ts +40 -12
- package/cli/dist-server/types/node/acp/usage-by-category-calculator.d.ts +21 -0
- package/cli/dist-server/types/node/bash-sandbox/bash-sandbox-protocol.d.ts +3 -0
- package/cli/dist-server/types/node/cli/cli-protocol.d.ts +3 -0
- package/cli/dist-server/types/node/cli/stream-json-protocol.d.ts +23 -2
- package/cli/dist-server/types/node/data-fs/index.d.ts +13 -1
- package/cli/dist-server/types/node/hooks/hook-protocol.d.ts +2 -2
- package/cli/dist-server/types/node/sensitive-content/sensitive-content-protocol.d.ts +7 -0
- package/cli/dist-server/types/node/server/boot.d.ts +7 -4
- package/{lib/components → cli/dist-server/types/node/server/formats}/acp/acp-error-model.d.ts +1 -1
- package/{lib/components → cli/dist-server/types/node/server/formats}/acp/acp-protocol.d.ts +2 -3
- package/cli/dist-server/types/node/server/formats/acp/index.d.ts +12 -0
- package/cli/dist-server/types/node/server/formats/acp/projection.d.ts +10 -0
- package/cli/dist-server/types/node/server/index.d.ts +1 -1
- package/cli/dist-server/types/node/server/sessions.d.ts +27 -2
- package/cli/dist-server/types/node/server/types.d.ts +65 -7
- package/cli/dist-server/types/node/settings/settings-protocol.d.ts +5 -0
- package/cli/dist-server/types/node/tools/tool-protocol.d.ts +128 -4
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-protocol.d.ts +60 -2
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-purpose-protocol.d.ts +8 -4
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-purpose-scope.d.ts +46 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-service.d.ts +28 -3
- package/cli/dist-server/types/vendor/cbc-core/node/agent/index.d.ts +4 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/interceptors/input-interceptors.d.ts +1 -6
- package/cli/dist-server/types/vendor/cbc-core/node/agent/model-call-failure.d.ts +9 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/model-step-sequence.d.ts +11 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/runner-factory.d.ts +56 -20
- package/cli/dist-server/types/vendor/cbc-core/node/agent/speaker-label.d.ts +44 -0
- package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-detector-service.d.ts +5 -4
- package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-guard-protocol.d.ts +1 -1
- package/cli/dist-server/types/vendor/cbc-core/node/agent/tool-call-loop-pattern.d.ts +16 -4
- package/cli/dist-server/types/vendor/cbc-core/node/context/compaction-lineage.d.ts +39 -0
- package/cli/dist-server/types/vendor/cbc-core/node/context/context-compact-summarizer.d.ts +2 -0
- package/cli/dist-server/types/vendor/cbc-core/node/context/context-protocol.d.ts +17 -0
- package/cli/dist-server/types/vendor/cbc-core/node/context/index.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-core/node/context/pre-message-compact-strategy.d.ts +1 -2
- package/cli/dist-server/types/vendor/cbc-core/node/hooks/agent-trigger.d.ts +6 -22
- package/cli/dist-server/types/vendor/cbc-core/node/hooks/hook-protocol.d.ts +4 -1
- package/cli/dist-server/types/vendor/cbc-core/node/session/idle-queue-drain-service.d.ts +4 -56
- package/cli/dist-server/types/vendor/cbc-core/node/session/index.d.ts +4 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/interruption-service.d.ts +63 -9
- package/cli/dist-server/types/vendor/cbc-core/node/session/model-request-retry-phase.d.ts +16 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/model-response-interceptors.d.ts +33 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/recovery-budget.d.ts +55 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-hook-manager.d.ts +15 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager-host-protocol.d.ts +3 -2
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-manager.d.ts +17 -4
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-persistence-error.d.ts +43 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-protocol.d.ts +110 -9
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-run-state-machine-protocol.d.ts +15 -1
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-runtime-lifecycle.d.ts +5 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-store.d.ts +150 -4
- package/cli/dist-server/types/vendor/cbc-core/node/session/stream-timeout-retry-budget.d.ts +20 -1
- package/cli/dist-server/types/vendor/cbc-core/node/trace/turn-context.d.ts +28 -1
- package/cli/dist-server/types/vendor/cbc-core/node/utils/command-message-utils.d.ts +20 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/history-utils.d.ts +27 -4
- package/cli/dist-server/types/vendor/cbc-core/node/utils/index.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/input-item-utils.d.ts +8 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/message-utils.d.ts +12 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/model-utils.d.ts +7 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/queue-dispatch-utils.d.ts +24 -2
- package/cli/dist-server/types/vendor/cbc-core/node/utils/session-utils.d.ts +4 -1
- package/cli/dist-server/types/vendor/cbc-core/node/utils/string-retention-utils.d.ts +4 -0
- package/cli/dist-server/types/vendor/cbc-core/node/utils/token-utils.d.ts +3 -1
- package/cli/dist-server/types/vendor/cbc-shared/node/agent/openai-agents-types.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/checkpoint/checkpoint-types.d.ts +6 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/hooks/hook-types.d.ts +7 -1
- package/cli/dist-server/types/vendor/cbc-shared/node/index.d.ts +2 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/model/model-errors.d.ts +36 -4
- package/cli/dist-server/types/vendor/cbc-shared/node/tools/tool-names.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/utils/retry-backoff.d.ts +30 -0
- package/cli/dist-server/types/vendor/cbc-shared/node/utils/retry-policy.d.ts +26 -0
- package/cli/dist-server/types/workspace/agent-client-protocol/lib/common/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/agent-client-protocol/lib/common/sandbox-rule-context.d.ts +38 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/account-scoped-external-link-authentication-provider.d.ts +5 -5
- package/cli/dist-server/types/workspace/authentication/lib/common/account-utils.d.ts +25 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-manager.d.ts +8 -2
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-observation.d.ts +36 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-protocol.d.ts +40 -2
- package/cli/dist-server/types/workspace/authentication/lib/common/external-link-authentication-provider.d.ts +21 -5
- package/cli/dist-server/types/workspace/authentication/lib/common/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/wx-authentication-provider.d.ts +2 -2
- package/cli/dist-server/types/workspace/cbc-checkpoint/lib/node/checkpoint/checkpoint-protocol.d.ts +2 -0
- package/cli/dist-server/types/workspace/cbc-checkpoint/lib/node/checkpoint/checkpoint-service.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-protocol.d.ts +60 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-purpose-protocol.d.ts +8 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-purpose-scope.d.ts +46 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/agent-service.d.ts +28 -3
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/index.d.ts +4 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/interceptors/input-interceptors.d.ts +1 -6
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/model-call-failure.d.ts +9 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/model-step-sequence.d.ts +11 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/runner-factory.d.ts +56 -20
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/speaker-label.d.ts +44 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-detector-service.d.ts +5 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-guard-protocol.d.ts +1 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/tool-call-loop-pattern.d.ts +16 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/compaction-lineage.d.ts +39 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/context-compact-summarizer.d.ts +2 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/context-protocol.d.ts +17 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/pre-message-compact-strategy.d.ts +1 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/hooks/agent-trigger.d.ts +6 -22
- package/cli/dist-server/types/workspace/cbc-core/lib/node/hooks/hook-protocol.d.ts +4 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/idle-queue-drain-service.d.ts +4 -56
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/index.d.ts +4 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/interruption-service.d.ts +63 -9
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/model-request-retry-phase.d.ts +16 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/model-response-interceptors.d.ts +33 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/recovery-budget.d.ts +55 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-hook-manager.d.ts +15 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager-host-protocol.d.ts +3 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-manager.d.ts +17 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-persistence-error.d.ts +43 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-protocol.d.ts +110 -9
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-run-state-machine-protocol.d.ts +15 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-runtime-lifecycle.d.ts +5 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-store.d.ts +150 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/stream-timeout-retry-budget.d.ts +20 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/trace/turn-context.d.ts +28 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/command-message-utils.d.ts +20 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/history-utils.d.ts +27 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/input-item-utils.d.ts +8 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/message-utils.d.ts +12 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/model-utils.d.ts +7 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/queue-dispatch-utils.d.ts +24 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/session-utils.d.ts +4 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/string-retention-utils.d.ts +4 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/token-utils.d.ts +3 -1
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/agent/openai-agents-types.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/checkpoint/checkpoint-types.d.ts +6 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/hooks/hook-types.d.ts +7 -1
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/index.d.ts +2 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/model/model-errors.d.ts +36 -4
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/tools/tool-names.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/utils/retry-backoff.d.ts +30 -0
- package/cli/dist-server/types/workspace/cbc-shared/lib/node/utils/retry-policy.d.ts +26 -0
- package/cli/dist-server/types/workspace/cbc-workflow/lib/node/workflow/workflow-execution.d.ts +14 -1
- package/cli/dist-server/types/workspace/cbc-workflow/lib/node/workflow/workflow-manager.d.ts +7 -0
- package/cli/dist-server/types/workspace/cbc-worktree/lib/node/worktree/worktree-service.d.ts +5 -0
- package/cli/dist-server/types/workspace/cbc-worktree/lib/node/worktree/worktree-session.d.ts +3 -0
- package/cli/dist-server/types/workspace/core/lib/common/protocol.d.ts +8 -1
- package/cli/dist-server/types/workspace/product/lib/common/cloud-product-provider.d.ts +9 -0
- package/cli/dist-server/types/workspace/product/lib/common/index.d.ts +2 -0
- package/cli/dist-server/types/workspace/product/lib/common/pick-market-skill-id.d.ts +13 -0
- package/cli/dist-server/types/workspace/product/lib/common/tencent-docs-endpoint.d.ts +37 -0
- package/cli/dist-server/types/workspace/product/lib/common/tool-control-catalog.d.ts +2 -2
- package/cli/dist-server/types/workspace/product/lib/common/types/config.d.ts +12 -0
- package/cli/dist-server/types/workspace/product/lib/common/types/features.d.ts +63 -11
- package/cli/dist-server/types/workspace/product/lib/common/types/language-model.d.ts +66 -0
- package/cli/dist-server/types/workspace/product/lib/common/types/product.d.ts +22 -1
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/backup-policy.d.ts +10 -1
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/center-protocol.generated.d.ts +375 -4
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/file-policy.d.ts +5 -2
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/http-policy.d.ts +20 -0
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/rule-config.d.ts +10 -0
- package/cli/dist-server/types/workspace/sandbox-cli/lib/node/sandbox-center-client.d.ts +219 -0
- package/cli/dist-server/types/workspace/telemetry/lib/common/event/types/craft.d.ts +43 -3
- package/cli/package.json +1 -1
- package/cli/product.cloudhosted.json +4 -4
- package/cli/product.internal.json +268 -45
- package/cli/product.ioa.json +354 -161
- package/cli/product.json +338 -352
- package/cli/product.selfhosted.json +2 -2
- package/cli/vendor/shim/brokered-bin/7z +675 -0
- package/cli/vendor/shim/brokered-bin/7za +675 -0
- package/cli/vendor/shim/brokered-bin/7zz +675 -0
- package/cli/vendor/shim/brokered-bin/rar +675 -0
- package/cli/vendor/shim/brokered-bin/tar +675 -0
- package/cli/vendor/shim/brokered-bin/zip +187 -0
- package/docs/README.md +1 -0
- package/docs/in-process.md +42 -2
- package/docs/protocol.md +7 -1
- package/docs/server.md +2 -0
- package/lib/agent/v2.js +1 -1
- package/lib/application/services.d.ts +3 -1
- package/lib/application/services.js +1 -1
- package/lib/client/client.js +1 -1
- package/lib/client/mcp.d.ts +1 -1
- package/lib/client/mcp.js +1 -1
- package/lib/components/acp-mcp-transport.d.mts +84 -1
- package/lib/components/question-elicitation.d.mts +20 -1
- package/lib/components/sandbox-center.d.mts +2 -0
- package/lib/components/sandbox-center.mjs +1 -0
- package/lib/components/{acp/acp-prompt-input.d.ts → session/prompt-input.d.ts} +1 -1
- package/lib/components/session-config.d.mts +2 -0
- package/lib/components/session-config.mjs +1 -1
- package/lib/components/session-replay.d.mts +6 -7
- package/lib/components/session-replay.mjs +1 -1
- package/lib/effect-runtime/mcp-lifecycle.mjs +1 -1
- package/lib/harness/create-harness.js +1 -1
- package/lib/harness/runtime.js +1 -1
- package/lib/harness/types.d.ts +3 -0
- package/lib/integration/agent-integration.d.ts +5 -0
- package/lib/integration/executor-supervisor.js +1 -1
- package/lib/public.d.ts +1 -0
- package/lib/runtime/private-runtime-role.js +1 -1
- package/lib/runtime/sandbox-center.d.ts +21 -0
- package/lib/runtime/sandbox-center.js +1 -0
- package/lib/server/public.d.ts +1 -0
- package/lib/session/agent-backend.d.ts +5 -0
- package/lib/session/agent-backend.js +1 -1
- package/lib/session/config-defaults.d.ts +4 -0
- package/lib/session/config-defaults.js +1 -0
- package/lib/session/config-store.d.ts +1 -1
- package/lib/session/config-store.js +1 -1
- package/lib/session/local-fs.js +1 -1
- package/lib/session/replay.d.ts +2 -2
- package/lib/session/replay.js +1 -1
- package/lib/session/server-config.d.ts +11 -2
- package/lib/session/server-config.js +1 -1
- package/lib/session/server-events.d.ts +10 -8
- package/lib/session/server-events.js +1 -1
- package/lib/session/server-interactions.js +1 -1
- package/lib/session/server-mcp.js +1 -1
- package/package.json +27 -16
- package/lib/components/acp/acp-client-channel.d.ts +0 -36
- package/lib/components/acp/acp-mcp-transport.d.ts +0 -84
- package/lib/components/acp/acp-question-elicitation.d.ts +0 -20
- package/lib/session/local-options.d.ts +0 -50
- package/lib/session/local-options.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var O=Object.defineProperty;var u=(o,e)=>O(o,"name",{value:e,configurable:!0});import{fork as k,spawn as P}from"node:child_process";import{randomUUID as x}from"node:crypto";import v from"node:path";import{EXECUTOR_PRIVATE_MAX_MESSAGE_BYTES as S,EXECUTOR_PRIVATE_MAX_TELEMETRY_MESSAGE_BYTES as q,EXECUTOR_PRIVATE_PROTOCOL_VERSION as T,isExecutorPrivateCatalogNotification as I,isExecutorPrivateResponse as B,isExecutorPrivateResult as D,isExecutorPrivateReverseRequest as N,isExecutorPrivateTelemetryNotification as V,isExecutorPrivateTelemetryNotificationCandidate as U}from"#agent-harness-executor/private-protocol";import{currentHarnessTraceCarrier as H,parseHarnessTraceCarrier as j,withHarnessTraceContext as C}from"#agent-harness-executor/trace-context";import{DEFAULT_MCP_TOOLS_SYNC_TTL_MS as z}from"#agent-harness-executor/types";import{maybeCurrentHarnessProcessRuntime as W}from"../effect-runtime/process-runtime-context.js";import{normalizeError as g}from"../internal/errors.js";import{boundedStringifyJson as E}from"../protocol/bounded-json.js";import{applyNodeRuntimeEnvironment as G,resolveNodeRuntimeLaunch as M}from"../runtime/node-runtime.js";import{AGENT_HARNESS_PRIVATE_RUNTIME_ROLE as _,createPrivateRuntimeLaunchSpec as A,isAgentHarnessStandaloneBinary as X}from"../runtime/private-runtime-role.js";import{CodeBuddyProcessContainment as $}from"../runtime/process-containment.js";import{isMissingProcess as J}from"../runtime/process-tree.js";import{assertAgentHarnessProcessContainment as Y}from"../runtime/sfe-process-containment.js";import{measure as w}from"../telemetry/index.js";import{attachPosixStdioMcpGuardian as K,resolveStdioMcpContainment as Q}from"./stdio-guardian.js";const Z=3e4,ee=15e3,te=5e3,ie=3e3,se=1e3,re=1e4,ne=3e3,oe=1024,ae=8*1024*1024,he=5,ce=6e4,le=100,b=5e3,F=16;export class ExecutorPrivateProcessExitedError extends Error{static{u(this,"ExecutorPrivateProcessExitedError")}constructor(){super("Private Executor child exited unexpectedly"),this.name="ExecutorPrivateProcessExitedError"}}export class ExecutorPrivateProtocolError extends Error{static{u(this,"ExecutorPrivateProtocolError")}constructor(e){super(e),this.name="ExecutorPrivateProtocolError"}}export class ExecutorPrivateOverloadedError extends Error{static{u(this,"ExecutorPrivateOverloadedError")}constructor(){super("Private Executor IPC queue is overloaded"),this.name="ExecutorPrivateOverloadedError"}}class ue extends Error{static{u(this,"ExecutorPrivateOperationError")}constructor(e,t,i){super(i),this.code=e,this.retryable=t,this.name=e}}export class ExecutorPrivateStartupCleanupError extends AggregateError{static{u(this,"ExecutorPrivateStartupCleanupError")}constructor(e,t){super([e,t],"Private Executor startup and cleanup both failed"),this.startupFailure=e,this.cleanupFailure=t,this.name="ExecutorPrivateStartupCleanupError"}}export class ExecutorPrivateShutdownTimeoutError extends Error{static{u(this,"ExecutorPrivateShutdownTimeoutError")}constructor(e){super(`Private Executor cleanup timed out after ${e}ms`),this.timeoutMs=e,this._tag="ExecutorPrivateShutdownTimeoutError",this.name=this._tag}}function de(){return X()?process.execPath:v.resolve(import.meta.dirname,"../../executor/lib/capsule/entry.mjs")}u(de,"defaultChildEntryPath");const fe=Object.freeze(["ALL_PROXY","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","NODE_EXTRA_CA_CERTS","NODE_NO_WARNINGS","NO_PROXY","PATH","SSL_CERT_DIR","SSL_CERT_FILE","SystemRoot","TEMP","TMP","TMPDIR","TZ","WINDIR","http_proxy","https_proxy","all_proxy","no_proxy"]);function pe(o){const e=u(n=>{const a=n?.trim();if(a)try{const h=new URL(a.includes("://")?a:`http://${a}`);return h.protocol==="http:"||h.protocol==="https:"?h.toString():void 0}catch{return}},"normalize"),t=e(o.ALL_PROXY??o.all_proxy),i=e(o.HTTP_PROXY??o.http_proxy??t),s=e(o.HTTPS_PROXY??o.https_proxy??t??i),r=[...new Set([...(o.NO_PROXY??o.no_proxy??"").split(",").map(n=>n.trim()).filter(Boolean),"localhost","127.0.0.1","::1"])];return Object.freeze({...i===void 0?{}:{httpProxyUrl:i},...s===void 0?{}:{httpsProxyUrl:s},mode:"auto",noProxy:Object.freeze(r),revision:"environment"})}u(pe,"defaultExecutorProxyPolicy");export function createExecutorChildEnvironment(o=process.env,e=M()){const t={AGENT_HARNESS_PRIVATE_EXECUTOR:"1"};for(const i of fe){const s=o[i];s!==void 0&&(t[i]=s)}return G(t,e)}u(createExecutorChildEnvironment,"createExecutorChildEnvironment");export function createExecutorWindowsSpawnSpec(o,e){const{execArgv:t=process.execArgv,execPath:i=process.execPath,silent:s,...r}=e,a=A({entryPath:o,nodeRuntime:{environment:{},executable:i},role:_.executor}),h=a.args[0]===o;return{...{args:Object.freeze([...h?t:[],...a.args]),command:a.command},options:{...r,env:{...r.env},windowsHide:!0}}}u(createExecutorWindowsSpawnSpec,"createExecutorWindowsSpawnSpec");function me(o,e){Y();const t=createExecutorWindowsSpawnSpec(o,e);return P(t.command,[...t.args],t.options)}u(me,"spawnExecutorChildOnWindows");function ge(o,e,t,i){if(t==="win32")return me(o,e);const s=A({entryPath:o,nodeRuntime:i,role:_.executor});if(s.args[0]===o)return k(o,[],e);const{execArgv:r,execPath:n,silent:a,...h}=e;return P(s.command,[...s.args],h)}u(ge,"spawnExecutorChild");function we(o){const e=u((a,h,l)=>{const d=a??h;if(!Number.isSafeInteger(d)||d<=0)throw new RangeError(`${l} must be a positive integer`);return d},"positive"),t=u((a,h,l)=>{const d=a??h;if(!Number.isSafeInteger(d)||d<0)throw new RangeError(`${l} must be a non-negative integer`);return d},"nonNegative"),i=o.platform??process.platform,s=Q({platform:i,requested:o.allowStdio??!0,windowsProcessContainmentEnabled:o.windowsProcessContainmentEnabled,windowsJob:o.windowsJob}),r=o.nodeRuntime??M(),n=createExecutorChildEnvironment(o.environment,r);return{allowStdio:s.allowStdio,childEntryPath:o.childEntryPath??de(),closeTimeoutMs:e(o.closeTimeoutMs,te,"closeTimeoutMs"),containment:o.containment??new $,crashWindowMs:e(o.crashWindowMs,ce,"crashWindowMs"),environment:n,healthIntervalMs:t(o.healthIntervalMs,re,"healthIntervalMs"),healthTimeoutMs:e(o.healthTimeoutMs,ne,"healthTimeoutMs"),instanceId:o.instanceId??x(),maxCrashes:e(o.maxCrashes,he,"maxCrashes"),maxPendingRequestBytes:e(o.maxPendingRequestBytes,ae,"maxPendingRequestBytes"),maxPendingRequests:e(o.maxPendingRequests,oe,"maxPendingRequests"),nodeRuntime:r,toolsSyncTtlMs:o.toolsSyncTtlMs===null?null:e(o.toolsSyncTtlMs,z,"toolsSyncTtlMs"),onElicitation:o.onElicitation,...o.onFailure===void 0?{}:{onFailure:o.onFailure},platform:i,proxyPolicy:o.proxyPolicy??pe(n),...o.recordLifecycle===void 0?{}:{recordLifecycle:o.recordLifecycle},...o.recordEffectTelemetry===void 0?{}:{recordEffectTelemetry:o.recordEffectTelemetry},requestTimeoutMs:e(o.requestTimeoutMs,Z,"requestTimeoutMs"),restartBackoffMs:e(o.restartBackoffMs,le,"restartBackoffMs"),spawnChild:o.spawnChild??((a,h)=>ge(a,h,i,r)),startTimeoutMs:e(o.startTimeoutMs,ee,"startTimeoutMs"),...o.stdioGuardianEntryPath===void 0?{}:{stdioGuardianEntryPath:o.stdioGuardianEntryPath},stdioContainment:s.mode,...s.mode==="windows_native_job_object"?{windowsJob:s.windowsJob}:{},termTimeoutMs:e(o.termTimeoutMs,ie,"termTimeoutMs")}}u(we,"resolveOptions");function L(o,e){return e?.aborted?Promise.reject(e.reason):new Promise((t,i)=>{let s=!1;const r=u(h=>{s||(s=!0,clearTimeout(a),e?.removeEventListener("abort",n),h===void 0?t():i(h))},"finish"),n=u(()=>r(e?.reason),"onAbort"),a=setTimeout(()=>r(),o);a.unref?.(),e?.addEventListener("abort",n,{once:!0})})}u(L,"standaloneDelay");function R(o,e,t){const i=new AbortController,s=setTimeout(()=>i.abort(t),o);s.unref?.();const r=AbortSignal.any([...e,i.signal]),n=[];let a=!1;const h=u(()=>{if(!a){a=!0,clearTimeout(s);for(const[l,d]of n)l.removeEventListener("abort",d);n.length=0}},"close");for(const l of e)n.push([l,h]),l.addEventListener("abort",h,{once:!0});return Object.freeze({close:h,signal:r})}u(R,"standaloneDeadline");export class ExecutorProcessSupervisor{static{u(this,"ExecutorProcessSupervisor")}registerClientSource(e,t){if(this.assertAccepting(),this.clientSources.has(e))throw new Error("Duplicate Client MCP source");const i=t.subscribe(()=>{for(const s of this.registrations.values())s.transport.transport==="client"&&s.transport.sourceId===e&&this.invalidateCatalog(s.registrationId)});return this.clientSources.set(e,{source:t,release:i}),()=>{if(this.clientSources.get(e)?.source===t){this.clientSources.delete(e),i();for(const r of this.clientRequests.values())r.sourceId===e&&r.controller.abort(new Error("Client MCP source closed"))}}}invalidateCatalog(e){if(this.isStopping()||!this.registrations.has(e))return;const t=this.catalogRefreshes.get(e);if(t){t.dirty=!0;return}const i={dirty:!0,promise:Promise.resolve()};i.promise=Promise.resolve().then(async()=>{do{if(i.dirty=!1,this.isStopping()||!this.registrations.has(e))return;await this.refreshRegistration(e)}while(i.dirty)}).catch(()=>{}).finally(()=>{this.catalogRefreshes.delete(e),this.scheduleCatalogRefresh(e)}),this.catalogRefreshes.set(e,i)}scheduleCatalogRefresh(e){if(clearTimeout(this.catalogTimers.get(e)),this.catalogTimers.delete(e),this.isStopping()||!this.registrations.has(e)||this.options.toolsSyncTtlMs===null)return;const t=setTimeout(()=>{this.catalogTimers.delete(e),this.invalidateCatalog(e)},Math.min(this.options.toolsSyncTtlMs,2147483647));t.unref(),this.catalogTimers.set(e,t)}constructor(e){if(this.crashTimes=[],this.failureTasks=new Set,this.fuseOpenAttempt=0,this.fuseState="closed",this.nextRequestId=1,this.nextRegistrationRevision=1,this.pending=new Map,this.pendingSendBytes=0,this.pendingSends=0,this.proxyTask=Promise.resolve(),this.registrationRevisions=new Map,this.registrationTasks=new Map,this.restartAttempt=0,this.shutdownController=new AbortController,this.registrations=new Map,this.snapshots=new Map,this.clientSources=new Map,this.clientRequests=new Map,this.catalogTimers=new Map,this.catalogRefreshes=new Map,this.snapshotListeners=new Set,this.stateValue="idle",this.options=we(e),this.proxyPolicy=this.options.proxyPolicy,this.processRuntime=e.processRuntime??W(),this.processRuntime===void 0&&process.env.NODE_ENV!=="test")throw new Error("Executor supervisor requires the process-owned Effect runtime");this.releaseProcessOwnership=this.processRuntime?.addFinalizer(()=>this.close(new Error("Agent Harness process runtime is closing")));const t=this.processRuntime?.shutdownSignal;if(t){const i=u(()=>{this.close(t.reason).catch(()=>{})},"onProcessShutdown");t.addEventListener("abort",i,{once:!0}),this.releaseProcessShutdownListener=()=>t.removeEventListener("abort",i)}}get runtimeEpoch(){return this.active?.epoch}get state(){return this.stateValue}async start(){await this.ensureReady()}async configureProxy(e){this.assertAccepting(),this.proxyPolicy=e;const t=this.proxyTask.then(()=>this.reconcileProxyPolicy());this.proxyTask=t.catch(()=>{}),await t}subscribeSnapshots(e){return this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e)}async upsertRegistration(e,t){this.assertAccepting();const i=this.nextRegistrationRevision++;this.registrations.set(e.registrationId,e),this.registrationRevisions.set(e.registrationId,i);try{return await this.ensureReady(),await this.withRegistrationLock(e.registrationId,async()=>{if(this.assertCurrentRegistration(e.registrationId,i),t?.signal?.aborted)throw t.signal.reason;const s=this.active,r=this.snapshots.get(e.registrationId);if(this.stateValue==="ready"&&s?.initialized===!0&&s.child.connected&&s.child.exitCode===null&&s.child.signalCode===null&&s.appliedRegistrationRevisions.get(e.registrationId)===i&&r?.status==="available"&&r?.registrationId===e.registrationId&&r?.runtimeEpoch===s.epoch)return r;const n=await w("registrationReconcile",()=>this.request("registration/upsert",{registration:e},t));return this.assertCurrentRegistration(e.registrationId,i),this.setSnapshot(e.registrationId,n),n})}catch(s){throw this.isCurrentRegistration(e.registrationId,i)&&this.deleteSnapshot(e.registrationId),s}}async refreshRegistration(e,t){this.requireRegistration(e);const i=this.requireRegistrationRevision(e);return await this.ensureReady(),this.withRegistrationLock(e,async()=>{this.assertCurrentRegistration(e,i);const s=await this.request("registration/refresh",{registrationId:e},t);return this.assertCurrentRegistration(e,i),this.setSnapshot(e,s),s})}getSnapshot(e){return this.snapshots.get(e)}async removeRegistration(e,t){const i=this.nextRegistrationRevision++;this.registrations.delete(e),this.registrationRevisions.set(e,i),this.deleteSnapshot(e),this.registrations.size===0&&this.cancelFuseRecovery(new Error("Executor fuse recovery is no longer needed")),!(this.stateValue==="closed"||this.stateValue==="closing")&&(await this.withRegistrationLock(e,async()=>{if(!this.isCurrentRegistrationRevision(e,i)||this.isStopping())return;const s=this.active;if(s?.initialized)try{await this.requestOnActive(s,"registration/remove",{registrationId:e},t),s.appliedRegistrationRevisions.delete(e)}catch(r){if(this.active===s&&!this.isStopping())throw this.handleChildFailure(s,r),r}}),this.isCurrentRegistrationRevision(e,i)&&(this.deleteSnapshot(e),this.registrationRevisions.delete(e)))}async callTool(e,t,i,s,r={}){this.requireRegistration(e);const n=this.requireRegistrationRevision(e);await this.ensureReady(),this.assertCurrentRegistration(e,n);let a=!1;const h=u(()=>{a||(a=!0,this.request("tool/cancel",{invocationId:t},{timeoutMs:Math.min(r.timeoutMs??this.options.requestTimeoutMs,2e3)}).catch(()=>{}))},"cancelInvocation");let l;r.signal&&(l=h,r.signal.addEventListener("abort",l,{once:!0}));try{return await this.request("tool/call",{args:s,executorAddress:i,invocationId:t,registrationId:e},r)}catch(d){throw h(),d}finally{l&&r.signal?.removeEventListener("abort",l)}}async close(e){return this.closePromise??=this.closeInternal(e),this.closePromise}async closeInternal(e){for(const c of this.catalogTimers.values())clearTimeout(c);this.catalogTimers.clear();for(const c of this.clientRequests.values())c.controller.abort(e);for(const c of this.clientSources.values())c.release();if(this.clientSources.clear(),this.stateValue==="closed")return;const t=e??new Error("Executor supervisor is closing"),i=this.createShutdownBudget(this.options.closeTimeoutMs,this.processRuntime?.shutdownDeadlineAt),{timeoutError:s}=i;this.shutdownBudget=i,this.stateValue="closing",this.cancelFuseRecovery(t),this.shutdownController.abort(t);const r=[],n=[],a=u((c,p=r)=>{c===s&&(r.includes(s)||n.includes(s))||p.push(c)},"addFailure"),h=u(async(c,p=r)=>{const y=await this.settleWithinShutdown(c,i);y.status==="rejected"?a(y.reason,p):y.status==="timed_out"&&a(s,p)},"attempt");this.clearHealthTimer();const l=this.active,d=this.startPromise;if(this.rejectPending(t),l&&!d&&l.initialized){const c=this.gracefulCloseBudgetMs(i,l.guardian!==void 0);c>0&&await h(this.requestOnActive(l,"runtime/close",{},{signal:i.deadline.signal,timeoutMs:c}))}if(l)try{await this.terminateChild(l,i)}catch(c){a(c,n)}if(d){const c=await this.settleWithinShutdown(d,i);c.status==="rejected"?c.reason instanceof ExecutorPrivateStartupCleanupError&&r.push(...this.flattenCleanupFailure(c.reason.cleanupFailure)):c.status==="timed_out"&&a(s)}const f=await this.settleWithinShutdown(Promise.allSettled([...this.failureTasks,...this.registrationTasks.values(),...[...this.catalogRefreshes.values()].map(c=>c.promise)]),i);if(f.status==="fulfilled")for(const c of f.value)c.status==="rejected"&&r.push(c.reason);else f.status==="rejected"?r.push(f.reason):a(s);r.push(...n);const m=this.active;if(m&&(m!==l||m.child.exitCode===null&&m.child.signalCode===null))try{await this.terminateChild(m,i)}catch(c){a(c)}i.deadline.signal.aborted&&a(s),this.active=void 0,this.recoveryPromise=void 0,this.startPromise=void 0,this.registrations.clear(),this.registrationRevisions.clear(),this.registrationTasks.clear();for(const c of this.snapshots.keys())this.deleteSnapshot(c);if(this.snapshotListeners.clear(),this.stateValue="closed",this.releaseProcessShutdownListener?.(),this.releaseProcessOwnership?.(),i.deadline.close(),r.length>0){const c=r.length===1?r[0]:new AggregateError(r,"Private Executor cleanup failed"),p=m??l;throw this.recordLifecycle({component:"executor",error:c,phase:"cleanup",...p===void 0?{}:{process:{exitCode:p.child.exitCode,pid:p.child.pid,signal:p.child.signalCode}},reason:"cleanup_failed",state:"shutdown_failed"}),c}}async ensureReady(){for(;;){if(this.assertAccepting(),this.stateValue==="ready"&&this.active)return;if(this.fuseState!=="closed")throw new Error(`Executor supervisor fuse is ${this.fuseState}; recovery is pending`);const e=this.recoveryPromise;if(!e)break;await e}await this.startWithoutRecoveryWait()}async startWithoutRecoveryWait(e){this.assertAccepting();const t=[this.shutdownController.signal];this.processRuntime?.shutdownSignal&&t.push(this.processRuntime.shutdownSignal),e&&t.push(e);const i=t.length===1?t[0]:AbortSignal.any(t);if(i.aborted)throw i.reason;if(this.stateValue==="ready"&&this.active)return;const s=this.startPromise??this.startChild(i);this.startPromise=s;try{await s}finally{this.startPromise===s&&(this.startPromise=void 0)}}async startChild(e){if(this.options.containment.assertHealthy(),e?.aborted||(this.stateValue=this.stateValue==="idle"?"starting":"restarting",this.restartAttempt>0&&await this.waitForRestartBackoff(this.restartAttempt,e),this.assertAccepting(),e?.aborted))throw e.reason;const t=x(),i=this.options.spawnChild(this.options.childEntryPath,{cwd:v.dirname(this.options.childEntryPath),detached:this.options.platform!=="win32",env:this.options.environment,execArgv:[],execPath:this.options.nodeRuntime.executable,serialization:"json",stdio:["ignore","ignore","pipe","ipc"]});if(!i.pid||!i.send)throw i.kill(),new Error("Private Executor child did not expose PID and IPC");const s=i.pid;i.stderr?.resume();const r={appliedRegistrationRevisions:new Map,child:i,epoch:t,exit:i.exitCode!==null||i.signalCode!==null?Promise.resolve():new Promise(n=>{i.once("exit",()=>n())}),initialized:!1};this.active=r,i.on("message",n=>this.handleMessage(r,n)),i.once("error",n=>this.handleChildFailure(r,n)),i.once("exit",()=>this.handleChildFailure(r,new ExecutorPrivateProcessExitedError));try{if(this.options.windowsJob&&!this.options.windowsJob.isProcessInJob(s))throw new Error("Private Executor did not inherit the host Windows Job");this.options.stdioContainment==="posix_guardian"&&await w("guardianBind",async()=>{const h=await K({...this.options.stdioGuardianEntryPath===void 0?{}:{childEntryPath:this.options.stdioGuardianEntryPath},containment:this.options.containment,...e===void 0?{}:{signal:e},shutdownDeadlineAt:u(()=>this.processRuntime?.shutdownDeadlineAt,"shutdownDeadlineAt"),targetProcessGroupId:s,termTimeoutMs:this.options.termTimeoutMs});if(r.guardian=h,e?.aborted||this.isStopping())throw e?.reason??new Error("Executor supervisor is closing");await h.bindAnchor(s),r.guardianBound=!0});const n=this.proxyPolicy,a=await w("executorInitialize",()=>this.requestOnActive(r,"runtime/initialize",{allowStdio:this.options.allowStdio,proxy:n,protocolVersion:T,runtimeEpoch:t,stdioContainment:this.options.stdioContainment,...this.options.windowsJob===void 0?{}:{windowsJobAddonPath:this.options.windowsJob.addonPath},...!this.options.allowStdio||r.guardian===void 0?{}:{stdioGuardianPid:r.guardian.guardianPid},tenantId:this.options.instanceId},{...e===void 0?{}:{signal:e},timeoutMs:this.options.startTimeoutMs}));if(a.protocolVersion!==T||a.runtimeEpoch!==t||a.proxyRevision!==n.revision||(this.options.stdioContainment==="posix_guardian"?a.stdioAnchorPid===void 0||a.stdioAnchorPid<=0:a.stdioAnchorPid!==void 0))throw new ExecutorPrivateProtocolError("Private Executor initialize response did not match its epoch");r.anchorPid=a.stdioAnchorPid,r.appliedProxyRevision=a.proxyRevision,await this.reconcileProxyPolicyOnActive(r,e),r.initialized=!0,await w("registrationReconcile",()=>this.reconcileRegistrationsAndCommitReady(r,e))}catch(n){let a=!1,h;try{await this.terminateChild(r)}catch(l){a=!0,h=l}throw this.active===r&&(this.active=void 0),!this.isStopping()&&this.fuseState==="closed"&&(this.stateValue="idle"),a?(this.recordLifecycle({component:"executor",error:h,phase:"cleanup",process:{exitCode:r.child.exitCode,pid:r.child.pid,signal:r.child.signalCode},reason:"cleanup_failed",state:"shutdown_failed"}),new ExecutorPrivateStartupCleanupError(n,h)):n}}async reconcileProxyPolicy(){const e=this.active;e?.initialized!==!0||this.isStopping()||await this.reconcileProxyPolicyOnActive(e)}async reconcileProxyPolicyOnActive(e,t){for(let i=0;i<F;i+=1){if(this.active!==e||this.isStopping())return;const s=this.proxyPolicy;if(e.appliedProxyRevision===s.revision)return;const r=await this.requestOnActive(e,"runtime/proxy-configure",{proxy:s},{...t===void 0?{}:{signal:t},timeoutMs:this.options.requestTimeoutMs});if(r.proxyRevision!==s.revision)throw new ExecutorPrivateProtocolError("Private Executor proxy revision did not match its request");e.appliedProxyRevision=r.proxyRevision}throw new ExecutorPrivateProtocolError("Private Executor proxy policy did not converge")}async reconcileRegistrationsAndCommitReady(e,t){for(let i=0;i<F;i+=1){const s=new Set([...e.appliedRegistrationRevisions.keys(),...this.registrations.keys()]);for(const r of s)await this.withRegistrationLock(r,async()=>{if(this.active!==e||this.isStopping()||t?.aborted)throw t?.reason??new ExecutorPrivateProcessExitedError;const n=this.registrations.get(r),a=this.registrationRevisions.get(r),h=e.appliedRegistrationRevisions.get(r);if(n&&a!==void 0){if(h===a)return;const l=await this.requestOnActive(e,"registration/upsert",{registration:n},t===void 0?{}:{signal:t});e.appliedRegistrationRevisions.set(r,a),this.isCurrentRegistration(r,a)&&this.setSnapshot(r,l);return}h!==void 0&&(await this.requestOnActive(e,"registration/remove",{registrationId:r},t===void 0?{}:{signal:t}),e.appliedRegistrationRevisions.delete(r),this.deleteSnapshot(r))});if(this.active!==e||this.isStopping()||t?.aborted)throw t?.reason??new ExecutorPrivateProcessExitedError;if(this.registrationsConverged(e)){this.restartAttempt=0,this.stateValue="ready",this.scheduleHealthCheck(e);return}}throw new ExecutorPrivateProtocolError("Private Executor registration state did not converge during startup")}registrationsConverged(e){if(e.appliedRegistrationRevisions.size!==this.registrations.size)return!1;for(const t of this.registrations.keys()){const i=this.registrationRevisions.get(t);if(i===void 0||e.appliedRegistrationRevisions.get(t)!==i)return!1}return!0}handleMessage(e,t){if(this.active===e){if(U(t)){try{E(t,q)}catch{return}if(!V(t)||t.params.runtimeEpoch!==e.epoch)return;try{const{signal:i}=t.params;i.kind==="log"?this.options.recordEffectTelemetry?.log(i.value):i.kind==="metrics"?this.options.recordEffectTelemetry?.metrics(Object.freeze({...i.value,runtimeEpoch:e.epoch})):this.options.recordEffectTelemetry?.span(i.value)}catch{}return}try{E(t,S)}catch(i){this.failProtocol(e,new ExecutorPrivateProtocolError(`Private Executor sent an invalid or oversized IPC payload: ${g(i).message}`));return}if(B(t)){if(t.runtimeEpoch!==e.epoch)return;if(typeof t.id!="number"){this.failProtocol(e,new ExecutorPrivateProtocolError("Private Executor response used an invalid request id"));return}const i=this.pending.get(t.id);if(!i||i.epoch!==e.epoch)return;if(this.pending.delete(t.id),i.deadline.close(),"error"in t){const s=new ue(t.error.data?.code??"ExecutorPrivateError",t.error.data?.retryable,t.error.message);i.reject(s)}else{if(!D(i.method,t.result)){i.reject(new ExecutorPrivateProtocolError(`Private Executor returned an invalid ${i.method} result`)),this.failProtocol(e,new ExecutorPrivateProtocolError("Private Executor response violated its method contract"));return}i.resolve(t.result)}return}if(I(t)){if(t.params.runtimeEpoch!==e.epoch)return;if(t.method==="client-mcp/cancel")this.clientRequests.get(t.params.requestId)?.controller.abort(new Error("MCP request cancelled"));else for(const i of this.registrations.values())i.executorSlug===t.params.integration&&i.connectionName===t.params.connection&&this.invalidateCatalog(i.registrationId);return}if(N(t)){if(t.params.runtimeEpoch!==e.epoch)return;this.handleReverseRequest(e,t);return}this.failProtocol(e,new ExecutorPrivateProtocolError("Private Executor sent an unknown IPC message"))}}async handleClientMcpRequest(e,t){const i=new AbortController;try{const s=this.clientSources.get(t.params.sourceId)?.source;if(!s||this.clientRequests.size>=this.options.maxPendingRequests||this.clientRequests.has(t.id)||![...this.registrations.values()].some(n=>n.transport.transport==="client"&&n.transport.sourceId===t.params.sourceId))throw new Error("Client MCP source unavailable");this.clientRequests.set(t.id,{sourceId:t.params.sourceId,epoch:e.epoch,controller:i});const r=await s.request(t.params.method,t.params.params,i.signal);if(this.active!==e||i.signal.aborted)return;await this.send(e,{id:t.id,jsonrpc:"2.0",result:r,runtimeEpoch:e.epoch})}catch{await this.send(e,{id:t.id,jsonrpc:"2.0",error:{code:-32e3,message:"Client MCP request failed"},runtimeEpoch:e.epoch}).catch(()=>{})}finally{this.clientRequests.delete(t.id)}}async handleReverseRequest(e,t){if(t.method==="client-mcp/request")return this.handleClientMcpRequest(e,t);try{const i=t.trace===void 0?void 0:j(t.trace),s=await C(i,()=>this.options.onElicitation({invocationId:t.params.invocationId,request:t.params.request,runtimeEpoch:e.epoch}));await this.send(e,{id:t.id,jsonrpc:"2.0",result:s,runtimeEpoch:e.epoch})}catch{await this.send(e,{error:{code:-32e3,message:"Elicitation was cancelled"},id:t.id,jsonrpc:"2.0",runtimeEpoch:e.epoch}).catch(()=>{})}}failProtocol(e,t){this.handleChildFailure(e,t)}handleChildFailure(e,t){if(this.active!==e)return;this.active=void 0;for(const n of this.clientRequests.values())n.epoch===e.epoch&&n.controller.abort(t);if(this.clearHealthTimer(),this.rejectPending(t,e.epoch),this.stateValue==="closing"||this.stateValue==="closed")return;const i=g(t);if(this.fuseState==="half_open"){const n=this.recordHalfOpenFailure(e,i).catch(()=>{});this.failureTasks.add(n),n.finally(()=>this.failureTasks.delete(n)).catch(()=>{}),this.reportFailure(i);return}this.stateValue="idle";const r=this.finishChildFailure(e,i).catch(n=>this.reportFailure(g(n))).catch(()=>{}).then(()=>{});this.recoveryPromise=r,this.failureTasks.add(r),r.then(()=>{this.failureTasks.delete(r),this.recoveryPromise===r&&(this.recoveryPromise=void 0,this.fuseRecoveryController=void 0)}).catch(()=>{}),this.reportFailure(i)}async finishChildFailure(e,t){const i=this.readPolicyNow();for(this.crashTimes.push(i);this.crashTimes.length>0&&this.crashTimes[0]<i-this.options.crashWindowMs;)this.crashTimes.shift();const s=this.crashTimes.length>this.options.maxCrashes;s?this.openFuse(e.epoch,t,e):(this.restartAttempt+=1,this.stateValue="idle",this.publishUnavailable(e.epoch,!1),this.registrations.size>0&&this.recordLifecycle({component:"executor",counts:{attempt:this.restartAttempt,failuresInWindow:this.crashTimes.length},error:t,phase:"recovery",process:{exitCode:e.child.exitCode,pid:e.child.pid,signal:e.child.signalCode},reason:t instanceof ExecutorPrivateProcessExitedError?"process_exit":t instanceof ExecutorPrivateProtocolError?"protocol_error":"process_error",state:"restarting"}));const r=s?new AbortController:void 0;r&&(this.fuseRecoveryController=r),await this.recoverAfterChildFailure(e,s,r)}async recordHalfOpenFailure(e,t){const i=this.readPolicyNow();for(this.crashTimes.push(i);this.crashTimes.length>0&&this.crashTimes[0]<i-this.options.crashWindowMs;)this.crashTimes.shift();this.openFuse(e.epoch,t,e)}async recoverAfterChildFailure(e,t,i){try{await this.terminateChild(e)}catch(r){throw this.recordLifecycle({component:"executor",error:r,phase:"cleanup",process:{exitCode:e.child.exitCode,pid:e.child.pid,signal:e.child.signalCode},reason:"cleanup_failed",state:"shutdown_failed"}),r}const s=this.startPromise;if(s&&await s.catch(()=>{}),this.isStopping()||this.registrations.size===0){t&&!this.isStopping()&&this.closeUnusedFuse();return}if(!t){await this.startWithoutRecoveryWait();return}if(!i)throw new Error("Executor fuse recovery omitted its controller");await this.recoverOpenFuse(i.signal)}async recoverOpenFuse(e){let t=e;for(;!this.isStopping();){if(t.aborted){const i=this.renewFuseRecoveryAfterCancellation(t);if(!i)return;t=i}if(this.registrations.size===0){this.closeUnusedFuse();return}this.fuseState="open",this.stateValue="failed";try{await this.waitForRestartBackoff(Math.max(1,this.fuseOpenAttempt),t)}catch(i){if(t.aborted){const s=this.renewFuseRecoveryAfterCancellation(t);if(!s)return;t=s;continue}if(this.isStopping())return;throw i}if(this.isStopping()||this.registrations.size===0){this.registrations.size===0&&!this.isStopping()&&this.closeUnusedFuse();return}this.fuseState="half_open",this.stateValue="restarting";try{if(await this.startWithoutRecoveryWait(t),this.fuseState==="half_open"&&this.state==="ready"&&this.active){this.closeFuse();return}this.fuseState==="half_open"&&this.openFuse()}catch(i){if(t.aborted){const s=this.renewFuseRecoveryAfterCancellation(t);if(!s)return;t=s;continue}if(this.isStopping())return;this.fuseState==="half_open"&&this.openFuse(),this.reportFailure(g(i))}}}renewFuseRecoveryAfterCancellation(e){if(this.isStopping())return;if(this.registrations.size===0){this.closeUnusedFuse();return}const t=this.fuseRecoveryController;if(t&&t.signal!==e&&!t.signal.aborted)return t.signal;const i=new AbortController;return this.fuseRecoveryController=i,i.signal}openFuse(e,t,i){const s=this.fuseState!=="open";this.fuseState!=="open"&&(this.fuseOpenAttempt+=1),this.fuseState="open",this.stateValue="failed",this.publishUnavailable(e,!0),s&&this.recordLifecycle({component:"executor",counts:{attempt:this.fuseOpenAttempt,failuresInWindow:this.crashTimes.length},...t===void 0?{}:{error:t},phase:"recovery",...i===void 0?{}:{process:{exitCode:i.child.exitCode,pid:i.child.pid,signal:i.child.signalCode}},reason:t instanceof ExecutorPrivateProcessExitedError?"process_exit":t instanceof ExecutorPrivateProtocolError?"protocol_error":"recovery_failed",state:"fused"})}closeFuse(){this.fuseState="closed",this.fuseOpenAttempt=0,this.crashTimes.length=0,this.restartAttempt=0,this.stateValue="ready"}closeUnusedFuse(){this.fuseState="closed",this.fuseOpenAttempt=0,this.crashTimes.length=0,this.restartAttempt=0,this.stateValue="idle"}cancelFuseRecovery(e){this.fuseRecoveryController?.abort(e)}publishUnavailable(e,t){for(const[i,s]of this.snapshots)this.setSnapshot(i,{error:{code:t?"executor_failed":"executor_restarting",message:t?"MCP runtime exceeded its restart limit; recovery is pending":"MCP runtime is restarting",retryable:!0},generation:s.generation+1,registrationId:i,runtimeEpoch:e??s.runtimeEpoch,status:"unavailable",tools:[]})}setSnapshot(e,t){this.snapshots.set(e,t),this.scheduleCatalogRefresh(e),this.publishSnapshot(e,t)}deleteSnapshot(e){clearTimeout(this.catalogTimers.get(e)),this.catalogTimers.delete(e),this.snapshots.delete(e)&&this.publishSnapshot(e,void 0)}publishSnapshot(e,t){for(const i of this.snapshotListeners)try{i(e,t)}catch{}}request(e,t,i){const s=this.active;return!s||this.stateValue!=="ready"?Promise.reject(new Error("Private Executor is not ready")):this.requestOnActive(s,e,t,i)}scheduleHealthCheck(e){if(this.clearHealthTimer(),this.options.healthIntervalMs===0)return;const t=new AbortController,i={close:u(()=>t.abort(new Error("Executor health delay completed")),"close")};this.healthTimer=i,C(void 0,()=>{this.waitForPolicyDelay(this.options.healthIntervalMs,t.signal,"Executor health delay cancelled").then(()=>{if(this.healthTimer===i)return this.healthTimer=void 0,this.checkHealth(e)}).catch(s=>{this.healthTimer===i&&(this.healthTimer=void 0),!t.signal.aborted&&!this.isStopping()&&this.failProtocol(e,g(s))})})}async checkHealth(e){if(!(this.active!==e||this.stateValue!=="ready")){try{const t=await this.requestOnActive(e,"runtime/health",{},{timeoutMs:this.options.healthTimeoutMs});if(t.status!=="ready"||t.runtimeEpoch!==e.epoch||t.stdioAnchorPid!==e.anchorPid)throw new ExecutorPrivateProtocolError("Private Executor health response did not match its epoch")}catch(t){this.active===e&&!this.isStopping()&&this.failProtocol(e,g(t));return}this.active===e&&this.stateValue==="ready"&&this.scheduleHealthCheck(e)}}clearHealthTimer(){this.healthTimer&&(this.healthTimer.close(),this.healthTimer=void 0)}requestOnActive(e,t,i,s={}){if(s.signal?.aborted)return Promise.reject(s.signal.reason);if(this.pending.size>=this.options.maxPendingRequests)return Promise.reject(new ExecutorPrivateOverloadedError);const r=this.nextRequestId++,n=H(),a={id:r,jsonrpc:"2.0",method:t,params:i,...n===void 0?{}:{trace:n}},h=s.timeoutMs??this.options.requestTimeoutMs;return new Promise((l,d)=>{const f=this.createPolicyDeadline(h,s.signal===void 0?[]:[s.signal],new Error(`Private Executor ${t} timed out after ${h}ms`)),m=u(()=>{const c=this.pending.get(r);c&&(this.pending.delete(r),f.close(),c.reject(f.signal.reason))},"onAbort");f.signal.addEventListener("abort",m,{once:!0}),this.pending.set(r,{deadline:f,epoch:e.epoch,method:t,reject:u(c=>{f.signal.removeEventListener("abort",m),d(c)},"reject"),resolve:u(c=>{f.signal.removeEventListener("abort",m),l(c)},"resolve")}),this.send(e,a).catch(c=>{const p=this.pending.get(r);p&&(this.pending.delete(r),f.close(),p.reject(c))})})}send(e,t){const{bytes:i}=E(t,S);return this.pendingSends>=this.options.maxPendingRequests||this.pendingSendBytes+i>this.options.maxPendingRequestBytes?Promise.reject(new ExecutorPrivateOverloadedError):this.active!==e||!e.child.connected||!e.child.send?Promise.reject(new ExecutorPrivateProcessExitedError):(this.pendingSends+=1,this.pendingSendBytes+=i,new Promise((s,r)=>{let n=!1;const a=u(h=>{n||(n=!0,this.pendingSends-=1,this.pendingSendBytes-=i,h?r(h):s())},"finish");try{e.child.send?.(t,h=>a(h))}catch(h){a(g(h))}}))}rejectPending(e,t){for(const[i,s]of this.pending)t!==void 0&&s.epoch!==t||(this.pending.delete(i),s.deadline.close(),s.reject(e))}terminateChild(e,t=this.shutdownBudget){if(e.terminationPromise)return e.terminationPromise;const i=t===void 0,s=t??this.createShutdownBudget(Math.min(Number.MAX_SAFE_INTEGER,this.options.termTimeoutMs*2));return e.terminationPromise=this.terminateChildOnce(e,s).finally(()=>{i&&s.deadline.close()}),e.terminationPromise}async terminateChildOnce(e,t){let i=!1,s;if(e.guardian){const n=this.remainingBeforeHandleReleaseReserve(t),a=Date.now()+n;try{await e.guardian.close({deadlineAt:a})}catch(h){i=!0,s=h}if(!i&&(e.guardianBound===!0||e.anchorPid!==void 0)){if(await this.waitForChildExit(e,this.remainingBeforeKillReserve(t)))return;const h=new Error("Private Executor did not exit after guardian cleanup");this.options.containment.trip(h);const l=[h];try{await this.terminateWithSignals(e,!0,t)}catch(d){l.push(...this.flattenCleanupFailure(d))}this.throwCleanupFailures(l,"Private Executor guardian cleanup did not reap its child")}}if(e.child.exitCode!==null||e.child.signalCode!==null){if(i)throw s;return}const r=[];i&&r.push(s);try{await this.terminateWithSignals(e,e.guardian!==void 0||this.options.allowStdio&&this.options.platform!=="win32",t)}catch(n){r.push(...this.flattenCleanupFailure(n))}this.throwCleanupFailures(r,"Private Executor guardian and child cleanup failed")}async terminateWithSignals(e,t,i){const s=[];try{e.child.disconnect?.()}catch(r){s.push(r)}for(const r of["SIGTERM","SIGKILL"]){if(e.child.exitCode!==null||e.child.signalCode!==null)break;const n=r==="SIGTERM"?this.remainingBeforeKillReserve(i):this.remainingBeforeHandleReleaseReserve(i);try{if(await this.killAndWait(e,r,n,t))break}catch(a){s.push(a)}}if(e.child.exitCode===null&&e.child.signalCode===null){const r=new Error("Private Executor process cleanup timed out");this.options.containment.trip(r),s.push(r);try{this.releaseChildHandles(e)}catch(n){s.push(...this.flattenCleanupFailure(n))}}this.throwCleanupFailures(s,"Private Executor child cleanup failed")}async killAndWait(e,t,i,s=!1){let r,n=!1;try{s||this.options.platform==="win32"?n=!e.child.kill(t):e.child.pid?process.kill(-e.child.pid,t):r=new Error(`Private Executor child has no PID for ${t}`)}catch(h){J(h)||(r=h)}const a=await this.waitForChildExit(e,i)||e.child.exitCode!==null||e.child.signalCode!==null;if(r!==void 0)throw r;if(n&&!a)throw new Error(`Private Executor child refused ${t}`);return a}async waitForChildExit(e,t){if(e.child.exitCode!==null||e.child.signalCode!==null)return!0;if(t<=0)return!1;let i;return Promise.race([e.exit.then(()=>!0),new Promise(s=>{i=setTimeout(()=>s(!1),t),i.unref?.()})]).finally(()=>{i&&clearTimeout(i)})}releaseChildHandles(e){const t=[],i=u(s=>{try{s()}catch(r){t.push(r)}},"attempt");e.child.connected&&i(()=>e.child.disconnect?.()),i(()=>e.child.channel?.unref()),i(()=>e.child.stdin?.destroy()),i(()=>e.child.stdout?.destroy()),i(()=>e.child.stderr?.destroy()),i(()=>e.child.unref()),this.throwCleanupFailures(t,"Private Executor child handles could not be released")}flattenCleanupFailure(e){return e instanceof AggregateError?e.errors:[e]}throwCleanupFailures(e,t){if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,t)}assertCurrentRegistration(e,t){if(!this.isCurrentRegistration(e,t))throw new Error(`MCP registration "${e}" was superseded`)}isCurrentRegistration(e,t){return this.registrations.has(e)&&this.isCurrentRegistrationRevision(e,t)}isCurrentRegistrationRevision(e,t){return this.registrationRevisions.get(e)===t}requireRegistration(e){const t=this.registrations.get(e);if(!t)throw new Error(`Unknown MCP registration "${e}"`);return t}requireRegistrationRevision(e){const t=this.registrationRevisions.get(e);if(t===void 0)throw new Error(`Unknown MCP registration "${e}"`);return t}async withRegistrationLock(e,t){const i=this.registrationTasks.get(e);let s;const r=new Promise(n=>{s=n});this.registrationTasks.set(e,r),i&&await i;try{return await t()}finally{s(),this.registrationTasks.get(e)===r&&this.registrationTasks.delete(e)}}createShutdownBudget(e,t){const i=Date.now(),s=i+e,r=t===void 0?s:Math.min(s,t),n=Math.max(1,Math.ceil(r-i)),a=new ExecutorPrivateShutdownTimeoutError(n);return{deadlineAt:r,deadline:R(n,[],a),timeoutError:a}}gracefulCloseBudgetMs(e,t=!1){if(!t)return this.remainingBeforeKillReserve(e);const i=this.remainingShutdownMs(e),s=Math.min(i,this.options.termTimeoutMs+se);return Math.max(0,i-s)}remainingBeforeKillReserve(e){const t=this.remainingShutdownMs(e);if(t<=1)return 0;const i=Math.min(this.options.termTimeoutMs,Math.max(1,Math.ceil(t/2)));return Math.max(0,t-i)}remainingBeforeHandleReleaseReserve(e){const t=this.remainingShutdownMs(e);if(t<=1)return 0;const i=Math.min(10,Math.max(1,Math.ceil(t/10)));return Math.max(0,t-i)}remainingShutdownMs(e){return Math.max(0,Math.ceil(e.deadlineAt-Date.now()))}async settleWithinShutdown(e,t,i=this.remainingShutdownMs(t)){const s=Math.min(this.remainingShutdownMs(t),Math.max(0,i));if(s<=0||t.deadline.signal.aborted)return e.catch(()=>{}),{status:"timed_out"};const r=R(s,[t.deadline.signal],t.timeoutError);return new Promise(n=>{let a=!1;const h=u(d=>{a||(a=!0,r.signal.removeEventListener("abort",l),r.close(),n(d))},"finish"),l=u(()=>h({status:"timed_out"}),"onAbort");if(r.signal.addEventListener("abort",l,{once:!0}),r.signal.aborted){l(),e.catch(()=>{});return}e.then(d=>h({status:"fulfilled",value:d}),d=>h({reason:d,status:"rejected"}))})}createPolicyDeadline(e,t,i){return this.processRuntime?.createPolicyDeadline(e,{signals:t,timeoutReason:i})??R(e,t,i)}readPolicyNow(){return this.processRuntime?.policyNow()??Date.now()}waitForPolicyDelay(e,t,i){return this.processRuntime?.policyDelay(e,t,i)??L(e,t)}waitForRestartBackoff(e,t){const i=t??new AbortController().signal;return this.processRuntime?this.processRuntime.policyBackoff(this.options.restartBackoffMs,e,b,i,"Executor restart backoff cancelled"):L(Math.min(b,this.options.restartBackoffMs*2**(e-1)),i)}assertAccepting(){if(this.stateValue==="closing"||this.stateValue==="closed")throw new Error(`Executor supervisor is ${this.stateValue}`);this.options.containment.assertHealthy()}isStopping(){return this.stateValue==="closing"||this.stateValue==="closed"}reportFailure(e){Promise.resolve().then(()=>this.options.onFailure?.(e)).catch(()=>{})}recordLifecycle(e){try{this.options.recordLifecycle?.(e)}catch{}}}
|
|
1
|
+
var O=Object.defineProperty;var u=(o,e)=>O(o,"name",{value:e,configurable:!0});import{fork as k,spawn as P}from"node:child_process";import{randomUUID as x}from"node:crypto";import v from"node:path";import{EXECUTOR_PRIVATE_MAX_MESSAGE_BYTES as S,EXECUTOR_PRIVATE_MAX_TELEMETRY_MESSAGE_BYTES as q,EXECUTOR_PRIVATE_PROTOCOL_VERSION as T,isExecutorPrivateCatalogNotification as I,isExecutorPrivateResponse as B,isExecutorPrivateResult as D,isExecutorPrivateReverseRequest as N,isExecutorPrivateTelemetryNotification as V,isExecutorPrivateTelemetryNotificationCandidate as U}from"#agent-harness-executor/private-protocol";import{currentHarnessTraceCarrier as H,parseHarnessTraceCarrier as j,withHarnessTraceContext as C}from"#agent-harness-executor/trace-context";import{DEFAULT_MCP_TOOLS_SYNC_TTL_MS as z}from"#agent-harness-executor/types";import{maybeCurrentHarnessProcessRuntime as W}from"../effect-runtime/process-runtime-context.js";import{normalizeError as g}from"../internal/errors.js";import{boundedStringifyJson as E}from"../protocol/bounded-json.js";import{applyNodeRuntimeEnvironment as G,resolveNodeRuntimeLaunch as M}from"../runtime/node-runtime.js";import{AGENT_HARNESS_PRIVATE_RUNTIME_ROLE as _,createPrivateRuntimeLaunchSpec as A,isAgentHarnessStandaloneBinary as X}from"../runtime/private-runtime-role.js";import{CodeBuddyProcessContainment as $}from"../runtime/process-containment.js";import{isMissingProcess as J}from"../runtime/process-tree.js";import{assertAgentHarnessProcessContainment as Y}from"../runtime/sfe-process-containment.js";import{measure as w}from"../telemetry/index.js";import{attachPosixStdioMcpGuardian as K,resolveStdioMcpContainment as Q}from"./stdio-guardian.js";const Z=3e4,ee=15e3,te=5e3,ie=3e3,se=1e3,re=1e4,ne=3e3,oe=1024,ae=8*1024*1024,he=5,ce=6e4,le=100,b=5e3,F=16;export class ExecutorPrivateProcessExitedError extends Error{static{u(this,"ExecutorPrivateProcessExitedError")}constructor(){super("Private Executor child exited unexpectedly"),this.name="ExecutorPrivateProcessExitedError"}}export class ExecutorPrivateProtocolError extends Error{static{u(this,"ExecutorPrivateProtocolError")}constructor(e){super(e),this.name="ExecutorPrivateProtocolError"}}export class ExecutorPrivateOverloadedError extends Error{static{u(this,"ExecutorPrivateOverloadedError")}constructor(){super("Private Executor IPC queue is overloaded"),this.name="ExecutorPrivateOverloadedError"}}class ue extends Error{static{u(this,"ExecutorPrivateOperationError")}constructor(e,t,i){super(i),this.code=e,this.retryable=t,this.name=e}}export class ExecutorPrivateStartupCleanupError extends AggregateError{static{u(this,"ExecutorPrivateStartupCleanupError")}constructor(e,t){super([e,t],"Private Executor startup and cleanup both failed"),this.startupFailure=e,this.cleanupFailure=t,this.name="ExecutorPrivateStartupCleanupError"}}export class ExecutorPrivateShutdownTimeoutError extends Error{static{u(this,"ExecutorPrivateShutdownTimeoutError")}constructor(e){super(`Private Executor cleanup timed out after ${e}ms`),this.timeoutMs=e,this._tag="ExecutorPrivateShutdownTimeoutError",this.name=this._tag}}function de(){return X()?process.execPath:v.resolve(import.meta.dirname,"../../executor/lib/capsule/entry.mjs")}u(de,"defaultChildEntryPath");const fe=Object.freeze(["ALL_PROXY","HTTP_PROXY","HTTPS_PROXY","LANG","LC_ALL","NODE_EXTRA_CA_CERTS","NODE_NO_WARNINGS","NO_PROXY","PATH","SSL_CERT_DIR","SSL_CERT_FILE","SystemRoot","TEMP","TMP","TMPDIR","TZ","WINDIR","http_proxy","https_proxy","all_proxy","no_proxy"]);function pe(o){const e=u(n=>{const a=n?.trim();if(a)try{const h=new URL(a.includes("://")?a:`http://${a}`);return h.protocol==="http:"||h.protocol==="https:"?h.toString():void 0}catch{return}},"normalize"),t=e(o.ALL_PROXY??o.all_proxy),i=e(o.HTTP_PROXY??o.http_proxy??t),s=e(o.HTTPS_PROXY??o.https_proxy??t??i),r=[...new Set([...(o.NO_PROXY??o.no_proxy??"").split(",").map(n=>n.trim()).filter(Boolean),"localhost","127.0.0.1","::1"])];return Object.freeze({...i===void 0?{}:{httpProxyUrl:i},...s===void 0?{}:{httpsProxyUrl:s},mode:"auto",noProxy:Object.freeze(r),revision:"environment"})}u(pe,"defaultExecutorProxyPolicy");export function createExecutorChildEnvironment(o=process.env,e=M()){const t={AGENT_HARNESS_PRIVATE_EXECUTOR:"1"};for(const i of fe){const s=o[i];s!==void 0&&(t[i]=s)}return G(t,e)}u(createExecutorChildEnvironment,"createExecutorChildEnvironment");export function createExecutorWindowsSpawnSpec(o,e){const{execArgv:t=process.execArgv,execPath:i=process.execPath,silent:s,...r}=e,a=A({entryPath:o,nodeRuntime:{environment:{},executable:i},role:_.executor}),h=a.args[0]===o;return{...{args:Object.freeze([...h?t:[],...a.args]),command:a.command},options:{...r,env:{...r.env},windowsHide:!0}}}u(createExecutorWindowsSpawnSpec,"createExecutorWindowsSpawnSpec");function me(o,e){Y();const t=createExecutorWindowsSpawnSpec(o,e);return P(t.command,[...t.args],t.options)}u(me,"spawnExecutorChildOnWindows");function ge(o,e,t,i){if(t==="win32")return me(o,e);const s=A({entryPath:o,nodeRuntime:i,role:_.executor});if(s.args[0]===o)return k(o,[],e);const{execArgv:r,execPath:n,silent:a,...h}=e;return P(s.command,[...s.args],h)}u(ge,"spawnExecutorChild");function we(o){const e=u((a,h,l)=>{const d=a??h;if(!Number.isSafeInteger(d)||d<=0)throw new RangeError(`${l} must be a positive integer`);return d},"positive"),t=u((a,h,l)=>{const d=a??h;if(!Number.isSafeInteger(d)||d<0)throw new RangeError(`${l} must be a non-negative integer`);return d},"nonNegative"),i=o.platform??process.platform,s=Q({platform:i,requested:o.allowStdio??!0,windowsProcessContainmentEnabled:o.windowsProcessContainmentEnabled,windowsJob:o.windowsJob}),r=o.nodeRuntime??M(),n=createExecutorChildEnvironment(o.environment,r);return{allowStdio:s.allowStdio,childEntryPath:o.childEntryPath??de(),closeTimeoutMs:e(o.closeTimeoutMs,te,"closeTimeoutMs"),containment:o.containment??new $,crashWindowMs:e(o.crashWindowMs,ce,"crashWindowMs"),environment:n,healthIntervalMs:t(o.healthIntervalMs,re,"healthIntervalMs"),healthTimeoutMs:e(o.healthTimeoutMs,ne,"healthTimeoutMs"),instanceId:o.instanceId??x(),maxCrashes:e(o.maxCrashes,he,"maxCrashes"),maxPendingRequestBytes:e(o.maxPendingRequestBytes,ae,"maxPendingRequestBytes"),maxPendingRequests:e(o.maxPendingRequests,oe,"maxPendingRequests"),nodeRuntime:r,toolsSyncTtlMs:o.toolsSyncTtlMs===null?null:e(o.toolsSyncTtlMs,z,"toolsSyncTtlMs"),onElicitation:o.onElicitation,...o.onFailure===void 0?{}:{onFailure:o.onFailure},platform:i,proxyPolicy:o.proxyPolicy??pe(n),...o.recordLifecycle===void 0?{}:{recordLifecycle:o.recordLifecycle},...o.recordEffectTelemetry===void 0?{}:{recordEffectTelemetry:o.recordEffectTelemetry},requestTimeoutMs:e(o.requestTimeoutMs,Z,"requestTimeoutMs"),restartBackoffMs:e(o.restartBackoffMs,le,"restartBackoffMs"),spawnChild:o.spawnChild??((a,h)=>ge(a,h,i,r)),startTimeoutMs:e(o.startTimeoutMs,ee,"startTimeoutMs"),...o.stdioGuardianEntryPath===void 0?{}:{stdioGuardianEntryPath:o.stdioGuardianEntryPath},stdioContainment:s.mode,...s.mode==="windows_native_job_object"?{windowsJob:s.windowsJob}:{},termTimeoutMs:e(o.termTimeoutMs,ie,"termTimeoutMs")}}u(we,"resolveOptions");function L(o,e){return e?.aborted?Promise.reject(e.reason):new Promise((t,i)=>{let s=!1;const r=u(h=>{s||(s=!0,clearTimeout(a),e?.removeEventListener("abort",n),h===void 0?t():i(h))},"finish"),n=u(()=>r(e?.reason),"onAbort"),a=setTimeout(()=>r(),o);a.unref?.(),e?.addEventListener("abort",n,{once:!0})})}u(L,"standaloneDelay");function R(o,e,t){const i=new AbortController,s=setTimeout(()=>i.abort(t),o);s.unref?.();const r=AbortSignal.any([...e,i.signal]),n=[];let a=!1;const h=u(()=>{if(!a){a=!0,clearTimeout(s);for(const[l,d]of n)l.removeEventListener("abort",d);n.length=0}},"close");for(const l of e)n.push([l,h]),l.addEventListener("abort",h,{once:!0});return Object.freeze({close:h,signal:r})}u(R,"standaloneDeadline");export class ExecutorProcessSupervisor{static{u(this,"ExecutorProcessSupervisor")}registerClientSource(e,t){if(this.assertAccepting(),this.clientSources.has(e))throw new Error("Duplicate Client MCP source");const i=t.subscribe(()=>{for(const s of this.registrations.values())s.transport.transport==="client"&&s.transport.sourceId===e&&this.invalidateCatalog(s.registrationId)});return this.clientSources.set(e,{source:t,release:i}),()=>{if(this.clientSources.get(e)?.source===t){this.clientSources.delete(e),i();for(const r of this.clientRequests.values())r.sourceId===e&&r.controller.abort(new Error("Client MCP source closed"))}}}invalidateCatalog(e){if(this.isStopping()||!this.registrations.has(e))return;const t=this.catalogRefreshes.get(e);if(t){t.dirty=!0;return}const i={dirty:!0,promise:Promise.resolve()};i.promise=Promise.resolve().then(async()=>{do{if(i.dirty=!1,this.isStopping()||!this.registrations.has(e))return;await this.refreshRegistration(e)}while(i.dirty)}).catch(()=>{}).finally(()=>{this.catalogRefreshes.delete(e),this.scheduleCatalogRefresh(e)}),this.catalogRefreshes.set(e,i)}scheduleCatalogRefresh(e){if(clearTimeout(this.catalogTimers.get(e)),this.catalogTimers.delete(e),this.isStopping()||!this.registrations.has(e)||this.options.toolsSyncTtlMs===null)return;const t=setTimeout(()=>{this.catalogTimers.delete(e),this.invalidateCatalog(e)},Math.min(this.options.toolsSyncTtlMs,2147483647));t.unref(),this.catalogTimers.set(e,t)}constructor(e){if(this.crashTimes=[],this.failureTasks=new Set,this.fuseOpenAttempt=0,this.fuseState="closed",this.nextRequestId=1,this.nextRegistrationRevision=1,this.pending=new Map,this.pendingSendBytes=0,this.pendingSends=0,this.proxyTask=Promise.resolve(),this.registrationRevisions=new Map,this.registrationTasks=new Map,this.restartAttempt=0,this.shutdownController=new AbortController,this.registrations=new Map,this.snapshots=new Map,this.clientSources=new Map,this.clientRequests=new Map,this.catalogTimers=new Map,this.catalogRefreshes=new Map,this.snapshotListeners=new Set,this.stateValue="idle",this.options=we(e),this.proxyPolicy=this.options.proxyPolicy,this.processRuntime=e.processRuntime??W(),this.processRuntime===void 0&&process.env.NODE_ENV!=="test")throw new Error("Executor supervisor requires the process-owned Effect runtime");this.releaseProcessOwnership=this.processRuntime?.addFinalizer(()=>this.close(new Error("Agent Harness process runtime is closing")));const t=this.processRuntime?.shutdownSignal;if(t){const i=u(()=>{this.close(t.reason).catch(()=>{})},"onProcessShutdown");t.addEventListener("abort",i,{once:!0}),this.releaseProcessShutdownListener=()=>t.removeEventListener("abort",i)}}get runtimeEpoch(){return this.active?.epoch}get state(){return this.stateValue}async start(){await this.ensureReady()}async configureProxy(e){this.assertAccepting(),this.proxyPolicy=e;const t=this.proxyTask.then(()=>this.reconcileProxyPolicy());this.proxyTask=t.catch(()=>{}),await t}subscribeSnapshots(e){return this.snapshotListeners.add(e),()=>this.snapshotListeners.delete(e)}async upsertRegistration(e,t){this.assertAccepting();const i=this.nextRegistrationRevision++;this.registrations.set(e.registrationId,e),this.registrationRevisions.set(e.registrationId,i);try{return await this.ensureReady(),await this.withRegistrationLock(e.registrationId,async()=>{if(this.assertCurrentRegistration(e.registrationId,i),t?.signal?.aborted)throw t.signal.reason;const s=this.active,r=this.snapshots.get(e.registrationId);if(this.stateValue==="ready"&&s?.initialized===!0&&s.child.connected&&s.child.exitCode===null&&s.child.signalCode===null&&s.appliedRegistrationRevisions.get(e.registrationId)===i&&r?.status==="available"&&r?.registrationId===e.registrationId&&r?.runtimeEpoch===s.epoch)return r;const n=await w("registrationReconcile",()=>this.request("registration/upsert",{registration:e},t));return this.assertCurrentRegistration(e.registrationId,i),this.setSnapshot(e.registrationId,n),n})}catch(s){throw this.isCurrentRegistration(e.registrationId,i)&&this.deleteSnapshot(e.registrationId),s}}async refreshRegistration(e,t){this.requireRegistration(e);const i=this.requireRegistrationRevision(e);return await this.ensureReady(),this.withRegistrationLock(e,async()=>{this.assertCurrentRegistration(e,i);const s=await this.request("registration/refresh",{registrationId:e},t);return this.assertCurrentRegistration(e,i),this.setSnapshot(e,s),s})}getSnapshot(e){return this.snapshots.get(e)}async removeRegistration(e,t){const i=this.nextRegistrationRevision++;this.registrations.delete(e),this.registrationRevisions.set(e,i),this.deleteSnapshot(e),this.registrations.size===0&&this.cancelFuseRecovery(new Error("Executor fuse recovery is no longer needed")),!(this.stateValue==="closed"||this.stateValue==="closing")&&(await this.withRegistrationLock(e,async()=>{if(!this.isCurrentRegistrationRevision(e,i)||this.isStopping())return;const s=this.active;if(s?.initialized)try{await this.requestOnActive(s,"registration/remove",{registrationId:e},t),s.appliedRegistrationRevisions.delete(e)}catch(r){if(this.active===s&&!this.isStopping())throw this.handleChildFailure(s,r),r}}),this.isCurrentRegistrationRevision(e,i)&&(this.deleteSnapshot(e),this.registrationRevisions.delete(e)))}async callTool(e,t,i,s,r={}){this.requireRegistration(e);const n=this.requireRegistrationRevision(e);await this.ensureReady(),this.assertCurrentRegistration(e,n);let a=!1;const h=u(()=>{a||(a=!0,this.request("tool/cancel",{invocationId:t},{timeoutMs:Math.min(r.timeoutMs??this.options.requestTimeoutMs,2e3)}).catch(()=>{}))},"cancelInvocation");let l;r.signal&&(l=h,r.signal.addEventListener("abort",l,{once:!0}));try{return await this.request("tool/call",{args:s,executorAddress:i,invocationId:t,registrationId:e},r)}catch(d){throw h(),d}finally{l&&r.signal?.removeEventListener("abort",l)}}async close(e){return this.closePromise??=this.closeInternal(e),this.closePromise}async closeInternal(e){for(const c of this.catalogTimers.values())clearTimeout(c);this.catalogTimers.clear();for(const c of this.clientRequests.values())c.controller.abort(e);for(const c of this.clientSources.values())c.release();if(this.clientSources.clear(),this.stateValue==="closed")return;const t=e??new Error("Executor supervisor is closing"),i=this.createShutdownBudget(this.options.closeTimeoutMs,this.processRuntime?.shutdownDeadlineAt),{timeoutError:s}=i;this.shutdownBudget=i,this.stateValue="closing",this.cancelFuseRecovery(t),this.shutdownController.abort(t);const r=[],n=[],a=u((c,p=r)=>{c===s&&(r.includes(s)||n.includes(s))||p.push(c)},"addFailure"),h=u(async(c,p=r)=>{const y=await this.settleWithinShutdown(c,i);y.status==="rejected"?a(y.reason,p):y.status==="timed_out"&&a(s,p)},"attempt");this.clearHealthTimer();const l=this.active,d=this.startPromise;if(this.rejectPending(t),l&&!d&&l.initialized){const c=this.gracefulCloseBudgetMs(i,l.guardian!==void 0);c>0&&await h(this.requestOnActive(l,"runtime/close",{},{signal:i.deadline.signal,timeoutMs:c}))}if(l)try{await this.terminateChild(l,i)}catch(c){a(c,n)}if(d){const c=await this.settleWithinShutdown(d,i);c.status==="rejected"?c.reason instanceof ExecutorPrivateStartupCleanupError&&r.push(...this.flattenCleanupFailure(c.reason.cleanupFailure)):c.status==="timed_out"&&a(s)}const f=await this.settleWithinShutdown(Promise.allSettled([...this.failureTasks,...this.registrationTasks.values(),...[...this.catalogRefreshes.values()].map(c=>c.promise)]),i);if(f.status==="fulfilled")for(const c of f.value)c.status==="rejected"&&r.push(c.reason);else f.status==="rejected"?r.push(f.reason):a(s);r.push(...n);const m=this.active;if(m&&(m!==l||m.child.exitCode===null&&m.child.signalCode===null))try{await this.terminateChild(m,i)}catch(c){a(c)}i.deadline.signal.aborted&&a(s),this.active=void 0,this.recoveryPromise=void 0,this.startPromise=void 0,this.registrations.clear(),this.registrationRevisions.clear(),this.registrationTasks.clear();for(const c of this.snapshots.keys())this.deleteSnapshot(c);if(this.snapshotListeners.clear(),this.stateValue="closed",this.releaseProcessShutdownListener?.(),this.releaseProcessOwnership?.(),i.deadline.close(),r.length>0){const c=r.length===1?r[0]:new AggregateError(r,"Private Executor cleanup failed"),p=m??l;throw this.recordLifecycle({component:"executor",error:c,phase:"cleanup",...p===void 0?{}:{process:{exitCode:p.child.exitCode,pid:p.child.pid,signal:p.child.signalCode}},reason:"cleanup_failed",state:"shutdown_failed"}),c}}async ensureReady(){for(;;){if(this.assertAccepting(),this.stateValue==="ready"&&this.active)return;if(this.fuseState!=="closed")throw new Error(`Executor supervisor fuse is ${this.fuseState}; recovery is pending`);const e=this.recoveryPromise;if(!e)break;await e}await this.startWithoutRecoveryWait()}async startWithoutRecoveryWait(e){this.assertAccepting();const t=[this.shutdownController.signal];this.processRuntime?.shutdownSignal&&t.push(this.processRuntime.shutdownSignal),e&&t.push(e);const i=t.length===1?t[0]:AbortSignal.any(t);if(i.aborted)throw i.reason;if(this.stateValue==="ready"&&this.active)return;const s=this.startPromise??this.startChild(i);this.startPromise=s;try{await s}finally{this.startPromise===s&&(this.startPromise=void 0)}}async startChild(e){if(this.options.containment.assertHealthy(),e?.aborted||(this.stateValue=this.stateValue==="idle"?"starting":"restarting",this.restartAttempt>0&&await this.waitForRestartBackoff(this.restartAttempt,e),this.assertAccepting(),e?.aborted))throw e.reason;const t=x(),i=this.options.spawnChild(this.options.childEntryPath,{cwd:v.dirname(this.options.childEntryPath),detached:this.options.platform!=="win32",env:this.options.environment,execArgv:[],execPath:this.options.nodeRuntime.executable,serialization:"json",stdio:["ignore","ignore","pipe","ipc"]});if(!i.pid||!i.send)throw i.kill(),new Error("Private Executor child did not expose PID and IPC");const s=i.pid;i.stderr?.resume();const r={appliedRegistrationRevisions:new Map,child:i,epoch:t,exit:i.exitCode!==null||i.signalCode!==null?Promise.resolve():new Promise(n=>{i.once("exit",()=>n())}),initialized:!1};this.active=r,i.on("message",n=>this.handleMessage(r,n)),i.once("error",n=>this.handleChildFailure(r,n)),i.once("exit",()=>{this.isStopping()||this.handleChildFailure(r,new ExecutorPrivateProcessExitedError)}),i.once("disconnect",()=>{this.isStopping()&&this.handleChildFailure(r,new ExecutorPrivateProcessExitedError)});try{if(this.options.windowsJob&&!this.options.windowsJob.isProcessInJob(s))throw new Error("Private Executor did not inherit the host Windows Job");this.options.stdioContainment==="posix_guardian"&&await w("guardianBind",async()=>{const h=await K({...this.options.stdioGuardianEntryPath===void 0?{}:{childEntryPath:this.options.stdioGuardianEntryPath},containment:this.options.containment,...e===void 0?{}:{signal:e},shutdownDeadlineAt:u(()=>this.processRuntime?.shutdownDeadlineAt,"shutdownDeadlineAt"),targetProcessGroupId:s,termTimeoutMs:this.options.termTimeoutMs});if(r.guardian=h,e?.aborted||this.isStopping())throw e?.reason??new Error("Executor supervisor is closing");await h.bindAnchor(s),r.guardianBound=!0});const n=this.proxyPolicy,a=await w("executorInitialize",()=>this.requestOnActive(r,"runtime/initialize",{allowStdio:this.options.allowStdio,proxy:n,protocolVersion:T,runtimeEpoch:t,stdioContainment:this.options.stdioContainment,...this.options.windowsJob===void 0?{}:{windowsJobAddonPath:this.options.windowsJob.addonPath},...!this.options.allowStdio||r.guardian===void 0?{}:{stdioGuardianPid:r.guardian.guardianPid},tenantId:this.options.instanceId},{...e===void 0?{}:{signal:e},timeoutMs:this.options.startTimeoutMs}));if(a.protocolVersion!==T||a.runtimeEpoch!==t||a.proxyRevision!==n.revision||(this.options.stdioContainment==="posix_guardian"?a.stdioAnchorPid===void 0||a.stdioAnchorPid<=0:a.stdioAnchorPid!==void 0))throw new ExecutorPrivateProtocolError("Private Executor initialize response did not match its epoch");r.anchorPid=a.stdioAnchorPid,r.appliedProxyRevision=a.proxyRevision,await this.reconcileProxyPolicyOnActive(r,e),r.initialized=!0,await w("registrationReconcile",()=>this.reconcileRegistrationsAndCommitReady(r,e))}catch(n){let a=!1,h;try{await this.terminateChild(r)}catch(l){a=!0,h=l}throw this.active===r&&(this.active=void 0),!this.isStopping()&&this.fuseState==="closed"&&(this.stateValue="idle"),a?(this.recordLifecycle({component:"executor",error:h,phase:"cleanup",process:{exitCode:r.child.exitCode,pid:r.child.pid,signal:r.child.signalCode},reason:"cleanup_failed",state:"shutdown_failed"}),new ExecutorPrivateStartupCleanupError(n,h)):n}}async reconcileProxyPolicy(){const e=this.active;e?.initialized!==!0||this.isStopping()||await this.reconcileProxyPolicyOnActive(e)}async reconcileProxyPolicyOnActive(e,t){for(let i=0;i<F;i+=1){if(this.active!==e||this.isStopping())return;const s=this.proxyPolicy;if(e.appliedProxyRevision===s.revision)return;const r=await this.requestOnActive(e,"runtime/proxy-configure",{proxy:s},{...t===void 0?{}:{signal:t},timeoutMs:this.options.requestTimeoutMs});if(r.proxyRevision!==s.revision)throw new ExecutorPrivateProtocolError("Private Executor proxy revision did not match its request");e.appliedProxyRevision=r.proxyRevision}throw new ExecutorPrivateProtocolError("Private Executor proxy policy did not converge")}async reconcileRegistrationsAndCommitReady(e,t){for(let i=0;i<F;i+=1){const s=new Set([...e.appliedRegistrationRevisions.keys(),...this.registrations.keys()]);for(const r of s)await this.withRegistrationLock(r,async()=>{if(this.active!==e||this.isStopping()||t?.aborted)throw t?.reason??new ExecutorPrivateProcessExitedError;const n=this.registrations.get(r),a=this.registrationRevisions.get(r),h=e.appliedRegistrationRevisions.get(r);if(n&&a!==void 0){if(h===a)return;const l=await this.requestOnActive(e,"registration/upsert",{registration:n},t===void 0?{}:{signal:t});e.appliedRegistrationRevisions.set(r,a),this.isCurrentRegistration(r,a)&&this.setSnapshot(r,l);return}h!==void 0&&(await this.requestOnActive(e,"registration/remove",{registrationId:r},t===void 0?{}:{signal:t}),e.appliedRegistrationRevisions.delete(r),this.deleteSnapshot(r))});if(this.active!==e||this.isStopping()||t?.aborted)throw t?.reason??new ExecutorPrivateProcessExitedError;if(this.registrationsConverged(e)){this.restartAttempt=0,this.stateValue="ready",this.scheduleHealthCheck(e);return}}throw new ExecutorPrivateProtocolError("Private Executor registration state did not converge during startup")}registrationsConverged(e){if(e.appliedRegistrationRevisions.size!==this.registrations.size)return!1;for(const t of this.registrations.keys()){const i=this.registrationRevisions.get(t);if(i===void 0||e.appliedRegistrationRevisions.get(t)!==i)return!1}return!0}handleMessage(e,t){if(this.active===e){if(U(t)){try{E(t,q)}catch{return}if(!V(t)||t.params.runtimeEpoch!==e.epoch)return;try{const{signal:i}=t.params;i.kind==="log"?this.options.recordEffectTelemetry?.log(i.value):i.kind==="metrics"?this.options.recordEffectTelemetry?.metrics(Object.freeze({...i.value,runtimeEpoch:e.epoch})):this.options.recordEffectTelemetry?.span(i.value)}catch{}return}try{E(t,S)}catch(i){this.failProtocol(e,new ExecutorPrivateProtocolError(`Private Executor sent an invalid or oversized IPC payload: ${g(i).message}`));return}if(B(t)){if(t.runtimeEpoch!==e.epoch)return;if(typeof t.id!="number"){this.failProtocol(e,new ExecutorPrivateProtocolError("Private Executor response used an invalid request id"));return}const i=this.pending.get(t.id);if(!i||i.epoch!==e.epoch)return;if(this.pending.delete(t.id),i.deadline.close(),"error"in t){const s=new ue(t.error.data?.code??"ExecutorPrivateError",t.error.data?.retryable,t.error.message);i.reject(s)}else{if(!D(i.method,t.result)){i.reject(new ExecutorPrivateProtocolError(`Private Executor returned an invalid ${i.method} result`)),this.failProtocol(e,new ExecutorPrivateProtocolError("Private Executor response violated its method contract"));return}i.resolve(t.result)}return}if(I(t)){if(t.params.runtimeEpoch!==e.epoch)return;if(t.method==="client-mcp/cancel")this.clientRequests.get(t.params.requestId)?.controller.abort(new Error("MCP request cancelled"));else for(const i of this.registrations.values())i.executorSlug===t.params.integration&&i.connectionName===t.params.connection&&this.invalidateCatalog(i.registrationId);return}if(N(t)){if(t.params.runtimeEpoch!==e.epoch)return;this.handleReverseRequest(e,t);return}this.failProtocol(e,new ExecutorPrivateProtocolError("Private Executor sent an unknown IPC message"))}}async handleClientMcpRequest(e,t){const i=new AbortController;try{const s=this.clientSources.get(t.params.sourceId)?.source;if(!s||this.clientRequests.size>=this.options.maxPendingRequests||this.clientRequests.has(t.id)||![...this.registrations.values()].some(n=>n.transport.transport==="client"&&n.transport.sourceId===t.params.sourceId))throw new Error("Client MCP source unavailable");this.clientRequests.set(t.id,{sourceId:t.params.sourceId,epoch:e.epoch,controller:i});const r=await s.request(t.params.method,t.params.params,i.signal);if(this.active!==e||i.signal.aborted)return;await this.send(e,{id:t.id,jsonrpc:"2.0",result:r,runtimeEpoch:e.epoch})}catch{await this.send(e,{id:t.id,jsonrpc:"2.0",error:{code:-32e3,message:"Client MCP request failed"},runtimeEpoch:e.epoch}).catch(()=>{})}finally{this.clientRequests.delete(t.id)}}async handleReverseRequest(e,t){if(t.method==="client-mcp/request")return this.handleClientMcpRequest(e,t);try{const i=t.trace===void 0?void 0:j(t.trace),s=await C(i,()=>this.options.onElicitation({invocationId:t.params.invocationId,request:t.params.request,runtimeEpoch:e.epoch}));await this.send(e,{id:t.id,jsonrpc:"2.0",result:s,runtimeEpoch:e.epoch})}catch{await this.send(e,{error:{code:-32e3,message:"Elicitation was cancelled"},id:t.id,jsonrpc:"2.0",runtimeEpoch:e.epoch}).catch(()=>{})}}failProtocol(e,t){this.handleChildFailure(e,t)}handleChildFailure(e,t){if(this.active!==e)return;this.active=void 0;for(const n of this.clientRequests.values())n.epoch===e.epoch&&n.controller.abort(t);if(this.clearHealthTimer(),this.rejectPending(t,e.epoch),this.stateValue==="closing"||this.stateValue==="closed")return;const i=g(t);if(this.fuseState==="half_open"){const n=this.recordHalfOpenFailure(e,i).catch(()=>{});this.failureTasks.add(n),n.finally(()=>this.failureTasks.delete(n)).catch(()=>{}),this.reportFailure(i);return}this.stateValue="idle";const r=this.finishChildFailure(e,i).catch(n=>this.reportFailure(g(n))).catch(()=>{}).then(()=>{});this.recoveryPromise=r,this.failureTasks.add(r),r.then(()=>{this.failureTasks.delete(r),this.recoveryPromise===r&&(this.recoveryPromise=void 0,this.fuseRecoveryController=void 0)}).catch(()=>{}),this.reportFailure(i)}async finishChildFailure(e,t){const i=this.readPolicyNow();for(this.crashTimes.push(i);this.crashTimes.length>0&&this.crashTimes[0]<i-this.options.crashWindowMs;)this.crashTimes.shift();const s=this.crashTimes.length>this.options.maxCrashes;s?this.openFuse(e.epoch,t,e):(this.restartAttempt+=1,this.stateValue="idle",this.publishUnavailable(e.epoch,!1),this.registrations.size>0&&this.recordLifecycle({component:"executor",counts:{attempt:this.restartAttempt,failuresInWindow:this.crashTimes.length},error:t,phase:"recovery",process:{exitCode:e.child.exitCode,pid:e.child.pid,signal:e.child.signalCode},reason:t instanceof ExecutorPrivateProcessExitedError?"process_exit":t instanceof ExecutorPrivateProtocolError?"protocol_error":"process_error",state:"restarting"}));const r=s?new AbortController:void 0;r&&(this.fuseRecoveryController=r),await this.recoverAfterChildFailure(e,s,r)}async recordHalfOpenFailure(e,t){const i=this.readPolicyNow();for(this.crashTimes.push(i);this.crashTimes.length>0&&this.crashTimes[0]<i-this.options.crashWindowMs;)this.crashTimes.shift();this.openFuse(e.epoch,t,e)}async recoverAfterChildFailure(e,t,i){try{await this.terminateChild(e)}catch(r){throw this.recordLifecycle({component:"executor",error:r,phase:"cleanup",process:{exitCode:e.child.exitCode,pid:e.child.pid,signal:e.child.signalCode},reason:"cleanup_failed",state:"shutdown_failed"}),r}const s=this.startPromise;if(s&&await s.catch(()=>{}),this.isStopping()||this.registrations.size===0){t&&!this.isStopping()&&this.closeUnusedFuse();return}if(!t){await this.startWithoutRecoveryWait();return}if(!i)throw new Error("Executor fuse recovery omitted its controller");await this.recoverOpenFuse(i.signal)}async recoverOpenFuse(e){let t=e;for(;!this.isStopping();){if(t.aborted){const i=this.renewFuseRecoveryAfterCancellation(t);if(!i)return;t=i}if(this.registrations.size===0){this.closeUnusedFuse();return}this.fuseState="open",this.stateValue="failed";try{await this.waitForRestartBackoff(Math.max(1,this.fuseOpenAttempt),t)}catch(i){if(t.aborted){const s=this.renewFuseRecoveryAfterCancellation(t);if(!s)return;t=s;continue}if(this.isStopping())return;throw i}if(this.isStopping()||this.registrations.size===0){this.registrations.size===0&&!this.isStopping()&&this.closeUnusedFuse();return}this.fuseState="half_open",this.stateValue="restarting";try{if(await this.startWithoutRecoveryWait(t),this.fuseState==="half_open"&&this.state==="ready"&&this.active){this.closeFuse();return}this.fuseState==="half_open"&&this.openFuse()}catch(i){if(t.aborted){const s=this.renewFuseRecoveryAfterCancellation(t);if(!s)return;t=s;continue}if(this.isStopping())return;this.fuseState==="half_open"&&this.openFuse(),this.reportFailure(g(i))}}}renewFuseRecoveryAfterCancellation(e){if(this.isStopping())return;if(this.registrations.size===0){this.closeUnusedFuse();return}const t=this.fuseRecoveryController;if(t&&t.signal!==e&&!t.signal.aborted)return t.signal;const i=new AbortController;return this.fuseRecoveryController=i,i.signal}openFuse(e,t,i){const s=this.fuseState!=="open";this.fuseState!=="open"&&(this.fuseOpenAttempt+=1),this.fuseState="open",this.stateValue="failed",this.publishUnavailable(e,!0),s&&this.recordLifecycle({component:"executor",counts:{attempt:this.fuseOpenAttempt,failuresInWindow:this.crashTimes.length},...t===void 0?{}:{error:t},phase:"recovery",...i===void 0?{}:{process:{exitCode:i.child.exitCode,pid:i.child.pid,signal:i.child.signalCode}},reason:t instanceof ExecutorPrivateProcessExitedError?"process_exit":t instanceof ExecutorPrivateProtocolError?"protocol_error":"recovery_failed",state:"fused"})}closeFuse(){this.fuseState="closed",this.fuseOpenAttempt=0,this.crashTimes.length=0,this.restartAttempt=0,this.stateValue="ready"}closeUnusedFuse(){this.fuseState="closed",this.fuseOpenAttempt=0,this.crashTimes.length=0,this.restartAttempt=0,this.stateValue="idle"}cancelFuseRecovery(e){this.fuseRecoveryController?.abort(e)}publishUnavailable(e,t){for(const[i,s]of this.snapshots)this.setSnapshot(i,{error:{code:t?"executor_failed":"executor_restarting",message:t?"MCP runtime exceeded its restart limit; recovery is pending":"MCP runtime is restarting",retryable:!0},generation:s.generation+1,registrationId:i,runtimeEpoch:e??s.runtimeEpoch,status:"unavailable",tools:[]})}setSnapshot(e,t){this.snapshots.set(e,t),this.scheduleCatalogRefresh(e),this.publishSnapshot(e,t)}deleteSnapshot(e){clearTimeout(this.catalogTimers.get(e)),this.catalogTimers.delete(e),this.snapshots.delete(e)&&this.publishSnapshot(e,void 0)}publishSnapshot(e,t){for(const i of this.snapshotListeners)try{i(e,t)}catch{}}request(e,t,i){const s=this.active;return!s||this.stateValue!=="ready"?Promise.reject(new Error("Private Executor is not ready")):this.requestOnActive(s,e,t,i)}scheduleHealthCheck(e){if(this.clearHealthTimer(),this.options.healthIntervalMs===0)return;const t=new AbortController,i={close:u(()=>t.abort(new Error("Executor health delay completed")),"close")};this.healthTimer=i,C(void 0,()=>{this.waitForPolicyDelay(this.options.healthIntervalMs,t.signal,"Executor health delay cancelled").then(()=>{if(this.healthTimer===i)return this.healthTimer=void 0,this.checkHealth(e)}).catch(s=>{this.healthTimer===i&&(this.healthTimer=void 0),!t.signal.aborted&&!this.isStopping()&&this.failProtocol(e,g(s))})})}async checkHealth(e){if(!(this.active!==e||this.stateValue!=="ready")){try{const t=await this.requestOnActive(e,"runtime/health",{},{timeoutMs:this.options.healthTimeoutMs});if(t.status!=="ready"||t.runtimeEpoch!==e.epoch||t.stdioAnchorPid!==e.anchorPid)throw new ExecutorPrivateProtocolError("Private Executor health response did not match its epoch")}catch(t){this.active===e&&!this.isStopping()&&this.failProtocol(e,g(t));return}this.active===e&&this.stateValue==="ready"&&this.scheduleHealthCheck(e)}}clearHealthTimer(){this.healthTimer&&(this.healthTimer.close(),this.healthTimer=void 0)}requestOnActive(e,t,i,s={}){if(s.signal?.aborted)return Promise.reject(s.signal.reason);if(this.pending.size>=this.options.maxPendingRequests)return Promise.reject(new ExecutorPrivateOverloadedError);const r=this.nextRequestId++,n=H(),a={id:r,jsonrpc:"2.0",method:t,params:i,...n===void 0?{}:{trace:n}},h=s.timeoutMs??this.options.requestTimeoutMs;return new Promise((l,d)=>{const f=this.createPolicyDeadline(h,s.signal===void 0?[]:[s.signal],new Error(`Private Executor ${t} timed out after ${h}ms`)),m=u(()=>{const c=this.pending.get(r);c&&(this.pending.delete(r),f.close(),c.reject(f.signal.reason))},"onAbort");f.signal.addEventListener("abort",m,{once:!0}),this.pending.set(r,{deadline:f,epoch:e.epoch,method:t,reject:u(c=>{f.signal.removeEventListener("abort",m),d(c)},"reject"),resolve:u(c=>{f.signal.removeEventListener("abort",m),l(c)},"resolve")}),this.send(e,a).catch(c=>{const p=this.pending.get(r);p&&(this.pending.delete(r),f.close(),p.reject(c))})})}send(e,t){const{bytes:i}=E(t,S);return this.pendingSends>=this.options.maxPendingRequests||this.pendingSendBytes+i>this.options.maxPendingRequestBytes?Promise.reject(new ExecutorPrivateOverloadedError):this.active!==e||!e.child.connected||!e.child.send?Promise.reject(new ExecutorPrivateProcessExitedError):(this.pendingSends+=1,this.pendingSendBytes+=i,new Promise((s,r)=>{let n=!1;const a=u(h=>{n||(n=!0,this.pendingSends-=1,this.pendingSendBytes-=i,h?r(h):s())},"finish");try{e.child.send?.(t,h=>a(h))}catch(h){a(g(h))}}))}rejectPending(e,t){for(const[i,s]of this.pending)t!==void 0&&s.epoch!==t||(this.pending.delete(i),s.deadline.close(),s.reject(e))}terminateChild(e,t=this.shutdownBudget){if(e.terminationPromise)return e.terminationPromise;const i=t===void 0,s=t??this.createShutdownBudget(Math.min(Number.MAX_SAFE_INTEGER,this.options.termTimeoutMs*2));return e.terminationPromise=this.terminateChildOnce(e,s).finally(()=>{i&&s.deadline.close()}),e.terminationPromise}async terminateChildOnce(e,t){let i=!1,s;if(e.guardian){const n=this.remainingBeforeHandleReleaseReserve(t),a=Date.now()+n;try{await e.guardian.close({deadlineAt:a})}catch(h){i=!0,s=h}if(!i&&(e.guardianBound===!0||e.anchorPid!==void 0)){if(await this.waitForChildExit(e,this.remainingBeforeKillReserve(t)))return;const h=new Error("Private Executor did not exit after guardian cleanup");this.options.containment.trip(h);const l=[h];try{await this.terminateWithSignals(e,!0,t)}catch(d){l.push(...this.flattenCleanupFailure(d))}this.throwCleanupFailures(l,"Private Executor guardian cleanup did not reap its child")}}if(e.child.exitCode!==null||e.child.signalCode!==null){if(i)throw s;return}const r=[];i&&r.push(s);try{await this.terminateWithSignals(e,e.guardian!==void 0||this.options.allowStdio&&this.options.platform!=="win32",t)}catch(n){r.push(...this.flattenCleanupFailure(n))}this.throwCleanupFailures(r,"Private Executor guardian and child cleanup failed")}async terminateWithSignals(e,t,i){const s=[];try{e.child.disconnect?.()}catch(r){s.push(r)}for(const r of["SIGTERM","SIGKILL"]){if(e.child.exitCode!==null||e.child.signalCode!==null)break;const n=r==="SIGTERM"?this.remainingBeforeKillReserve(i):this.remainingBeforeHandleReleaseReserve(i);try{if(await this.killAndWait(e,r,n,t))break}catch(a){s.push(a)}}if(e.child.exitCode===null&&e.child.signalCode===null){const r=new Error("Private Executor process cleanup timed out");this.options.containment.trip(r),s.push(r);try{this.releaseChildHandles(e)}catch(n){s.push(...this.flattenCleanupFailure(n))}}this.throwCleanupFailures(s,"Private Executor child cleanup failed")}async killAndWait(e,t,i,s=!1){let r,n=!1;try{s||this.options.platform==="win32"?n=!e.child.kill(t):e.child.pid?process.kill(-e.child.pid,t):r=new Error(`Private Executor child has no PID for ${t}`)}catch(h){J(h)||(r=h)}const a=await this.waitForChildExit(e,i)||e.child.exitCode!==null||e.child.signalCode!==null;if(r!==void 0)throw r;if(n&&!a)throw new Error(`Private Executor child refused ${t}`);return a}async waitForChildExit(e,t){if(e.child.exitCode!==null||e.child.signalCode!==null)return!0;if(t<=0)return!1;let i;return Promise.race([e.exit.then(()=>!0),new Promise(s=>{i=setTimeout(()=>s(!1),t),i.unref?.()})]).finally(()=>{i&&clearTimeout(i)})}releaseChildHandles(e){const t=[],i=u(s=>{try{s()}catch(r){t.push(r)}},"attempt");e.child.connected&&i(()=>e.child.disconnect?.()),i(()=>e.child.channel?.unref()),i(()=>e.child.stdin?.destroy()),i(()=>e.child.stdout?.destroy()),i(()=>e.child.stderr?.destroy()),i(()=>e.child.unref()),this.throwCleanupFailures(t,"Private Executor child handles could not be released")}flattenCleanupFailure(e){return e instanceof AggregateError?e.errors:[e]}throwCleanupFailures(e,t){if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,t)}assertCurrentRegistration(e,t){if(!this.isCurrentRegistration(e,t))throw new Error(`MCP registration "${e}" was superseded`)}isCurrentRegistration(e,t){return this.registrations.has(e)&&this.isCurrentRegistrationRevision(e,t)}isCurrentRegistrationRevision(e,t){return this.registrationRevisions.get(e)===t}requireRegistration(e){const t=this.registrations.get(e);if(!t)throw new Error(`Unknown MCP registration "${e}"`);return t}requireRegistrationRevision(e){const t=this.registrationRevisions.get(e);if(t===void 0)throw new Error(`Unknown MCP registration "${e}"`);return t}async withRegistrationLock(e,t){const i=this.registrationTasks.get(e);let s;const r=new Promise(n=>{s=n});this.registrationTasks.set(e,r),i&&await i;try{return await t()}finally{s(),this.registrationTasks.get(e)===r&&this.registrationTasks.delete(e)}}createShutdownBudget(e,t){const i=Date.now(),s=i+e,r=t===void 0?s:Math.min(s,t),n=Math.max(1,Math.ceil(r-i)),a=new ExecutorPrivateShutdownTimeoutError(n);return{deadlineAt:r,deadline:R(n,[],a),timeoutError:a}}gracefulCloseBudgetMs(e,t=!1){if(!t)return this.remainingBeforeKillReserve(e);const i=this.remainingShutdownMs(e),s=Math.min(i,this.options.termTimeoutMs+se);return Math.max(0,i-s)}remainingBeforeKillReserve(e){const t=this.remainingShutdownMs(e);if(t<=1)return 0;const i=Math.min(this.options.termTimeoutMs,Math.max(1,Math.ceil(t/2)));return Math.max(0,t-i)}remainingBeforeHandleReleaseReserve(e){const t=this.remainingShutdownMs(e);if(t<=1)return 0;const i=Math.min(10,Math.max(1,Math.ceil(t/10)));return Math.max(0,t-i)}remainingShutdownMs(e){return Math.max(0,Math.ceil(e.deadlineAt-Date.now()))}async settleWithinShutdown(e,t,i=this.remainingShutdownMs(t)){const s=Math.min(this.remainingShutdownMs(t),Math.max(0,i));if(s<=0||t.deadline.signal.aborted)return e.catch(()=>{}),{status:"timed_out"};const r=R(s,[t.deadline.signal],t.timeoutError);return new Promise(n=>{let a=!1;const h=u(d=>{a||(a=!0,r.signal.removeEventListener("abort",l),r.close(),n(d))},"finish"),l=u(()=>h({status:"timed_out"}),"onAbort");if(r.signal.addEventListener("abort",l,{once:!0}),r.signal.aborted){l(),e.catch(()=>{});return}e.then(d=>h({status:"fulfilled",value:d}),d=>h({reason:d,status:"rejected"}))})}createPolicyDeadline(e,t,i){return this.processRuntime?.createPolicyDeadline(e,{signals:t,timeoutReason:i})??R(e,t,i)}readPolicyNow(){return this.processRuntime?.policyNow()??Date.now()}waitForPolicyDelay(e,t,i){return this.processRuntime?.policyDelay(e,t,i)??L(e,t)}waitForRestartBackoff(e,t){const i=t??new AbortController().signal;return this.processRuntime?this.processRuntime.policyBackoff(this.options.restartBackoffMs,e,b,i,"Executor restart backoff cancelled"):L(Math.min(b,this.options.restartBackoffMs*2**(e-1)),i)}assertAccepting(){if(this.stateValue==="closing"||this.stateValue==="closed")throw new Error(`Executor supervisor is ${this.stateValue}`);this.options.containment.assertHealthy()}isStopping(){return this.stateValue==="closing"||this.stateValue==="closed"}reportFailure(e){Promise.resolve().then(()=>this.options.onFailure?.(e)).catch(()=>{})}recordLifecycle(e){try{this.options.recordLifecycle?.(e)}catch{}}}
|
package/lib/public.d.ts
CHANGED
|
@@ -4,6 +4,7 @@ export { createClient, RequestError } from './client/public.js';
|
|
|
4
4
|
export type { Client, ClientOptions, ClientOn, ClientState, ConnectOptions, ConnectSettings, NotificationHandler, RequestContext, RequestHandler, RequestOptions, Unsubscribe, } from './client/types.js';
|
|
5
5
|
export { createHarness } from './harness/create-harness.js';
|
|
6
6
|
export type { Harness, HarnessOptions, HarnessTools, HostInfo, ProductConfig, ToolDefinition } from './harness/types.js';
|
|
7
|
+
export type { SandboxCenterOption } from './runtime/sandbox-center.js';
|
|
7
8
|
export type { TelemetryOptions, LogSink } from './telemetry/public.js';
|
|
8
9
|
export { createServer } from './server/create-server.js';
|
|
9
10
|
export type { ServerOptions } from './server/create-server.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var o=(e,n)=>E(e,"name",{value:n,configurable:!0});export const AGENT_HARNESS_PRIVATE_RUNTIME_ROLE=Object.freeze({codebuddy:"--agent-harness-private-codebuddy",executor:"--agent-harness-private-executor",processGroupAnchor:"--agent-harness-private-process-group-anchor",resource:"--agent-harness-private-resource",stdioGroupAnchor:"--agent-harness-private-stdio-group-anchor",stdioGuardian:"--agent-harness-private-stdio-guardian"}),AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-loader"),AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-runtime"),AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-node-pty-loader"),AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD_ENV="AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD";export{AGENT_HARNESS_HOST_NODE_EXECUTABLE_ENV,AGENT_HARNESS_HOST_NODE_RUN_AS_NODE_ENV}from"../binary/host-node-environment.js";export const AGENT_HARNESS_PRIVATE_PRODUCT_ROOT_ENV="AGENT_HARNESS_PRIVATE_PRODUCT_ROOT";const d=Symbol.for("codebuddy.ai/agent-harness/embedded-agent-server");export function installEmbeddedAgentServerLoader(e){const n=globalThis;if(n[d]!==void 0)throw new Error("Embedded Agent server already installed");n[d]=e}o(installEmbeddedAgentServerLoader,"installEmbeddedAgentServerLoader");export async function loadAgentServerModule(){const e=globalThis[d];return typeof e=="function"?e():import("#agent-harness-codebuddy/server")}o(loadAgentServerModule,"loadAgentServerModule");export function isAgentHarnessStandaloneBinary(){return typeof AGENT_HARNESS_PACKAGE_TYPE=="string"&&AGENT_HARNESS_PACKAGE_TYPE==="binary"}o(isAgentHarnessStandaloneBinary,"isAgentHarnessStandaloneBinary");export function installEmbeddedCodeBuddyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]!==void 0)throw new Error("Embedded CodeBuddy loader is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]=e}o(installEmbeddedCodeBuddyLoader,"installEmbeddedCodeBuddyLoader");export function installEmbeddedNodePtyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]!==void 0)throw new Error("Embedded node-pty loader is already installed");n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]=e}o(installEmbeddedNodePtyLoader,"installEmbeddedNodePtyLoader");export function installEmbeddedCodeBuddyRuntime(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]!==void 0)throw new Error("Embedded CodeBuddy runtime is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]=Object.freeze({...e})}o(installEmbeddedCodeBuddyRuntime,"installEmbeddedCodeBuddyRuntime");export function resolveEmbeddedCodeBuddyLoader(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER];return typeof e=="function"?e:void 0}o(resolveEmbeddedCodeBuddyLoader,"resolveEmbeddedCodeBuddyLoader");export function resolveEmbeddedCodeBuddyRuntime(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME];if(!(typeof e!="object"||e===null||!("binPath"in e)||typeof e.binPath!="string"||!("packageJsonPath"in e)||typeof e.packageJsonPath!="string"||!("version"in e)||typeof e.version!="string"))return e}o(resolveEmbeddedCodeBuddyRuntime,"resolveEmbeddedCodeBuddyRuntime");export function createPrivateRuntimeLaunchSpec({args:e=[],currentExecutable:n=process.execPath,entryPath:t,nodeRuntime:a,role:
|
|
1
|
+
var E=Object.defineProperty;var o=(e,n)=>E(e,"name",{value:n,configurable:!0});export const AGENT_HARNESS_PRIVATE_RUNTIME_ROLE=Object.freeze({codebuddy:"--agent-harness-private-codebuddy",executor:"--agent-harness-private-executor",processGroupAnchor:"--agent-harness-private-process-group-anchor",resource:"--agent-harness-private-resource",stdioGroupAnchor:"--agent-harness-private-stdio-group-anchor",stdioGuardian:"--agent-harness-private-stdio-guardian"}),AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-loader"),AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-runtime"),AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-node-pty-loader"),AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD_ENV="AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD";export{AGENT_HARNESS_HOST_NODE_EXECUTABLE_ENV,AGENT_HARNESS_HOST_NODE_RUN_AS_NODE_ENV}from"../binary/host-node-environment.js";export const AGENT_HARNESS_PRIVATE_PRODUCT_ROOT_ENV="AGENT_HARNESS_PRIVATE_PRODUCT_ROOT";const d=Symbol.for("codebuddy.ai/agent-harness/embedded-agent-server");export function installEmbeddedAgentServerLoader(e){const n=globalThis;if(n[d]!==void 0)throw new Error("Embedded Agent server already installed");n[d]=e}o(installEmbeddedAgentServerLoader,"installEmbeddedAgentServerLoader");export async function loadAgentServerModule(){process.env.CODEBUDDY_DISABLE_FILE_LOGS??="0",process.env.CODEBUDDY_DISABLE_SHELL_SNAPSHOT??="0";const e=globalThis[d];return typeof e=="function"?e():import("#agent-harness-codebuddy/server")}o(loadAgentServerModule,"loadAgentServerModule");export function isAgentHarnessStandaloneBinary(){return typeof AGENT_HARNESS_PACKAGE_TYPE=="string"&&AGENT_HARNESS_PACKAGE_TYPE==="binary"}o(isAgentHarnessStandaloneBinary,"isAgentHarnessStandaloneBinary");export function installEmbeddedCodeBuddyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]!==void 0)throw new Error("Embedded CodeBuddy loader is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]=e}o(installEmbeddedCodeBuddyLoader,"installEmbeddedCodeBuddyLoader");export function installEmbeddedNodePtyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]!==void 0)throw new Error("Embedded node-pty loader is already installed");n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]=e}o(installEmbeddedNodePtyLoader,"installEmbeddedNodePtyLoader");export function installEmbeddedCodeBuddyRuntime(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]!==void 0)throw new Error("Embedded CodeBuddy runtime is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]=Object.freeze({...e})}o(installEmbeddedCodeBuddyRuntime,"installEmbeddedCodeBuddyRuntime");export function resolveEmbeddedCodeBuddyLoader(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER];return typeof e=="function"?e:void 0}o(resolveEmbeddedCodeBuddyLoader,"resolveEmbeddedCodeBuddyLoader");export function resolveEmbeddedCodeBuddyRuntime(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME];if(!(typeof e!="object"||e===null||!("binPath"in e)||typeof e.binPath!="string"||!("packageJsonPath"in e)||typeof e.packageJsonPath!="string"||!("version"in e)||typeof e.version!="string"))return e}o(resolveEmbeddedCodeBuddyRuntime,"resolveEmbeddedCodeBuddyRuntime");export function createPrivateRuntimeLaunchSpec({args:e=[],currentExecutable:n=process.execPath,entryPath:t,nodeRuntime:a,role:s,standaloneBinary:i=isAgentHarnessStandaloneBinary()}){const r=i;return Object.freeze({args:Object.freeze(r?[s,...e]:[t,...e]),command:r?n:a.executable})}o(createPrivateRuntimeLaunchSpec,"createPrivateRuntimeLaunchSpec");
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type SandboxCenterOption = 'managed' | {
|
|
2
|
+
readonly address: string;
|
|
3
|
+
};
|
|
4
|
+
/** One center address per Harness process. The Agent and sandbox-cli daemons consume it through env. */
|
|
5
|
+
export declare class HarnessSandboxCenter {
|
|
6
|
+
readonly address: string;
|
|
7
|
+
readonly managed: boolean;
|
|
8
|
+
private uid;
|
|
9
|
+
private child;
|
|
10
|
+
private client;
|
|
11
|
+
private tail;
|
|
12
|
+
private closing;
|
|
13
|
+
constructor(appHome: string, option?: SandboxCenterOption, inheritedAddress?: string);
|
|
14
|
+
private readonly appHome;
|
|
15
|
+
get environment(): Record<string, string>;
|
|
16
|
+
/** Called before admitting a query; Account fencing has already drained the previous owner. */
|
|
17
|
+
prepare(uid: string | undefined, signal?: AbortSignal): Promise<void>;
|
|
18
|
+
close(): Promise<void>;
|
|
19
|
+
private enqueue;
|
|
20
|
+
private stopOwned;
|
|
21
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var u=Object.defineProperty;var r=(s,t)=>u(s,"name",{value:t,configurable:!0});import{buildEpochCenterAddress as f,createSandboxCenterClient as h,getSandboxCenterPath as m,SANDBOX_CENTER_IPC_ADDRESS_ENV as p,SANDBOX_CENTER_LIFECYCLE_COMMANDS as w,SANDBOX_CENTER_START_MODE_ENV as E,SANDBOX_RULES_COMMANDS as C,spawnSandboxCenter as S}from"#agent-harness-components/sandbox-center";const a=3e3;function o(s){return s.exitCode!==null||s.signalCode!==null}r(o,"hasExited");function c(s,t){return o(s)?Promise.resolve(!0):new Promise(e=>{const i=setTimeout(()=>{s.off("exit",n),e(o(s))},t),n=r(()=>{clearTimeout(i),e(!0)},"onExit");s.once("exit",n)})}r(c,"waitForExit");export class HarnessSandboxCenter{static{r(this,"HarnessSandboxCenter")}constructor(t,e,i){this.tail=Promise.resolve(),this.closing=!1;const n=typeof e=="object"?e.address:e===void 0?i:void 0;if(n!==void 0&&!n.trim())throw new TypeError("sandboxCenter.address must be a non-empty IPC address");this.managed=n===void 0,this.address=n??f(t,process.pid),this.appHome=t}get environment(){return{[p]:this.address,[E]:"connect-only"}}prepare(t,e){return t?.trim()?this.enqueue(async()=>{if(e?.throwIfAborted(),this.closing)throw new Error("Harness sandbox-center is closing");const i=t.trim();this.uid&&this.uid!==i&&(this.managed?await this.stopOwned():(this.client?.close(),this.client=void 0,this.uid=void 0));const n=this.managed?m():void 0;if(this.managed&&!n||this.uid===i&&this.client?.isConnected?.()&&(!this.managed||this.child&&!o(this.child)))return;this.client?.close(),this.managed&&(!this.child||o(this.child))&&(this.child=await S({appHome:this.appHome,executablePath:n,socketPath:this.address,uid:i}));const d=h({clientRole:"agent-harness",startMode:"connect-only",resolveRuntimeContext:r(()=>({appHome:this.appHome,socketPath:this.address,uid:i}),"resolveRuntimeContext")});this.client=d;try{await d.request(C.GET_RULES,{},{signal:e}),e?.throwIfAborted(),this.uid=i}catch(l){throw d.close(),this.managed&&await this.stopOwned(i),l}}):Promise.resolve()}close(){return this.closing=!0,this.enqueue(async()=>{this.managed?await this.stopOwned():this.client?.close(),this.client=void 0,this.uid=void 0})}enqueue(t){const e=this.tail.then(t,t);return this.tail=e.catch(()=>{}),e}async stopOwned(t=this.uid){const e=this.child,i=this.client;if(this.child=void 0,this.client=void 0,this.uid=void 0,!e){i?.close();return}try{if(!o(e)&&t){const n=i??h({clientRole:"agent-harness",startMode:"connect-only",resolveRuntimeContext:r(()=>({appHome:this.appHome,socketPath:this.address,uid:t}),"resolveRuntimeContext")});try{if((await n.request(w.SHUTDOWN,{},{signal:AbortSignal.timeout(a),timeoutMs:a}))?.accepted===!0&&await c(e,a))return}catch{}finally{n.close()}}if(!o(e)&&(e.kill("SIGTERM"),!await c(e,a)&&!o(e)&&(e.kill("SIGKILL"),!await c(e,2e3))))throw new Error("Owned sandbox-center did not exit")}finally{i?.close()}}}
|
package/lib/server/public.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { tool } from '#agent-harness-components/tool-definition';
|
|
|
2
2
|
/** Embedding entry point: importable under Node and Bun, independent of the binary. */
|
|
3
3
|
export { createHarness } from '../harness/create-harness.js';
|
|
4
4
|
export type { Harness, HarnessOptions, HarnessTools, HostInfo, ProductConfig, ToolDefinition } from '../harness/types.js';
|
|
5
|
+
export type { SandboxCenterOption } from '../runtime/sandbox-center.js';
|
|
5
6
|
export { AgentHarnessServer } from './agent-harness-server.js';
|
|
6
7
|
export { installNoOrphans } from '../runtime/windows-stdio-containment.js';
|
|
7
8
|
export type { AgentHarnessServerOptions } from './types.js';
|
|
@@ -3,6 +3,7 @@ import type { QueryOptions } from '#agent-harness-codebuddy/server';
|
|
|
3
3
|
import { AgentServer } from './agent-server.js';
|
|
4
4
|
import { SessionConfigStore } from './config-store.js';
|
|
5
5
|
import { type SessionOpenOptions, SessionRuntime } from './runtime.js';
|
|
6
|
+
import { type SessionConfigDefaults } from './server-config.js';
|
|
6
7
|
export interface AgentBackendOptions<R = never> {
|
|
7
8
|
/** Host application headers forwarded through the Agent query boundary. */
|
|
8
9
|
readonly headers?: Readonly<Record<string, string>>;
|
|
@@ -10,6 +11,10 @@ export interface AgentBackendOptions<R = never> {
|
|
|
10
11
|
readonly checkpoints?: boolean;
|
|
11
12
|
/** Assembly seam: resolve admitted Product/settings into Agent execution inputs. */
|
|
12
13
|
readonly resolveOptions?: (options: SessionOpenOptions) => Effect.Effect<QueryOptions, unknown, R>;
|
|
14
|
+
/** Ensure the process-owned sandbox center is ready for this run's Account. */
|
|
15
|
+
readonly prepareSandboxCenter?: (options: QueryOptions, signal: AbortSignal) => Promise<void>;
|
|
16
|
+
/** Host-owned effective defaults used only to project ACP selectors. */
|
|
17
|
+
readonly resolveConfigDefaults?: (options: SessionOpenOptions) => Effect.Effect<SessionConfigDefaults, unknown, R>;
|
|
13
18
|
}
|
|
14
19
|
export declare function workspaceQueryOptions(open: SessionOpenOptions): Effect.Effect<QueryOptions, Error>;
|
|
15
20
|
/** Shared Agent service, scoped session instances. No child process or prewarm protocol. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var ne=Object.defineProperty;var n=(h,f)=>ne(h,"name",{value:f,configurable:!0});import{randomUUID as ie}from"node:crypto";import{isAbsolute as se}from"node:path";import{Effect as d,Layer as oe}from"effect";import{abortReason as re}from"../internal/async.js";import{promptMetadata as ae}from"../protocol/prompt.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as J,AgentHarnessInvalidParamsError as X,AgentHarnessJsonRpcError as K}from"../server/errors.js";import{readSessionTree as ce}from"../subagent/history.js";import{AgentServer as de}from"./agent-server.js";import{SessionConfigStore as le}from"./config-store.js";import{replayCodecs as M,replaySession as ue}from"./replay.js";import{SessionRuntime as V,SessionRuntimeClosedError as F}from"./runtime.js";import{ServerSessionConfig as W}from"./server-config.js";import{ServerSessionEvents as fe}from"./server-events.js";import{serverCanUseTool as ge}from"./server-interactions.js";import{ServerSessionMcp as we}from"./server-mcp.js";import{serverPromptInput as pe}from"./server-prompt.js";export function workspaceQueryOptions(h){return h.workspace?.product?d.succeed({product:h.workspace.product,persistSession:!0,tools:{type:"preset",preset:"default"},freezeToolsDuringRun:!0,settings:{enabledPlugins:{...h.pluginSettings.enabledPlugins}}}):d.fail(new Error("In-process Agent backend requires a resolved workspace Product"))}n(workspaceQueryOptions,"workspaceQueryOptions");const Y={compact:!0,configReload:!0,promptSteer:!0},R={session:{additionalDirectories:{},delete:{},fork:{},mcp:{acp:{},http:{},stdio:{}},prompt:{image:{},embeddedContext:{}}}};export function AgentBackend(h={}){return oe.effect(V,d.gen(function*(){const f=yield*de,q=yield*le,x=yield*d.context();yield*d.tryPromise({try:M,catch:n(r=>r,"catch")});const C=new AbortController;return yield*d.addFinalizer(()=>d.sync(()=>C.abort(new F))),V.of({profile:{capabilities:R,supports:Y,checkpoints:h.checkpoints===!0},prepare:d.void,readCatalog:n((r,a)=>d.gen(function*(){const c=yield*(h.resolveOptions??workspaceQueryOptions)(a).pipe(d.provideContext(x)),v=yield*d.tryPromise({try:n(()=>W.create(c,a.workspace?.sessionModelConfigOption,a.clientCapabilities),"try"),catch:n(S=>S,"catch")}),o=a.cwd??c.cwd??process.cwd();v.restore(yield*q.read({sessionId:r,cwd:o}));const{fs:w,settings:O,product:p,agents:u,agent:m}={...c,...v.queryOptions};return yield*d.tryPromise({try:n(async()=>{const S=AbortSignal.any([C.signal,a.signal]),I=await f.readSessionCatalog({cwd:o,fs:w,settings:O,product:p,agents:u,agent:m,signal:S});return S.throwIfAborted(),(await M()).projectAgentEvent({type:"agent_event",session_id:r,event:{type:"catalog",data:I}})},"try"),catch:n(S=>S,"catch")})}),"readCatalog"),rewind:n((r,a)=>d.tryPromise({try:n(async()=>{const c=await f.readSession(r.sessionId,a);if(!c)throw new X("Session history was not found");const{selectRewindMessage:v}=await M();let o;try{o=v(c,r._meta)}catch(w){throw w instanceof Error&&"code"in w&&["invalid_history","invalid_boundary","cursor_not_found"].includes(String(w.code))?new X(w.message):w}return await f.rewind(r.sessionId,{...a,to:o}),{}},"try"),catch:n(c=>c,"catch")}),"rewind"),open:n(r=>d.acquireRelease(d.gen(function*(){let a=yield*(h.resolveOptions??workspaceQueryOptions)(r).pipe(d.provideContext(x));const c=yield*d.tryPromise({try:n(()=>W.create(a,r.workspace?.sessionModelConfigOption,r.clientCapabilities),"try"),catch:n(e=>e,"catch")}),v=AbortSignal.any([r.signal,C.signal]);v.throwIfAborted();let o,w={},O,p,u,m=-1,S=0,I,k,T,G,D=!1;const U=n((e,t,i)=>d.runPromise(q.write({sessionId:e,cwd:t},i.selections())),"saveConfig"),z=n(e=>{D||T||(D=!0,G=e,k?.abort(e),p?.fail(e),r.onFailure(e))},"fail"),H=new we(r.callbacks,()=>k?.signal??C.signal),y=n(()=>{if(T||C.signal.aborted)throw new F;if(D)throw G},"assertOpen"),E=n(e=>{if(y(),e!==o)throw new Error("Session does not belong to this execution")},"assertSession"),P=n((e,t)=>{if(y(),I)throw new Error("Session is already running");const i=new AbortController;k=i;const s=AbortSignal.any([i.signal,C.signal,...e?.signal?[e.signal]:[]]),l=n(()=>i.abort(re(s)),"abort");s.addEventListener("abort",l,{once:!0}),s.aborted&&l();const A=Promise.resolve().then(()=>(s.throwIfAborted(),t(i))).finally(()=>{s.removeEventListener("abort",l),I=void 0,k=void 0});return I=A,A},"run"),L=n(()=>T??=(async()=>{k?.abort(new F);try{if(!o)return;await f.interrupt(o),await I?.catch(()=>{})}finally{try{o&&await f.close(o)}finally{O?.unsubscribe(),await H.close()}}})(),"dispose"),Z=a.canUseTool??ge(r,()=>({id:o,meta:p?.meta??{}}),(e,t)=>p?.interaction(e,t)??Promise.resolve()),$=n(async({signal:e})=>{e.throwIfAborted(),y();const t=u;if(!t||!r.callbacks.refreshAuthentication)throw new Error("Authentication required");const i=await r.callbacks.refreshAuthentication({accountId:t.account.id,generation:t.generation},{signal:e});if(e.throwIfAborted(),y(),!u||i.account.id!==t.account.id||m>i.generation)throw new Error("Authentication changed during refresh");return u=i,m=i.generation,{accessToken:i.credential.accessToken,method:i.credential.type}},"refreshAuthentication"),N=n(()=>({...a,...w,...c.queryOptions,includePartialMessages:!0,...!r.clientCapabilities.elicitation?.form&&!a.canUseTool?{disallowedTools:[...new Set([...a.disallowedTools??[],"AskUserQuestion"])]}:{},headers:{...h.headers,...u?.credential.domain?{"X-Domain":u.credential.domain}:{},...u?.account.organization?.id?{"X-Tenant-Id":u.account.organization.id}:{},...a.headers},auth:u?{accessToken:u.credential.accessToken,method:u.credential.type,...r.callbacks.refreshAuthentication?{refresh:$}:{}}:m<0?a.auth:void 0,account:u?{uid:u.account.id,...u.account.organization?.id?{enterpriseId:u.account.organization.id}:{}}:m<0?a.account:void 0,canUseTool:Z}),"runOptions"),Q=n((e,t,i)=>{const s=Promise.withResolvers();let l=!1;return P(i,async g=>{const b=f.query(o,e,{...N(),_meta:t,abortController:g});c.lockAgent(),b.catch(()=>{});try{const _=p.begin(b.runId);l=!0,s.resolve({_meta:{"codebuddy.ai/requestId":b.runId}}),await _;const ee=await p.waitForCompletion(b.runId);await b.catch(te=>{if(ee.stopReason!=="error")throw te}),y()}catch(_){throw g.abort(_),await f.interrupt(o),await b.catch(()=>{}),_}}).catch(g=>{l?z(g):s.reject(g)}),s.promise},"acceptQuery"),j=n((e,t,i)=>{if(y(),i?.signal?.throwIfAborted(),o)throw new Error("Execution is already bound to a session");if(!se(t.cwd))throw new Error("Session cwd must be an absolute path");const s=H.configure(t.mcpServers??[],a.mcpServers),l=new fe(e,async g=>{try{await r.callbacks.sessionUpdate(g)}catch(b){throw z(b),b}},c,g=>U(e,t.cwd,g)),A=f.subscribe(e,g=>l.accept(g));o=e,w={cwd:t.cwd,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:a.additionalDirectories,mcpServers:s},p=l,O=A,O.closed.then(g=>{g.reason==="failed"&&z(g.error)}).catch(()=>{})},"bindSession"),B=n(e=>P(e,async t=>{const{cwd:i,fs:s,settings:l,product:A,agents:g,agent:b}=N(),_=await f.readSessionCatalog({cwd:i,fs:s,settings:l,product:A,agents:g,agent:b,signal:t.signal});t.signal.throwIfAborted(),y(),await p.accept({type:"agent_event",session_id:o,origin:{},event:{type:"catalog",data:_}})}),"publishCatalog");return{capabilities:{...R,session:{...R.session,mcp:{...R.session.mcp,acp:{}}}},supports:Y,dispose:L,newSession:n(async(e,t)=>{if(y(),o)throw new Error("Execution is already bound to a session");t?.signal?.throwIfAborted(),c.initializeBlank();const i=ie();return await f.createSession(i,{cwd:e.cwd,signal:t?.signal?AbortSignal.any([v,t.signal]):v}),await U(i,e.cwd,c),j(i,e,t),await p.restoreUsage([]),await B(t),{sessionId:o,configOptions:c.snapshot()}},"newSession"),resumeSession:n(async(e,t)=>{if(y(),o){if(E(e.sessionId),w.cwd!==e.cwd)throw new Error("Session cwd cannot change");if(I)throw new Error("Session is already running")}o||c.restore(await d.runPromise(q.read({sessionId:e.sessionId,cwd:e.cwd})));const i=e.replayFrom?await P(t,s=>ue(f.readSession,e,{signal:s.signal,onUpdate:r.callbacks.sessionUpdate,config:c})):{};if(o)w.additionalDirectories=e.additionalDirectories?[...e.additionalDirectories]:w.additionalDirectories;else{const s=await P(t,l=>ce(f.readSession,e,l.signal));j(e.sessionId,e,t),await p.restoreUsage(s.find(l=>l.snapshot.sessionId===e.sessionId)?.snapshot.history??[],s)}return await B(t),c.lockAgent(),{...i,configOptions:c.snapshot()}},"resumeSession"),prompt:n(async(e,t)=>{E(e.sessionId);const i=await pe(e),s=ae(e._meta);if(s?.mode==="steer"){const l=await f.steer(e.sessionId,i,{expectedRunId:s.expectedRequestId,signal:t?.signal});if(!l.steered)throw new K(J.invalidRequest,l.reason==="stale"?"Active query does not match expectedRequestId":"Session has no active query accepting steer");return{_meta:{"codebuddy.ai/requestId":l.runId}}}return Q(i,e._meta,t)},"prompt"),compactSession:n(async(e,t)=>(E(e.sessionId),Q({type:"compact"},e._meta,t)),"compactSession"),cancelSession:n(async e=>{E(e.sessionId),k?.abort(),await f.interrupt(e.sessionId),await I?.catch(()=>{})},"cancelSession"),closeSession:n(async e=>(E(e.sessionId),await L(),{}),"closeSession"),setAuthentication:n(async e=>e.generation<m?{applied:!1}:(u=e,m=e.generation,{applied:!0}),"setAuthentication"),clearAuthentication:n(async e=>e.generation<m?{applied:!1}:(u=void 0,m=e.generation,{applied:!0}),"clearAuthentication"),refreshUserConfig:n(async(e,t)=>{y(),t?.signal?.throwIfAborted();const i=++S,s=await d.runPromise((h.resolveOptions??workspaceQueryOptions)(r).pipe(d.provideContext(x)),{signal:t?.signal});y(),t?.signal?.throwIfAborted(),i===S&&(o&&f.reload(o,{settings:s.settings??{},agents:s.agents??{}}),a={...a,settings:s.settings,agents:s.agents})},"refreshUserConfig"),setSessionConfigOption:n(async(e,t)=>{if(E(e.sessionId),t?.signal?.throwIfAborted(),I)throw new K(J.invalidParams,"Cannot change Agent configuration during a prompt");const i=c.copy();i.set(e),await U(e.sessionId,w.cwd,i),c.replace(i);const s=c.snapshot();return await p.configuration(s),{configOptions:s}},"setSessionConfigOption")}}),a=>d.promise(()=>a.dispose())),"open")})}))}n(AgentBackend,"AgentBackend");
|
|
1
|
+
var re=Object.defineProperty;var n=(w,a)=>re(w,"name",{value:a,configurable:!0});import{randomUUID as ae}from"node:crypto";import{isAbsolute as ce}from"node:path";import{Effect as i,Layer as de}from"effect";import{abortReason as le}from"../internal/async.js";import{promptMetadata as ue}from"../protocol/prompt.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as V,AgentHarnessInvalidParamsError as W,AgentHarnessJsonRpcError as Y}from"../server/errors.js";import{readSessionTree as fe}from"../subagent/history.js";import{AgentServer as ge}from"./agent-server.js";import{SessionConfigStore as we}from"./config-store.js";import{replayCodecs as H,replaySession as pe}from"./replay.js";import{SessionRuntime as Z,SessionRuntimeClosedError as L}from"./runtime.js";import{ServerSessionConfig as $}from"./server-config.js";import{ServerSessionEvents as he}from"./server-events.js";import{serverCanUseTool as ye}from"./server-interactions.js";import{ServerSessionMcp as me}from"./server-mcp.js";import{serverPromptInput as be}from"./server-prompt.js";export function workspaceQueryOptions(w){if(!w.workspace?.product)return i.fail(new Error("In-process Agent backend requires a resolved workspace Product"));const a=w.workspace.product;return i.succeed({product:{...a,skills:a.skills??[],commands:a.commands??[]},persistSession:!0,tools:{type:"preset",preset:"default"},freezeToolsDuringRun:!0,...process.platform==="win32"?{usePty:!1}:{},settings:{enabledPlugins:{...w.pluginSettings.enabledPlugins}}})}n(workspaceQueryOptions,"workspaceQueryOptions");const ee={compact:!0,configReload:!0,promptSteer:!0},T={session:{additionalDirectories:{},delete:{},fork:{},mcp:{acp:{},http:{},stdio:{}},prompt:{image:{},embeddedContext:{}}}};export function AgentBackend(w={}){return de.effect(Z,i.gen(function*(){const a=yield*ge,U=yield*we,R=yield*i.context();yield*i.tryPromise({try:H,catch:n(r=>r,"catch")});const E=new AbortController;return yield*i.addFinalizer(()=>i.sync(()=>E.abort(new L))),Z.of({profile:{capabilities:T,supports:ee,checkpoints:w.checkpoints===!0},prepare:i.void,readCatalog:n((r,h)=>i.gen(function*(){const c=yield*(w.resolveOptions??workspaceQueryOptions)(h).pipe(i.provideContext(R)),A=yield*i.tryPromise({try:n(()=>$.create(c,h.workspace?.sessionModelConfigOption,h.clientCapabilities),"try"),catch:n(p=>p,"catch")}),d=h.cwd??c.cwd??process.cwd();A.restore(yield*U.read({sessionId:r,cwd:d}));const b=yield*i.tryPromise(()=>a.readSession(r,{cwd:d,signal:h.signal}));b?.mainAgent&&A.update({agent:b.mainAgent});const{fs:l,settings:v,product:_,agents:y,agent:u}={...c,...A.queryOptions};return yield*i.tryPromise({try:n(async()=>{const p=AbortSignal.any([E.signal,h.signal]),x=await a.readSessionCatalog({cwd:d,fs:l,settings:v,product:_,agents:y,agent:u,signal:p});return p.throwIfAborted(),(await H()).projectAgentEvent({type:"agent_event",session_id:r,event:{type:"catalog",data:x}})},"try"),catch:n(p=>p,"catch")})}),"readCatalog"),rewind:n((r,h)=>i.tryPromise({try:n(async()=>{const c=await a.readSession(r.sessionId,h);if(!c)throw new W("Session history was not found");const{selectRewindMessage:A}=await H();let d;try{d=A(c,r._meta)}catch(b){throw b instanceof Error&&"code"in b&&["invalid_history","invalid_boundary","cursor_not_found"].includes(String(b.code))?new W(b.message):b}return await a.rewind(r.sessionId,{...h,to:d}),{}},"try"),catch:n(c=>c,"catch")}),"rewind"),open:n(r=>i.acquireRelease(i.gen(function*(){const h=yield*i.all([(w.resolveOptions??workspaceQueryOptions)(r).pipe(i.provideContext(R)),w.resolveConfigDefaults?w.resolveConfigDefaults(r).pipe(i.provideContext(R)):i.succeed({})],{concurrency:"unbounded"});let c=h[0];const A=h[1],d=yield*i.tryPromise({try:n(()=>$.create(c,r.workspace?.sessionModelConfigOption,r.clientCapabilities,A),"try"),catch:n(e=>e,"catch")}),b=AbortSignal.any([r.signal,E.signal]);b.throwIfAborted();let l,v={},_,y,u,p=-1,x=0,C,P,z,N,M=!1;const Q=n((e,t,s)=>i.runPromise(U.write({sessionId:e,cwd:t},s.selections())),"saveConfig"),F=n(e=>{M||z||(M=!0,N=e,P?.abort(e),y?.fail(e),r.onFailure(e))},"fail"),G=new me(r.callbacks,()=>P?.signal??E.signal),S=n(()=>{if(z||E.signal.aborted)throw new L;if(M)throw N},"assertOpen"),O=n(e=>{if(S(),e!==l)throw new Error("Session does not belong to this execution")},"assertSession"),D=n((e,t)=>{if(S(),C)throw new Error("Session is already running");const s=new AbortController;P=s;const o=AbortSignal.any([s.signal,E.signal,...e?.signal?[e.signal]:[]]),f=n(()=>s.abort(le(o)),"abort");o.addEventListener("abort",f,{once:!0}),o.aborted&&f();const m=Promise.resolve().then(()=>(o.throwIfAborted(),t(s))).finally(()=>{o.removeEventListener("abort",f),C=void 0,P=void 0});return C=m,m},"run"),j=n(()=>z??=(async()=>{P?.abort(new L);try{if(!l)return;await a.interrupt(l),await C?.catch(()=>{})}finally{try{l&&await a.close(l)}finally{_?.unsubscribe(),await G.close()}}})(),"dispose"),te=c.canUseTool??ye(r,()=>({id:l,meta:y?.meta??{}}),(e,t)=>y?.interaction(e,t)??Promise.resolve()),ne=n(async({signal:e})=>{e.throwIfAborted(),S();const t=u;if(!t||!r.callbacks.refreshAuthentication)throw new Error("Authentication required");const s=await r.callbacks.refreshAuthentication({accountId:t.account.id,generation:t.generation},{signal:e});if(e.throwIfAborted(),S(),!u||s.account.id!==t.account.id||p>s.generation)throw new Error("Authentication changed during refresh");return u=s,p=s.generation,{accessToken:s.credential.accessToken,method:s.credential.type}},"refreshAuthentication"),se=n(async e=>{if(!w.resolveConfigDefaults)return;const t=await i.runPromise(w.resolveConfigDefaults({...r,signal:e}).pipe(i.provideContext(R)),{signal:e});S(),e.throwIfAborted(),d.refreshDefaults(t)&&y&&await y.configuration(d.snapshot())},"refreshDefaults"),B=n(()=>({...c,...v,...d.queryOptions,includePartialMessages:!0,...!r.clientCapabilities.elicitation?.form&&!c.canUseTool?{disallowedTools:[...new Set([...c.disallowedTools??[],"AskUserQuestion"])]}:{},headers:{...w.headers,...u?.credential.domain?{"X-Domain":u.credential.domain}:{},...u?.account.organization?.id?{"X-Tenant-Id":u.account.organization.id}:{},...c.headers},auth:u?{accessToken:u.credential.accessToken,method:u.credential.type,...r.callbacks.refreshAuthentication?{refresh:ne}:{}}:p<0?c.auth:void 0,account:u?{uid:u.account.id,...u.account.organization?.id?{enterpriseId:u.account.organization.id}:{}}:p<0?c.account:void 0,canUseTool:te}),"runOptions"),J=n((e,t,s)=>{const o=Promise.withResolvers();let f=!1;return D(s,async g=>{const k=B();await w.prepareSandboxCenter?.(k,g.signal),g.signal.throwIfAborted();const I=a.query(l,e,{...k,_meta:t,abortController:g});d.lockAgent(),I.catch(()=>{});try{const q=y.begin(I.runId);f=!0,o.resolve({_meta:{"codebuddy.ai/requestId":I.runId}}),await q;const oe=await y.waitForCompletion(I.runId);await I.catch(ie=>{if(oe.stopReason!=="error")throw ie}),S()}catch(q){throw g.abort(q),await a.interrupt(l),await I.catch(()=>{}),q}}).catch(g=>{f?F(g):o.reject(g)}),o.promise},"acceptQuery"),X=n((e,t,s)=>{if(S(),s?.signal?.throwIfAborted(),l)throw new Error("Execution is already bound to a session");if(!ce(t.cwd))throw new Error("Session cwd must be an absolute path");const o=G.configure(t.mcpServers??[],c.mcpServers),f=new he(e,async g=>{try{await r.callbacks.sessionUpdate(g)}catch(k){throw F(k),k}},d,g=>Q(e,t.cwd,g)),m=a.subscribe(e,g=>f.accept(g),{format:"acp-v2"});l=e,v={cwd:t.cwd,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:c.additionalDirectories,mcpServers:o},y=f,_=m,_.closed.then(g=>{g.reason==="failed"&&F(g.error)}).catch(()=>{})},"bindSession"),K=n(e=>D(e,async t=>{const{cwd:s,fs:o,settings:f,product:m,agents:g,agent:k}=B(),I=await a.readSessionCatalog({cwd:s,fs:o,settings:f,product:m,agents:g,agent:k,signal:t.signal});t.signal.throwIfAborted(),S(),await y.catalog(I)}),"publishCatalog");return{capabilities:{...T,session:{...T.session,mcp:{...T.session.mcp,acp:{}}}},supports:ee,dispose:j,newSession:n(async(e,t)=>{if(S(),l)throw new Error("Execution is already bound to a session");t?.signal?.throwIfAborted(),d.initializeBlank();const s=ae();return await a.createSession(s,{cwd:e.cwd,signal:t?.signal?AbortSignal.any([b,t.signal]):b}),X(s,e,t),await y.restoreUsage([]),await K(t),{sessionId:l,configOptions:d.snapshot()}},"newSession"),resumeSession:n(async(e,t)=>{if(S(),l){if(O(e.sessionId),v.cwd!==e.cwd)throw new Error("Session cwd cannot change");if(C)throw new Error("Session is already running")}l||d.restore(await i.runPromise(U.read({sessionId:e.sessionId,cwd:e.cwd})));const s=e.replayFrom?await D(t,o=>pe(a.readSession,e,{signal:o.signal,onUpdate:r.callbacks.sessionUpdate,config:d})):{};if(l)v={...v,additionalDirectories:[...e.additionalDirectories??[]],mcpServers:G.configure(e.mcpServers??[],c.mcpServers)};else{const o=await D(t,m=>fe(a.readSession,e,m.signal)),f=o.find(m=>m.snapshot.sessionId===e.sessionId)?.snapshot;f?.mainAgent&&d.update({agent:f.mainAgent}),X(e.sessionId,e,t),await y.restoreUsage(o.find(m=>m.snapshot.sessionId===e.sessionId)?.snapshot.history??[],o)}return await K(t),d.lockAgent(),{...s,configOptions:d.snapshot()}},"resumeSession"),prompt:n(async(e,t)=>{O(e.sessionId);const s=await be(e),o=ue(e._meta);if(o?.mode==="steer"){const f=await a.steer(e.sessionId,s,{expectedRunId:o.expectedRequestId,signal:t?.signal});if(!f.steered)throw new Y(V.invalidRequest,f.reason==="stale"?"Active query does not match expectedRequestId":"Session has no active query accepting steer");return{_meta:{"codebuddy.ai/requestId":f.runId}}}return J(s,e._meta,t)},"prompt"),compactSession:n(async(e,t)=>(O(e.sessionId),J({type:"compact"},e._meta,t)),"compactSession"),cancelSession:n(async e=>{O(e.sessionId),P?.abort(),await a.interrupt(e.sessionId),await C?.catch(()=>{})},"cancelSession"),closeSession:n(async e=>(O(e.sessionId),await j(),{}),"closeSession"),setAuthentication:n(async e=>e.generation<p?{applied:!1}:(u=e,p=e.generation,{applied:!0}),"setAuthentication"),clearAuthentication:n(async e=>e.generation<p?{applied:!1}:(u=void 0,p=e.generation,{applied:!0}),"clearAuthentication"),refreshUserConfig:n(async(e,t)=>{S(),t?.signal?.throwIfAborted();const s=++x,o=await i.runPromise((w.resolveOptions??workspaceQueryOptions)(r).pipe(i.provideContext(R)),{signal:t?.signal});S(),t?.signal?.throwIfAborted(),s===x&&(l&&a.reload(l,{settings:o.settings??{},agents:o.agents??{}}),c={...c,settings:o.settings,agents:o.agents},await se(t?.signal??r.signal))},"refreshUserConfig"),setSessionConfigOption:n(async(e,t)=>{if(O(e.sessionId),t?.signal?.throwIfAborted(),C)throw new Y(V.invalidParams,"Cannot change Agent configuration during a prompt");const s=d.copy();s.set(e),await Q(e.sessionId,v.cwd,s),d.replace(s);const o=d.snapshot();return await y.configuration(o),{configOptions:o}},"setSessionConfigOption")}}),h=>i.promise(()=>h.dispose())),"open")})}))}n(AgentBackend,"AgentBackend");
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ConfigReader } from '../config/types.js';
|
|
2
|
+
import type { SessionConfigDefaults } from './server-config.js';
|
|
3
|
+
/** Read the Host's effective workspace setting for ACP display, without adding an Agent execution override. */
|
|
4
|
+
export declare function readSessionConfigDefaults(config: ConfigReader, cwd: string, signal: AbortSignal): Promise<SessionConfigDefaults>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d=Object.defineProperty;var a=(e,t)=>d(e,"name",{value:t,configurable:!0});import{isRecord as b}from"../internal/guards.js";export async function readSessionConfigDefaults(e,t,o){o.throwIfAborted();let n;try{n=await e.readConfig({cwd:t},{signal:o})}catch{return o.throwIfAborted(),{readFailed:!0}}o.throwIfAborted();const r=n.config.sandbox;return b(r)&&typeof r.enabled=="boolean"?{sandboxEnabled:r.enabled}:{}}a(readSessionConfigDefaults,"readSessionConfigDefaults");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Schema } from 'effect';
|
|
2
2
|
declare const document: Schema.Struct<{
|
|
3
|
-
readonly version: Schema.Literal<
|
|
3
|
+
readonly version: Schema.Literal<2>;
|
|
4
4
|
readonly values: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Boolean]>>;
|
|
5
5
|
}>;
|
|
6
6
|
export type SessionConfigValues = typeof document.Type['values'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var r=(c,s)=>p(c,"name",{value:s,configurable:!0});import{createHash as v,randomUUID as g}from"node:crypto";import{mkdir as x,open as N,readFile as f,rename as S,rm as O}from"node:fs/promises";import{join as l,resolve as U}from"node:path";import{Context as E,Effect as i,Layer as y,Schema as t}from"effect";const w=t.Record(t.String,t.Union([t.String,t.Boolean])),$=t.Struct({version:t.Literal(1),values:w}),h=t.Struct({version:t.Literal(2),values:w});function a(c){return v("sha256").update(JSON.stringify([U(c.cwd),c.sessionId])).digest("hex")}r(a,"keyOf");export class SessionConfigStore extends E.Service()("@genie/agent-harness/session/SessionConfigStore"){static{r(this,"SessionConfigStore")}static layer(s){return y.succeed(SessionConfigStore,SessionConfigStore.of({read:r(o=>i.tryPromise({try:r(async()=>{try{const e=t.decodeUnknownSync(t.Union([$,h]))(JSON.parse(await f(l(s,`${a(o)}.selections.json`),"utf8").catch(n=>{if(n.code!=="ENOENT")throw n;return f(l(s,`${a(o)}.json`),"utf8")})));if(e.version===1){const n={...e.values};return n.sandbox===!1&&delete n.sandbox,n}return e.values}catch(e){if(e.code==="ENOENT")return{};throw e}},"try"),catch:r(e=>e,"catch")}),"read"),write:r((o,e)=>i.tryPromise({try:r(async()=>{const n=JSON.stringify(t.decodeUnknownSync(h)({version:2,values:e}));await x(s,{recursive:!0,mode:448});const m=l(s,`${a(o)}.selections.json`),d=`${m}.${g()}.tmp`;try{const u=await N(d,"wx",384);try{await u.writeFile(n),await u.sync()}finally{await u.close()}await S(d,m)}finally{await O(d,{force:!0})}},"try"),catch:r(n=>n,"catch")}),"write")}))}static{this.memory=y.sync(SessionConfigStore,()=>{const s=new Map;return SessionConfigStore.of({read:r(o=>i.sync(()=>structuredClone(s.get(a(o))??{})),"read"),write:r((o,e)=>i.sync(()=>{s.set(a(o),structuredClone(e))}),"write")})})}}
|
package/lib/session/local-fs.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var r=(e,i)=>c(e,"name",{value:i,configurable:!0});import{access as l,
|
|
1
|
+
var c=Object.defineProperty;var r=(e,i)=>c(e,"name",{value:i,configurable:!0});import{access as l,lstat as m,mkdir as o,readdir as s,readFile as a,realpath as n,rename as y,rm as F,stat as d,writeFile as u}from"node:fs/promises";export const localFs={pathStyle:"native",readFile:r(e=>a(e,"utf8"),"readFile"),readFileBuffer:r(e=>a(e),"readFileBuffer"),writeFile:r((e,i)=>u(e,i),"writeFile"),exists:r(async e=>{try{return await l(e),!0}catch(i){const t=i.code;if(t==="ENOENT"||t==="ENOTDIR")return!1;throw i}},"exists"),stat:r(async e=>{const i=await d(e);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),size:i.size,mtime:i.mtime}},"stat"),lstat:r(async e=>{const i=await m(e);return{isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink(),size:i.size,mtime:i.mtime}},"lstat"),realpath:n,mkdir:r(async(e,i)=>{await o(e,i)},"mkdir"),readdir:r(e=>s(e),"readdir"),readdirWithFileTypes:r(async e=>(await s(e,{withFileTypes:!0})).map(i=>({name:i.name,isFile:i.isFile(),isDirectory:i.isDirectory(),isSymbolicLink:i.isSymbolicLink()})),"readdirWithFileTypes"),rm:r((e,i)=>F(e,i),"rm"),mv:r((e,i)=>y(e,i),"mv")};
|
package/lib/session/replay.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { AcpV2ResumeSessionRequest, AcpV2UpdateSessionNotification } from '
|
|
|
4
4
|
import { type SessionHistoryReader, type SubagentHistory } from '../subagent/history.js';
|
|
5
5
|
import { SessionConfigStore } from './config-store.js';
|
|
6
6
|
import type { SessionOpenOptions } from './runtime.js';
|
|
7
|
-
import { ServerSessionConfig } from './server-config.js';
|
|
7
|
+
import { ServerSessionConfig, type SessionConfigDefaults } from './server-config.js';
|
|
8
8
|
import { type AgentHarnessResumeSessionRequest, type AgentHarnessResumeSessionResponse } from './turn.js';
|
|
9
9
|
export interface SessionReplayOptions {
|
|
10
10
|
readonly signal: AbortSignal;
|
|
@@ -48,6 +48,6 @@ declare const SessionReplay_base: Context.ServiceClass<SessionReplay, "@genie/ag
|
|
|
48
48
|
}>;
|
|
49
49
|
/** Reads transcripts and Host selections; uses the admitted Product without acquiring an executor. */
|
|
50
50
|
export declare class SessionReplay extends SessionReplay_base {
|
|
51
|
-
static layer(options?: ReadSessionOptions, readFile?: (path: string) => Promise<Uint8Array>): Layer.Layer<SessionReplay, never, SessionConfigStore>;
|
|
51
|
+
static layer(options?: ReadSessionOptions, readFile?: (path: string) => Promise<Uint8Array>, readDefaults?: (cwd: string, signal: AbortSignal) => Promise<SessionConfigDefaults>): Layer.Layer<SessionReplay, never, SessionConfigStore>;
|
|
52
52
|
}
|
|
53
53
|
export {};
|
package/lib/session/replay.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var S=Object.defineProperty;var
|
|
1
|
+
var S=Object.defineProperty;var r=(l,o)=>S(l,"name",{value:o,configurable:!0});import{Context as b,Effect as p,Layer as x}from"effect";import{isRecord as A}from"../internal/guards.js";import{loadAgentServerModule as I}from"../runtime/private-runtime-role.js";import{AgentHarnessInvalidParamsError as y}from"../server/errors.js";import{createSubagentHistory as v,readSessionTree as C}from"../subagent/history.js";import{SessionConfigStore as R}from"./config-store.js";import{ServerSessionConfig as h}from"./server-config.js";import{turnReplayValidationError as U}from"./turn.js";let _;export const replayCodecs=r(()=>_??=import("#agent-harness-components/session-replay"),"replayCodecs");export async function replaySession(l,o,s,g={},w){s.signal.throwIfAborted();const t=U(o.replayFrom);if(t)throw new y(t);const e=await l(o.sessionId,{...g,cwd:o.cwd,signal:s.signal,includeSubagents:!0});if(!e)throw new y(`Session '${o.sessionId}' was not found in the requested cwd`);if(s.signal.throwIfAborted(),e.mainAgent&&s.config?.update({agent:e.mainAgent}),o.replayFrom==null)return{};const{projectSessionReplay:a,createSessionUsage:f}=await replayCodecs(),c=s.config?f(e.sessionId,e.history,await C(l,o,s.signal,g,e)):void 0,i=o.replayFrom,u=await a(e,i,w).catch(n=>{throw n instanceof Error&&"code"in n&&typeof n.code=="string"&&["invalid_history","invalid_replay","cursor_not_found"].includes(n.code)?new y(n.message):n});for(const n of u.events){s.signal.throwIfAborted();const d=n.update._meta;if(A(d)){const m=d["codebuddy.ai/requestId"];typeof m=="string"&&d["codebuddy.ai/rootRequestId"]===void 0&&(n.update._meta={...d,"codebuddy.ai/rootRequestId":m})}await s.onUpdate(n)}if(s.config){const n=c?.context,d=s.config.contextSize();s.signal.throwIfAborted(),n&&d!==void 0&&await s.onUpdate({sessionId:e.sessionId,update:{sessionUpdate:"usage_update",used:n.used,size:d,...c?.cost?{cost:c.cost}:{}}})}return s.signal.throwIfAborted(),u.response}r(replaySession,"replaySession");export class SessionReplay extends b.Service()("@genie/agent-harness/session/SessionReplay"){static{r(this,"SessionReplay")}static layer(o={},s,g){return x.effect(SessionReplay,p.gen(function*(){const w=yield*R;return SessionReplay.of({subagents:v(async(t,e)=>(await I()).readSession(t,e),async(...t)=>(await replayCodecs()).projectSessionReplay(...t),o,s,async(t,e,a,f)=>{const c=await h.create({product:t.workspace?.product});c.restore(await p.runPromise(w.read(t)));const i=(await replayCodecs()).createSessionUsage(t.sessionId,[],a).snapshot(e),u=c.contextSize(i.context?.modelId);return f.throwIfAborted(),i.context&&u!==void 0?{sessionId:e,update:{sessionUpdate:"usage_update",used:i.context.used,size:u,...i.cost?{cost:i.cost}:{}}}:void 0}),resume:r((t,e)=>p.tryPromise({try:r(async()=>{const a=await I(),[f,c]=await Promise.all([g?.(t.cwd,e.signal),p.runPromise(w.read({sessionId:t.sessionId,cwd:t.cwd}))]),i=await h.create({product:e.workspace?.product},e.workspace?.sessionModelConfigOption,e.clientCapabilities,f);return i.restore(c),{...await replaySession(a.readSession,t,{...e,config:i},o,s),configOptions:i.snapshot()}},"try"),catch:r(a=>a,"catch")}),"resume")})}))}}
|
|
@@ -5,6 +5,10 @@ import type { WorkspaceSessionModelConfigOption } from '../runtime/product-manag
|
|
|
5
5
|
import type { SessionConfigValues } from './config-store.js';
|
|
6
6
|
export type SessionConfigProjector = (options: QueryOptions, catalog?: WorkspaceSessionModelConfigOption) => SessionConfigOption[];
|
|
7
7
|
type ConfigQueryOptions = Pick<QueryOptions, 'model' | 'permissionMode' | 'thinking' | 'effort' | 'contextWindow' | 'agent' | 'multitask' | 'sandboxEnabled'>;
|
|
8
|
+
export interface SessionConfigDefaults {
|
|
9
|
+
readonly sandboxEnabled?: boolean;
|
|
10
|
+
readonly readFailed?: boolean;
|
|
11
|
+
}
|
|
8
12
|
/** Session selections are validated against the same projection sent to clients. */
|
|
9
13
|
export declare class ServerSessionConfig {
|
|
10
14
|
private readonly options;
|
|
@@ -13,10 +17,13 @@ export declare class ServerSessionConfig {
|
|
|
13
17
|
private readonly restoreProject;
|
|
14
18
|
private readonly projectContextSize;
|
|
15
19
|
private readonly values;
|
|
20
|
+
/** Explicit Host choices and subsequent Agent configuration transitions survive resume. */
|
|
21
|
+
private explicitSelections;
|
|
16
22
|
private agentLocked;
|
|
17
23
|
private modelExplicit;
|
|
18
24
|
private constructor();
|
|
19
|
-
static create(options: QueryOptions, catalog?: WorkspaceSessionModelConfigOption, capabilities?: AcpV2ClientCapabilities): Promise<ServerSessionConfig>;
|
|
25
|
+
static create(options: QueryOptions, catalog?: WorkspaceSessionModelConfigOption, capabilities?: AcpV2ClientCapabilities, defaults?: SessionConfigDefaults): Promise<ServerSessionConfig>;
|
|
26
|
+
refreshDefaults(defaults: SessionConfigDefaults): boolean;
|
|
20
27
|
get queryOptions(): ConfigQueryOptions;
|
|
21
28
|
copy(): ServerSessionConfig;
|
|
22
29
|
replace(config: ServerSessionConfig): void;
|
|
@@ -24,10 +31,12 @@ export declare class ServerSessionConfig {
|
|
|
24
31
|
restore(values: SessionConfigValues): void;
|
|
25
32
|
snapshot(): SessionConfigOption[];
|
|
26
33
|
contextSize(modelId?: string): number | undefined;
|
|
27
|
-
update(values: Pick<ConfigQueryOptions, 'permissionMode' | 'agent' | 'multitask'
|
|
34
|
+
update(values: Pick<ConfigQueryOptions, 'permissionMode' | 'agent' | 'multitask'>, rememberChanges?: boolean): boolean;
|
|
28
35
|
lockAgent(): void;
|
|
29
36
|
initializeBlank(): void;
|
|
30
37
|
set(params: AcpV2SetSessionConfigOptionRequest): void;
|
|
38
|
+
private reconcileSelections;
|
|
39
|
+
private remember;
|
|
31
40
|
private apply;
|
|
32
41
|
}
|
|
33
42
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var r=(c,e)=>h(c,"name",{value:e,configurable:!0});import{AgentHarnessInvalidParamsError as l}from"../server/errors.js";function d(c){return c?.type==="select"&&Array.isArray(c.options)}r(d,"isSelect");export class ServerSessionConfig{static{r(this,"ServerSessionConfig")}constructor(e,i,n,s,t){this.options=e,this.catalog=i,this.project=n,this.restoreProject=s,this.projectContextSize=t,this.explicitSelections={},this.agentLocked=!1;const o=e.model??i?.currentValue;if(this.modelExplicit=e.model!==void 0,o&&i&&!i.options.some(a=>a.value===o))throw new l("Agent model is outside the admitted Harness catalog");this.values={model:o,permissionMode:e.permissionMode??e.settings?.permissions?.defaultMode??"default",...e.thinking?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.contextWindow!==void 0?{contextWindow:e.contextWindow}:{},...e.agent!==void 0?{agent:e.agent}:{},...e.multitask!==void 0?{multitask:e.multitask}:{},...e.sandboxEnabled!==void 0?{sandboxEnabled:e.sandboxEnabled}:{}}}static async create(e,i,n={},s={}){const{createSessionConfigProjector:t,projectSessionContextSize:o}=await import("#agent-harness-components/session-config"),a=s.sandboxEnabled===void 0?{...e}:{...e,settings:{...e.settings,sandbox:{...e.settings?.sandbox,enabled:s.sandboxEnabled}}},u=await t(a,{_meta:{"codebuddy.ai":{mainAgentSupport:!0}}});return new ServerSessionConfig(a,i,await t(a,n),u,o)}refreshDefaults(e){if(e.readFailed)return!1;const i=JSON.stringify(this.snapshot());return this.options.settings={...this.options.settings,sandbox:{...this.options.settings?.sandbox,enabled:e.sandboxEnabled}},i!==JSON.stringify(this.snapshot())}get queryOptions(){return{...this.values}}copy(){const e=new ServerSessionConfig(this.options,this.catalog,this.project,this.restoreProject,this.projectContextSize);return e.replace(this),e}replace(e){for(const i of Object.keys(this.values))delete this.values[i];Object.assign(this.values,structuredClone(e.values)),this.explicitSelections=structuredClone(e.explicitSelections),this.agentLocked=e.agentLocked,this.modelExplicit=e.modelExplicit}selections(){return structuredClone(this.explicitSelections)}restore(e){const i=e.model,n=typeof i=="string"&&this.catalog!==void 0&&!this.catalog.options.some(s=>s.value===i);for(const s of["multitask","sandbox","agent","model","mode","context_window","thought_level"]){if(n&&["model","context_window","thought_level"].includes(s))continue;const t=e[s];if(t!==void 0)try{this.apply(typeof t=="boolean"?{sessionId:"",configId:s,type:"boolean",value:t}:{sessionId:"",configId:s,type:"id",value:t},this.restoreProject),this.remember(s)}catch(o){if(!(o instanceof l))throw o}}}snapshot(){return this.project({...this.options,...this.values},this.catalog)}contextSize(e){return this.projectContextSize({...this.options,...this.values},e)}update(e,i=!1){const n=Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));if(Object.entries(n).every(([t,o])=>this.values[t]===o))return!1;const s=Object.keys(n).filter(t=>this.values[t]!==n[t]);if(Object.assign(this.values,n),i)for(const t of s)this.remember(t==="permissionMode"?"mode":t);return!0}lockAgent(){this.agentLocked=!0}initializeBlank(){const e=this.snapshot().find(i=>i.configId==="agent");d(e)&&!this.values.agent&&this.apply({sessionId:"",configId:"agent",type:"id",value:e.currentValue},this.project)}set(e){this.apply(e,this.project),this.remember(e.configId)}reconcileSelections(){const e=new Map(this.restoreProject({...this.options,...this.values},this.catalog).map(i=>[i.configId,i.currentValue]));for(const[i,n]of Object.entries(this.explicitSelections))e.get(i)!==n&&delete this.explicitSelections[i]}remember(e){this.reconcileSelections();const i=this.restoreProject({...this.options,...this.values},this.catalog).find(n=>n.configId===e);(typeof i?.currentValue=="string"||typeof i?.currentValue=="boolean")&&(this.explicitSelections[e]=i.currentValue)}apply(e,i){const n=i({...this.options,...this.values},this.catalog).find(t=>t.configId===e.configId);if(!n)throw new l(`Unknown Agent configuration option: ${e.configId}`);if(n.type==="boolean"){if(e.type!=="boolean"||typeof e.value!="boolean")throw new l("Agent boolean configuration requires a boolean value");if(e.configId==="multitask"){this.values.multitask=e.value;return}if(e.configId==="sandbox"){this.values.sandboxEnabled=e.value;return}throw new l(`Unsupported Agent configuration option: ${e.configId}`)}if(e.type!=="id"||typeof e.value!="string")throw new l("Agent select configuration requires an option id");if(!(d(n)?n.options.flatMap(t=>"options"in t?t.options:[t]):[]).some(t=>t.value===e.value))throw new l(`Unknown Agent configuration option: ${e.configId}=${e.value}`);switch(e.configId){case"agent":if(this.agentLocked)throw new l("Main Agent can only change in a blank session");if(e.value==="minimal"&&this.values.multitask)throw new l("Disable Multitask before selecting Minimal");if(this.values.agent=e.value,!this.modelExplicit){const t=this.options.product?.agents?.find(o=>o.name===e.value)?.declaredModel;t&&(!this.catalog||this.catalog.options.some(o=>o.value===t))&&(this.values.model=t)}e.value==="minimal"&&this.values.permissionMode==="plan"&&(this.values.permissionMode="default");return;case"mode":this.values.permissionMode=e.value;return;case"model":{this.modelExplicit=!0,this.values.model=e.value,(this.values.thinking!==void 0||this.values.effort!==void 0)&&(this.values.thinking={type:"adaptive"},this.values.effort=null);const t=this.snapshot().find(o=>o.configId==="context_window");this.values.contextWindow!=null&&(!d(t)||!t.options.some(o=>"value"in o&&o.value===String(this.values.contextWindow)))&&(this.values.contextWindow=null);return}case"thought_level":this.values.thinking={type:e.value==="disabled"?"disabled":"adaptive"},this.values.effort=e.value==="disabled"||e.value==="enabled"?null:e.value;return;case"context_window":this.values.contextWindow=Number(e.value);return;default:throw new l(`Unsupported Agent configuration option: ${e.configId}`)}}}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AgentEvent, FormattedSessionEvent, QueryResult } from '#agent-harness-codebuddy/server';
|
|
2
2
|
import type { AcpV2SetSessionConfigOptionResponse, AcpV2UpdateSessionNotification } from '../protocol/acp-v2.js';
|
|
3
3
|
import { type SessionUsageHistory } from './replay.js';
|
|
4
4
|
import type { ServerSessionConfig } from './server-config.js';
|
|
5
|
-
/**
|
|
5
|
+
/** Host policy and delivery for Server-projected ACP; no stream-json conversion. */
|
|
6
6
|
export declare class ServerSessionEvents {
|
|
7
7
|
private readonly sessionId;
|
|
8
8
|
private readonly deliver;
|
|
9
9
|
private readonly config?;
|
|
10
|
-
private readonly
|
|
10
|
+
private readonly persistConfig?;
|
|
11
11
|
private requestId?;
|
|
12
12
|
private delivery;
|
|
13
13
|
private completion?;
|
|
@@ -15,12 +15,10 @@ export declare class ServerSessionEvents {
|
|
|
15
15
|
private accounting?;
|
|
16
16
|
private foregroundError?;
|
|
17
17
|
private resultError?;
|
|
18
|
-
|
|
19
|
-
constructor(sessionId: string, deliver: (update: AcpV2UpdateSessionNotification) => Promise<void>, config?: ServerSessionConfig | undefined, persistConfiguration?: ((candidate: ServerSessionConfig) => Promise<void>) | undefined);
|
|
18
|
+
constructor(sessionId: string, deliver: (update: AcpV2UpdateSessionNotification) => Promise<void>, config?: ServerSessionConfig | undefined, persistConfig?: ((config: ServerSessionConfig) => Promise<void>) | undefined);
|
|
20
19
|
get meta(): Record<string, string>;
|
|
20
|
+
private configurationObserved;
|
|
21
21
|
private readonly interactions;
|
|
22
|
-
private readonly toolStreams;
|
|
23
|
-
private readonly toolParsers;
|
|
24
22
|
private readonly pendingTools;
|
|
25
23
|
interaction(waiting: boolean, meta: Record<string, unknown>): Promise<void>;
|
|
26
24
|
begin(requestId: string): Promise<void>;
|
|
@@ -33,6 +31,10 @@ export declare class ServerSessionEvents {
|
|
|
33
31
|
private send;
|
|
34
32
|
private finishTools;
|
|
35
33
|
private usage;
|
|
36
|
-
|
|
34
|
+
/** Catalog reads are host operations outside the Agent subscription. */
|
|
35
|
+
catalog(data: Extract<AgentEvent['event'], {
|
|
36
|
+
type: 'catalog';
|
|
37
|
+
}>['data']): Promise<void>;
|
|
38
|
+
accept(frame: FormattedSessionEvent<'acp-v2'>): Promise<void>;
|
|
37
39
|
private completeToolInvocation;
|
|
38
40
|
}
|