@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
|
@@ -3,6 +3,7 @@ import { composeAgentHarnessModules } from '../module/compose.js';
|
|
|
3
3
|
import { type AgentHarnessClientIdentity } from '../runtime/client-identity.js';
|
|
4
4
|
import { CodeBuddyProcessContainment } from '../runtime/process-containment.js';
|
|
5
5
|
import { type AgentHarnessProductInput } from '../runtime/product-config.js';
|
|
6
|
+
import { type SandboxCenterOption } from '../runtime/sandbox-center.js';
|
|
6
7
|
import type { TelemetryOptions } from '../telemetry/public.js';
|
|
7
8
|
import { createTelemetry, type RuntimeLifecycleRecorder } from '../telemetry/runtime.js';
|
|
8
9
|
import { AgentHarnessShutdownCoordinator } from './lifecycle.js';
|
|
@@ -14,6 +15,7 @@ export interface ApplicationServicesOptions {
|
|
|
14
15
|
readonly packageVersion: string;
|
|
15
16
|
readonly processRuntime: ApplicationProcessRuntime;
|
|
16
17
|
readonly productConfig?: string | AgentHarnessProductInput;
|
|
18
|
+
readonly sandboxCenter?: SandboxCenterOption;
|
|
17
19
|
readonly signal?: AbortSignal;
|
|
18
20
|
readonly tools?: QueryOptions['tools'];
|
|
19
21
|
readonly strictMcpConfig: boolean;
|
|
@@ -31,4 +33,4 @@ export interface ApplicationServices {
|
|
|
31
33
|
readonly runtimeShutdown: AbortController;
|
|
32
34
|
readonly recordLifecycle: RuntimeLifecycleRecorder;
|
|
33
35
|
}
|
|
34
|
-
export declare function createApplicationServices({ clientIdentity, clientIdentityEnv, dependencies, packageVersion, processRuntime, productConfig, tools, strictMcpConfig, mcp, shutdown, telemetryOptions, signal, }: ApplicationServicesOptions): Promise<ApplicationServices>;
|
|
36
|
+
export declare function createApplicationServices({ clientIdentity, clientIdentityEnv, dependencies, packageVersion, processRuntime, productConfig, sandboxCenter, tools, strictMcpConfig, mcp, shutdown, telemetryOptions, signal, }: ApplicationServicesOptions): Promise<ApplicationServices>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var We=Object.defineProperty;var t=(y,U)=>We(y,"name",{value:U,configurable:!0});import{homedir as Ye}from"node:os";import*as O from"node:path";import{isDeepStrictEqual as Ne}from"node:util";import{Context as p,Effect as m,Exit as g,Layer as s,Logger as c,Option as je,Scope as h}from"effect";import{createAgentProtocolModule as Ge}from"../agent/router.js";import{createAgentV2Facade as qe}from"../agent/v2.js";import{AgentDiscovery as Ke}from"../agent-registry/discovery.js";import{ManagedAuthLocal as Ve}from"../auth/local.js";import{ManagedAuth as Qe}from"../auth/managed.js";import{createAuthProtocolModule as Je}from"../auth/module.js";import{Checkpoints as ve}from"../checkpoint/service.js";import{ConfigFiles as Z}from"../config/files.js";import{createDefaultAgentMcpIntegration as Xe}from"../integration/agent-integration.js";import{PluginMcp as Se}from"../integration/plugin-mcp.js";import{UserMcp as Pe}from"../integration/user-mcp.js";import{requestWithEnvironment as Ze}from"../internal/http.js";import{createMcpServerProtocolModule as $e}from"../mcp-server/module.js";import{composeAgentHarnessModules as er}from"../module/compose.js";import{PluginComponents as $}from"../plugin/components.js";import{createProductProtocolModule as rr}from"../product/module.js";import{preflightCodeBuddyCode as tr}from"../runtime/agent-runtime.js";import{buildAgentHarnessClientIdentityEnv as or,buildAgentHarnessClientIdentityHeaders as nr}from"../runtime/client-identity.js";import{createCodeBuddyAuthRuntime as ir}from"../runtime/codebuddy-auth.js";import{createCodeBuddyProductLifecycle as ar}from"../runtime/codebuddy-product.js";import{DEFAULT_HOST_HEALTH_TIMEOUT_MS as sr,DEFAULT_READY_TIMEOUT_MS as cr}from"../runtime/codebuddy-resource-timeouts.js";import{CodeBuddyProcessContainment as dr}from"../runtime/process-containment.js";import{parseAgentHarnessProductConfig as pr,parseHarnessProductInput as ur}from"../runtime/product-config.js";import{ProductManager as mr}from"../runtime/product-manager.js";import{ProductResolver as we}from"../runtime/product-resolver.js";import{ProductResolverRequestError as lr}from"../runtime/product-resolver-error.js";import{loadProductSource as fr}from"../runtime/product-source.js";import{AgentHarnessServer as hr,DEFAULT_LIFECYCLE_HOOK_TIMEOUT_MS as gr}from"../server/index.js";import{makeServiceRpcs as yr}from"../server/rpc-services.js";import{AgentBackend as Er}from"../session/agent-backend.js";import{AgentServer as Ce}from"../session/agent-server.js";import{SessionConfigStore as vr}from"../session/config-store.js";import{SessionFiles as Sr}from"../session/files.js";import{localFs as Ae}from"../session/local-fs.js";import{localQueryOptions as Pr}from"../session/local-options.js";import{SessionReplay as ke}from"../session/replay.js";import{SessionRuntime as wr}from"../session/runtime.js";import{Sessions as be}from"../session/service.js";import{toExecutorPrivateProxyPolicy as _e}from"../settings/proxy-policy.js";import{createHarnessSettingsRuntime as Cr}from"../settings/runtime.js";import{Settings as Ar}from"../settings/service.js";import{createSubagentProtocolModule as kr}from"../subagent/module.js";import{createEffectTelemetryMetricAggregator as br}from"../telemetry/effect-metric-aggregation.js";import{createTelemetry as _r}from"../telemetry/runtime.js";import{measureStartup as ee,startupProfiler as i}from"../telemetry/startup-profile.js";import{closeInPhases as re,closeTelemetry as Mr,createCloseOnce as b,DEFAULT_TELEMETRY_CLOSE_TIMEOUT_MS as Lr}from"./lifecycle.js";export async function createApplicationServices({clientIdentity:y,clientIdentityEnv:U,dependencies:S,packageVersion:Me,processRuntime:E,productConfig:T,tools:te,strictMcpConfig:Le,mcp:Ie,shutdown:x,telemetryOptions:oe,signal:u}){u?.throwIfAborted();const P=t(e=>m.runPromise(e,{signal:u}),"runStartupEffect"),z=x,ne={name:"@genie/agent-harness",title:"Agent Harness",version:Me},ie=(S.preflightCodeBuddyCode??tr)(),_=new dr,F=new AbortController,l=_r(oe),B=b(()=>Mr(l,E,Math.max(1,Math.min(x.remainingMs(),oe.flushTimeoutMs??Lr))));x.registerTelemetryCloser(B);const ae=br(e=>l.recordEffectMetrics(e));try{E.addFinalizer(B)}catch(e){throw await B(),e}try{E.setTelemetryObserver({log:t(e=>l.recordEffectLog(e),"log"),metrics:t(e=>ae.record("harness",e),"metrics"),span:t(e=>l.recordEffectSpan(e),"span")})}catch{}const k=t(e=>l.recordLifecycle(e),"recordLifecycle");let se=!1;const W=t((e,d,D)=>{se||(se=!0,k({component:"server",error:e,phase:"runtime",process:{pid:process.pid},reason:D,state:d}))},"recordRootFailure");_.signal.addEventListener("abort",()=>{W(_.signal.reason,"containment_tripped","containment_failed")},{once:!0});const De={log(e){try{l.recordEffectLog(e)}catch{}},metrics(e){ae.record("executor",e)},span(e){try{l.recordEffectSpan(e)}catch{}}};let w,n,R,M,a,A,L,C;const I=h.makeUnsafe(),Y=b(e=>m.runPromise(h.close(I,e===void 0?g.void:g.fail(e))));E.addFinalizer(()=>Y(void 0));const N=t(()=>{R&&m.runPromise(m.forkIn(R.prepare,I,{startImmediately:!0})).catch(()=>{})},"prepareRuntime"),ce=h.makeUnsafe(),j=b(async e=>{try{await a?.close(e)}finally{await m.runPromise(h.close(ce,e===void 0?g.void:g.fail(e)))}});E.addFinalizer(()=>j(void 0));const G=h.makeUnsafe(),q=b(e=>m.runPromise(h.close(G,e===void 0?g.void:g.fail(e))));E.addFinalizer(()=>q(void 0));const de=h.makeUnsafe(),K=b(e=>m.runPromise(h.close(de,e===void 0?g.void:g.fail(e))));E.addFinalizer(()=>K(void 0));const pe=h.makeUnsafe(),V=b(async e=>{try{await n?.close(e)}finally{await m.runPromise(h.close(pe,e===void 0?g.void:g.fail(e)))}});E.addFinalizer(()=>V(void 0));try{const e={...process.env},d={...U},D=typeof T=="object"?ur(T):fr(T,{parse:pr});u?.throwIfAborted(),i()?.markStart("harness.product");const Te=await P(s.buildWithScope(we.layer({projection:D.projection,baseConfiguration:T===void 0?void 0:{},packageRoot:ie.productRoot??O.dirname(ie.packageJsonPath),clientIdentity:{ideName:y.ideName,ideType:y.ideType,ideVersion:y.ideVersion,...y.userAgent===void 0?{}:{userAgent:y.userAgent}},environment:t(()=>({...e,...d}),"environment")}),ce));a=await(S.createProductManager??((r,o)=>mr.create(r,o)))({bootstrap:D.bootstrap,projection:D.projection,resolver:p.get(Te,we)},u),i()?.markEnd("harness.product");const Fe=t(()=>{if(!a)throw new Error("Product manager is not ready");return a.getLaunchSnapshot()},"productLaunch");u?.throwIfAborted(),i()?.markStart("harness.config");const Re=await P(s.buildWithScope(Z.layer.pipe(s.provide(c.layer([c.withConsoleError(c.formatLogFmt)]))),G));i()?.markEnd("harness.config");const me=p.get(Re,Z);u?.throwIfAborted(),i()?.markStart("harness.settings"),A=await(S.createSettingsRuntime??Cr)({ambientEnvironment:e,config:me,environment:d,observe:t(r=>l.recordEffectLog({annotations:{component:"harness",operation:"refresh",reason:r.reason,resource:"policy","runtime.role":"harness",status:r.status,...r.policy===void 0?{}:{mode:r.policy.mode,noProxyCount:r.policy.noProxyCount,proxyConfigured:r.policy.proxyConfigured,proxySupport:r.policy.proxySupport,revision:r.policy.revision}},level:r.status==="failed"?"warn":"info",message:"harness.settings.proxy"}),"observe"),processRuntime:E}),i()?.markEnd("harness.settings");const le=vr.layer(O.join(e.CODEBUDDY_CONFIG_DIR?.trim()?O.resolve(e.CODEBUDDY_CONFIG_DIR.trim()):O.join(Ye(),".codebuddy"),"harness","sessions"));u?.throwIfAborted(),i()?.markStart("harness.session-runtime");const fe=await P(s.buildWithScope(S.sessionRuntimeLayer??Er({checkpoints:!0,headers:nr(y),resolveOptions:t(r=>m.map(Pr(r),o=>({...o,...te===void 0?{}:{tools:te}})),"resolveOptions")}).pipe(s.provideMerge(Ce.layer({product:{},fs:Ae,settingSources:["user","project","local"],env:{...or(y),CODEBUDDY_API_KEY_DISABLED:"1",CODEBUDDY_REMOTE_CONFIG_DISABLED:"1",CODEBUDDY_INCLUDE_TOPIC_MESSAGE:"true",CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING:e.CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING??"0"}})),s.provide(le),s.provide(Ke.layer.pipe(s.provide(c.layer([c.withConsoleError(c.formatLogFmt)]))))),I));i()?.markEnd("harness.session-runtime"),R=p.get(fe,wr),u?.throwIfAborted(),i()?.markStart("harness.replay");const He=p.get(await P(s.buildWithScope(ke.layer({},r=>Ae.readFileBuffer(r)).pipe(s.provide(le)),I)),ke);i()?.markEnd("harness.replay"),u?.throwIfAborted(),i()?.markStart("harness.storage");const he=await P(s.buildWithScope(s.mergeAll(be.layer,ve.layer).pipe(s.provide(Sr.layer),s.provide(c.layer([c.withConsoleError(c.formatLogFmt)]))),I));i()?.markEnd("harness.storage");const Oe=p.get(he,be),Ue=p.get(he,ve);M=(S.createMcpIntegration??(r=>Xe({containment:r.containment,recordEffectTelemetry:r.recordEffectTelemetry,recordLifecycle:r.recordLifecycle,supervisor:{environment:r.environment,toolsSyncTtlMs:Ie?.toolsSyncTtlMs,proxyPolicy:r.proxyPolicy}})))({containment:_,environment:d,proxyPolicy:_e(A.currentProxyPolicy,d),recordEffectTelemetry:De,recordLifecycle:k}),L=A.subscribe(r=>{const o=_e(r,d);M?.configureProxy?.(o).catch(()=>{l.recordEffectLog({annotations:{component:"harness",operation:"update",resource:"policy","runtime.role":"harness",status:"failed"},level:"warn",message:"harness.settings.proxy"})})});const ge=je.getOrUndefined(p.getOption(fe,Ce));u?.throwIfAborted(),i()?.markStart("harness.mcp-services");const Q=await P(s.buildWithScope(s.mergeAll(Pe.layer({environment:t(()=>({...e,...d}),"environment")}),Se.layer).pipe(s.provideMerge($.layer({environment:t(()=>({...e,...d}),"environment"),product:t(()=>a.getConfiguration(),"product"),writeContext:t(async()=>{await n?.prepareHostExecution(F.signal);const r=t(()=>({environment:{...e,...d},product:structuredClone(a.getConfiguration()),authentication:n?.currentSessionAuthentication()}),"capture");return n?n.runConsistentRead(r):r()},"writeContext"),onConfigChange:ge?async(r,o)=>{const f=o.authentication;ge.notifyConfigChange({source:r.source,filePath:r.file_path,cwd:r.cwd},{product:o.product,environment:o.environment,fetch:t((X,H)=>Ze(X,H,o.environment),"fetch"),auth:f?{accessToken:f.credential.accessToken,method:f.credential.type,refresh:t(async({signal:X})=>{if(!n||!a)throw new Error("Hook authentication is unavailable");const H=t(()=>{if(!Ne(o.product,a.getConfiguration()))throw new Error("Hook Product changed")},"checkProduct");await n.runConsistentRead(H);const Ee=await n.refreshHostAuthentication(f,X);return await n.runConsistentRead(H),{accessToken:Ee.credential.accessToken,method:Ee.credential.type}},"refresh")}:void 0,account:f?{uid:f.account.id,enterpriseId:f.account.organization?.id}:void 0}).catch(()=>m.runSync(m.logWarning("harness.config-change.failed").pipe(m.provide(c.layer([c.withConsoleError(c.formatLogFmt)])))))}:void 0,reloadUserConfig:t(r=>w?.reloadUserConfig(r)??Promise.resolve(),"reloadUserConfig")})),s.provide(c.layer([c.withConsoleError(c.formatLogFmt)]))),de));i()?.markEnd("harness.mcp-services"),u?.throwIfAborted(),i()?.markStart("harness.agent-facade"),w=await(S.createAgentFacade??qe)({userMcp:p.get(Q,Pe),pluginMcp:p.get(Q,Se),checkpoints:Ue,sessions:Oe,initialProductGeneration:Fe().productGeneration,mcpIntegration:M,strictMcpConfig:Le,onPermanentFailure:t(r=>{W(r,"fused","recovery_failed"),F.abort(r)},"onPermanentFailure"),prepareSessionRuntime:t((r,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.prepareSessionRuntime(r,o.connectionSignal)},"prepareSessionRuntime"),prepareSessionWorkspace:t(async(r,o)=>{if(!n||!a)throw new Error("Product manager is not ready");try{return await a.prepareWorkspace(r,{signal:o})}catch(f){if(!(f instanceof lr&&f.code==="AUTH_REFRESH_REQUIRED"))throw f;return await n.refreshProductAuthentication(o),a.prepareWorkspace(r,{force:!0,signal:o})}},"prepareSessionWorkspace"),releaseSessionWorkspace:t((r,o)=>a?a.releaseWorkspace(r,o):Promise.resolve(),"releaseSessionWorkspace"),refreshAuthentication:t((r,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.refreshAuthentication(r,{signal:o?.signal??AbortSignal.abort(new Error("Authentication refresh has no operation signal"))})},"refreshAuthentication"),serverInfo:ne,sessionRuntime:R,sessionReplay:He}),i()?.markEnd("harness.agent-facade");const ye=ar({facade:w,onExecutionProductCommitted:N,product:a});u?.throwIfAborted(),i()?.markStart("harness.auth-service");const xe=await P(s.buildWithScope(S.managedAuthLayer??Ve({...a.resolveLoginProduct?{resolveLoginProduct:t((r,o)=>a.resolveLoginProduct(r,o),"resolveLoginProduct")}:{},environment:t(()=>({...e,...d}),"environment"),product:t(()=>a.getConfiguration(),"product")}).pipe(s.provide(c.layer([c.withConsoleError(c.formatLogFmt)]))),pe));i()?.markEnd("harness.auth-service"),n=ir({consumer:w,getAuthMethods:t(()=>a.getAuthMethods(),"getAuthMethods"),managedAuth:p.get(xe,Qe),onRuntimePreparing:N,onRuntimePrepared:N,productLifecycle:ye});const v=await Je(n);n.bindProtocolBridge(v.bridge);const J=rr({selectConnectionProductProfile:t((r,o)=>n.selectConnectionProductProfile(r,o),"selectConnectionProductProfile"),provisionProduct:t((r,o)=>v.runAuthMutation(()=>n.provisionProduct(r,o)),"provisionProduct"),readProduct:t((r,o)=>n.readProduct(r,o),"readProduct"),provisionWorkspaceProduct:t((r,o)=>v.runAuthMutation(()=>n.provisionWorkspaceProduct(r,o)),"provisionWorkspaceProduct"),readWorkspaceProduct:t((r,o)=>a.readWorkspaceProduct(r,o),"readWorkspaceProduct")});a.bindPublisher({notifyProductUpdated:t(()=>J.publisher.notifyProductUpdated(ye.currentProductSnapshot()),"notifyProductUpdated"),notifyWorkspaceProductUpdated:t(r=>J.publisher.notifyWorkspaceProductUpdated(r),"notifyWorkspaceProductUpdated")});const ze=p.empty().pipe(p.add(Ar,A),p.add(Z,me),p.add($,p.get(Q,$)));u?.throwIfAborted(),i()?.markStart("harness.rpc-services");const Be=await P(m.provide(yr.pipe(h.provide(G)),ze));i()?.markEnd("harness.rpc-services"),C=er([{name:"private-runtime-lifecycle",capabilities:{},initialize:t(async(r,o)=>{await ee("harness.initialize.settings",()=>A?.initialize(o.connectionSignal))},"initialize"),close:t(async r=>{L?.(),L=void 0,await K(r),await A?.close(r),await re([[()=>Y(r),()=>M?.close(r)??Promise.resolve()],[()=>j(r)]],z,"private runtime shutdown")},"close")},Ge({v2:w}),$e({backend:w}),kr({backend:w}),J,{name:v.name,capabilities:v.capabilities,initialize:t(async(r,o)=>ee("harness.initialize.auth",()=>v.initialize(r,o)),"initialize"),initialized:v.initialized,notificationHandlers:v.notificationHandlers,requestHandlers:v.requestHandlers,close:V},{...Be,close:q}])}catch(e){throw L?.(),L=void 0,k({component:"server",error:e,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),await re([[()=>q(e)],[()=>V(e)],[()=>w?.close(e)??Promise.resolve(),()=>Y(e)],[()=>M?.close(e)??Promise.resolve()],[()=>K(e)],[()=>A?.close(e)??Promise.resolve()],[()=>j(e)]],z,"module startup cleanup").catch(()=>{}),e}let ue;try{u?.throwIfAborted(),ue=(S.createServer??(e=>new hr(e)))({serverInfo:ne,capabilities:C.capabilities,initializeHookTimeoutMs:cr+sr+gr,initialize:t(async(e,d)=>(i()?.markEnd("harness.wait-initialize"),ee("harness.initialize",()=>C.initialize(e,d))),"initialize"),initialized:C.initialized,notificationHandlers:C.notificationHandlers,onContainmentFailure:t(e=>{W(e,"containment_tripped","containment_failed"),F.abort(e)},"onContainmentFailure"),readinessSignal:_.signal,requestHandlers:C.requestHandlers,telemetryRuntime:l})}catch(e){k({component:"server",error:e,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"});try{await re([[()=>C.close(e)]],z,"server construction cleanup")}catch(d){k({component:"server",error:d,phase:"cleanup",process:{pid:process.pid},reason:"cleanup_failed",state:"shutdown_failed"})}throw e}return{server:ue,modules:C,telemetry:l,containment:_,runtimeShutdown:F,recordLifecycle:k}}t(createApplicationServices,"createApplicationServices");
|
|
1
|
+
var Ve=Object.defineProperty;var t=(E,H)=>Ve(E,"name",{value:H,configurable:!0});import{homedir as we}from"node:os";import*as k from"node:path";import{isDeepStrictEqual as Xe}from"node:util";import{WORKBUDDY_ENABLE_LINUX_SANDBOX_CLI as Ae}from"@genie/product";import{Context as d,Effect as m,Exit as y,Layer as s,Logger as u,Option as Qe,Scope as h}from"effect";import{createAgentProtocolModule as Je}from"../agent/router.js";import{createAgentV2Facade as Ze}from"../agent/v2.js";import{ManagedAuthLocal as $e}from"../auth/local.js";import{ManagedAuth as er}from"../auth/managed.js";import{createAuthProtocolModule as rr}from"../auth/module.js";import{Checkpoints as _e}from"../checkpoint/service.js";import{ConfigFiles as re}from"../config/files.js";import{createDefaultAgentMcpIntegration as tr}from"../integration/agent-integration.js";import{PluginMcp as be}from"../integration/plugin-mcp.js";import{UserMcp as ke}from"../integration/user-mcp.js";import{requestWithEnvironment as or}from"../internal/http.js";import{createMcpServerProtocolModule as nr}from"../mcp-server/module.js";import{composeAgentHarnessModules as ir}from"../module/compose.js";import{PluginComponents as te}from"../plugin/components.js";import{createProductProtocolModule as ar}from"../product/module.js";import{preflightCodeBuddyCode as sr}from"../runtime/agent-runtime.js";import{buildAgentHarnessClientIdentityEnv as cr,buildAgentHarnessClientIdentityHeaders as dr}from"../runtime/client-identity.js";import{createCodeBuddyAuthRuntime as ur}from"../runtime/codebuddy-auth.js";import{createCodeBuddyProductLifecycle as pr}from"../runtime/codebuddy-product.js";import{DEFAULT_HOST_HEALTH_TIMEOUT_MS as mr,DEFAULT_READY_TIMEOUT_MS as lr}from"../runtime/codebuddy-resource-timeouts.js";import{CodeBuddyProcessContainment as fr}from"../runtime/process-containment.js";import{parseAgentHarnessProductConfig as hr,parseHarnessProductInput as gr}from"../runtime/product-config.js";import{ProductManager as yr}from"../runtime/product-manager.js";import{ProductResolver as De}from"../runtime/product-resolver.js";import{ProductResolverRequestError as Er}from"../runtime/product-resolver-error.js";import{loadProductSource as Sr}from"../runtime/product-source.js";import{HarnessSandboxCenter as vr}from"../runtime/sandbox-center.js";import{AgentHarnessServer as Cr,DEFAULT_LIFECYCLE_HOOK_TIMEOUT_MS as Pr}from"../server/index.js";import{makeServiceRpcs as wr}from"../server/rpc-services.js";import{AgentBackend as Ar,workspaceQueryOptions as _r}from"../session/agent-backend.js";import{AgentServer as Ie}from"../session/agent-server.js";import{readSessionConfigDefaults as br}from"../session/config-defaults.js";import{SessionConfigStore as kr}from"../session/config-store.js";import{SessionFiles as Dr}from"../session/files.js";import{localFs as Me}from"../session/local-fs.js";import{SessionReplay as Le}from"../session/replay.js";import{SessionRuntime as Ir}from"../session/runtime.js";import{Sessions as Te}from"../session/service.js";import{toExecutorPrivateProxyPolicy as Oe}from"../settings/proxy-policy.js";import{createHarnessSettingsRuntime as Mr}from"../settings/runtime.js";import{Settings as Lr}from"../settings/service.js";import{createSubagentProtocolModule as Tr}from"../subagent/module.js";import{createEffectTelemetryMetricAggregator as Or}from"../telemetry/effect-metric-aggregation.js";import{createTelemetry as xr}from"../telemetry/runtime.js";import{measureStartup as oe,startupProfiler as i}from"../telemetry/startup-profile.js";import{closeInPhases as ne,closeTelemetry as Rr,createCloseOnce as _,DEFAULT_TELEMETRY_CLOSE_TIMEOUT_MS as Fr}from"./lifecycle.js";export async function createApplicationServices({clientIdentity:E,clientIdentityEnv:H,dependencies:v,packageVersion:xe,processRuntime:g,productConfig:O,sandboxCenter:Re,tools:ie,strictMcpConfig:Fe,mcp:Ue,shutdown:B,telemetryOptions:ae,signal:p}){p?.throwIfAborted();const C=t(r=>m.runPromise(r,{signal:p}),"runStartupEffect"),z=B,se={name:"@genie/agent-harness",title:"Agent Harness",version:xe},ce=(v.preflightCodeBuddyCode??sr)(),D=new fr,x=new AbortController,l=xr(ae),W=_(()=>Rr(l,g,Math.max(1,Math.min(B.remainingMs(),ae.flushTimeoutMs??Fr))));B.registerTelemetryCloser(W);const de=Or(r=>l.recordEffectMetrics(r));try{g.addFinalizer(W)}catch(r){throw await W(),r}try{g.setTelemetryObserver({log:t(r=>l.recordEffectLog(r),"log"),metrics:t(r=>de.record("harness",r),"metrics"),span:t(r=>l.recordEffectSpan(r),"span")})}catch{}const b=t(r=>l.recordLifecycle(r),"recordLifecycle"),R=new vr(process.env.CODEBUDDY_CONFIG_DIR?.trim()?k.resolve(process.env.CODEBUDDY_CONFIG_DIR.trim()):k.join(we(),".codebuddy"),Re,process.env.SANDBOX_CENTER_IPC_ADDRESS?.trim()),N=_(()=>R.close());g.addFinalizer(N);let ue=!1;const Y=t((r,c,T)=>{ue||(ue=!0,b({component:"server",error:r,phase:"runtime",process:{pid:process.pid},reason:T,state:c}))},"recordRootFailure");D.signal.addEventListener("abort",()=>{Y(D.signal.reason,"containment_tripped","containment_failed")},{once:!0});const He={log(r){try{l.recordEffectLog(r)}catch{}},metrics(r){de.record("executor",r)},span(r){try{l.recordEffectSpan(r)}catch{}}};let P,n,F,I,a,A,M,w;const L=h.makeUnsafe(),G=_(r=>m.runPromise(h.close(L,r===void 0?y.void:y.fail(r))));g.addFinalizer(()=>G(void 0));const j=t(()=>{F&&m.runPromise(m.forkIn(F.prepare,L,{startImmediately:!0})).catch(()=>{})},"prepareRuntime"),pe=h.makeUnsafe(),q=_(async r=>{try{await a?.close(r)}finally{await m.runPromise(h.close(pe,r===void 0?y.void:y.fail(r)))}});g.addFinalizer(()=>q(void 0));const K=h.makeUnsafe(),V=_(r=>m.runPromise(h.close(K,r===void 0?y.void:y.fail(r))));g.addFinalizer(()=>V(void 0));const me=h.makeUnsafe(),X=_(r=>m.runPromise(h.close(me,r===void 0?y.void:y.fail(r))));g.addFinalizer(()=>X(void 0));const le=h.makeUnsafe(),Q=_(async r=>{try{await n?.close(r)}finally{await m.runPromise(h.close(le,r===void 0?y.void:y.fail(r)))}});g.addFinalizer(()=>Q(void 0));try{const r={...process.env},c={...H,...R.environment},T=typeof O=="object"?gr(O):Sr(O,{parse:hr});p?.throwIfAborted(),i()?.markStart("harness.product");const Be=await C(s.buildWithScope(De.layer({projection:T.projection,baseConfiguration:O===void 0?void 0:{},packageRoot:ce.productRoot??k.dirname(ce.packageJsonPath),clientIdentity:{ideName:E.ideName,ideType:E.ideType,ideVersion:E.ideVersion,...E.userAgent===void 0?{}:{userAgent:E.userAgent}},environment:t(()=>({...r,...c}),"environment")}),pe));a=await(v.createProductManager??((e,o)=>yr.create(e,o)))({bootstrap:T.bootstrap,projection:T.projection,resolver:d.get(Be,De)},p),i()?.markEnd("harness.product");const ze=t(()=>{if(!a)throw new Error("Product manager is not ready");return a.getLaunchSnapshot()},"productLaunch");p?.throwIfAborted(),i()?.markStart("harness.config");const We=await C(s.buildWithScope(re.layer.pipe(s.provide(u.layer([u.withConsoleError(u.formatLogFmt)]))),K));i()?.markEnd("harness.config");const J=d.get(We,re),he=t((e,o)=>br(J,e,o),"sessionConfigDefaults");p?.throwIfAborted(),i()?.markStart("harness.settings"),A=await(v.createSettingsRuntime??Mr)({ambientEnvironment:r,config:J,environment:c,observe:t(e=>l.recordEffectLog({annotations:{component:"harness",operation:"refresh",reason:e.reason,resource:"policy","runtime.role":"harness",status:e.status,...e.policy===void 0?{}:{mode:e.policy.mode,noProxyCount:e.policy.noProxyCount,proxyConfigured:e.policy.proxyConfigured,proxySupport:e.policy.proxySupport,revision:e.policy.revision}},level:e.status==="failed"?"warn":"info",message:"harness.settings.proxy"}),"observe"),processRuntime:g}),i()?.markEnd("harness.settings");const ge=kr.layer(k.join(r.CODEBUDDY_CONFIG_DIR?.trim()?k.resolve(r.CODEBUDDY_CONFIG_DIR.trim()):k.join(we(),".codebuddy"),"harness","sessions"));p?.throwIfAborted(),i()?.markStart("harness.session-runtime");const ye=process.platform==="linux"?r[Ae]??((await import("#agent-harness-components/session-config")).isLinuxSandboxCLIInstalled()?"1":"0"):void 0,Ee=await C(s.buildWithScope(v.sessionRuntimeLayer??Ar({checkpoints:!0,headers:dr(E),prepareSandboxCenter:t((e,o)=>R.prepare(e.account?.uid,o),"prepareSandboxCenter"),resolveOptions:t(e=>m.map(_r(e),o=>({...o,...ie===void 0?{}:{tools:ie}})),"resolveOptions"),resolveConfigDefaults:t(e=>m.tryPromise({try:t(()=>he(e.workspace?.canonicalCwd??e.cwd??process.cwd(),e.signal),"try"),catch:t(o=>o,"catch")}),"resolveConfigDefaults")}).pipe(s.provideMerge(Ie.layer({product:{},fs:Me,settingSources:["user","project","local"],env:{...cr(E),CODEBUDDY_API_KEY_DISABLED:"1",CODEBUDDY_REMOTE_CONFIG_DISABLED:"1",CODEBUDDY_INCLUDE_TOPIC_MESSAGE:"true",...ye===void 0?{}:{[Ae]:ye},...R.environment,CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING:r.CODEBUDDY_CODE_DISABLE_FILE_CHECKPOINTING??"0"}})),s.provide(ge)),L));i()?.markEnd("harness.session-runtime"),F=d.get(Ee,Ir),p?.throwIfAborted(),i()?.markStart("harness.replay");const Ne=d.get(await C(s.buildWithScope(Le.layer({},e=>Me.readFileBuffer(e),he).pipe(s.provide(ge)),L)),Le);i()?.markEnd("harness.replay"),p?.throwIfAborted(),i()?.markStart("harness.storage");const Se=await C(s.buildWithScope(s.mergeAll(Te.layer,_e.layer).pipe(s.provide(Dr.layer),s.provide(u.layer([u.withConsoleError(u.formatLogFmt)]))),L));i()?.markEnd("harness.storage");const Ye=d.get(Se,Te),Ge=d.get(Se,_e);I=(v.createMcpIntegration??(e=>tr({containment:e.containment,recordEffectTelemetry:e.recordEffectTelemetry,recordLifecycle:e.recordLifecycle,supervisor:{environment:e.environment,toolsSyncTtlMs:Ue?.toolsSyncTtlMs,proxyPolicy:e.proxyPolicy}})))({containment:D,environment:c,proxyPolicy:Oe(A.currentProxyPolicy,c),recordEffectTelemetry:He,recordLifecycle:b}),M=A.subscribe(e=>{const o=Oe(e,c);I?.configureProxy?.(o).catch(()=>{l.recordEffectLog({annotations:{component:"harness",operation:"update",resource:"policy","runtime.role":"harness",status:"failed"},level:"warn",message:"harness.settings.proxy"})})});const ve=Qe.getOrUndefined(d.getOption(Ee,Ie));p?.throwIfAborted(),i()?.markStart("harness.mcp-services");const Z=await C(s.buildWithScope(s.mergeAll(ke.layer({environment:t(()=>({...r,...c}),"environment")}),be.layer).pipe(s.provideMerge(te.layer({environment:t(()=>({...r,...c}),"environment"),product:t(()=>a.getConfiguration(),"product"),writeContext:t(async()=>{await n?.prepareHostExecution(x.signal);const e=t(()=>({environment:{...r,...c},product:structuredClone(a.getConfiguration()),authentication:n?.currentSessionAuthentication()}),"capture");return n?n.runConsistentRead(e):e()},"writeContext"),onConfigChange:ve?async(e,o)=>{const f=o.authentication;ve.notifyConfigChange({source:e.source,filePath:e.file_path,cwd:e.cwd},{product:o.product,environment:o.environment,fetch:t((ee,U)=>or(ee,U,o.environment),"fetch"),auth:f?{accessToken:f.credential.accessToken,method:f.credential.type,refresh:t(async({signal:ee})=>{if(!n||!a)throw new Error("Hook authentication is unavailable");const U=t(()=>{if(!Xe(o.product,a.getConfiguration()))throw new Error("Hook Product changed")},"checkProduct");await n.runConsistentRead(U);const Pe=await n.refreshHostAuthentication(f,ee);return await n.runConsistentRead(U),{accessToken:Pe.credential.accessToken,method:Pe.credential.type}},"refresh")}:void 0,account:f?{uid:f.account.id,enterpriseId:f.account.organization?.id}:void 0}).catch(()=>m.runSync(m.logWarning("harness.config-change.failed").pipe(m.provide(u.layer([u.withConsoleError(u.formatLogFmt)])))))}:void 0,reloadUserConfig:t(e=>P?.reloadUserConfig(e)??Promise.resolve(),"reloadUserConfig")})),s.provide(u.layer([u.withConsoleError(u.formatLogFmt)]))),me));i()?.markEnd("harness.mcp-services"),p?.throwIfAborted(),i()?.markStart("harness.agent-facade"),P=await(v.createAgentFacade??Ze)({userMcp:d.get(Z,ke),pluginMcp:d.get(Z,be),checkpoints:Ge,sessions:Ye,initialProductGeneration:ze().productGeneration,mcpIntegration:I,strictMcpConfig:Fe,onPermanentFailure:t(e=>{Y(e,"fused","recovery_failed"),x.abort(e)},"onPermanentFailure"),prepareSessionRuntime:t((e,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.prepareSessionRuntime(e,o.connectionSignal)},"prepareSessionRuntime"),prepareSessionWorkspace:t(async(e,o)=>{if(!n||!a)throw new Error("Product manager is not ready");try{return await a.prepareWorkspace(e,{signal:o})}catch(f){if(!(f instanceof Er&&f.code==="AUTH_REFRESH_REQUIRED"))throw f;return await n.refreshProductAuthentication(o),a.prepareWorkspace(e,{force:!0,signal:o})}},"prepareSessionWorkspace"),releaseSessionWorkspace:t((e,o)=>a?a.releaseWorkspace(e,o):Promise.resolve(),"releaseSessionWorkspace"),refreshAuthentication:t((e,o)=>{if(!n)throw new Error("Authentication runtime is not ready");return n.refreshAuthentication(e,{signal:o?.signal??AbortSignal.abort(new Error("Authentication refresh has no operation signal"))})},"refreshAuthentication"),serverInfo:se,sessionRuntime:F,sessionReplay:Ne}),i()?.markEnd("harness.agent-facade");const Ce=pr({facade:P,onExecutionProductCommitted:j,product:a});p?.throwIfAborted(),i()?.markStart("harness.auth-service");const je=await C(s.buildWithScope(v.managedAuthLayer??$e({...a.resolveLoginProduct?{resolveLoginProduct:t((e,o)=>a.resolveLoginProduct(e,o),"resolveLoginProduct")}:{},environment:t(()=>({...r,...c}),"environment"),product:t(()=>a.getConfiguration(),"product")}).pipe(s.provide(u.layer([u.withConsoleError(u.formatLogFmt)]))),le));i()?.markEnd("harness.auth-service"),n=ur({consumer:P,getAuthMethods:t(()=>a.getAuthMethods(),"getAuthMethods"),managedAuth:d.get(je,er),onRuntimePreparing:j,onRuntimePrepared:j,productLifecycle:Ce});const S=await rr(n);n.bindProtocolBridge(S.bridge);const $=ar({selectConnectionProductProfile:t((e,o)=>n.selectConnectionProductProfile(e,o),"selectConnectionProductProfile"),provisionProduct:t((e,o)=>S.runAuthMutation(()=>n.provisionProduct(e,o)),"provisionProduct"),readProduct:t((e,o)=>n.readProduct(e,o),"readProduct"),provisionWorkspaceProduct:t((e,o)=>S.runAuthMutation(()=>n.provisionWorkspaceProduct(e,o)),"provisionWorkspaceProduct"),readWorkspaceProduct:t((e,o)=>a.readWorkspaceProduct(e,o),"readWorkspaceProduct")});a.bindPublisher({notifyProductUpdated:t(()=>$.publisher.notifyProductUpdated(Ce.currentProductSnapshot()),"notifyProductUpdated"),notifyWorkspaceProductUpdated:t(e=>$.publisher.notifyWorkspaceProductUpdated(e),"notifyWorkspaceProductUpdated")});const qe=d.empty().pipe(d.add(Lr,A),d.add(re,J),d.add(te,d.get(Z,te)));p?.throwIfAborted(),i()?.markStart("harness.rpc-services");const Ke=await C(m.provide(wr.pipe(h.provide(K)),qe));i()?.markEnd("harness.rpc-services"),w=ir([{name:"private-runtime-lifecycle",capabilities:{},initialize:t(async(e,o)=>{await oe("harness.initialize.settings",()=>A?.initialize(o.connectionSignal))},"initialize"),close:t(async e=>{M?.(),M=void 0,await X(e),await A?.close(e),await ne([[()=>G(e),()=>I?.close(e)??Promise.resolve()],[()=>N()],[()=>q(e)]],z,"private runtime shutdown")},"close")},Je({v2:P}),nr({backend:P}),Tr({backend:P}),$,{name:S.name,capabilities:S.capabilities,initialize:t(async(e,o)=>oe("harness.initialize.auth",()=>S.initialize(e,o)),"initialize"),initialized:S.initialized,notificationHandlers:S.notificationHandlers,requestHandlers:S.requestHandlers,close:Q},{...Ke,close:V}])}catch(r){throw M?.(),M=void 0,b({component:"server",error:r,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"}),await ne([[()=>V(r)],[()=>Q(r)],[()=>P?.close(r)??Promise.resolve(),()=>G(r)],[()=>I?.close(r)??Promise.resolve()],[()=>X(r)],[()=>A?.close(r)??Promise.resolve()],[()=>N()],[()=>q(r)]],z,"module startup cleanup").catch(()=>{}),r}let fe;try{p?.throwIfAborted(),fe=(v.createServer??(r=>new Cr(r)))({serverInfo:se,capabilities:w.capabilities,initializeHookTimeoutMs:lr+mr+Pr,initialize:t(async(r,c)=>(i()?.markEnd("harness.wait-initialize"),oe("harness.initialize",()=>w.initialize(r,c))),"initialize"),initialized:w.initialized,notificationHandlers:w.notificationHandlers,onContainmentFailure:t(r=>{Y(r,"containment_tripped","containment_failed"),x.abort(r)},"onContainmentFailure"),readinessSignal:D.signal,requestHandlers:w.requestHandlers,telemetryRuntime:l})}catch(r){b({component:"server",error:r,phase:"startup",process:{pid:process.pid},reason:"startup_failed",state:"startup_failed"});try{await ne([[()=>w.close(r)]],z,"server construction cleanup")}catch(c){b({component:"server",error:c,phase:"cleanup",process:{pid:process.pid},reason:"cleanup_failed",state:"shutdown_failed"})}throw r}return{server:fe,modules:w,telemetry:l,containment:D,runtimeShutdown:x,recordLifecycle:b}}t(createApplicationServices,"createApplicationServices");
|
package/lib/client/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=Object.defineProperty;var h=(f,e)=>q(f,"name",{value:e,configurable:!0});import{client as C,methods as c,PROTOCOL_VERSION as g,RequestError as E}from"@agentclientprotocol/sdk/experimental/v2";import{Effect as b,Stream as M}from"effect";import{isRecord as p}from"../internal/guards.js";import{toAcpStream as v}from"../transport/effect.js";import{CLIENT_MCP_METHODS as P,ClientMcp as S,isSessionMcpMethod as A}from"./mcp.js";import{clientMethods as I,notificationDecoders as j,notificationMethods as z,peerRequestDecoders as O,requestDecoders as T,requestMethods as R,reverseMethods as N,sendNotificationMethods as _}from"./rpc.js";import{isInMemoryEndpoint as D,openTransport as L}from"./transport.js";class V{static{h(this,"ClientLifecycle")}constructor(e){this.options=e,this.state="disconnected",this.cleanup=Promise.resolve(),this.handlers=new Map,this.listeners=new Map,this.mcp=new S({request:h((i,o)=>this.requireConnected().request(c.agent.mcp.message,i,{cancellationSignal:o?.signal}),"request"),notify:h(i=>this.requireConnected().notify(c.agent.mcp.message,i),"notify")})}on(e,i){if(this.assertOpen(),P.has(e))throw new TypeError("Client owns MCP handlers; configure mcpServers on the session instead");if(typeof i!="function")throw new TypeError("Client.on requires a function");if(N.has(e))return this.register(e,i);if(z.has(e))return this.subscribe(e,i);throw new TypeError(`${e} is not an incoming Client method`)}register(e,i){if(this.handlers.has(e))throw new Error(`${e} already has a request handler`);return this.handlers.set(e,i),()=>{this.handlers.get(e)===i&&this.handlers.delete(e)}}subscribe(e,i){let o=this.listeners.get(e);return o||this.listeners.set(e,o=new Set),o.add(i),()=>{o.delete(i)}}assertOpen(){if(this.state==="closed"||this.state==="closing")throw new Error("Client is closed")}async publish(e,i){const t=(await Promise.allSettled([...this.listeners.get(e)??[]].map(async n=>{await n(i)}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(t.length>0)throw new AggregateError(t,`Notification listener failed for ${e}`)}handle(e,i,o){const t=this.handlers.get(e);if(t)return t(i,o);if(e===c.client.session.requestPermission)return{outcome:{outcome:"cancelled"}};throw E.methodNotFound(e)}async request(e,i={},o){const t=this.requireConnected(),n=T[e],l=A(e)?this.mcp.prepare(i):void 0;try{const r=l?.params??i,
|
|
1
|
+
var q=Object.defineProperty;var h=(f,e)=>q(f,"name",{value:e,configurable:!0});import{client as C,methods as c,PROTOCOL_VERSION as g,RequestError as E}from"@agentclientprotocol/sdk/experimental/v2";import{Effect as b,Stream as M}from"effect";import{isRecord as p}from"../internal/guards.js";import{toAcpStream as v}from"../transport/effect.js";import{CLIENT_MCP_METHODS as P,ClientMcp as S,isSessionMcpMethod as A}from"./mcp.js";import{clientMethods as I,notificationDecoders as j,notificationMethods as z,peerRequestDecoders as O,requestDecoders as T,requestMethods as R,reverseMethods as N,sendNotificationMethods as _}from"./rpc.js";import{isInMemoryEndpoint as D,openTransport as L}from"./transport.js";class V{static{h(this,"ClientLifecycle")}constructor(e){this.options=e,this.state="disconnected",this.cleanup=Promise.resolve(),this.handlers=new Map,this.listeners=new Map,this.mcp=new S({request:h((i,o)=>this.requireConnected().request(c.agent.mcp.message,i,{cancellationSignal:o?.signal}),"request"),notify:h(i=>this.requireConnected().notify(c.agent.mcp.message,i),"notify")})}on(e,i){if(this.assertOpen(),P.has(e))throw new TypeError("Client owns MCP handlers; configure mcpServers on the session instead");if(typeof i!="function")throw new TypeError("Client.on requires a function");if(N.has(e))return this.register(e,i);if(z.has(e))return this.subscribe(e,i);throw new TypeError(`${e} is not an incoming Client method`)}register(e,i){if(this.handlers.has(e))throw new Error(`${e} already has a request handler`);return this.handlers.set(e,i),()=>{this.handlers.get(e)===i&&this.handlers.delete(e)}}subscribe(e,i){let o=this.listeners.get(e);return o||this.listeners.set(e,o=new Set),o.add(i),()=>{o.delete(i)}}assertOpen(){if(this.state==="closed"||this.state==="closing")throw new Error("Client is closed")}async publish(e,i){const t=(await Promise.allSettled([...this.listeners.get(e)??[]].map(async n=>{await n(i)}))).filter(n=>n.status==="rejected").map(n=>n.reason);if(t.length>0)throw new AggregateError(t,`Notification listener failed for ${e}`)}handle(e,i,o){const t=this.handlers.get(e);if(t)return t(i,o);if(e===c.client.session.requestPermission)return{outcome:{outcome:"cancelled"}};throw E.methodNotFound(e)}async request(e,i={},o){const t=this.requireConnected(),n=T[e],l=A(e)?this.mcp.prepare(i):void 0;let a;try{const r=l?.params??i,d=await t.request(e,n?n.params(r):r,o);a=n?n.result(d):d}catch(r){throw await l?.rollback(),r}return await l?.commit(a),e===c.agent.session.close&&p(i)&&typeof i.sessionId=="string"&&await this.mcp.closeSession(i.sessionId),a}async notify(e,i){await this.requireConnected().notify(e,i)}requireConnected(){if(this.state!=="connected"||!this.agent)throw new Error("Await client.connect() before making requests");return this.agent}connect(e,i){if(this.state!=="disconnected")return Promise.reject(new Error(`Client is ${this.state}`));if(!p(e))return Promise.reject(new TypeError("connect requires a Server or connection options"));const o=D(e);if(i!==void 0&&!o)return Promise.reject(new TypeError("Separate connection settings require a Server"));const t=o?i??{}:e,n=this.options.capabilities?.elicitation;return(n?.form||n?.url)&&!this.handlers.has(c.client.elicitation.create)?Promise.reject(new Error("Register client.on('elicitation/create', handler) before advertising elicitation capabilities")):t.timeoutMs!==void 0&&(!Number.isFinite(t.timeoutMs)||t.timeoutMs<=0)?Promise.reject(new TypeError("timeoutMs must be positive")):(this.state="connecting",this.initialization=void 0,this.connectAbort=new AbortController,this.connecting=this.open(e,t,this.connectAbort),this.connecting)}async open(e,i,o){const t=setTimeout(()=>o.abort(new Error("Client connect timed out")),i.timeoutMs??3e4),n=i.signal?AbortSignal.any([i.signal,o.signal]):o.signal;let l;try{n.throwIfAborted(),await this.cleanup;const a=await L(e);this.stream=a,n.throwIfAborted();const r=C();r.onConnect(({agent:s})=>{this.agent=s}),r.onRequest(c.client.session.requestPermission,async s=>await this.handle(c.client.session.requestPermission,s.params,s)),r.onRequest(c.client.elicitation.create,async s=>await this.handle(c.client.elicitation.create,s.params,s)),r.onNotification(c.client.session.update,({params:s})=>this.publish(c.client.session.update,s)),r.onNotification(c.client.elicitation.complete,({params:s})=>this.publish(c.client.elicitation.complete,s));for(const[s,u]of Object.entries(O))r.onRequest(s,u.params,async m=>u.result(await this.handle(s,m.params,m)));for(const[s,u]of Object.entries(j))r.onNotification(s,u,({params:m})=>this.publish(s,m));r.onRequest(c.client.mcp.connect,s=>this.mcp.connect(s.params,s.signal)),r.onRequest(c.client.mcp.disconnect,s=>this.mcp.disconnect(s.params)),r.onRequest(c.client.mcp.message,s=>this.mcp.message(s.params,s.signal)),r.onNotification(c.client.mcp.message,s=>this.mcp.notify(s.params));const d=r.connect(v(this.adaptInitialize(a)));this.connection=d,this.cleanup=d.closed.then(async()=>{this.connection===d&&(this.connection=void 0,this.agent=void 0,this.state==="connected"&&(this.state="disconnected")),await this.mcp.close(),await b.runPromise(a.close())}),this.cleanup.catch(()=>{});const w=this.agent;if(!w)throw new Error("ACP SDK did not create its client context");const y=w.request(c.agent.initialize,{protocolVersion:g,info:this.options.clientInfo??{name:"agent-harness-client",version:"0.1.0"},capabilities:this.options.capabilities??{}});if(await Promise.race([y,new Promise((s,u)=>{l=h(()=>{d.close(n.reason),u(n.reason)},"onAbort"),n.addEventListener("abort",l,{once:!0}),n.aborted&&l()})]),await w.notify("initialized",{}),n.throwIfAborted(),d.signal.aborted)throw d.signal.reason;this.state="connected"}catch(a){throw this.connection?.close(a),await this.releaseStream(a),this.agent=void 0,this.connection=void 0,this.initialization=void 0,this.state==="connecting"&&(this.state="disconnected"),a}finally{clearTimeout(t),l&&n.removeEventListener("abort",l)}}adaptInitialize(e){let i;const o=h(t=>{if("id"in t&&t.id===i&&"result"in t){const n=t.result;if(!p(n)||n.protocolVersion!==1||!p(n.serverInfo)||!p(n.capabilities))throw new TypeError("Invalid Harness initialize response");return this.initialization=n,{...t,result:{protocolVersion:g,info:n.serverInfo,capabilities:n.capabilities.agent??{},...n.authMethods===void 0?{}:{authMethods:n.authMethods},...n._meta===void 0?{}:{_meta:n._meta}}}}return t},"project");return{...e,incoming:M.map(e.incoming,t=>Array.isArray(t)?t.map(o):o(t)),send:h(t=>!Array.isArray(t)&&"method"in t&&"id"in t&&t.method===c.agent.initialize?(i=t.id,e.send({...t,params:{protocolVersion:1,clientInfo:this.options.clientInfo??{name:"agent-harness-client",version:"0.1.0"},capabilities:{agent:this.options.capabilities??{},...this.options.account===void 0?{}:{account:this.options.account},...this.options.product===void 0?{}:{product:this.options.product}}}})):e.send(t),"send")}}async releaseStream(e){this.stream&&await b.runPromise(this.stream.close(e)).catch(()=>{}),await this.cleanup.catch(()=>{}),this.stream=void 0}close(){return this.closing??=(async()=>{this.state="closing",this.connectAbort?.abort(new Error("Client closed")),this.connection?.close(),await this.connecting?.catch(()=>{}),await this.releaseStream(),await this.mcp.close(),this.handlers.clear(),this.listeners.clear(),this.state="closed"})()}}export function createClient(f={}){const e=new V(structuredClone(f));function i(o){const t={};for(const[n,l]of Object.entries(o))if(typeof l!="string"){const a=i(l);Object.keys(a).length>0&&(t[n]=a)}else _.has(l)?t[n]=a=>e.notify(l,a):R.has(l)&&(t[n]=(a,r)=>e.request(l,a,r));return Object.freeze(t)}return h(i,"project"),Object.freeze(Object.defineProperties({...i(I)},{state:{get:h(()=>e.state,"get")},initialization:{get:h(()=>e.initialization,"get")},on:{value:h((o,t)=>e.on(o,t),"value")},connect:{value:h((o,t)=>e.connect(o,t),"value")},close:{value:h(()=>e.close(),"value")}}))}h(createClient,"createClient");
|
package/lib/client/mcp.d.ts
CHANGED
|
@@ -19,7 +19,7 @@ export declare class ClientMcp {
|
|
|
19
19
|
constructor(peer: AgentMcpPeer);
|
|
20
20
|
prepare(params: unknown): {
|
|
21
21
|
params: unknown;
|
|
22
|
-
commit(result: unknown): void
|
|
22
|
+
commit(result: unknown): Promise<void>;
|
|
23
23
|
rollback(): Promise<void>;
|
|
24
24
|
};
|
|
25
25
|
connect(params: ConnectMcpRequest, signal: AbortSignal): Promise<{
|
package/lib/client/mcp.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var M=Object.defineProperty;var a=(d,e)=>M(d,"name",{value:e,configurable:!0});import{randomUUID as u}from"node:crypto";import{methods as w,RequestError as y}from"@agentclientprotocol/sdk/experimental/v2";import{McpPeerTransport as I}from"../integration/mcp-peer-transport.js";import{isRecord as h}from"../internal/guards.js";const g=new WeakSet,P=128,C=128;export class ClientMcp{static{a(this,"ClientMcp")}constructor(e){this.peer=e,this.providers=new Map,this.connections=new Map,this.sessions=new Map,this.generation=0,this.opening=0}prepare(e){const n=[];let r=e;try{h(e)&&Array.isArray(e.mcpServers)&&(r={...e,mcpServers:e.mcpServers.map(t=>{if(!h(t)||!("transport"in t))return t;if(typeof t.name!="string"||!t.name.trim()||"type"in t||"serverId"in t)throw new TypeError("Local MCP requires { name, transport }");const o=t.transport;if(typeof o!="function"&&!v(o))throw new TypeError("MCP transport must implement the MCP SDK Transport interface");if(this.providers.size>=P)throw new RangeError("Too many local MCP providers");const s=u();return this.providers.set(s,{source:o,connections:new Set}),n.push(s),{type:"acp",name:t.name,serverId:s,...t._meta===void 0?{}:{_meta:t._meta}}})})}catch(t){for(const o of n)this.providers.delete(o);throw t}return{params:r,commit:a(async t=>{const o=h(t)&&typeof t.sessionId=="string"?t.sessionId:h(e)&&typeof e.sessionId=="string"?e.sessionId:void 0;if(!o){if(n.length)throw new Error("Session setup returned no sessionId for its MCP providers");return}const s=this.sessions.get(o)??new Set,i=new Set(n);if(h(r)&&Array.isArray(r.mcpServers))for(const c of r.mcpServers)h(c)&&typeof c.serverId=="string"&&this.providers.has(c.serverId)&&i.add(c.serverId);this.sessions.set(o,i),await this.release([...s].filter(c=>!i.has(c)))},"commit"),rollback:a(()=>this.release(n),"rollback")}}async connect(e,n){const r=this.providers.get(e.serverId);if(!r)throw y.invalidParams("Unknown MCP serverId");if(this.connections.size+this.opening>=C)throw new Error("Too many local MCP connections");this.opening++;try{const t=this.generation;n.throwIfAborted();const o=typeof r.source=="function"?await r.source():r.source;if(!v(o))throw new TypeError("MCP transport factory did not return a Transport");if(g.has(o)||o.onmessage||o.onclose||o.onerror)throw new Error("MCP Transport is already owned; return a fresh transport from a factory for each connection");if(g.add(o),n.aborted||t!==this.generation||this.providers.get(e.serverId)!==r)throw await o.close(),n.reason??new Error("MCP provider closed during connection");const s=u(),i=new I(s,this.peer);let c;const l=a(()=>c??=Promise.resolve().then(async()=>{this.connections.delete(s),r.connections.delete(s),i.closeFromScope(new Error("MCP connection closed")),await o.close()}),"close"),p=a(()=>{l().catch(()=>{})},"fail");i.onmessage=f=>{o.send(f).catch(p)},o.onmessage=f=>{i.send(f).catch(p)},i.onclose=o.onclose=p,i.onerror=o.onerror=p,this.connections.set(s,{provider:r,bridge:i,transport:o,close:l}),r.connections.add(s);const m=a(()=>{p()},"abort");n.addEventListener("abort",m,{once:!0});try{if(await i.start(),await o.start(),n.throwIfAborted(),c)throw new Error("MCP Transport closed during startup");return{connectionId:s}}catch(f){throw await l(),f}finally{n.removeEventListener("abort",m)}}finally{this.opening--}}message(e,n){return this.require(e.connectionId).bridge.receiveRequest(e.method,e.params,n)}notify(e){this.require(e.connectionId).bridge.receiveNotification(e.method,e.params)}async disconnect(e){return await this.connections.get(e.connectionId)?.close(),{}}async closeSession(e){const n=this.sessions.get(e)??[];this.sessions.delete(e),await this.release(n)}async close(){this.generation++,this.sessions.clear(),await this.release([...this.providers.keys()])}async release(e){const n=[];for(const r of e){const t=this.providers.get(r);this.providers.delete(r);for(const o of t?.connections??[]){const s=this.connections.get(o);s&&n.push(s)}}await Promise.all(n.map(r=>r.close()))}require(e){const n=this.connections.get(e);if(!n)throw y.invalidParams("Unknown MCP connectionId");return n}}function v(d){return h(d)&&["start","send","close"].every(e=>typeof d[e]=="function")}a(v,"isTransport");export const CLIENT_MCP_METHODS=new Set(Object.values(w.client.mcp)),sessionMcpMethods=[w.agent.session.new,w.agent.session.resume,w.agent.session.fork];export function isSessionMcpMethod(d){return sessionMcpMethods.some(e=>e===d)}a(isSessionMcpMethod,"isSessionMcpMethod");
|
|
@@ -1 +1,84 @@
|
|
|
1
|
-
|
|
1
|
+
import { type AgentContext, type JsonRpcId as AcpJsonRpcId, type MessageMcpNotification, type MessageMcpRequest } from '@agentclientprotocol/sdk/experimental/v2';
|
|
2
|
+
import type { Transport, TransportSendOptions } from '@modelcontextprotocol/sdk/shared/transport.js';
|
|
3
|
+
import { type JSONRPCMessage, type RequestId } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
type McpClientContext = Pick<AgentContext, 'request' | 'notify'>;
|
|
5
|
+
type AcpMcpParams = Record<string, unknown> | null | undefined;
|
|
6
|
+
export interface AcpMcpPeerRegistration {
|
|
7
|
+
readonly peer: AcpMcpPeer;
|
|
8
|
+
dispose(reason?: unknown): Promise<void>;
|
|
9
|
+
}
|
|
10
|
+
export interface AcpMcpTransportOptions {
|
|
11
|
+
readonly routeId: string;
|
|
12
|
+
readonly serverId: string;
|
|
13
|
+
/** Cancels acquisition without transferring ownership of an established connection. */
|
|
14
|
+
readonly signal?: AbortSignal;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Registers the client side of one live ACP v2 connection.
|
|
18
|
+
*
|
|
19
|
+
* Session MCP configuration crosses the Agent CLI's internal HTTP boundary, so
|
|
20
|
+
* it carries only the opaque route id and resolves the live `AgentContext`
|
|
21
|
+
* here. A route is exact and cannot be replaced while it is active.
|
|
22
|
+
*/
|
|
23
|
+
export declare function registerAcpMcpPeer(routeId: string, client: McpClientContext, signal: AbortSignal): AcpMcpPeerRegistration;
|
|
24
|
+
export declare function requireAcpMcpPeer(routeId: string): AcpMcpPeer;
|
|
25
|
+
/**
|
|
26
|
+
* Connection-scoped MCP-over-ACP dispatcher. One peer may own many physical
|
|
27
|
+
* MCP connections, each selected by the provider-generated `connectionId`.
|
|
28
|
+
*/
|
|
29
|
+
export declare class AcpMcpPeer {
|
|
30
|
+
private readonly client;
|
|
31
|
+
private readonly rootSignal;
|
|
32
|
+
private readonly transports;
|
|
33
|
+
private isClosed;
|
|
34
|
+
constructor(client: McpClientContext, rootSignal: AbortSignal);
|
|
35
|
+
get closed(): boolean;
|
|
36
|
+
connect(serverId: string, signal: AbortSignal): Promise<string>;
|
|
37
|
+
attach(connectionId: string, transport: AcpMcpTransport): void;
|
|
38
|
+
request(transport: AcpMcpTransport, connectionId: string, method: string, params: AcpMcpParams, signal: AbortSignal): Promise<unknown>;
|
|
39
|
+
notify(transport: AcpMcpTransport, connectionId: string, method: string, params: AcpMcpParams): Promise<void>;
|
|
40
|
+
disconnect(transport: AcpMcpTransport, connectionId: string): Promise<void>;
|
|
41
|
+
disconnectUnattached(connectionId: string): Promise<void>;
|
|
42
|
+
receiveRequest(params: MessageMcpRequest, requestId: AcpJsonRpcId, signal: AbortSignal): Promise<unknown>;
|
|
43
|
+
receiveNotification(params: MessageMcpNotification): void;
|
|
44
|
+
closeFromRoot(reason?: unknown): Promise<void>;
|
|
45
|
+
private requireTransport;
|
|
46
|
+
private assertAttached;
|
|
47
|
+
private assertOpen;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* MCP SDK transport backed by the standard ACP v2 MCP methods.
|
|
51
|
+
*
|
|
52
|
+
* ACP intentionally omits the inner JSON-RPC envelope. The outer request id is
|
|
53
|
+
* the id observed by the MCP provider, while this transport restores the local
|
|
54
|
+
* MCP SDK's id when it delivers the response back to the SDK.
|
|
55
|
+
*/
|
|
56
|
+
export declare class AcpMcpTransport implements Transport {
|
|
57
|
+
private readonly options;
|
|
58
|
+
private state;
|
|
59
|
+
private peer?;
|
|
60
|
+
private connectionIdValue?;
|
|
61
|
+
private startController?;
|
|
62
|
+
private closePromise?;
|
|
63
|
+
private closeNotified;
|
|
64
|
+
private readonly outbound;
|
|
65
|
+
private readonly inbound;
|
|
66
|
+
onclose?: () => void;
|
|
67
|
+
onerror?: (error: Error) => void;
|
|
68
|
+
onmessage?: <T extends JSONRPCMessage>(message: T) => void;
|
|
69
|
+
constructor(options: AcpMcpTransportOptions);
|
|
70
|
+
get sessionId(): string | undefined;
|
|
71
|
+
start(): Promise<void>;
|
|
72
|
+
send(message: JSONRPCMessage, _options?: TransportSendOptions): Promise<void>;
|
|
73
|
+
close(): Promise<void>;
|
|
74
|
+
closeFromPeer(reason?: unknown): Promise<void>;
|
|
75
|
+
receiveRequest(requestId: RequestId, method: string, params: AcpMcpParams, signal: AbortSignal): Promise<unknown>;
|
|
76
|
+
receiveNotification(method: string, params: AcpMcpParams): void;
|
|
77
|
+
private sendRequest;
|
|
78
|
+
private sendNotification;
|
|
79
|
+
private settleInbound;
|
|
80
|
+
private finishClose;
|
|
81
|
+
private deliver;
|
|
82
|
+
private notifyClose;
|
|
83
|
+
}
|
|
84
|
+
export {};
|
|
@@ -1 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
import type { CreateElicitationRequest, ElicitationSchema } from '@agentclientprotocol/sdk';
|
|
2
|
+
export interface AskUserQuestionInput {
|
|
3
|
+
questions: Array<{
|
|
4
|
+
question: string;
|
|
5
|
+
header: string;
|
|
6
|
+
options: Array<{
|
|
7
|
+
label: string;
|
|
8
|
+
description: string;
|
|
9
|
+
}>;
|
|
10
|
+
multiSelect?: boolean;
|
|
11
|
+
}>;
|
|
12
|
+
metadata?: {
|
|
13
|
+
source?: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export declare function createAskUserQuestionElicitation(input: AskUserQuestionInput, sessionId: string, toolCallId: string, meta?: Record<string, unknown>): CreateElicitationRequest & {
|
|
17
|
+
mode: 'form';
|
|
18
|
+
requestedSchema: ElicitationSchema;
|
|
19
|
+
};
|
|
20
|
+
export declare function normalizeAskUserQuestionElicitationAnswers(input: AskUserQuestionInput, content: unknown): Record<string, string>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { buildEpochCenterAddress, createSandboxCenterClient, SANDBOX_CENTER_IPC_ADDRESS_ENV, SANDBOX_CENTER_LIFECYCLE_COMMANDS, SANDBOX_CENTER_START_MODE_ENV, SANDBOX_RULES_COMMANDS, spawnSandboxCenter, } from '../../cli/dist-server/types/workspace/sandbox-cli/lib/node/sandbox-center-client.js';
|
|
2
|
+
export { getSandboxCenterPath } from '../../cli/dist-server/types/workspace/sandbox-cli/lib/node/resolver.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import e from"#agent-harness-runtime";const n=e["component-sandbox-center"]();export const{buildEpochCenterAddress,createSandboxCenterClient,SANDBOX_CENTER_IPC_ADDRESS_ENV,SANDBOX_CENTER_LIFECYCLE_COMMANDS,SANDBOX_CENTER_START_MODE_ENV,SANDBOX_RULES_COMMANDS,spawnSandboxCenter,getSandboxCenterPath}=n;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { PromptRequest as V2PromptRequest } from '@agentclientprotocol/sdk/experimental/v2';
|
|
2
|
+
import type { PromptRequest } from '../../../cli/dist-server/types/node/server/formats/acp/acp-protocol.js';
|
|
2
3
|
import type { AgentInputItem } from '../../../cli/dist-server/types/vendor/cbc-shared/node/index.js';
|
|
3
|
-
import type { PromptRequest } from './acp-protocol.js';
|
|
4
4
|
/** Persist SDK content once. Resource bytes are projected for the model only at its boundary. */
|
|
5
5
|
export declare function acpPromptInput(input: PromptRequest | V2PromptRequest): AgentInputItem[];
|
|
6
6
|
export { projectPromptFilesForModel } from '../../../cli/dist-server/types/node/utils/embedded-resource.js';
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import type { QueryOptions } from '#agent-harness-codebuddy/server';
|
|
2
2
|
import type { AcpV2ClientCapabilities } from '../protocol/acp-v2.js';
|
|
3
3
|
import type { SessionConfigProjector } from '../session/server-config.js';
|
|
4
|
+
/** Harness opts in to the native Linux sandbox only when its executable is present. */
|
|
5
|
+
export declare function isLinuxSandboxCLIInstalled(): boolean;
|
|
4
6
|
/** Both backends use the CLI's option vocabulary and ACP v2 projection. */
|
|
5
7
|
export declare const projectSessionConfig: SessionConfigProjector;
|
|
6
8
|
export declare function projectSessionContextSize(options: QueryOptions, modelId?: string): number | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"#agent-harness-runtime";const e=o["component-session-config"]();export const{projectSessionContextSize,createSessionConfigProjector,projectSessionConfig}=e;
|
|
1
|
+
import o from"#agent-harness-runtime";const e=o["component-session-config"]();export const{isLinuxSandboxCLIInstalled,projectSessionContextSize,createSessionConfigProjector,projectSessionConfig}=e;
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
+
import { codeBuddyErrorFromRequestError } from '../../cli/dist-server/types/node/server/formats/acp/acp-error-model.js';
|
|
1
2
|
import type { AgentInputItem } from '../../cli/dist-server/types/vendor/cbc-shared/node/index.js';
|
|
2
|
-
import type {
|
|
3
|
+
import type { SessionReplayProjector, SessionUsage, SessionUsageHistory } from '../session/replay.js';
|
|
3
4
|
import type { AgentHarnessRewindSessionRequest } from '../session/turn.js';
|
|
4
|
-
|
|
5
|
-
export { acpPromptInput } from './
|
|
5
|
+
export { AcpSessionFormatter } from '../../cli/dist-server/types/node/server/formats/acp/index.js';
|
|
6
|
+
export { acpPromptInput } from './session/prompt-input.js';
|
|
6
7
|
/** Interpret ACP turn cursors outside the Agent's native storage API. */
|
|
7
8
|
export declare function selectRewindMessage(snapshot: Parameters<SessionReplayProjector>[0], boundary: AgentHarnessRewindSessionRequest['_meta']): string | null;
|
|
8
9
|
export declare function createToolInputParser(): (delta: string) => Record<string, unknown>;
|
|
@@ -13,12 +14,10 @@ export declare function projectAgentError(message: string, info?: {
|
|
|
13
14
|
code?: string | number;
|
|
14
15
|
details?: string;
|
|
15
16
|
} | null): ReturnType<typeof codeBuddyErrorFromRequestError>;
|
|
17
|
+
export declare function projectAgentFailure(error: unknown): ReturnType<typeof projectAgentError>;
|
|
16
18
|
/** The durable assistant error carries its original HTTP/category fields. */
|
|
17
19
|
export declare function projectAgentItemError(item: AgentInputItem): ReturnType<typeof projectAgentError> | undefined;
|
|
18
|
-
|
|
19
|
-
export declare const projectAgentItem: AgentItemProjector;
|
|
20
|
-
/** Reuse the CLI's ACP extension vocabulary; the Agent only exports kernel facts. */
|
|
21
|
-
export declare const projectAgentEvent: AgentEventProjector;
|
|
20
|
+
export { projectAgentItem, projectAgentEvent } from '../../cli/dist-server/types/node/server/formats/acp/projection.js';
|
|
22
21
|
/** Storage-only ACP projection: no Cell container or execution services. */
|
|
23
22
|
export declare const projectSessionReplay: SessionReplayProjector;
|
|
24
23
|
/** Per-transcript billing stages and context; tree edges come from live lifecycle or SessionStore. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"#agent-harness-runtime";const t=e["component-session-replay"]();export const{selectRewindMessage,createToolInputParser,projectAgentError,projectAgentItemError,createSessionUsage,acpPromptInput,projectAgentItem,projectAgentEvent,projectSessionReplay}=t;
|
|
1
|
+
import e from"#agent-harness-runtime";const t=e["component-session-replay"]();export const{selectRewindMessage,createToolInputParser,projectAgentError,projectAgentFailure,projectAgentItemError,createSessionUsage,AcpSessionFormatter,acpPromptInput,projectAgentItem,projectAgentEvent,projectSessionReplay}=t;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var r=(e,t)=>N(e,"name",{value:t,configurable:!0});import{Effect as c,Exit as b,MutableList as
|
|
1
|
+
var N=Object.defineProperty;var r=(e,t)=>N(e,"name",{value:t,configurable:!0});import{Effect as c,Exit as b,MutableList as R,PubSub as w,Queue as S,Scope as y,Semaphore as U,SubscriptionRef as B,SynchronizedRef as E}from"effect";class k extends Error{static{r(this,"McpPromiseError")}constructor(t,s){super(`MCP Promise rejected during ${t}`),this.operation=t,this.cause=s,this._tag="McpPromiseError",this.name=this._tag}}function x(e,t){return c.tryPromise({catch:r(s=>new k(e,s),"catch"),try:t})}r(x,"tryMcpPromise");function q(e){return e.catch(t=>{throw t instanceof k?t.cause:t})}r(q,"preserveMcpPromiseError");function $(e){return e}r($,"runtimeOf");function C(e){return e.forkScopeUnsafe()}r(C,"forkProcessScope");export async function createMcpSubscriptionState(e,t){const s=e,i=await s.runEffect(B.make(t));return{close:r(()=>s.runEffect(w.shutdown(i.pubsub)),"close"),get:r(()=>s.runEffect(B.get(i)),"get"),getUnsafe:r(()=>B.getUnsafe(i),"getUnsafe"),modify:r(f=>s.runEffect(B.modify(i,f)),"modify")}}r(createMcpSubscriptionState,"createMcpSubscriptionState");export function createMcpKeyedSerialExecutor(e){const t=e,s=E.makeUnsafe(new Map),i=r(n=>t.runEffect(E.modify(s,a=>{const o=a.get(n);if(o){const p={...o,users:o.users+1};return[p,new Map(a).set(n,p)]}const u={semaphore:U.makeUnsafe(1),users:1};return[u,new Map(a).set(n,u)]})),"gateFor"),f=r((n,a)=>t.runEffect(E.update(s,o=>{const u=o.get(n);if(u?.semaphore!==a.semaphore)return o;const p=new Map(o);return u.users<=1?p.delete(n):p.set(n,{...u,users:u.users-1}),p})),"releaseGate"),l=r(n=>t.runEffect(n.semaphore.withPermit(c.void)),"waitForGate");return{get activeKeyCount(){return E.getUnsafe(s).size},run:r(async(n,a,o)=>{const u=await i(n);try{return await q(t.runEffect(G(u.semaphore.withPermit(x("registry.reconcile",o)),a)))}finally{await f(n,u)}},"run"),waitForIdle:r(async()=>{const n=await t.runEffect(E.get(s));await Promise.all([...n.values()].map(l))},"waitForIdle"),waitForKey:r(async n=>{const a=(await t.runEffect(E.get(s))).get(n);a&&await l(a)},"waitForKey")}}r(createMcpKeyedSerialExecutor,"createMcpKeyedSerialExecutor");export async function openMcpEffectScope(e,t={}){const s=e,i=C(e),f=new Map;let l=!1,n;return{acquire:r(async o=>{if(l)throw new Error("MCP Effect scope is closed");const u=Symbol("mcp-scope-acquire"),p=new AbortController,g=(async()=>{const m=await s.runEffect(y.fork(i,"sequential"),{signal:p.signal}),d=o.acquire(p.signal),v=t.interruptPendingAcquires===!1?d:F(d,p.signal,o.release);let z;try{z=await q(s.runEffect(y.provide(c.acquireRelease(x("attachment.acquire",()=>v),h=>x("attachment.release",()=>o.release(h)).pipe(c.orDie)),m),{signal:p.signal}))}catch(h){throw await s.runEffect(y.close(m,b.fail(h))).catch(()=>{}),h}let P;const M=r(()=>(P??=q(s.runEffect(y.close(m,b.void))),P),"release");if(l)throw await M(),new Error("MCP Effect scope is closed");return{release:M,value:z}})();f.set(u,{controller:p,promise:g});try{return await g}finally{f.delete(u)}},"acquire"),close:r(()=>{if(n)return n;l=!0;const o=new Error("MCP Effect scope is closed");if(t.interruptPendingAcquires!==!1)for(const u of f.values())u.controller.abort(o);return n=(async()=>{await Promise.allSettled([...f.values()].map(u=>u.promise)),await q(s.runEffect(y.close(i,b.void)))})(),n},"close")}}r(openMcpEffectScope,"openMcpEffectScope");function F(e,t,s){return new Promise((i,f)=>{let l=!1;const n=r(()=>{l||(l=!0,f(t.reason??new Error("MCP scoped acquisition aborted")))},"abort");t.aborted?n():t.addEventListener("abort",n,{once:!0}),e.then(a=>{if(t.removeEventListener("abort",n),l){s(a).catch(()=>{});return}l=!0,i(a)},a=>{t.removeEventListener("abort",n),!l&&(l=!0,f(a))})})}r(F,"interruptibleAcquisition");function G(e,t){const s="harness.executor.runtime",i={component:"executor",operation:t,resource:"registration"};return e.pipe(c.tap(()=>c.logInfo(s).pipe(c.annotateLogs({...i,outcome:"success"}))),c.tapError(()=>c.logWarning(s).pipe(c.annotateLogs({...i,outcome:"error"}))),c.withSpan(s,{attributes:i}))}r(G,"observeExecutorRegistrationEffect");export async function openMcpLivePubSub(e){if(!Number.isSafeInteger(e.capacity)||e.capacity<=0)throw new RangeError("MCP live PubSub capacity must be a positive safe integer");I(e.maxBufferedBytes,"MCP live PubSub");const t=e.processRuntime,s=C(e.processRuntime),i=await t.runEffect(w.sliding({capacity:e.capacity,replay:0})),f=U.makeUnsafe(1),l=[];let n=0,a=!1,o;const u=r(()=>{i.pubsub.slide();const m=l.shift();n-=m?.size??0},"removeOldest"),p=r(()=>{const m=w.sizeUnsafe(i);for(;l.length>m;){const d=l.shift();n-=d?.size??0}n<0&&(n=0)},"reconcile"),g=r(()=>{l.length=0,n=0},"clearBudget");return{capacity:e.capacity,buffered:r(()=>w.sizeUnsafe(i),"buffered"),bufferedBytes:r(()=>(p(),n),"bufferedBytes"),close:r(()=>o||(a=!0,o=t.runEffect(w.shutdown(i).pipe(c.andThen(y.close(s,b.void)),c.ensuring(c.sync(g)))),o),"close"),publish:r(m=>{if(a)return Promise.resolve(!1);const d={message:m,size:L(e.sizeOf,m,"MCP live PubSub")};return d.size>e.maxBufferedBytes?Promise.resolve(!1):t.runEffect(f.withPermit(c.gen(function*(){if(a)return!1;for(p();l.length>=e.capacity||n+d.size>e.maxBufferedBytes;)u();l.push(d),n+=d.size;const v=yield*w.publish(i,d);return p(),v})))},"publish"),subscribe:r(async m=>{if(a)throw new Error("MCP live PubSub is closed");const d=await t.runEffect(y.fork(s,"sequential")),v=await t.runEffect(y.provide(w.subscribe(i),d)),z=c.gen(function*(){for(;;){const h=yield*w.take(v);yield*c.sync(p),yield*x("registry.consume",A=>m(h.message,A)).pipe(c.catchCause(()=>c.void))}});await t.runEffect(c.forkIn(z,d));let P;const M=r(()=>(P??=t.runEffect(y.close(d,b.void).pipe(c.ensuring(c.sync(p)))),P),"release");if(a)throw await M(),new Error("MCP live PubSub is closed");return{release:M}},"subscribe")}}r(openMcpLivePubSub,"openMcpLivePubSub");export async function openMcpLiveQueue(e){if(!Number.isSafeInteger(e.capacity)||e.capacity<=0)throw new RangeError("MCP live queue capacity must be a positive safe integer");I(e.maxBufferedBytes,"MCP live queue");const t=e.processRuntime,s=C(e.processRuntime),i=await t.runEffect(S.sliding(e.capacity));let f=0;const l=c.gen(function*(){for(;;){const o=yield*S.take(i);yield*c.sync(()=>{f=Math.max(0,f-o.size)}),yield*x("queue.consume",u=>e.consume(o.message,u)).pipe(c.catchCause(()=>c.void))}});await t.runEffect(c.forkIn(l,s));let n=!1,a;return{capacity:e.capacity,buffered:r(()=>S.sizeUnsafe(i),"buffered"),bufferedBytes:r(()=>f,"bufferedBytes"),close:r(()=>a||(n=!0,a=t.runEffect(S.shutdown(i).pipe(c.andThen(y.close(s,b.void)),c.ensuring(c.sync(()=>{f=0})))),a),"close"),offer:r(o=>{if(n)return!1;const u={message:o,size:L(e.sizeOf,o,"MCP live queue")};if(u.size>e.maxBufferedBytes)return!1;for(;i.messages.length>=e.capacity||f+u.size>e.maxBufferedBytes;){const g=R.take(i.messages);if(g===R.Empty)break;f=Math.max(0,f-g.size)}const p=S.offerUnsafe(i,u);return p&&(f+=u.size),p},"offer")}}r(openMcpLiveQueue,"openMcpLiveQueue");function I(e,t){if(!Number.isSafeInteger(e)||e<=0)throw new RangeError(`${t} maxBufferedBytes must be a positive safe integer`)}r(I,"assertByteBudget");function L(e,t,s){const i=e(t);if(!Number.isSafeInteger(i)||i<0)throw new RangeError(`${s} message size must be a non-negative safe integer`);return i}r(L,"sizeMessage");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var l=Object.defineProperty;var r=(e,n)=>l(e,"name",{value:n,configurable:!0});import{isAbsolute as b}from"node:path";const o=Symbol.for("codebuddy.ai/agent-harness/application-owner");export async function createHarness(e={}){if(e.signal?.throwIfAborted(),e.configDir!==void 0&&!b(e.configDir))throw new TypeError("Harness configDir must be an absolute path");if(typeof e.sandboxCenter=="object"&&!e.sandboxCenter.address?.trim())throw new TypeError("sandboxCenter.address must be a non-empty IPC address");const n=globalThis;if(n[o]!==void 0)throw new Error("This process already owns a Harness. Reuse it for additional Clients and Sessions, or await its close() before creating another.");const d={};n[o]=d;const i=process.env.CODEBUDDY_CONFIG_DIR;e.configDir!==void 0&&(process.env.CODEBUDDY_CONFIG_DIR=e.configDir);const f=r(()=>{n[o]===d&&(delete n[o],e.configDir!==void 0&&process.env.CODEBUDDY_CONFIG_DIR===e.configDir&&(i===void 0?delete process.env.CODEBUDDY_CONFIG_DIR:process.env.CODEBUDDY_CONFIG_DIR=i))},"release");try{const t={...e,host:e.host===void 0?void 0:{...e.host},productConfig:typeof e.productConfig=="object"?structuredClone(e.productConfig):e.productConfig,sandboxCenter:typeof e.sandboxCenter=="object"?{...e.sandboxCenter}:e.sandboxCenter},{startHarness:u}=await import("./runtime.js"),s=await u(t),c=s.closed.then(f);c.catch(()=>{});const D=r(()=>(s.close().catch(()=>{}),c),"close");return{get ready(){return s.ready},connect:r((a,C)=>s.connect(a,C),"connect"),connectInMemory:r(a=>s.connectInMemory(a),"connectInMemory"),closed:c,close:D,[Symbol.asyncDispose]:D}}catch(t){throw f(),t}}r(createHarness,"createHarness");
|
package/lib/harness/runtime.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var H=Object.defineProperty;var i=(e,s)=>H(e,"name",{value:s,configurable:!0});import{readFileSync as S}from"node:fs";import{closeHarnessProcessRuntime as P,closeInPhases as v,closeWithLifecycleTelemetry as M,resolveShutdownCoordinator as R,runUntilClosed as L}from"../application/lifecycle.js";import{createApplicationServices as k}from"../application/services.js";import{createHarnessProcessRuntime as x}from"../effect-runtime/process-runtime.mjs";import{buildAgentHarnessClientIdentityEnv as T,resolveAgentHarnessClientIdentity as N}from"../runtime/client-identity.js";import{startupProfiler as O}from"../telemetry/startup-profile.js";export async function startHarness(e,s={}){e.signal?.throwIfAborted();const l=e.mcp?.toolsSyncTtlMs;if(l!=null&&(!Number.isSafeInteger(l)||l<=0))throw new RangeError("mcp.toolsSyncTtlMs must be a positive integer or null");const g=s.packageVersion??JSON.parse(S(new URL("../../package.json",import.meta.url),"utf8")).version,p=N(e.host??{},g),a=R(s),m=await(s.createProcessRuntime??x)(),w=Promise.withResolvers(),n=new AbortController,d=new Error("Agent Harness is shutting down"),u=i(()=>n.abort(e.signal?.reason??d),"cancel");e.signal?.addEventListener("abort",u,{once:!0}),e.signal?.aborted&&u();const I=Promise.resolve().then(()=>m.run(async t=>{n.signal.throwIfAborted();const{server:r,modules:o,telemetry:E,containment:A,runtimeShutdown:C,recordLifecycle:h}=await k({signal:AbortSignal.any([n.signal,t]),clientIdentity:p,clientIdentityEnv:T(p),dependencies:s,packageVersion:g,processRuntime:m,productConfig:e.productConfig,sandboxCenter:e.sandboxCenter,tools:e.tools,strictMcpConfig:e.strictMcpConfig??!1,mcp:e.mcp,shutdown:a,telemetryOptions:e.telemetry??{}});if(!("connectInMemory"in r)||typeof r.connectInMemory!="function")throw await v([[()=>r.close(),()=>o.close()]],a),new TypeError("Application Server does not implement the in-memory endpoint");O()?.markEvent("harness-services-ready"),h({component:"server",phase:"startup",process:{pid:process.pid},reason:"startup_completed",state:"started"}),w.resolve(r),await L(new Promise(()=>{}),b=>M(E,()=>v([[()=>r.close(b),()=>o.close(b)]],a,"in-memory shutdown")),void 0,n.signal,[A.signal,C.signal,t],{timeouts:a}),h({component:"server",phase:"shutdown",process:{pid:process.pid},reason:"shutdown_completed",state:"stopped"})})),c=(async()=>{let t,r=!1;try{await I}catch(o){t=o,r=!0}n.abort(d),a.start();try{await P(m,a)}catch(o){throw r?new AggregateError([t,o],"Harness execution and cleanup failed"):o}finally{e.signal?.removeEventListener("abort",u)}if(r)throw t})();c.catch(()=>{});const f=await Promise.race([w.promise,c.then(()=>{throw new Error("Harness closed before startup completed")})]);e.signal?.aborted&&(await c,e.signal.throwIfAborted());const y=i(()=>(n.abort(d),c),"close");return{get ready(){return!n.signal.aborted&&f.ready},closed:c,connect:i((t,r)=>{if(n.signal.aborted)throw new Error("Harness is closing");return f.connect(t,r)},"connect"),connectInMemory:i(t=>{if(n.signal.aborted)throw new Error("Harness is closing");return f.connectInMemory(t)},"connectInMemory"),close:y,[Symbol.asyncDispose]:y}}i(startHarness,"startHarness");
|
package/lib/harness/types.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { QueryOptions, SdkMcpToolDefinition } from '#agent-harness-codebuddy/server';
|
|
2
2
|
import type { AgentHarnessClientIdentity } from '../runtime/client-identity.js';
|
|
3
3
|
import type { AgentHarnessProductInput } from '../runtime/product-config.js';
|
|
4
|
+
import type { SandboxCenterOption } from '../runtime/sandbox-center.js';
|
|
4
5
|
import type { TelemetryOptions } from '../telemetry/public.js';
|
|
5
6
|
import type { InMemoryEndpoint } from '../transport/effect.js';
|
|
6
7
|
import type { AgentHarnessConnectionAcceptor } from '../transport/types.js';
|
|
@@ -14,6 +15,8 @@ export interface HarnessOptions {
|
|
|
14
15
|
readonly productConfig?: ProductConfig | string;
|
|
15
16
|
/** Application-wide directory; defaults to CODEBUDDY_CONFIG_DIR or ~/.codebuddy. */
|
|
16
17
|
readonly configDir?: string;
|
|
18
|
+
/** Managed by Harness by default; pass an IPC address to borrow a Host-owned center. */
|
|
19
|
+
readonly sandboxCenter?: SandboxCenterOption;
|
|
17
20
|
readonly tools?: HarnessTools;
|
|
18
21
|
readonly strictMcpConfig?: boolean;
|
|
19
22
|
readonly mcp?: {
|
|
@@ -49,6 +49,11 @@ export interface AgentMcpAttachment {
|
|
|
49
49
|
message(params: AcpV2MessageMcpRequest, options: AgentMcpMessageOptions): Promise<unknown>;
|
|
50
50
|
notify(params: AcpV2MessageMcpNotification, options: AgentMcpNotificationOptions): void;
|
|
51
51
|
callTool(logicalName: string, toolName: string, args: unknown, signal?: AbortSignal): Promise<ExecutorMcpCallResult>;
|
|
52
|
+
/**
|
|
53
|
+
* Irreversibly disable this attachment's access, then release resources.
|
|
54
|
+
* A cleanup rejection must not restore access. This releases session
|
|
55
|
+
* capabilities; it does not revoke the user's upstream OAuth/API token.
|
|
56
|
+
*/
|
|
52
57
|
revoke(): Promise<void>;
|
|
53
58
|
subscribeServerStatus(listener: (status: SessionMcpServerStatus) => void): () => void;
|
|
54
59
|
}
|