@tencent-ai/agent-harness 0.2.0-beta.2 → 0.2.0-beta.4
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 +40 -2
- package/cli/CHANGELOG.md +64 -0
- package/cli/dist-server/shared.cjs +450 -329
- package/cli/dist-server/types/node/acp/acp-protocol.d.ts +8 -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 +8 -1
- package/cli/dist-server/types/node/loopback/server-protocol.d.ts +5 -0
- 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 +3 -2
- package/cli/dist-server/types/node/server/types.d.ts +59 -7
- package/cli/dist-server/types/node/tools/tool-protocol.d.ts +39 -24
- package/cli/dist-server/types/vendor/cbc-core/node/agent/agent-protocol.d.ts +31 -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 +26 -3
- package/cli/dist-server/types/vendor/cbc-core/node/agent/index.d.ts +3 -0
- 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 +43 -9
- 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 +9 -8
- 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 +2 -0
- package/cli/dist-server/types/vendor/cbc-core/node/context/mods-bridge.d.ts +115 -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/message-queue/followup-queue-protocol.d.ts +3 -2
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/followup-queue.d.ts +1 -1
- package/cli/dist-server/types/vendor/cbc-core/node/message-queue/steer-input-buffer-protocol.d.ts +4 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/can-use-tool.d.ts +4 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/index.d.ts +1 -0
- package/cli/dist-server/types/vendor/cbc-core/node/session/interruption-service.d.ts +8 -0
- 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 +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 +37 -3
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-protocol.d.ts +59 -5
- package/cli/dist-server/types/vendor/cbc-core/node/session/session-run-state-machine-protocol.d.ts +14 -1
- package/cli/dist-server/types/vendor/cbc-core/node/session/stream-timeout-retry-budget.d.ts +8 -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 +4 -4
- package/cli/dist-server/types/vendor/cbc-core/node/utils/input-item-utils.d.ts +9 -1
- 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/model/model-errors.d.ts +30 -2
- 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/prompt-codec.d.ts +4 -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/agent-client-protocol/lib/common/types.d.ts +15 -1
- package/cli/dist-server/types/workspace/authentication/lib/common/account-scoped-external-link-authentication-provider.d.ts +3 -3
- package/cli/dist-server/types/workspace/authentication/lib/common/authentication-manager.d.ts +6 -0
- 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 +21 -0
- package/cli/dist-server/types/workspace/authentication/lib/common/external-link-authentication-provider.d.ts +20 -4
- package/cli/dist-server/types/workspace/authentication/lib/common/index.d.ts +1 -0
- 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 +31 -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 +26 -3
- package/cli/dist-server/types/workspace/cbc-core/lib/node/agent/index.d.ts +3 -0
- 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 +43 -9
- 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 +9 -8
- 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 +2 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/context/mods-bridge.d.ts +115 -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/message-queue/followup-queue-protocol.d.ts +3 -2
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/followup-queue.d.ts +1 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/message-queue/steer-input-buffer-protocol.d.ts +4 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/can-use-tool.d.ts +4 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/index.d.ts +1 -0
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/interruption-service.d.ts +8 -0
- 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 +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 +37 -3
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-protocol.d.ts +59 -5
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/session-run-state-machine-protocol.d.ts +14 -1
- package/cli/dist-server/types/workspace/cbc-core/lib/node/session/stream-timeout-retry-budget.d.ts +8 -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 +4 -4
- package/cli/dist-server/types/workspace/cbc-core/lib/node/utils/input-item-utils.d.ts +9 -1
- 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/model/model-errors.d.ts +30 -2
- package/cli/dist-server/types/workspace/cbc-worktree/lib/node/worktree/worktree-service.d.ts +5 -0
- package/cli/dist-server/types/workspace/core/lib/common/protocol.d.ts +8 -1
- package/cli/dist-server/types/workspace/product/lib/common/index.d.ts +1 -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/types/config.d.ts +12 -0
- package/cli/dist-server/types/workspace/product/lib/common/types/features.d.ts +17 -9
- package/cli/dist-server/types/workspace/product/lib/common/types/product.d.ts +15 -0
- package/cli/dist-server/types/workspace/prompts/lib/common/product-prompt-provider.d.ts +3 -1
- package/cli/dist-server/types/workspace/prompts/lib/common/prompt-protocol.d.ts +6 -0
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/center-protocol.generated.d.ts +5 -0
- package/cli/dist-server/types/workspace/sandbox-cli/lib/common/file-policy.d.ts +4 -1
- 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 +3 -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 +1 -803
- package/cli/product.internal.json +1 -1057
- package/cli/product.ioa.json +1 -1515
- package/cli/product.json +1 -2189
- package/cli/product.selfhosted.json +1 -364
- 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/acp-v2.md +19 -0
- package/docs/client.md +7 -0
- package/docs/in-process.md +26 -2
- package/docs/product.md +4 -0
- package/docs/protocol.md +10 -2
- package/docs/server.md +2 -0
- package/lib/agent/v2.js +1 -1
- package/lib/application/services.js +1 -1
- package/lib/auth/module.d.ts +3 -1
- package/lib/auth/module.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.d.mts +2 -0
- package/lib/components/sandbox.mjs +1 -0
- package/lib/components/{acp/acp-prompt-input.d.ts → session/prompt-input.d.ts} +1 -1
- package/lib/components/session-replay.d.mts +8 -7
- package/lib/components/session-replay.mjs +1 -1
- package/lib/effect-runtime/concurrency.d.mts +2 -4
- package/lib/effect-runtime/concurrency.mjs +1 -1
- package/lib/effect-runtime/mcp-lifecycle.mjs +1 -1
- package/lib/effect-runtime/process-runtime-context.d.ts +5 -1
- package/lib/harness/create-harness.js +1 -1
- package/lib/integration/agent-integration.d.ts +5 -0
- package/lib/protocol/acp-v2-credits.d.ts +10 -0
- package/lib/protocol/acp-v2-credits.js +1 -0
- package/lib/protocol/acp-v2-private-client.d.ts +1 -10
- package/lib/runtime/codebuddy-auth.d.ts +5 -3
- package/lib/runtime/codebuddy-auth.js +1 -1
- package/lib/runtime/private-runtime-role.js +1 -1
- package/lib/session/agent-backend.d.ts +3 -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/replay.d.ts +3 -3
- 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/lib/subagent/history.js +1 -1
- package/package.json +26 -20
- 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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AnyWireMessage, Stream
|
|
1
|
+
import type { AnyWireMessage, Stream } from '@agentclientprotocol/sdk/experimental/v2' with { 'resolution-mode': 'import' };
|
|
2
2
|
import { AGENT_HARNESS_PRIVATE_COMPACT_METHOD } from '../session/compact.js';
|
|
3
3
|
import type { AcpV2SdkModule } from './acp-v2.js';
|
|
4
4
|
export declare const AGENT_HARNESS_PRIVATE_AUTH_METHODS: Readonly<{
|
|
@@ -10,15 +10,6 @@ export interface ProtocolNeutralJsonRpcStream {
|
|
|
10
10
|
readonly readable: ReadableStream<unknown>;
|
|
11
11
|
readonly writable: WritableStream<unknown>;
|
|
12
12
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Keep CodeBuddy's private Credit unit intact across the official SDK's
|
|
15
|
-
* lenient v2 parser. The SDK accepts only three uppercase currency characters
|
|
16
|
-
* and otherwise silently drops `cost`, so the private transport substitutes a
|
|
17
|
-
* valid placeholder plus a reserved marker before the SDK sees the message.
|
|
18
|
-
*/
|
|
19
|
-
export declare function normalizePrivateAcpV2WireMessageForSdk(message: AnyWireMessage): AnyWireMessage;
|
|
20
|
-
/** Restore the product Credit unit and remove the private transport marker. */
|
|
21
|
-
export declare function restoreCodeBuddyCreditsFromSdk(notification: UpdateSessionNotification): UpdateSessionNotification;
|
|
22
13
|
/**
|
|
23
14
|
* Exact ACP v2 registry used between Agent Harness and its private CodeBuddy
|
|
24
15
|
* child. Keeping this object narrower than the SDK-wide method unions prevents
|
|
@@ -220,7 +220,9 @@ export declare class CodeBuddyAuthRuntime implements AuthProtocolBackend {
|
|
|
220
220
|
* tail makes either the old pair or the new pair observable, never the
|
|
221
221
|
* private midpoint.
|
|
222
222
|
*/
|
|
223
|
-
runConsistentRead<Value>(operation: () => Value | PromiseLike<Value
|
|
223
|
+
runConsistentRead<Value>(operation: () => Value | PromiseLike<Value>, options?: {
|
|
224
|
+
readonly signal?: AbortSignal;
|
|
225
|
+
}): Promise<Value>;
|
|
224
226
|
listAuthMethods(_params: AgentHarnessInitializeParams, _context: AgentHarnessHandlerContext): Promise<readonly AcpV2AuthMethod[]>;
|
|
225
227
|
login(params: AcpV2LoginAuthRequest, context: AgentHarnessHandlerContext): Promise<AcpV2LoginAuthResponse>;
|
|
226
228
|
logout(_params: AcpV2LogoutAuthRequest, context: AgentHarnessHandlerContext): Promise<AcpV2LogoutAuthResponse>;
|
|
@@ -238,8 +240,8 @@ export declare class CodeBuddyAuthRuntime implements AuthProtocolBackend {
|
|
|
238
240
|
* Installs or clears one workspace execution Product for the current
|
|
239
241
|
* Account binding. The outer Auth protocol mutation gate keeps
|
|
240
242
|
* owner detach and public Account/Product replacement behind this
|
|
241
|
-
* operation
|
|
242
|
-
*
|
|
243
|
+
* operation. Preparation is cancellable; once started, the atomic commit
|
|
244
|
+
* finishes before releasing that gate, even if the carrier disconnects.
|
|
243
245
|
*/
|
|
244
246
|
provisionWorkspaceProduct(params: ProductWorkspaceProvisionParams, context: AgentHarnessHandlerContext): Promise<ProductWorkspaceProvisionResponse>;
|
|
245
247
|
detachExternalAccount(context: AgentHarnessHandlerContext, _reason: unknown): Promise<boolean>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var z=Object.defineProperty;var d=(s,t)=>z(s,"name",{value:t,configurable:!0});import{randomUUID as N}from"node:crypto";import"../auth/session.js";import{createManagedAuthPreparation as G}from"../effect-runtime/managed-auth-preparation.mjs";import{currentHarnessProcessRuntime as L}from"../effect-runtime/process-runtime-context.js";import{abortable as v,abortReason as M}from"../internal/async.js";import{isRecord as C}from"../internal/guards.js";import{ACP_V2_METHODS as b}from"../protocol/acp-v2.js";import{validateAcpV2CoreSchema as T}from"../protocol/acp-v2-schema.js";import{AGENT_HARNESS_ERROR_META_KEY as B}from"../protocol/error.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as p,AgentHarnessJsonRpcError as g}from"../server/errors.js";import{measure as P}from"../telemetry/runtime.js";import{accountBinding as S}from"./external-product-binding.js";const q=-32e3,V=200,H=5e3,j=3e4,J=10*6e4;class _ extends Error{static{d(this,"AuthenticationOperationSupersededError")}constructor(){super("Authentication operation was superseded")}}class O extends Error{static{d(this,"AuthenticationGenerationChangedError")}constructor(){super("Authentication generation changed during reconciliation")}}class A extends Error{static{d(this,"CodeBuddyAuthProductLifecycleError")}constructor(t){super(`Authentication Product ${t} failed`),this.name="CodeBuddyAuthProductLifecycleError"}}export class CodeBuddyAuthProductRefreshRequiredError extends Error{static{d(this,"CodeBuddyAuthProductRefreshRequiredError")}constructor(){super("Authentication Product refresh required"),this.name="CodeBuddyAuthProductRefreshRequiredError"}}export const CODEBUDDY_AUTH_PRODUCT_RESOLVE_ERROR_CODES=["PRODUCT_AUTH_INVALID","PRODUCT_REMOTE_RESPONSE_INVALID","PRODUCT_REMOTE_TIMEOUT","PRODUCT_REMOTE_UNAVAILABLE","PRODUCT_RESOLVE_TIMEOUT","PRODUCT_ROUTING_INVALID"];const W=new Set(CODEBUDDY_AUTH_PRODUCT_RESOLVE_ERROR_CODES);export function isCodeBuddyAuthProductResolveErrorCode(s){return W.has(s)}d(isCodeBuddyAuthProductResolveErrorCode,"isCodeBuddyAuthProductResolveErrorCode");export class CodeBuddyAuthProductResolveError extends Error{static{d(this,"CodeBuddyAuthProductResolveError")}constructor(t){super("Authentication Product resolution failed"),this.code=t,this.name="CodeBuddyAuthProductResolveError"}}const Y={PRODUCT_AUTH_INVALID:{code:"product_auth_invalid",message:"Product authentication context is invalid."},PRODUCT_REMOTE_RESPONSE_INVALID:{code:"product_remote_response_invalid",message:"Product configuration response is invalid."},PRODUCT_REMOTE_TIMEOUT:{code:"product_resolve_timeout",message:"Product configuration resolution timed out."},PRODUCT_REMOTE_UNAVAILABLE:{code:"product_remote_unavailable",message:"Product configuration is unavailable."},PRODUCT_RESOLVE_TIMEOUT:{code:"product_resolve_timeout",message:"Product configuration resolution timed out."},PRODUCT_ROUTING_INVALID:{code:"product_routing_invalid",message:"Product routing is invalid."}};function y(s){return{authMode:"none",generation:s,snapshot:{account:null,mode:null,state:"unauthenticated"}}}d(y,"unauthenticated");function D(s){return{id:s.id,...s.displayName===void 0?{}:{displayName:s.displayName},...s.avatarUrl===void 0?{}:{avatarUrl:s.avatarUrl},...s.enterpriseId===void 0?{}:{organization:{id:s.enterpriseId,...s.enterpriseName===void 0?{}:{displayName:s.enterpriseName}}},...s.department===void 0?{}:{department:s.department}}}d(D,"projectManagedAccount");function E(s){return{account:D(s.account),providerIdentity:{accountType:s.account.accountType,...s.account.idp===void 0?{}:{idp:s.account.idp},...s.account.oneidAccountId===void 0?{}:{oneidAccountId:s.account.oneidAccountId}},credential:s.credential}}d(E,"projectManagedCredential");function h(s){return new g(q,"Authentication required",s?{reason:s}:void 0)}d(h,"authRequired");function I(s){if(s instanceof CodeBuddyAuthProductRefreshRequiredError)return h("credential_rejected");if(!(s instanceof CodeBuddyAuthProductResolveError))return;const t=Y[s.code];return new g(p.notReady,t.message,{reason:t.code,[B]:t})}d(I,"projectPublicProductError");class x extends g{static{d(this,"CodeBuddyAuthProductPreconditionError")}}function X(s){return s instanceof _||s instanceof CodeBuddyAuthProductRefreshRequiredError||s instanceof CodeBuddyAuthProductResolveError||s instanceof x}d(X,"canRetryExternalInitialization");export function productProvisionError(s,t,e={}){return new x(p.invalidRequest,t,{...e,reason:s})}d(productProvisionError,"productProvisionError");function U(s,t){const e=new AbortController,i=Promise.withResolvers(),n=s.createPolicyDeadline(t,{signals:[e.signal],timeoutReason:new Error("Product provision timed out")});return{controller:e,completed:i.promise,complete:d(()=>{n.close(),i.resolve()},"complete"),signal:n.signal}}d(U,"createPendingProductProvision");const l="Authentication operation aborted";function $(s){const t=s.client?.capabilities?.agent;return!C(t)||!C(t.elicitation)?!1:C(t.elicitation.url)}d($,"supportsUrlElicitation");function F(s,t){return JSON.stringify(s)===JSON.stringify(t)}d(F,"sameIdentity");function R(s,t,e,i,n,a){return s?.id===i.id&&(s.authMethodId??null)===(i.authMethodId??null)&&(s.organization?.id??null)===(i.organization?.id??null)&&(s.department??null)===(i.department??null)&&(t?.accountType??null)===(n?.accountType??null)&&(t?.oneidAccountId??null)===(n?.oneidAccountId??null)&&(t?.idp??null)===(n?.idp??null)&&e?.type===a.type&&(e.domain??null)===(a.domain??null)}d(R,"sameCredentialContext");export class CodeBuddyAuthRuntime{static{d(this,"CodeBuddyAuthRuntime")}constructor(t,e=L()){if(this.initializationController=new AbortController,this.managedActivationEpoch=0,this.connectionAuthProfiles=new WeakMap,this.connectionProductProfiles=new WeakMap,this.activeProductMode="managed",this.managedDiscoveryLastApplied=0,this.managedDiscoverySequence=0,this.authenticationEpoch=0,this.pendingManagedRestore=!1,this.closed=!1,this.processRuntime=e,this.mutationGate=e.createSerialGate("Authentication mutation"),this.refreshFlights=e.createSingleFlight("Authentication refresh"),this.stateCell=e.createStateCell(y(0)),this.managedPreparation=G(e),this.consumer=t.consumer,this.getAuthMethods=t.getAuthMethods??(()=>[]),this.managedAuth=t.managedAuth,this.onRuntimePreparing=t.onRuntimePreparing,this.onRuntimePrepared=t.onRuntimePrepared,this.productLifecycle=t.productLifecycle,this.productLifecycle&&(this.accountUpdatePublication="backend"),this.loginCleanupTimeoutMs=t.loginCleanupTimeoutMs??H,this.loginPollIntervalMs=t.loginPollIntervalMs??V,this.refreshTimeoutMs=t.refreshTimeoutMs??j,this.productProvisionTimeoutMs=t.productProvisionTimeoutMs??J,!Number.isSafeInteger(this.loginCleanupTimeoutMs)||this.loginCleanupTimeoutMs<=0||!Number.isSafeInteger(this.loginPollIntervalMs)||this.loginPollIntervalMs<=0||!Number.isSafeInteger(this.refreshTimeoutMs)||this.refreshTimeoutMs<=0||!Number.isSafeInteger(this.productProvisionTimeoutMs)||this.productProvisionTimeoutMs<=0)throw new RangeError("Authentication timeouts must be positive integers");this.releaseProcessOwnership=e.addFinalizer(()=>this.close(new Error("Agent Harness process runtime is closing")))}get state(){return this.stateCell.current}setState(t){return this.stateCell.set(t)}clearPendingManagedRestore(){this.pendingManagedRestore=!1,this.pendingManagedAccount=void 0}bindProtocolBridge(t){if(this.bridge&&this.bridge!==t)throw new Error("Authentication protocol bridge is already bound");this.bridge=t}selectConnectionProductProfile(t,e){const i=this.connectionProductProfiles.get(e.connectionSignal);if(i&&(i.mode!==t.mode||i.workspace!==t.workspace))throw new g(p.invalidRequest,"Product management profile cannot change on an initialized connection");this.connectionProductProfiles.set(e.connectionSignal,Object.freeze({...t})),this.state.authMode==="none"&&(this.activeProductMode=t.mode)}productModeFor(t){return(t===void 0?void 0:this.connectionProductProfiles.get(t)?.mode)??this.activeProductMode}activateProductMode(t){const e=this.productModeFor(t);return this.activeProductMode=e,e}startManagedDiscovery(){return this.closed?Promise.reject(new Error("Authentication runtime is closed")):this.state.authMode!=="none"?Promise.resolve():this.getOrStartManagedDiscovery().promise.then(()=>{})}selectConnectionAuthProfile(t,e){const i=this.connectionProductProfiles.get(e.connectionSignal);this.connectionAuthProfiles.set(e.connectionSignal,t),this.activeProductMode=i?.mode??this.activeProductMode,t.mode!=="external"&&this.startManagedDiscovery().catch(()=>{})}markConnectionInitialized(t){if(t.mode!=="external"){try{this.onRuntimePreparing?.()}catch{}this.startManagedPreparation().then(()=>{!this.closed&&this.state.authMode==="none"&&this.notifyRuntimePrepared()},()=>{})}}notifyRuntimePrepared(){if(this.productLifecycle?.isProductReady?.(this.activeProductMode)!==!1)try{this.onRuntimePrepared?.()}catch{}}async notifyCurrentAccountUpdated(){const t=this.bridge;if(t){if(this.state.authMode==="external"&&this.state.externalOwner){await t.notifyAccountUpdated(this.state.snapshot,{sourceOwner:this.state.externalOwner});return}await t.notifyAccountUpdated(this.state.snapshot)}}close(t){return this.closePromise??=this.closeInternal(t),this.closePromise}async closeInternal(t){if(this.closed)return;const e=t??new Error("Authentication runtime is closed");this.closed=!0,this.initializationController.abort(e),this.authenticationEpoch+=1,this.authenticationOperationController?.abort(e),this.authenticationOperationController=void 0,this.pendingManagedLoginId=void 0,this.abortReconciliation(e),this.abortRefreshFlights(e),this.pendingProductProvision?.controller.abort(e),await this.managedPreparation.close(e).catch(()=>{}),await this.refreshFlights.close(e),await this.pendingProductProvision?.completed;try{await this.withPolicyDeadline(this.loginCleanupTimeoutMs,[],i=>this.runMutation(async()=>{const n=this.nextGeneration();await this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"shutdown_cleanup",signal:i,commitCredential:d(async()=>{this.clearPendingManagedRestore(),await this.setState(y(n)),await this.consumer.clearAuthentication({generation:n})},"commitCredential")})},{allowClosed:!0})).catch(()=>{})}finally{await this.mutationGate.close(e)}this.releaseProcessOwnership()}async readAccount(t,e){const i=await this.runConsistentRead(()=>this.state.authMode==="none"?void 0:structuredClone(this.state.snapshot));if(i!==void 0)return i;const n=this.initialization;return n&&!this.pendingManagedRestore?(await v(n,e.signal,l),this.runConsistentRead(()=>structuredClone(this.state.snapshot))):this.connectionAuthProfiles.get(e.connectionSignal)?.mode==="external"?this.runConsistentRead(()=>structuredClone(this.state.snapshot)):this.reconciliation!==void 0?this.runConsistentRead(()=>structuredClone(this.state.snapshot)):(await this.awaitManagedDiscovery(e.signal),this.runConsistentRead(()=>this.state.authMode!=="none"?structuredClone(this.state.snapshot):this.pendingManagedRestore&&this.pendingManagedAccount?{account:structuredClone(this.pendingManagedAccount),mode:"managed",state:"authenticated"}:structuredClone(this.state.snapshot)))}async prepareAuthStatus(t,e){this.connectionAuthProfiles.get(e.connectionSignal)?.mode!=="external"&&this.reconciliation===void 0&&await this.awaitManagedDiscovery(e.signal)}async readAuthStatus(t,e){return this.runConsistentRead(()=>({authenticated:this.state.authMode!=="none"||this.pendingManagedRestore&&this.reconciliation===void 0&&this.connectionAuthProfiles.get(e.connectionSignal)?.mode!=="external"}))}async readProduct(t,e){return this.runConsistentRead(()=>{const i=this.productLifecycle;if(!i)throw new g(p.notReady,"Product lifecycle is unavailable");const n=i.readProduct;if(!n)throw new g(p.notReady,"Product projection is unavailable");return n.call(i,this.productModeFor(e.connectionSignal))})}async prepareHostExecution(t){await this.awaitManagedDiscovery(t),await this.runConsistentRead(()=>this.state.authMode==="none"&&this.pendingManagedRestore)&&await this.ensurePublicInitialized(t)}currentSessionAuthentication(){const t=this.state;if(!(t.snapshot.state!=="authenticated"||!t.credential))return structuredClone({generation:t.generation,account:t.snapshot.account,credential:t.credential,providerIdentity:t.providerIdentity})}async refreshHostAuthentication(t,e){const i=d(()=>this.runConsistentRead(()=>{const a=this.currentSessionAuthentication();if(!a||!R(t.account,t.providerIdentity,t.credential,a.account,a.providerIdentity,a.credential))throw h("account_changed");return a}),"capture"),n=await i();if(n.generation!==t.generation)return n;try{return await this.refreshAuthentication({accountId:t.account.id,generation:t.generation},{signal:e})}catch(a){e.throwIfAborted();const o=await i();if(o.generation>t.generation&&o.credential.accessToken!==t.credential.accessToken)return o;throw a}}async prepareSessionRuntime(t,e){if((e===void 0?void 0:this.connectionAuthProfiles.get(e)?.mode)==="external"&&this.state.authMode==="none")throw h("account_provision_required");await this.ensurePublicInitialized(t),this.productLifecycle?.assertProductReady?.(this.productModeFor(e))}async refreshProductAuthentication(t){await this.ensureInitialized(t);const e=this.state;if(e.authMode==="none"||e.snapshot.state!=="authenticated")throw h();await this.refreshAuthentication({accountId:e.snapshot.account.id,generation:e.generation},{signal:t})}async runConsistentRead(t){for(;;){const e=this.pendingProductProvision;if(e){await e.completed;continue}const i=await this.runMutation(async()=>this.pendingProductProvision?{retry:!0}:{retry:!1,value:await t()});if(!i.retry)return i.value}}async listAuthMethods(t,e){return structuredClone(this.getAuthMethods())}async login(t,e){this.activateProductMode(e.connectionSignal);const{pendingLoginId:i,token:n}=this.beginExplicitAuthenticationOperation(new Error("Authentication login superseded prior reconciliation"));await this.ensurePublicInitialized(e.signal),this.assertCurrentAuthenticationOperation(n),i&&await this.cancelSupersededManagedLogin(n,i);const a=N();this.pendingManagedLoginId=a;let o,r;try{if(o=await this.managedAuth.startManagedAuthLogin(t.methodId,{loginId:a,signal:e.signal}),this.assertCurrentAuthenticationOperation(n),this.pendingManagedLoginId=o.loginId,r=await this.awaitManagedLogin(o,e),r.state!=="succeeded")throw h(r.state);return await this.reconcileManagedLoginForRequest(n),{}}catch(c){if(!this.isCurrentAuthenticationOperation(n))throw c;if(r?.state==="succeeded")throw this.startManagedLoginReconciliation(n),c;if(!r||r.state==="pending"||!r.settled){const u=o?.loginId??a,f=await this.withAuthenticationDeadline(n,this.loginCleanupTimeoutMs,m=>Promise.resolve(this.managedAuth.readManagedAuthLogin(u,{signal:m}))).catch(()=>{});if(!this.isCurrentAuthenticationOperation(n))throw c;if(f?.state==="succeeded")return await this.reconcileManagedLoginForRequest(n),{};if(await this.cancelManagedLogin(u),!this.isCurrentAuthenticationOperation(n))throw c;const w=await this.withAuthenticationDeadline(n,this.loginCleanupTimeoutMs,m=>this.awaitManagedLoginSettlement(u,f,m)).catch(()=>{});if(!this.isCurrentAuthenticationOperation(n))throw c;if(w?.state==="succeeded")return await this.reconcileManagedLoginForRequest(n),{};this.pendingManagedLoginId=w?.settled===!0?void 0:u,this.pendingManagedLoginId&&this.startPendingManagedLoginReconciliation(n,this.pendingManagedLoginId)}else this.pendingManagedLoginId=void 0;throw c}}async logout(t,e){this.activateProductMode(e.connectionSignal);const i=this.reconciliation,{pendingLoginId:n,token:a}=this.beginExplicitAuthenticationOperation(new Error("Authentication logout superseded prior reconciliation")),o=n??i?.loginId,r=o===void 0?void 0:await this.cancelManagedLogin(o);let c=this.state.authMode==="managed"||o!==void 0||i?.kind==="managed_login"||i?.kind==="managed_logout"||i?.kind==="pending_login";if(c||(await this.ensurePublicInitialized(e.signal),c=this.state.authMode==="managed"),this.assertCurrentAuthenticationOperation(a),!c&&this.state.authMode==="external")return await this.fenceAuthenticationForOperation(a,new Error("External authentication was detached")),this.pendingManagedLoginId=void 0,{};if(!c&&this.state.authMode==="none")return{};let u;try{await this.withAuthenticationDeadline(a,this.loginCleanupTimeoutMs,w=>this.managedAuth.logoutManagedAuth({signal:w}))}catch(w){u=w}const f=o!==void 0&&r?.settled!==!0;if(u!==void 0||f)throw await this.fenceAuthenticationForOperation(a,new Error("Managed authentication logout is ambiguous")),this.startManagedLogoutReconciliation(a,o),this.productLifecycle||await this.notifyCurrentAccountUpdated().catch(()=>{}),u??h("managed_login_cancellation_ambiguous");return await this.fenceAuthenticationForOperation(a,new Error("Authentication was logged out")),this.pendingManagedLoginId=void 0,{}}async provisionAccount(t,e){this.activateProductMode(e.connectionSignal);const{pendingLoginId:i,token:n}=this.beginExplicitAuthenticationOperation(new Error("External authentication superseded prior reconciliation"));if(t.state==="authenticated"&&this.initialization===void 0){this.managedActivationEpoch+=1,this.clearPendingManagedRestore();const a=(async()=>(await this.managedPreparation.join(),this.assertCurrentAuthenticationOperation(n),this.commitExternalAccount(t,e,n,i)))(),o=a.then(()=>{},r=>{throw this.initialization===o&&X(r)&&(this.initialization=void 0),r});return this.initialization=o,o.catch(()=>{}),a.catch(r=>{throw I(r)??r})}if(await this.ensurePublicInitialized(e.signal),this.assertCurrentAuthenticationOperation(n),i&&await this.cancelSupersededManagedLogin(n,i),t.state==="unauthenticated"){if(this.state.authMode==="managed")throw new g(p.invalidRequest,"account/provision cannot detach managed authentication");return await this.runMutation(async()=>{this.assertCurrentAuthenticationOperation(n);const a=this.nextGeneration();this.abortRefreshFlights(new Error("External authentication was detached")),await this.withAuthenticationDeadline(n,this.loginCleanupTimeoutMs,o=>this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"explicit_auth_mutation",signal:o,commitCredential:d(async()=>{if(this.productLifecycle){this.clearPendingManagedRestore(),await this.setState(y(a)),await this.consumer.clearAuthentication({generation:a});return}await this.consumer.clearAuthentication({generation:a}),this.clearPendingManagedRestore(),await this.setState(y(a))},"commitCredential")}))}),structuredClone(this.state.snapshot)}try{return await this.commitExternalAccount(t,e,n)}catch(a){throw I(a)??a}}async commitExternalAccount(t,e,i,n){return this.assertCurrentAuthenticationOperation(i),n&&await this.cancelSupersededManagedLogin(i,n),await this.runMutation(async()=>{this.assertCurrentAuthenticationOperation(i);const a=this.nextGeneration(),o=this.state.authMode!=="none"&&(this.state.authMode!=="external"||this.state.snapshot.state!=="authenticated"||this.state.snapshot.account.id!==t.account.id||!R(this.state.snapshot.account,this.state.providerIdentity,this.state.credential,t.account,void 0,t.credential));this.abortRefreshFlights(new Error("Authentication state was replaced"));const r={account:t.account,credential:t.credential,generation:a};await this.withAuthenticationDeadline(i,this.refreshTimeoutMs,c=>this.executeProductTransition({authentication:r,credentialOrder:"after_product",mode:"external",origin:"explicit_auth_mutation",signal:c,commitCredential:d(async()=>{await this.consumer.setAuthentication(r,{fenceExisting:o}),this.clearPendingManagedRestore(),await this.setState({authMode:"external",credential:structuredClone(t.credential),externalOwner:e.connectionSignal,generation:a,snapshot:{account:structuredClone(t.account),mode:"external",state:"authenticated"}})},"commitCredential")}))}),this.notifyRuntimePrepared(),structuredClone(this.state.snapshot)}async provisionProduct(t,e){await this.ensurePublicInitialized(e.signal);const i=this.productLifecycle,n=i?.provisionExternal,a=i?.reserveExternalProvision;if(!n||!a)throw new g(p.notReady,"External Product provisioning is unavailable");if(this.connectionProductProfiles.get(e.connectionSignal)?.mode!=="external")throw new g(p.invalidRequest,"product/provision requires external Product management");const o=U(this.processRuntime,this.productProvisionTimeoutMs);let r,c;await this.runMutation(async()=>{if(this.pendingProductProvision)throw new g(p.notReady,"Product provisioning is already in progress");const u=this.state;if(u.snapshot.state!=="authenticated"||e.connectionSignal.aborted)throw h();r=S(u.snapshot.account,u.credential?.domain),c=a.call(i,r),this.pendingProductProvision=o});try{return await n.call(i,t,{binding:r,reservation:c,signal:o.signal})}finally{await this.runMutation(async()=>{if(this.pendingProductProvision===o){this.pendingProductProvision=void 0;try{c?.release()}finally{o.complete()}}},{allowClosed:!0})}}async provisionWorkspaceProduct(t,e){await this.ensurePublicInitialized(e.signal);const i=this.productLifecycle,n=i?.provisionWorkspace;if(!n)throw new g(p.notReady,"Workspace Product provisioning is unavailable");const a=U(this.processRuntime,this.productProvisionTimeoutMs);let o,r;await this.runMutation(async()=>{if(this.pendingProductProvision)throw new g(p.notReady,"Product provisioning is already in progress");const c=this.state;if(c.snapshot.state!=="authenticated"||e.connectionSignal.aborted)throw h();r=this.productModeFor(e.connectionSignal),i.assertProductReady?.(r),o=S(c.snapshot.account,c.credential?.domain),this.pendingProductProvision=a});try{return await n.call(i,t,{binding:o,mode:r,signal:a.signal})}finally{await this.runMutation(async()=>{this.pendingProductProvision===a&&(this.pendingProductProvision=void 0,a.complete())},{allowClosed:!0})}}async detachExternalAccount(t,e){if(this.activateProductMode(t.connectionSignal),await this.withPolicyDeadline(this.loginCleanupTimeoutMs,[],o=>this.ensureInitialized(o)),this.state.authMode!=="external"||this.state.externalOwner!==t.connectionSignal)return!1;const{pendingLoginId:i,token:n}=this.beginExplicitAuthenticationOperation(new Error("External authentication detach superseded prior reconciliation"));let a=!1;if(i)try{await this.cancelSupersededManagedLogin(n,i)}catch{a=!0}return this.runMutation(async()=>{if(this.assertCurrentAuthenticationOperation(n),this.state.authMode!=="external"||this.state.externalOwner!==t.connectionSignal)return a&&this.state.authMode==="none";const o=this.nextGeneration();return this.abortRefreshFlights(new Error("External authentication owner detached")),await this.withAuthenticationDeadline(n,this.loginCleanupTimeoutMs,r=>this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"explicit_auth_mutation",signal:r,commitCredential:d(async()=>{this.clearPendingManagedRestore(),await this.setState(y(o)),await this.consumer.clearAuthentication({generation:o})},"commitCredential")})),!0})}async refreshAuthentication(t,e){await this.ensureInitialized(e.signal);const i=JSON.stringify([this.state.authMode,t.accountId,t.generation]),n=this.state;if(n.authMode==="none"||n.generation!==t.generation||n.snapshot.state!=="authenticated"||n.snapshot.account.id!==t.accountId)throw h();return this.refreshFlights.run(i,a=>this.performAuthenticationRefresh(n,t,AbortSignal.any([a,...n.authMode==="external"&&n.externalOwner?[n.externalOwner]:[]])),{abortMessage:l,signal:e.signal,timeoutMs:this.refreshTimeoutMs})}async performAuthenticationRefresh(t,e,i){const n=t.authMode;if(n==="none")throw h();const a=n==="managed"?E(await this.managedAuth.refreshManagedAuthCredential(e.accountId,{signal:i})):await this.refreshExternal(e,i,t.externalOwner);if(i.aborted)throw n==="external"&&t.externalOwner?.aborted?h("owner_disconnected"):M(i,l);if(a.account.id!==e.accountId||!R(t.snapshot.account,t.providerIdentity,t.credential,a.account,a.providerIdentity,a.credential))throw h("account_changed");if(n==="external"&&a.credential.accessToken===t.credential?.accessToken)throw h("credential_unchanged");let o,r=!1;return await this.runMutation(async()=>{if(i.aborted)throw M(i,l);if(this.state.authMode!==t.authMode||this.state.generation!==t.generation||this.state.snapshot.state!=="authenticated"||this.state.snapshot.account.id!==e.accountId||n==="external"&&(t.externalOwner?.aborted!==!1||this.state.externalOwner!==t.externalOwner))throw h("stale_generation");const c=this.nextGeneration(),u=this.state.snapshot.account;o={account:structuredClone(a.account),...a.providerIdentity===void 0?{}:{providerIdentity:structuredClone(a.providerIdentity)},credential:structuredClone(a.credential),generation:c},await this.executeProductTransition({authentication:o,credentialOrder:"after_product",mode:n,origin:"child_refresh",signal:i,commitCredential:d(async()=>{await this.consumer.setAuthentication(o),r=!F(u,a.account),await this.setState({...this.state,...a.providerIdentity===void 0?{}:{providerIdentity:structuredClone(a.providerIdentity)},credential:structuredClone(a.credential),generation:c,snapshot:{account:structuredClone(a.account),mode:n,state:"authenticated"}})},"commitCredential")})}),!this.productLifecycle&&r&&await this.notifyCurrentAccountUpdated(),o}async ensurePublicInitialized(t){try{await this.ensureInitialized(t)}catch(e){throw I(e)??e}}getOrStartManagedDiscovery(){const t=this.managedActivationEpoch,e=this.authenticationEpoch,i=this.managedDiscovery;if(i&&i.activationEpoch===t&&i.authenticationEpoch===e)return i;const n=++this.managedDiscoverySequence,o=this.discoverManagedAuthentication({activationEpoch:t,authenticationEpoch:e,sequence:n}).then(c=>(this.managedDiscovery?.promise===o&&!c.applied&&(this.managedDiscovery=void 0),c),c=>{throw this.managedDiscovery?.promise===o&&(this.managedDiscovery=void 0),c});o.catch(()=>{});const r={activationEpoch:t,authenticationEpoch:e,promise:o};return this.managedDiscovery=r,r}async discoverManagedAuthentication(t){const e=await this.managedAuth.readManagedAuth({signal:this.initializationController.signal});let i=!1;return await this.runMutation(async()=>{if(this.closed||t.activationEpoch!==this.managedActivationEpoch||t.authenticationEpoch!==this.authenticationEpoch||this.initialization!==void 0||this.state.authMode!=="none"||t.sequence<this.managedDiscoveryLastApplied)return;this.managedDiscoveryLastApplied=t.sequence;const n=e.account;this.pendingManagedRestore=e.authenticated&&n!==null;const a=this.pendingManagedRestore&&n?D(n):void 0;this.pendingManagedAccount=a,i=!0}),{...t,applied:i,snapshot:e}}async awaitManagedDiscovery(t){for(;;){if(this.closed)throw new Error("Authentication runtime is closed");if(t.aborted)throw M(t,l);if(this.state.authMode!=="none"||this.initialization!==void 0)return;const e=this.getOrStartManagedDiscovery();let i;try{i=await P("managedAuthDiscoveryWait",()=>v(e.promise,t,l))}catch(n){if(this.state.authMode!=="none"||this.initialization!==void 0||e.activationEpoch!==this.managedActivationEpoch||e.authenticationEpoch!==this.authenticationEpoch)return;throw n}if(i.applied&&i.activationEpoch===this.managedActivationEpoch&&i.authenticationEpoch===this.authenticationEpoch&&this.state.authMode==="none"&&this.initialization===void 0)return i.snapshot}}async ensureInitialized(t){for(;;){if(this.closed)throw new Error("Authentication runtime is closed");if(t.aborted)throw M(t,l);if(this.initialization){await v(this.initialization,t,l);return}if(this.state.authMode!=="none")return;try{await this.managedPreparation.run((e,i)=>this.initializeManagedRuntime(e,i),{signal:t})}catch(e){if(this.initialization!==void 0)continue;throw e}}}startManagedPreparation(){return this.closed?Promise.reject(new Error("Authentication runtime is closed")):this.initialization!==void 0||this.state.authMode!=="none"?Promise.resolve():this.managedPreparation.run((t,e)=>this.initializeManagedRuntime(t,e))}async initializeManagedRuntime(t,e){for(;;){if(this.closed)throw new Error("Authentication runtime is closed");if(t.aborted)throw M(t,l);if(this.initialization!==void 0||this.state.authMode!=="none")return;const i=await this.awaitManagedDiscovery(t);if(e.phaseCompleted("discovery_ready"),this.initialization!==void 0||this.state.authMode!=="none")return;if(i){if(!i.authenticated||!i.account){this.initialization??=Promise.resolve();return}this.managedActivationEpoch+=1,this.managedDiscovery=void 0,await this.initializeFromManaged(i.account,t,e),this.initialization??=Promise.resolve();return}}}async initializeFromManaged(t,e,i){let n=await P("managedCredentialRead",()=>this.managedAuth.readManagedAuthCredential({signal:e}));if(i.phaseCompleted("credential_ready"),n.account.id!==t.id)throw new Error("Managed authentication projection changed identity");try{await P("productReconcile",()=>this.commitManaged(n,void 0,e))}catch(a){if(!(a instanceof CodeBuddyAuthProductRefreshRequiredError))throw a;const o=await P("managedCredentialRefresh",()=>this.managedAuth.refreshManagedAuthCredential(t.id,{signal:e}));i.phaseCompleted("credential_refreshed");const r=E(n),c=E(o);if(!R(r.account,r.providerIdentity,r.credential,c.account,c.providerIdentity,c.credential))throw h("account_changed");n=o,await P("productReconcile",()=>this.commitManaged(n,void 0,e))}i.phaseCompleted("product_ready")}async reconcileManagedLoginForRequest(t){try{await this.reconcileSucceededManagedLogin(t)}catch(e){throw this.isCurrentAuthenticationOperation(t)&&this.startManagedLoginReconciliation(t),e}}async reconcileSucceededManagedLogin(t,e){await this.fencePreviousAuthenticationForManagedLogin(t),this.assertCurrentAuthenticationOperation(t);const i=this.state.generation;await this.withPolicyDeadline(this.loginCleanupTimeoutMs,[t.signal,...e===void 0?[]:[e]],async n=>{const[a,o]=await Promise.all([this.managedAuth.readManagedAuth({signal:n}),this.managedAuth.readManagedAuthCredential({signal:n})]);if(!a.authenticated||!a.account||a.account.id!==o.account.id)throw h("managed_projection_unavailable");if(n.aborted)throw M(n,l);await this.commitManaged(o,{expectedGeneration:i,signal:n,token:t})}),this.assertCurrentAuthenticationOperation(t),this.pendingManagedLoginId=void 0}fencePreviousAuthenticationForManagedLogin(t){return this.fenceAuthenticationForOperation(t,new Error("Managed login replaced the authentication state"))}async commitManaged(t,e,i){if(i===void 0)return this.withPolicyDeadline(this.refreshTimeoutMs,e?.signal===void 0?[]:[e.signal],o=>this.commitManaged(t,e,o));const n=E(t),a=await this.runMutation(async()=>{if(e){if(this.assertCurrentAuthenticationOperation(e.token),e.signal?.aborted)throw M(e.signal,l);if(this.state.generation!==e.expectedGeneration)throw new O}const o=this.state.authMode!=="managed"||this.state.snapshot.state!=="authenticated"||!F(this.state.snapshot.account,n.account),r=this.nextGeneration(),c=this.state.authMode!=="none"&&(this.state.authMode!=="managed"||this.state.snapshot.state!=="authenticated"||this.state.snapshot.account.id!==n.account.id||!R(this.state.snapshot.account,this.state.providerIdentity,this.state.credential,n.account,n.providerIdentity,n.credential));this.abortRefreshFlights(new Error("Managed authentication state was replaced"));const u={...n,generation:r};return await this.executeProductTransition({authentication:u,credentialOrder:"after_product",mode:"managed",origin:e?"explicit_auth_mutation":"lazy_activation",signal:i,commitCredential:d(async()=>{await this.consumer.setAuthentication(u,{fenceExisting:c}),this.clearPendingManagedRestore(),await this.setState({authMode:"managed",providerIdentity:structuredClone(n.providerIdentity),credential:structuredClone(n.credential),generation:r,snapshot:{account:structuredClone(n.account),mode:"managed",state:"authenticated"}})},"commitCredential")}),o});return this.notifyRuntimePrepared(),a}startPendingManagedLoginReconciliation(t,e){this.startReconciliation("pending_login",t,async i=>{for(;this.canContinueReconciliation(t,i);){let n;try{n=await this.withBackgroundDeadline(t,i,a=>this.managedAuth.readManagedAuthLogin(e,{signal:a}))}catch{}if(!this.canContinueReconciliation(t,i))return;if(n?.state==="succeeded"){await this.runManagedLoginReconciliation(t,i);return}if(n?.settled){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}await this.waitForDelay(this.loginPollIntervalMs,i)}},e)}startManagedLoginReconciliation(t){this.startReconciliation("managed_login",t,e=>this.runManagedLoginReconciliation(t,e))}async runManagedLoginReconciliation(t,e){for(;this.canContinueReconciliation(t,e);){try{if(await this.reconcileSucceededManagedLogin(t,e),!this.canContinueReconciliation(t,e))return;this.productLifecycle||await this.notifyCurrentAccountUpdated().catch(()=>{});return}catch(i){if(this.shouldStopReconciliation(i,t,e))return}await this.waitForDelay(this.loginPollIntervalMs,e)}}startManagedLogoutReconciliation(t,e,i=!0){this.startReconciliation("managed_logout",t,async n=>{let a=!1;for(;this.canContinueReconciliation(t,n);){let o=e===void 0;if(e!==void 0){const c=await this.withBackgroundDeadline(t,n,u=>this.managedAuth.readManagedAuthLogin(e,{signal:u})).catch(()=>{});if(!this.canContinueReconciliation(t,n))return;if(a||=c?.state==="succeeded",o=a||c?.settled===!0,c?.state==="pending"&&await this.withBackgroundDeadline(t,n,u=>this.managedAuth.cancelManagedAuthLogin(e,{signal:u})).catch(()=>{}),!a&&c?.settled===!0&&c?.state!=="succeeded"&&!i){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}}if(!i&&a&&await this.fenceManagedAuthenticationForOperation(t,new Error("Superseded managed login committed durably")),!i&&!o){await this.waitForDelay(this.loginPollIntervalMs,n);continue}const r=await this.withBackgroundDeadline(t,n,c=>this.managedAuth.readManagedAuth({signal:c})).catch(()=>{});if(!this.canContinueReconciliation(t,n))return;if(r&&!r.authenticated&&o){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}r?.authenticated&&await this.withBackgroundDeadline(t,n,c=>this.managedAuth.logoutManagedAuth({signal:c})).catch(()=>{}),await this.waitForDelay(this.loginPollIntervalMs,n)}},e,i)}startReconciliation(t,e,i,n,a){if(!this.isCurrentAuthenticationOperation(e))return;const o=this.reconciliation;if(o&&o.epoch===e.epoch&&o.kind===t&&o.loginId===n&&o.logoutCurrentManaged===a)return;this.abortReconciliation(new Error("Authentication reconciliation was replaced"));const r=new AbortController,c=AbortSignal.any([e.signal,r.signal]),u=i(c).catch(()=>{}).finally(()=>{this.reconciliation?.controller===r&&(this.reconciliation=void 0)}),f={controller:r,epoch:e.epoch,kind:t,...n===void 0?{}:{loginId:n},...a===void 0?{}:{logoutCurrentManaged:a},promise:u};this.reconciliation=f}async awaitManagedLogin(t,e){const i=new AbortController,n=AbortSignal.any([e.signal,e.connectionSignal,i.signal]);let a,o,r,c=t;try{for(;c.state==="pending";){if(e.signal.aborted||e.connectionSignal.aborted)throw M(e.signal.aborted?e.signal:e.connectionSignal,l);if("error"in(o??{}))throw o.error;if(o&&"action"in o&&o.action!=="accept")throw h(o.action);if(c.authUrl&&!r){if(!$(e))throw h("url_elicitation_unsupported");if(e.requestId===void 0||e.requestId===null)throw new Error("Authentication request has no JSON-RPC request id");a=c.loginId;const f={elicitationId:a,message:"Complete sign-in in your browser.",mode:"url",requestId:e.requestId,url:c.authUrl},w=T("CreateElicitationRequest",f);if(w)throw new Error(`Invalid authentication elicitation: ${w.message}`);r=e.request(b.client.elicitation.create,f,{signal:n,timeoutMs:null}).then(m=>{if(T("CreateElicitationResponse",m)||!C(m))throw new Error("Client returned an invalid elicitation response");o={action:m.action}}).catch(m=>{i.signal.aborted||(o={error:m})})}const u=Date.parse(c.expiresAt);if(!Number.isFinite(u)||this.processRuntime.policyNow()>=u)throw h("timed_out");await this.waitForDelay(this.loginPollIntervalMs,e.signal),c=await this.managedAuth.readManagedAuthLogin(c.loginId,{signal:e.signal})}return c}finally{i.abort(new Error("Authentication elicitation completed")),await r?.catch(()=>{}),a&&await e.notify(b.client.elicitation.complete,{elicitationId:a}).catch(()=>{})}}async awaitManagedLoginSettlement(t,e,i){let n=e;for(;!n?.settled;){n&&await this.waitForDelay(this.loginPollIntervalMs,i);const a=await this.managedAuth.readManagedAuthLogin(t,{signal:i});if(!a)throw new Error("Host returned no authentication login state");n=a}return n}async cancelManagedLogin(t){return this.withPolicyDeadline(this.loginCleanupTimeoutMs,[],e=>Promise.resolve(this.managedAuth.cancelManagedAuthLogin(t,{signal:e}))).catch(()=>{})}async cancelSupersededManagedLogin(t,e){this.pendingManagedLoginId??=e;const i=await this.cancelManagedLogin(e);if(this.assertCurrentAuthenticationOperation(t),i?.settled&&i.state!=="succeeded"){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}if(i?.settled&&i.state==="succeeded")try{await this.fenceManagedAuthenticationForOperation(t,new Error("Superseded managed login committed durably")),await this.withAuthenticationDeadline(t,this.loginCleanupTimeoutMs,n=>this.managedAuth.logoutManagedAuth({signal:n})),this.assertCurrentAuthenticationOperation(t),this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}catch(n){throw this.isCurrentAuthenticationOperation(t)&&this.startManagedLogoutReconciliation(t,e,!1),n}throw this.startManagedLogoutReconciliation(t,e,!1),h("managed_login_cancellation_ambiguous")}async refreshExternal(t,e,i){if(!this.bridge||!i)throw h();let n;try{n=await this.bridge.requestAccountRefresh({accountId:t.accountId},{expectedOwner:i,signal:e})}catch(a){throw i.aborted?h("owner_disconnected"):a}return{account:n.account,credential:n.credential}}beginExplicitAuthenticationOperation(t){if(this.closed)throw new Error("Authentication runtime is closed");const e=this.pendingManagedLoginId;this.authenticationEpoch+=1,this.authenticationOperationController?.abort(t),this.abortReconciliation(t);const i=new AbortController;return this.authenticationOperationController=i,{...e===void 0?{}:{pendingLoginId:e},token:{epoch:this.authenticationEpoch,signal:i.signal}}}isCurrentAuthenticationOperation(t){return!this.closed&&t.epoch===this.authenticationEpoch&&this.authenticationOperationController?.signal===t.signal&&!t.signal.aborted}assertCurrentAuthenticationOperation(t){if(!this.isCurrentAuthenticationOperation(t))throw new _}withAuthenticationDeadline(t,e,i){return this.withPolicyDeadline(e,[t.signal],i)}withBackgroundDeadline(t,e,i){return this.withPolicyDeadline(this.loginCleanupTimeoutMs,[t.signal,e],i)}async fenceAuthenticationForOperation(t,e,i={}){for(;;){this.assertCurrentAuthenticationOperation(t);const n=this.state.generation;try{return await this.runMutation(async()=>{if(this.assertCurrentAuthenticationOperation(t),this.state.generation!==n)throw new O;if(this.state.authMode==="none"||i.authMode!==void 0&&this.state.authMode!==i.authMode)return!1;const a=this.nextGeneration();return this.abortRefreshFlights(e),await this.withAuthenticationDeadline(t,this.loginCleanupTimeoutMs,o=>this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"explicit_auth_mutation",signal:o,commitCredential:d(async()=>{this.clearPendingManagedRestore(),await this.setState(y(a)),await this.consumer.clearAuthentication({generation:a})},"commitCredential")})),!0})}catch(a){if(a instanceof O&&this.isCurrentAuthenticationOperation(t))continue;throw a}}}async fenceManagedAuthenticationForOperation(t,e){await this.fenceAuthenticationForOperation(t,e,{authMode:"managed"})&&!this.productLifecycle&&await this.notifyCurrentAccountUpdated().catch(()=>{})}canContinueReconciliation(t,e){return!e.aborted&&this.isCurrentAuthenticationOperation(t)}shouldStopReconciliation(t,e,i){return i.aborted||!this.isCurrentAuthenticationOperation(e)||t instanceof _}abortReconciliation(t){const e=this.reconciliation;e&&!e.controller.signal.aborted&&e.controller.abort(t)}nextGeneration(){if(this.state.generation>=Number.MAX_SAFE_INTEGER)throw new Error("Authentication generation exhausted");return this.state.generation+1}abortRefreshFlights(t){this.refreshFlights.abortAll(t)}async executeProductTransition(t){const e=this.productLifecycle;if(!e){await t.commitCredential();return}if(t.signal.aborted)throw M(t.signal,l);let i=!1,n=!1,a,o;try{o=await e.transition({...t.authentication===void 0?{}:{authentication:structuredClone(t.authentication)},credentialOrder:t.credentialOrder,mode:t.mode,origin:t.origin,productMode:t.productMode??this.activeProductMode,signal:t.signal,commitCredential:d(async()=>{if(i)throw new A("transition");i=!0;try{await t.commitCredential(),n=!0}catch(r){throw a=r,r}},"commitCredential")})}catch(r){if(a!==void 0)throw a;if(n)try{await this.notifyCurrentAccountUpdated()}catch(c){throw e.fail?.(c),new A("publication")}throw r instanceof CodeBuddyAuthProductRefreshRequiredError||!n&&r instanceof CodeBuddyAuthProductResolveError||!n&&r instanceof g||r instanceof A?r:new A("transition")}if(!n)throw new A("transition");try{await this.notifyCurrentAccountUpdated(),await o.publish()}catch(r){throw e.fail?.(r),new A("publication")}}runMutation(t,e={}){if(this.closed&&e.allowClosed!==!0)return Promise.reject(new Error("Authentication runtime is closed"));const i=d(()=>this.closed&&e.allowClosed!==!0?Promise.reject(new Error("Authentication runtime is closed")):t(),"guardedOperation");return this.mutationGate.run(()=>i())}waitForDelay(t,e){return this.processRuntime.policyDelay(t,e,l)}async withPolicyDeadline(t,e,i){const n=this.processRuntime.createPolicyDeadline(t,{signals:e});try{return await i(n.signal)}finally{n.close()}}}export function createCodeBuddyAuthRuntime(s,t=L()){return new CodeBuddyAuthRuntime(s,t)}d(createCodeBuddyAuthRuntime,"createCodeBuddyAuthRuntime");
|
|
1
|
+
var z=Object.defineProperty;var d=(s,t)=>z(s,"name",{value:t,configurable:!0});import{randomUUID as N}from"node:crypto";import"../auth/session.js";import{createManagedAuthPreparation as G}from"../effect-runtime/managed-auth-preparation.mjs";import{currentHarnessProcessRuntime as L}from"../effect-runtime/process-runtime-context.js";import{abortable as C,abortReason as M}from"../internal/async.js";import{isRecord as E}from"../internal/guards.js";import{ACP_V2_METHODS as b}from"../protocol/acp-v2.js";import{validateAcpV2CoreSchema as T}from"../protocol/acp-v2-schema.js";import{AGENT_HARNESS_ERROR_META_KEY as B}from"../protocol/error.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as f,AgentHarnessJsonRpcError as g}from"../server/errors.js";import{measure as P}from"../telemetry/runtime.js";import{accountBinding as S}from"./external-product-binding.js";const q=-32e3,V=200,H=5e3,j=3e4,J=10*6e4;class _ extends Error{static{d(this,"AuthenticationOperationSupersededError")}constructor(){super("Authentication operation was superseded")}}class O extends Error{static{d(this,"AuthenticationGenerationChangedError")}constructor(){super("Authentication generation changed during reconciliation")}}class A extends Error{static{d(this,"CodeBuddyAuthProductLifecycleError")}constructor(t){super(`Authentication Product ${t} failed`),this.name="CodeBuddyAuthProductLifecycleError"}}export class CodeBuddyAuthProductRefreshRequiredError extends Error{static{d(this,"CodeBuddyAuthProductRefreshRequiredError")}constructor(){super("Authentication Product refresh required"),this.name="CodeBuddyAuthProductRefreshRequiredError"}}export const CODEBUDDY_AUTH_PRODUCT_RESOLVE_ERROR_CODES=["PRODUCT_AUTH_INVALID","PRODUCT_REMOTE_RESPONSE_INVALID","PRODUCT_REMOTE_TIMEOUT","PRODUCT_REMOTE_UNAVAILABLE","PRODUCT_RESOLVE_TIMEOUT","PRODUCT_ROUTING_INVALID"];const W=new Set(CODEBUDDY_AUTH_PRODUCT_RESOLVE_ERROR_CODES);export function isCodeBuddyAuthProductResolveErrorCode(s){return W.has(s)}d(isCodeBuddyAuthProductResolveErrorCode,"isCodeBuddyAuthProductResolveErrorCode");export class CodeBuddyAuthProductResolveError extends Error{static{d(this,"CodeBuddyAuthProductResolveError")}constructor(t){super("Authentication Product resolution failed"),this.code=t,this.name="CodeBuddyAuthProductResolveError"}}const Y={PRODUCT_AUTH_INVALID:{code:"product_auth_invalid",message:"Product authentication context is invalid."},PRODUCT_REMOTE_RESPONSE_INVALID:{code:"product_remote_response_invalid",message:"Product configuration response is invalid."},PRODUCT_REMOTE_TIMEOUT:{code:"product_resolve_timeout",message:"Product configuration resolution timed out."},PRODUCT_REMOTE_UNAVAILABLE:{code:"product_remote_unavailable",message:"Product configuration is unavailable."},PRODUCT_RESOLVE_TIMEOUT:{code:"product_resolve_timeout",message:"Product configuration resolution timed out."},PRODUCT_ROUTING_INVALID:{code:"product_routing_invalid",message:"Product routing is invalid."}};function y(s){return{authMode:"none",generation:s,snapshot:{account:null,mode:null,state:"unauthenticated"}}}d(y,"unauthenticated");function D(s){return{id:s.id,...s.displayName===void 0?{}:{displayName:s.displayName},...s.avatarUrl===void 0?{}:{avatarUrl:s.avatarUrl},...s.enterpriseId===void 0?{}:{organization:{id:s.enterpriseId,...s.enterpriseName===void 0?{}:{displayName:s.enterpriseName}}},...s.department===void 0?{}:{department:s.department}}}d(D,"projectManagedAccount");function v(s){return{account:D(s.account),providerIdentity:{accountType:s.account.accountType,...s.account.idp===void 0?{}:{idp:s.account.idp},...s.account.oneidAccountId===void 0?{}:{oneidAccountId:s.account.oneidAccountId}},credential:s.credential}}d(v,"projectManagedCredential");function h(s){return new g(q,"Authentication required",s?{reason:s}:void 0)}d(h,"authRequired");function I(s){if(s instanceof CodeBuddyAuthProductRefreshRequiredError)return h("credential_rejected");if(!(s instanceof CodeBuddyAuthProductResolveError))return;const t=Y[s.code];return new g(f.notReady,t.message,{reason:t.code,[B]:t})}d(I,"projectPublicProductError");class x extends g{static{d(this,"CodeBuddyAuthProductPreconditionError")}}function X(s){return s instanceof _||s instanceof CodeBuddyAuthProductRefreshRequiredError||s instanceof CodeBuddyAuthProductResolveError||s instanceof x}d(X,"canRetryExternalInitialization");export function productProvisionError(s,t,e={}){return new x(f.invalidRequest,t,{...e,reason:s})}d(productProvisionError,"productProvisionError");function U(s,t,e){const n=new AbortController,i=Promise.withResolvers(),a=s.createPolicyDeadline(t,{signals:[n.signal,e],timeoutReason:new Error("Product provision timed out")});return{controller:n,completed:i.promise,complete:d(()=>{a.close(),i.resolve()},"complete"),signal:a.signal}}d(U,"createPendingProductProvision");const l="Authentication operation aborted";function $(s){const t=s.client?.capabilities?.agent;return!E(t)||!E(t.elicitation)?!1:E(t.elicitation.url)}d($,"supportsUrlElicitation");function F(s,t){return JSON.stringify(s)===JSON.stringify(t)}d(F,"sameIdentity");function R(s,t,e,n,i,a){return s?.id===n.id&&(s.authMethodId??null)===(n.authMethodId??null)&&(s.organization?.id??null)===(n.organization?.id??null)&&(s.department??null)===(n.department??null)&&(t?.accountType??null)===(i?.accountType??null)&&(t?.oneidAccountId??null)===(i?.oneidAccountId??null)&&(t?.idp??null)===(i?.idp??null)&&e?.type===a.type&&(e.domain??null)===(a.domain??null)}d(R,"sameCredentialContext");export class CodeBuddyAuthRuntime{static{d(this,"CodeBuddyAuthRuntime")}constructor(t,e=L()){if(this.initializationController=new AbortController,this.managedActivationEpoch=0,this.connectionAuthProfiles=new WeakMap,this.connectionProductProfiles=new WeakMap,this.activeProductMode="managed",this.managedDiscoveryLastApplied=0,this.managedDiscoverySequence=0,this.authenticationEpoch=0,this.pendingManagedRestore=!1,this.closed=!1,this.processRuntime=e,this.mutationGate=e.createSerialGate("Authentication mutation"),this.refreshFlights=e.createSingleFlight("Authentication refresh"),this.stateCell=e.createStateCell(y(0)),this.managedPreparation=G(e),this.consumer=t.consumer,this.getAuthMethods=t.getAuthMethods??(()=>[]),this.managedAuth=t.managedAuth,this.onRuntimePreparing=t.onRuntimePreparing,this.onRuntimePrepared=t.onRuntimePrepared,this.productLifecycle=t.productLifecycle,this.productLifecycle&&(this.accountUpdatePublication="backend"),this.loginCleanupTimeoutMs=t.loginCleanupTimeoutMs??H,this.loginPollIntervalMs=t.loginPollIntervalMs??V,this.refreshTimeoutMs=t.refreshTimeoutMs??j,this.productProvisionTimeoutMs=t.productProvisionTimeoutMs??J,!Number.isSafeInteger(this.loginCleanupTimeoutMs)||this.loginCleanupTimeoutMs<=0||!Number.isSafeInteger(this.loginPollIntervalMs)||this.loginPollIntervalMs<=0||!Number.isSafeInteger(this.refreshTimeoutMs)||this.refreshTimeoutMs<=0||!Number.isSafeInteger(this.productProvisionTimeoutMs)||this.productProvisionTimeoutMs<=0)throw new RangeError("Authentication timeouts must be positive integers");this.releaseProcessOwnership=e.addFinalizer(()=>this.close(new Error("Agent Harness process runtime is closing")))}get state(){return this.stateCell.current}setState(t){return this.stateCell.set(t)}clearPendingManagedRestore(){this.pendingManagedRestore=!1,this.pendingManagedAccount=void 0}bindProtocolBridge(t){if(this.bridge&&this.bridge!==t)throw new Error("Authentication protocol bridge is already bound");this.bridge=t}selectConnectionProductProfile(t,e){const n=this.connectionProductProfiles.get(e.connectionSignal);if(n&&(n.mode!==t.mode||n.workspace!==t.workspace))throw new g(f.invalidRequest,"Product management profile cannot change on an initialized connection");this.connectionProductProfiles.set(e.connectionSignal,Object.freeze({...t})),this.state.authMode==="none"&&(this.activeProductMode=t.mode)}productModeFor(t){return(t===void 0?void 0:this.connectionProductProfiles.get(t)?.mode)??this.activeProductMode}activateProductMode(t){const e=this.productModeFor(t);return this.activeProductMode=e,e}startManagedDiscovery(){return this.closed?Promise.reject(new Error("Authentication runtime is closed")):this.state.authMode!=="none"?Promise.resolve():this.getOrStartManagedDiscovery().promise.then(()=>{})}selectConnectionAuthProfile(t,e){const n=this.connectionProductProfiles.get(e.connectionSignal);this.connectionAuthProfiles.set(e.connectionSignal,t),this.activeProductMode=n?.mode??this.activeProductMode,t.mode!=="external"&&this.startManagedDiscovery().catch(()=>{})}markConnectionInitialized(t){if(t.mode!=="external"){try{this.onRuntimePreparing?.()}catch{}this.startManagedPreparation().then(()=>{!this.closed&&this.state.authMode==="none"&&this.notifyRuntimePrepared()},()=>{})}}notifyRuntimePrepared(){if(this.productLifecycle?.isProductReady?.(this.activeProductMode)!==!1)try{this.onRuntimePrepared?.()}catch{}}async notifyCurrentAccountUpdated(){const t=this.bridge;if(t){if(this.state.authMode==="external"&&this.state.externalOwner){await t.notifyAccountUpdated(this.state.snapshot,{sourceOwner:this.state.externalOwner});return}await t.notifyAccountUpdated(this.state.snapshot)}}close(t){return this.closePromise??=this.closeInternal(t),this.closePromise}async closeInternal(t){if(this.closed)return;const e=t??new Error("Authentication runtime is closed");this.closed=!0,this.initializationController.abort(e),this.authenticationEpoch+=1,this.authenticationOperationController?.abort(e),this.authenticationOperationController=void 0,this.pendingManagedLoginId=void 0,this.abortReconciliation(e),this.abortRefreshFlights(e),this.pendingProductProvision?.controller.abort(e),await this.managedPreparation.close(e).catch(()=>{}),await this.refreshFlights.close(e),await this.pendingProductProvision?.completed;try{await this.withPolicyDeadline(this.loginCleanupTimeoutMs,[],n=>this.runMutation(async()=>{const i=this.nextGeneration();await this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"shutdown_cleanup",signal:n,commitCredential:d(async()=>{this.clearPendingManagedRestore(),await this.setState(y(i)),await this.consumer.clearAuthentication({generation:i})},"commitCredential")})},{allowClosed:!0})).catch(()=>{})}finally{await this.mutationGate.close(e)}this.releaseProcessOwnership()}async readAccount(t,e){const n=await this.runConsistentRead(()=>this.state.authMode==="none"?void 0:structuredClone(this.state.snapshot),{signal:e.signal});if(n!==void 0)return n;const i=this.initialization;return i&&!this.pendingManagedRestore?(await C(i,e.signal,l),this.runConsistentRead(()=>structuredClone(this.state.snapshot),{signal:e.signal})):this.connectionAuthProfiles.get(e.connectionSignal)?.mode==="external"?this.runConsistentRead(()=>structuredClone(this.state.snapshot),{signal:e.signal}):this.reconciliation!==void 0?this.runConsistentRead(()=>structuredClone(this.state.snapshot),{signal:e.signal}):(await this.awaitManagedDiscovery(e.signal),this.runConsistentRead(()=>this.state.authMode!=="none"?structuredClone(this.state.snapshot):this.pendingManagedRestore&&this.pendingManagedAccount?{account:structuredClone(this.pendingManagedAccount),mode:"managed",state:"authenticated"}:structuredClone(this.state.snapshot),{signal:e.signal}))}async prepareAuthStatus(t,e){this.connectionAuthProfiles.get(e.connectionSignal)?.mode!=="external"&&this.reconciliation===void 0&&await this.awaitManagedDiscovery(e.signal)}async readAuthStatus(t,e){return this.runConsistentRead(()=>({authenticated:this.state.authMode!=="none"||this.pendingManagedRestore&&this.reconciliation===void 0&&this.connectionAuthProfiles.get(e.connectionSignal)?.mode!=="external"}),{signal:e.signal})}async readProduct(t,e){return this.runConsistentRead(()=>{const n=this.productLifecycle;if(!n)throw new g(f.notReady,"Product lifecycle is unavailable");const i=n.readProduct;if(!i)throw new g(f.notReady,"Product projection is unavailable");return i.call(n,this.productModeFor(e.connectionSignal))},{signal:e.signal})}async prepareHostExecution(t){await this.awaitManagedDiscovery(t),await this.runConsistentRead(()=>this.state.authMode==="none"&&this.pendingManagedRestore,{signal:t})&&await this.ensurePublicInitialized(t)}currentSessionAuthentication(){const t=this.state;if(!(t.snapshot.state!=="authenticated"||!t.credential))return structuredClone({generation:t.generation,account:t.snapshot.account,credential:t.credential,providerIdentity:t.providerIdentity})}async refreshHostAuthentication(t,e){const n=d(()=>this.runConsistentRead(()=>{const a=this.currentSessionAuthentication();if(!a||!R(t.account,t.providerIdentity,t.credential,a.account,a.providerIdentity,a.credential))throw h("account_changed");return a},{signal:e}),"capture"),i=await n();if(i.generation!==t.generation)return i;try{return await this.refreshAuthentication({accountId:t.account.id,generation:t.generation},{signal:e})}catch(a){e.throwIfAborted();const o=await n();if(o.generation>t.generation&&o.credential.accessToken!==t.credential.accessToken)return o;throw a}}async prepareSessionRuntime(t,e){if((e===void 0?void 0:this.connectionAuthProfiles.get(e)?.mode)==="external"&&this.state.authMode==="none")throw h("account_provision_required");await this.ensurePublicInitialized(t),this.productLifecycle?.assertProductReady?.(this.productModeFor(e))}async refreshProductAuthentication(t){await this.ensureInitialized(t);const e=this.state;if(e.authMode==="none"||e.snapshot.state!=="authenticated")throw h();await this.refreshAuthentication({accountId:e.snapshot.account.id,generation:e.generation},{signal:t})}async runConsistentRead(t,e={}){for(;;){e.signal?.throwIfAborted();const n=this.pendingProductProvision;if(n){await C(n.completed,e.signal,l);continue}const i=await this.runMutation(async()=>this.pendingProductProvision?{retry:!0}:{retry:!1,value:await t()},e);if(!i.retry)return i.value}}async listAuthMethods(t,e){return structuredClone(this.getAuthMethods())}async login(t,e){this.activateProductMode(e.connectionSignal);const{pendingLoginId:n,token:i}=this.beginExplicitAuthenticationOperation(new Error("Authentication login superseded prior reconciliation"));await this.ensurePublicInitialized(e.signal),this.assertCurrentAuthenticationOperation(i),n&&await this.cancelSupersededManagedLogin(i,n);const a=N();this.pendingManagedLoginId=a;let o,r;try{if(o=await this.managedAuth.startManagedAuthLogin(t.methodId,{loginId:a,signal:e.signal}),this.assertCurrentAuthenticationOperation(i),this.pendingManagedLoginId=o.loginId,r=await this.awaitManagedLogin(o,e),r.state!=="succeeded")throw h(r.state);return await this.reconcileManagedLoginForRequest(i),{}}catch(c){if(!this.isCurrentAuthenticationOperation(i))throw c;if(r?.state==="succeeded")throw this.startManagedLoginReconciliation(i),c;if(!r||r.state==="pending"||!r.settled){const u=o?.loginId??a,p=await this.withAuthenticationDeadline(i,this.loginCleanupTimeoutMs,m=>Promise.resolve(this.managedAuth.readManagedAuthLogin(u,{signal:m}))).catch(()=>{});if(!this.isCurrentAuthenticationOperation(i))throw c;if(p?.state==="succeeded")return await this.reconcileManagedLoginForRequest(i),{};if(await this.cancelManagedLogin(u),!this.isCurrentAuthenticationOperation(i))throw c;const w=await this.withAuthenticationDeadline(i,this.loginCleanupTimeoutMs,m=>this.awaitManagedLoginSettlement(u,p,m)).catch(()=>{});if(!this.isCurrentAuthenticationOperation(i))throw c;if(w?.state==="succeeded")return await this.reconcileManagedLoginForRequest(i),{};this.pendingManagedLoginId=w?.settled===!0?void 0:u,this.pendingManagedLoginId&&this.startPendingManagedLoginReconciliation(i,this.pendingManagedLoginId)}else this.pendingManagedLoginId=void 0;throw c}}async logout(t,e){this.activateProductMode(e.connectionSignal);const n=this.reconciliation,{pendingLoginId:i,token:a}=this.beginExplicitAuthenticationOperation(new Error("Authentication logout superseded prior reconciliation")),o=i??n?.loginId,r=o===void 0?void 0:await this.cancelManagedLogin(o);let c=this.state.authMode==="managed"||o!==void 0||n?.kind==="managed_login"||n?.kind==="managed_logout"||n?.kind==="pending_login";if(c||(await this.ensurePublicInitialized(e.signal),c=this.state.authMode==="managed"),this.assertCurrentAuthenticationOperation(a),!c&&this.state.authMode==="external")return await this.fenceAuthenticationForOperation(a,new Error("External authentication was detached")),this.pendingManagedLoginId=void 0,{};if(!c&&this.state.authMode==="none")return{};let u;try{await this.withAuthenticationDeadline(a,this.loginCleanupTimeoutMs,w=>this.managedAuth.logoutManagedAuth({signal:w}))}catch(w){u=w}const p=o!==void 0&&r?.settled!==!0;if(u!==void 0||p)throw await this.fenceAuthenticationForOperation(a,new Error("Managed authentication logout is ambiguous")),this.startManagedLogoutReconciliation(a,o),this.productLifecycle||await this.notifyCurrentAccountUpdated().catch(()=>{}),u??h("managed_login_cancellation_ambiguous");return await this.fenceAuthenticationForOperation(a,new Error("Authentication was logged out")),this.pendingManagedLoginId=void 0,{}}async provisionAccount(t,e){this.activateProductMode(e.connectionSignal);const{pendingLoginId:n,token:i}=this.beginExplicitAuthenticationOperation(new Error("External authentication superseded prior reconciliation"));if(t.state==="authenticated"&&this.initialization===void 0){this.managedActivationEpoch+=1,this.clearPendingManagedRestore();const a=(async()=>(await this.managedPreparation.join(),this.assertCurrentAuthenticationOperation(i),this.commitExternalAccount(t,e,i,n)))(),o=a.then(()=>{},r=>{throw this.initialization===o&&X(r)&&(this.initialization=void 0),r});return this.initialization=o,o.catch(()=>{}),a.catch(r=>{throw I(r)??r})}if(await this.ensurePublicInitialized(e.signal),this.assertCurrentAuthenticationOperation(i),n&&await this.cancelSupersededManagedLogin(i,n),t.state==="unauthenticated"){if(this.state.authMode==="managed")throw new g(f.invalidRequest,"account/provision cannot detach managed authentication");return await this.runMutation(async()=>{this.assertCurrentAuthenticationOperation(i);const a=this.nextGeneration();this.abortRefreshFlights(new Error("External authentication was detached")),await this.withAuthenticationDeadline(i,this.loginCleanupTimeoutMs,o=>this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"explicit_auth_mutation",signal:o,commitCredential:d(async()=>{if(this.productLifecycle){this.clearPendingManagedRestore(),await this.setState(y(a)),await this.consumer.clearAuthentication({generation:a});return}await this.consumer.clearAuthentication({generation:a}),this.clearPendingManagedRestore(),await this.setState(y(a))},"commitCredential")}))}),structuredClone(this.state.snapshot)}try{return await this.commitExternalAccount(t,e,i)}catch(a){throw I(a)??a}}async commitExternalAccount(t,e,n,i){return this.assertCurrentAuthenticationOperation(n),i&&await this.cancelSupersededManagedLogin(n,i),await this.runMutation(async()=>{this.assertCurrentAuthenticationOperation(n);const a=this.nextGeneration(),o=this.state.authMode!=="none"&&(this.state.authMode!=="external"||this.state.snapshot.state!=="authenticated"||this.state.snapshot.account.id!==t.account.id||!R(this.state.snapshot.account,this.state.providerIdentity,this.state.credential,t.account,void 0,t.credential));this.abortRefreshFlights(new Error("Authentication state was replaced"));const r={account:t.account,credential:t.credential,generation:a};await this.withAuthenticationDeadline(n,this.refreshTimeoutMs,c=>this.executeProductTransition({authentication:r,credentialOrder:"after_product",mode:"external",origin:"explicit_auth_mutation",signal:c,commitCredential:d(async()=>{await this.consumer.setAuthentication(r,{fenceExisting:o}),this.clearPendingManagedRestore(),await this.setState({authMode:"external",credential:structuredClone(t.credential),externalOwner:e.connectionSignal,generation:a,snapshot:{account:structuredClone(t.account),mode:"external",state:"authenticated"}})},"commitCredential")}))}),this.notifyRuntimePrepared(),structuredClone(this.state.snapshot)}async provisionProduct(t,e){await this.ensurePublicInitialized(e.signal);const n=this.productLifecycle,i=n?.provisionExternal,a=n?.reserveExternalProvision;if(!i||!a)throw new g(f.notReady,"External Product provisioning is unavailable");if(this.connectionProductProfiles.get(e.connectionSignal)?.mode!=="external")throw new g(f.invalidRequest,"product/provision requires external Product management");const o=U(this.processRuntime,this.productProvisionTimeoutMs,e.signal);let r,c;try{return await this.runMutation(async()=>{if(this.pendingProductProvision)throw new g(f.notReady,"Product provisioning is already in progress");const u=this.state;if(u.snapshot.state!=="authenticated"||e.connectionSignal.aborted)throw h();r=S(u.snapshot.account,u.credential?.domain),c=a.call(n,r),this.pendingProductProvision=o},{signal:o.signal}),await i.call(n,t,{binding:r,reservation:c,signal:o.signal})}finally{try{this.pendingProductProvision===o&&await this.runMutation(async()=>{this.pendingProductProvision===o&&(this.pendingProductProvision=void 0,c?.release())},{allowClosed:!0})}finally{o.complete()}}}async provisionWorkspaceProduct(t,e){await this.ensurePublicInitialized(e.signal);const n=this.productLifecycle,i=n?.provisionWorkspace;if(!i)throw new g(f.notReady,"Workspace Product provisioning is unavailable");const a=U(this.processRuntime,this.productProvisionTimeoutMs,e.signal);let o,r;try{return await this.runMutation(async()=>{if(this.pendingProductProvision)throw new g(f.notReady,"Product provisioning is already in progress");const c=this.state;if(c.snapshot.state!=="authenticated"||e.connectionSignal.aborted)throw h();r=this.productModeFor(e.connectionSignal),n.assertProductReady?.(r),o=S(c.snapshot.account,c.credential?.domain),this.pendingProductProvision=a},{signal:a.signal}),await i.call(n,t,{binding:o,mode:r,signal:a.signal})}finally{try{this.pendingProductProvision===a&&await this.runMutation(async()=>{this.pendingProductProvision===a&&(this.pendingProductProvision=void 0)},{allowClosed:!0})}finally{a.complete()}}}async detachExternalAccount(t,e){if(this.activateProductMode(t.connectionSignal),await this.withPolicyDeadline(this.loginCleanupTimeoutMs,[],o=>this.ensureInitialized(o)),this.state.authMode!=="external"||this.state.externalOwner!==t.connectionSignal)return!1;const{pendingLoginId:n,token:i}=this.beginExplicitAuthenticationOperation(new Error("External authentication detach superseded prior reconciliation"));let a=!1;if(n)try{await this.cancelSupersededManagedLogin(i,n)}catch{a=!0}return this.runMutation(async()=>{if(this.assertCurrentAuthenticationOperation(i),this.state.authMode!=="external"||this.state.externalOwner!==t.connectionSignal)return a&&this.state.authMode==="none";const o=this.nextGeneration();return this.abortRefreshFlights(new Error("External authentication owner detached")),await this.withAuthenticationDeadline(i,this.loginCleanupTimeoutMs,r=>this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"explicit_auth_mutation",signal:r,commitCredential:d(async()=>{this.clearPendingManagedRestore(),await this.setState(y(o)),await this.consumer.clearAuthentication({generation:o})},"commitCredential")})),!0})}async refreshAuthentication(t,e){await this.ensureInitialized(e.signal);const n=JSON.stringify([this.state.authMode,t.accountId,t.generation]),i=this.state;if(i.authMode==="none"||i.generation!==t.generation||i.snapshot.state!=="authenticated"||i.snapshot.account.id!==t.accountId)throw h();return this.refreshFlights.run(n,a=>this.performAuthenticationRefresh(i,t,AbortSignal.any([a,...i.authMode==="external"&&i.externalOwner?[i.externalOwner]:[]])),{abortMessage:l,signal:e.signal,timeoutMs:this.refreshTimeoutMs})}async performAuthenticationRefresh(t,e,n){const i=t.authMode;if(i==="none")throw h();const a=i==="managed"?v(await this.managedAuth.refreshManagedAuthCredential(e.accountId,{signal:n})):await this.refreshExternal(e,n,t.externalOwner);if(n.aborted)throw i==="external"&&t.externalOwner?.aborted?h("owner_disconnected"):M(n,l);if(a.account.id!==e.accountId||!R(t.snapshot.account,t.providerIdentity,t.credential,a.account,a.providerIdentity,a.credential))throw h("account_changed");if(i==="external"&&a.credential.accessToken===t.credential?.accessToken)throw h("credential_unchanged");let o,r=!1;return await this.runMutation(async()=>{if(n.aborted)throw M(n,l);if(this.state.authMode!==t.authMode||this.state.generation!==t.generation||this.state.snapshot.state!=="authenticated"||this.state.snapshot.account.id!==e.accountId||i==="external"&&(t.externalOwner?.aborted!==!1||this.state.externalOwner!==t.externalOwner))throw h("stale_generation");const c=this.nextGeneration(),u=this.state.snapshot.account;o={account:structuredClone(a.account),...a.providerIdentity===void 0?{}:{providerIdentity:structuredClone(a.providerIdentity)},credential:structuredClone(a.credential),generation:c},await this.executeProductTransition({authentication:o,credentialOrder:"after_product",mode:i,origin:"child_refresh",signal:n,commitCredential:d(async()=>{await this.consumer.setAuthentication(o),r=!F(u,a.account),await this.setState({...this.state,...a.providerIdentity===void 0?{}:{providerIdentity:structuredClone(a.providerIdentity)},credential:structuredClone(a.credential),generation:c,snapshot:{account:structuredClone(a.account),mode:i,state:"authenticated"}})},"commitCredential")})}),!this.productLifecycle&&r&&await this.notifyCurrentAccountUpdated(),o}async ensurePublicInitialized(t){try{await this.ensureInitialized(t)}catch(e){throw I(e)??e}}getOrStartManagedDiscovery(){const t=this.managedActivationEpoch,e=this.authenticationEpoch,n=this.managedDiscovery;if(n&&n.activationEpoch===t&&n.authenticationEpoch===e)return n;const i=++this.managedDiscoverySequence,o=this.discoverManagedAuthentication({activationEpoch:t,authenticationEpoch:e,sequence:i}).then(c=>(this.managedDiscovery?.promise===o&&!c.applied&&(this.managedDiscovery=void 0),c),c=>{throw this.managedDiscovery?.promise===o&&(this.managedDiscovery=void 0),c});o.catch(()=>{});const r={activationEpoch:t,authenticationEpoch:e,promise:o};return this.managedDiscovery=r,r}async discoverManagedAuthentication(t){const e=await this.managedAuth.readManagedAuth({signal:this.initializationController.signal});let n=!1;return await this.runMutation(async()=>{if(this.closed||t.activationEpoch!==this.managedActivationEpoch||t.authenticationEpoch!==this.authenticationEpoch||this.initialization!==void 0||this.state.authMode!=="none"||t.sequence<this.managedDiscoveryLastApplied)return;this.managedDiscoveryLastApplied=t.sequence;const i=e.account;this.pendingManagedRestore=e.authenticated&&i!==null;const a=this.pendingManagedRestore&&i?D(i):void 0;this.pendingManagedAccount=a,n=!0}),{...t,applied:n,snapshot:e}}async awaitManagedDiscovery(t){for(;;){if(this.closed)throw new Error("Authentication runtime is closed");if(t.aborted)throw M(t,l);if(this.state.authMode!=="none"||this.initialization!==void 0)return;const e=this.getOrStartManagedDiscovery();let n;try{n=await P("managedAuthDiscoveryWait",()=>C(e.promise,t,l))}catch(i){if(this.state.authMode!=="none"||this.initialization!==void 0||e.activationEpoch!==this.managedActivationEpoch||e.authenticationEpoch!==this.authenticationEpoch)return;throw i}if(n.applied&&n.activationEpoch===this.managedActivationEpoch&&n.authenticationEpoch===this.authenticationEpoch&&this.state.authMode==="none"&&this.initialization===void 0)return n.snapshot}}async ensureInitialized(t){for(;;){if(this.closed)throw new Error("Authentication runtime is closed");if(t.aborted)throw M(t,l);if(this.initialization){await C(this.initialization,t,l);return}if(this.state.authMode!=="none")return;try{await this.managedPreparation.run((e,n)=>this.initializeManagedRuntime(e,n),{signal:t})}catch(e){if(this.initialization!==void 0)continue;throw e}}}startManagedPreparation(){return this.closed?Promise.reject(new Error("Authentication runtime is closed")):this.initialization!==void 0||this.state.authMode!=="none"?Promise.resolve():this.managedPreparation.run((t,e)=>this.initializeManagedRuntime(t,e))}async initializeManagedRuntime(t,e){for(;;){if(this.closed)throw new Error("Authentication runtime is closed");if(t.aborted)throw M(t,l);if(this.initialization!==void 0||this.state.authMode!=="none")return;const n=await this.awaitManagedDiscovery(t);if(e.phaseCompleted("discovery_ready"),this.initialization!==void 0||this.state.authMode!=="none")return;if(n){if(!n.authenticated||!n.account){this.initialization??=Promise.resolve();return}this.managedActivationEpoch+=1,this.managedDiscovery=void 0,await this.initializeFromManaged(n.account,t,e),this.initialization??=Promise.resolve();return}}}async initializeFromManaged(t,e,n){let i=await P("managedCredentialRead",()=>this.managedAuth.readManagedAuthCredential({signal:e}));if(n.phaseCompleted("credential_ready"),i.account.id!==t.id)throw new Error("Managed authentication projection changed identity");try{await P("productReconcile",()=>this.commitManaged(i,void 0,e))}catch(a){if(!(a instanceof CodeBuddyAuthProductRefreshRequiredError))throw a;const o=await P("managedCredentialRefresh",()=>this.managedAuth.refreshManagedAuthCredential(t.id,{signal:e}));n.phaseCompleted("credential_refreshed");const r=v(i),c=v(o);if(!R(r.account,r.providerIdentity,r.credential,c.account,c.providerIdentity,c.credential))throw h("account_changed");i=o,await P("productReconcile",()=>this.commitManaged(i,void 0,e))}n.phaseCompleted("product_ready")}async reconcileManagedLoginForRequest(t){try{await this.reconcileSucceededManagedLogin(t)}catch(e){throw this.isCurrentAuthenticationOperation(t)&&this.startManagedLoginReconciliation(t),e}}async reconcileSucceededManagedLogin(t,e){await this.fencePreviousAuthenticationForManagedLogin(t),this.assertCurrentAuthenticationOperation(t);const n=this.state.generation;await this.withPolicyDeadline(this.loginCleanupTimeoutMs,[t.signal,...e===void 0?[]:[e]],async i=>{const[a,o]=await Promise.all([this.managedAuth.readManagedAuth({signal:i}),this.managedAuth.readManagedAuthCredential({signal:i})]);if(!a.authenticated||!a.account||a.account.id!==o.account.id)throw h("managed_projection_unavailable");if(i.aborted)throw M(i,l);await this.commitManaged(o,{expectedGeneration:n,signal:i,token:t})}),this.assertCurrentAuthenticationOperation(t),this.pendingManagedLoginId=void 0}fencePreviousAuthenticationForManagedLogin(t){return this.fenceAuthenticationForOperation(t,new Error("Managed login replaced the authentication state"))}async commitManaged(t,e,n){if(n===void 0)return this.withPolicyDeadline(this.refreshTimeoutMs,e?.signal===void 0?[]:[e.signal],o=>this.commitManaged(t,e,o));const i=v(t),a=await this.runMutation(async()=>{if(e){if(this.assertCurrentAuthenticationOperation(e.token),e.signal?.aborted)throw M(e.signal,l);if(this.state.generation!==e.expectedGeneration)throw new O}const o=this.state.authMode!=="managed"||this.state.snapshot.state!=="authenticated"||!F(this.state.snapshot.account,i.account),r=this.nextGeneration(),c=this.state.authMode!=="none"&&(this.state.authMode!=="managed"||this.state.snapshot.state!=="authenticated"||this.state.snapshot.account.id!==i.account.id||!R(this.state.snapshot.account,this.state.providerIdentity,this.state.credential,i.account,i.providerIdentity,i.credential));this.abortRefreshFlights(new Error("Managed authentication state was replaced"));const u={...i,generation:r};return await this.executeProductTransition({authentication:u,credentialOrder:"after_product",mode:"managed",origin:e?"explicit_auth_mutation":"lazy_activation",signal:n,commitCredential:d(async()=>{await this.consumer.setAuthentication(u,{fenceExisting:c}),this.clearPendingManagedRestore(),await this.setState({authMode:"managed",providerIdentity:structuredClone(i.providerIdentity),credential:structuredClone(i.credential),generation:r,snapshot:{account:structuredClone(i.account),mode:"managed",state:"authenticated"}})},"commitCredential")}),o});return this.notifyRuntimePrepared(),a}startPendingManagedLoginReconciliation(t,e){this.startReconciliation("pending_login",t,async n=>{for(;this.canContinueReconciliation(t,n);){let i;try{i=await this.withBackgroundDeadline(t,n,a=>this.managedAuth.readManagedAuthLogin(e,{signal:a}))}catch{}if(!this.canContinueReconciliation(t,n))return;if(i?.state==="succeeded"){await this.runManagedLoginReconciliation(t,n);return}if(i?.settled){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}await this.waitForDelay(this.loginPollIntervalMs,n)}},e)}startManagedLoginReconciliation(t){this.startReconciliation("managed_login",t,e=>this.runManagedLoginReconciliation(t,e))}async runManagedLoginReconciliation(t,e){for(;this.canContinueReconciliation(t,e);){try{if(await this.reconcileSucceededManagedLogin(t,e),!this.canContinueReconciliation(t,e))return;this.productLifecycle||await this.notifyCurrentAccountUpdated().catch(()=>{});return}catch(n){if(this.shouldStopReconciliation(n,t,e))return}await this.waitForDelay(this.loginPollIntervalMs,e)}}startManagedLogoutReconciliation(t,e,n=!0){this.startReconciliation("managed_logout",t,async i=>{let a=!1;for(;this.canContinueReconciliation(t,i);){let o=e===void 0;if(e!==void 0){const c=await this.withBackgroundDeadline(t,i,u=>this.managedAuth.readManagedAuthLogin(e,{signal:u})).catch(()=>{});if(!this.canContinueReconciliation(t,i))return;if(a||=c?.state==="succeeded",o=a||c?.settled===!0,c?.state==="pending"&&await this.withBackgroundDeadline(t,i,u=>this.managedAuth.cancelManagedAuthLogin(e,{signal:u})).catch(()=>{}),!a&&c?.settled===!0&&c?.state!=="succeeded"&&!n){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}}if(!n&&a&&await this.fenceManagedAuthenticationForOperation(t,new Error("Superseded managed login committed durably")),!n&&!o){await this.waitForDelay(this.loginPollIntervalMs,i);continue}const r=await this.withBackgroundDeadline(t,i,c=>this.managedAuth.readManagedAuth({signal:c})).catch(()=>{});if(!this.canContinueReconciliation(t,i))return;if(r&&!r.authenticated&&o){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}r?.authenticated&&await this.withBackgroundDeadline(t,i,c=>this.managedAuth.logoutManagedAuth({signal:c})).catch(()=>{}),await this.waitForDelay(this.loginPollIntervalMs,i)}},e,n)}startReconciliation(t,e,n,i,a){if(!this.isCurrentAuthenticationOperation(e))return;const o=this.reconciliation;if(o&&o.epoch===e.epoch&&o.kind===t&&o.loginId===i&&o.logoutCurrentManaged===a)return;this.abortReconciliation(new Error("Authentication reconciliation was replaced"));const r=new AbortController,c=AbortSignal.any([e.signal,r.signal]),u=n(c).catch(()=>{}).finally(()=>{this.reconciliation?.controller===r&&(this.reconciliation=void 0)}),p={controller:r,epoch:e.epoch,kind:t,...i===void 0?{}:{loginId:i},...a===void 0?{}:{logoutCurrentManaged:a},promise:u};this.reconciliation=p}async awaitManagedLogin(t,e){const n=new AbortController,i=AbortSignal.any([e.signal,e.connectionSignal,n.signal]);let a,o,r,c=t;try{for(;c.state==="pending";){if(e.signal.aborted||e.connectionSignal.aborted)throw M(e.signal.aborted?e.signal:e.connectionSignal,l);if("error"in(o??{}))throw o.error;if(o&&"action"in o&&o.action!=="accept")throw h(o.action);if(c.authUrl&&!r){if(!$(e))throw h("url_elicitation_unsupported");if(e.requestId===void 0||e.requestId===null)throw new Error("Authentication request has no JSON-RPC request id");a=c.loginId;const p={elicitationId:a,message:"Complete sign-in in your browser.",mode:"url",requestId:e.requestId,url:c.authUrl},w=T("CreateElicitationRequest",p);if(w)throw new Error(`Invalid authentication elicitation: ${w.message}`);r=e.request(b.client.elicitation.create,p,{signal:i,timeoutMs:null}).then(m=>{if(T("CreateElicitationResponse",m)||!E(m))throw new Error("Client returned an invalid elicitation response");o={action:m.action}}).catch(m=>{n.signal.aborted||(o={error:m})})}const u=Date.parse(c.expiresAt);if(!Number.isFinite(u)||this.processRuntime.policyNow()>=u)throw h("timed_out");await this.waitForDelay(this.loginPollIntervalMs,e.signal),c=await this.managedAuth.readManagedAuthLogin(c.loginId,{signal:e.signal})}return c}finally{n.abort(new Error("Authentication elicitation completed")),await r?.catch(()=>{}),a&&await e.notify(b.client.elicitation.complete,{elicitationId:a}).catch(()=>{})}}async awaitManagedLoginSettlement(t,e,n){let i=e;for(;!i?.settled;){i&&await this.waitForDelay(this.loginPollIntervalMs,n);const a=await this.managedAuth.readManagedAuthLogin(t,{signal:n});if(!a)throw new Error("Host returned no authentication login state");i=a}return i}async cancelManagedLogin(t){return this.withPolicyDeadline(this.loginCleanupTimeoutMs,[],e=>Promise.resolve(this.managedAuth.cancelManagedAuthLogin(t,{signal:e}))).catch(()=>{})}async cancelSupersededManagedLogin(t,e){this.pendingManagedLoginId??=e;const n=await this.cancelManagedLogin(e);if(this.assertCurrentAuthenticationOperation(t),n?.settled&&n.state!=="succeeded"){this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}if(n?.settled&&n.state==="succeeded")try{await this.fenceManagedAuthenticationForOperation(t,new Error("Superseded managed login committed durably")),await this.withAuthenticationDeadline(t,this.loginCleanupTimeoutMs,i=>this.managedAuth.logoutManagedAuth({signal:i})),this.assertCurrentAuthenticationOperation(t),this.pendingManagedLoginId===e&&(this.pendingManagedLoginId=void 0);return}catch(i){throw this.isCurrentAuthenticationOperation(t)&&this.startManagedLogoutReconciliation(t,e,!1),i}throw this.startManagedLogoutReconciliation(t,e,!1),h("managed_login_cancellation_ambiguous")}async refreshExternal(t,e,n){if(!this.bridge||!n)throw h();let i;try{i=await this.bridge.requestAccountRefresh({accountId:t.accountId},{expectedOwner:n,signal:e})}catch(a){throw n.aborted?h("owner_disconnected"):a}return{account:i.account,credential:i.credential}}beginExplicitAuthenticationOperation(t){if(this.closed)throw new Error("Authentication runtime is closed");const e=this.pendingManagedLoginId;this.authenticationEpoch+=1,this.authenticationOperationController?.abort(t),this.abortReconciliation(t);const n=new AbortController;return this.authenticationOperationController=n,{...e===void 0?{}:{pendingLoginId:e},token:{epoch:this.authenticationEpoch,signal:n.signal}}}isCurrentAuthenticationOperation(t){return!this.closed&&t.epoch===this.authenticationEpoch&&this.authenticationOperationController?.signal===t.signal&&!t.signal.aborted}assertCurrentAuthenticationOperation(t){if(!this.isCurrentAuthenticationOperation(t))throw new _}withAuthenticationDeadline(t,e,n){return this.withPolicyDeadline(e,[t.signal],n)}withBackgroundDeadline(t,e,n){return this.withPolicyDeadline(this.loginCleanupTimeoutMs,[t.signal,e],n)}async fenceAuthenticationForOperation(t,e,n={}){for(;;){this.assertCurrentAuthenticationOperation(t);const i=this.state.generation;try{return await this.runMutation(async()=>{if(this.assertCurrentAuthenticationOperation(t),this.state.generation!==i)throw new O;if(this.state.authMode==="none"||n.authMode!==void 0&&this.state.authMode!==n.authMode)return!1;const a=this.nextGeneration();return this.abortRefreshFlights(e),await this.withAuthenticationDeadline(t,this.loginCleanupTimeoutMs,o=>this.executeProductTransition({credentialOrder:"before_product",mode:"none",origin:"explicit_auth_mutation",signal:o,commitCredential:d(async()=>{this.clearPendingManagedRestore(),await this.setState(y(a)),await this.consumer.clearAuthentication({generation:a})},"commitCredential")})),!0})}catch(a){if(a instanceof O&&this.isCurrentAuthenticationOperation(t))continue;throw a}}}async fenceManagedAuthenticationForOperation(t,e){await this.fenceAuthenticationForOperation(t,e,{authMode:"managed"})&&!this.productLifecycle&&await this.notifyCurrentAccountUpdated().catch(()=>{})}canContinueReconciliation(t,e){return!e.aborted&&this.isCurrentAuthenticationOperation(t)}shouldStopReconciliation(t,e,n){return n.aborted||!this.isCurrentAuthenticationOperation(e)||t instanceof _}abortReconciliation(t){const e=this.reconciliation;e&&!e.controller.signal.aborted&&e.controller.abort(t)}nextGeneration(){if(this.state.generation>=Number.MAX_SAFE_INTEGER)throw new Error("Authentication generation exhausted");return this.state.generation+1}abortRefreshFlights(t){this.refreshFlights.abortAll(t)}async executeProductTransition(t){const e=this.productLifecycle;if(!e){await t.commitCredential();return}if(t.signal.aborted)throw M(t.signal,l);let n=!1,i=!1,a,o;try{o=await e.transition({...t.authentication===void 0?{}:{authentication:structuredClone(t.authentication)},credentialOrder:t.credentialOrder,mode:t.mode,origin:t.origin,productMode:t.productMode??this.activeProductMode,signal:t.signal,commitCredential:d(async()=>{if(n)throw new A("transition");n=!0;try{await t.commitCredential(),i=!0}catch(r){throw a=r,r}},"commitCredential")})}catch(r){if(a!==void 0)throw a;if(i)try{await this.notifyCurrentAccountUpdated()}catch(c){throw e.fail?.(c),new A("publication")}throw r instanceof CodeBuddyAuthProductRefreshRequiredError||!i&&r instanceof CodeBuddyAuthProductResolveError||!i&&r instanceof g||r instanceof A?r:new A("transition")}if(!i)throw new A("transition");try{await this.notifyCurrentAccountUpdated(),await o.publish()}catch(r){throw e.fail?.(r),new A("publication")}}runMutation(t,e={}){if(this.closed&&e.allowClosed!==!0)return Promise.reject(new Error("Authentication runtime is closed"));const n=d(()=>this.closed&&e.allowClosed!==!0?Promise.reject(new Error("Authentication runtime is closed")):t(),"guardedOperation");return this.mutationGate.run(()=>n(),{signal:e.signal,uninterruptible:!0})}waitForDelay(t,e){return this.processRuntime.policyDelay(t,e,l)}async withPolicyDeadline(t,e,n){const i=this.processRuntime.createPolicyDeadline(t,{signals:e});try{return await n(i.signal)}finally{i.close()}}}export function createCodeBuddyAuthRuntime(s,t=L()){return new CodeBuddyAuthRuntime(s,t)}d(createCodeBuddyAuthRuntime,"createCodeBuddyAuthRuntime");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var o=(e,n)=>E(e,"name",{value:n,configurable:!0});export const AGENT_HARNESS_PRIVATE_RUNTIME_ROLE=Object.freeze({codebuddy:"--agent-harness-private-codebuddy",executor:"--agent-harness-private-executor",processGroupAnchor:"--agent-harness-private-process-group-anchor",resource:"--agent-harness-private-resource",stdioGroupAnchor:"--agent-harness-private-stdio-group-anchor",stdioGuardian:"--agent-harness-private-stdio-guardian"}),AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-loader"),AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-runtime"),AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-node-pty-loader"),AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD_ENV="AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD";export{AGENT_HARNESS_HOST_NODE_EXECUTABLE_ENV,AGENT_HARNESS_HOST_NODE_RUN_AS_NODE_ENV}from"../binary/host-node-environment.js";export const AGENT_HARNESS_PRIVATE_PRODUCT_ROOT_ENV="AGENT_HARNESS_PRIVATE_PRODUCT_ROOT";const d=Symbol.for("codebuddy.ai/agent-harness/embedded-agent-server");export function installEmbeddedAgentServerLoader(e){const n=globalThis;if(n[d]!==void 0)throw new Error("Embedded Agent server already installed");n[d]=e}o(installEmbeddedAgentServerLoader,"installEmbeddedAgentServerLoader");export async function loadAgentServerModule(){const e=globalThis[d];return typeof e=="function"?e():import("#agent-harness-codebuddy/server")}o(loadAgentServerModule,"loadAgentServerModule");export function isAgentHarnessStandaloneBinary(){return typeof AGENT_HARNESS_PACKAGE_TYPE=="string"&&AGENT_HARNESS_PACKAGE_TYPE==="binary"}o(isAgentHarnessStandaloneBinary,"isAgentHarnessStandaloneBinary");export function installEmbeddedCodeBuddyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]!==void 0)throw new Error("Embedded CodeBuddy loader is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]=e}o(installEmbeddedCodeBuddyLoader,"installEmbeddedCodeBuddyLoader");export function installEmbeddedNodePtyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]!==void 0)throw new Error("Embedded node-pty loader is already installed");n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]=e}o(installEmbeddedNodePtyLoader,"installEmbeddedNodePtyLoader");export function installEmbeddedCodeBuddyRuntime(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]!==void 0)throw new Error("Embedded CodeBuddy runtime is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]=Object.freeze({...e})}o(installEmbeddedCodeBuddyRuntime,"installEmbeddedCodeBuddyRuntime");export function resolveEmbeddedCodeBuddyLoader(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER];return typeof e=="function"?e:void 0}o(resolveEmbeddedCodeBuddyLoader,"resolveEmbeddedCodeBuddyLoader");export function resolveEmbeddedCodeBuddyRuntime(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME];if(!(typeof e!="object"||e===null||!("binPath"in e)||typeof e.binPath!="string"||!("packageJsonPath"in e)||typeof e.packageJsonPath!="string"||!("version"in e)||typeof e.version!="string"))return e}o(resolveEmbeddedCodeBuddyRuntime,"resolveEmbeddedCodeBuddyRuntime");export function createPrivateRuntimeLaunchSpec({args:e=[],currentExecutable:n=process.execPath,entryPath:t,nodeRuntime:a,role:
|
|
1
|
+
var E=Object.defineProperty;var o=(e,n)=>E(e,"name",{value:n,configurable:!0});export const AGENT_HARNESS_PRIVATE_RUNTIME_ROLE=Object.freeze({codebuddy:"--agent-harness-private-codebuddy",executor:"--agent-harness-private-executor",processGroupAnchor:"--agent-harness-private-process-group-anchor",resource:"--agent-harness-private-resource",stdioGroupAnchor:"--agent-harness-private-stdio-group-anchor",stdioGuardian:"--agent-harness-private-stdio-guardian"}),AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-loader"),AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME=Symbol.for("codebuddy.ai/agent-harness/embedded-codebuddy-runtime"),AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER=Symbol.for("codebuddy.ai/agent-harness/embedded-node-pty-loader"),AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD_ENV="AGENT_HARNESS_PRIVATE_CODEBUDDY_CHILD";export{AGENT_HARNESS_HOST_NODE_EXECUTABLE_ENV,AGENT_HARNESS_HOST_NODE_RUN_AS_NODE_ENV}from"../binary/host-node-environment.js";export const AGENT_HARNESS_PRIVATE_PRODUCT_ROOT_ENV="AGENT_HARNESS_PRIVATE_PRODUCT_ROOT";const d=Symbol.for("codebuddy.ai/agent-harness/embedded-agent-server");export function installEmbeddedAgentServerLoader(e){const n=globalThis;if(n[d]!==void 0)throw new Error("Embedded Agent server already installed");n[d]=e}o(installEmbeddedAgentServerLoader,"installEmbeddedAgentServerLoader");export async function loadAgentServerModule(){process.env.CODEBUDDY_DISABLE_FILE_LOGS??="0",process.env.CODEBUDDY_DISABLE_SHELL_SNAPSHOT??="0";const e=globalThis[d];return typeof e=="function"?e():import("#agent-harness-codebuddy/server")}o(loadAgentServerModule,"loadAgentServerModule");export function isAgentHarnessStandaloneBinary(){return typeof AGENT_HARNESS_PACKAGE_TYPE=="string"&&AGENT_HARNESS_PACKAGE_TYPE==="binary"}o(isAgentHarnessStandaloneBinary,"isAgentHarnessStandaloneBinary");export function installEmbeddedCodeBuddyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]!==void 0)throw new Error("Embedded CodeBuddy loader is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER]=e}o(installEmbeddedCodeBuddyLoader,"installEmbeddedCodeBuddyLoader");export function installEmbeddedNodePtyLoader(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]!==void 0)throw new Error("Embedded node-pty loader is already installed");n[AGENT_HARNESS_EMBEDDED_NODE_PTY_LOADER]=e}o(installEmbeddedNodePtyLoader,"installEmbeddedNodePtyLoader");export function installEmbeddedCodeBuddyRuntime(e){const n=globalThis;if(n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]!==void 0)throw new Error("Embedded CodeBuddy runtime is already installed");n[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME]=Object.freeze({...e})}o(installEmbeddedCodeBuddyRuntime,"installEmbeddedCodeBuddyRuntime");export function resolveEmbeddedCodeBuddyLoader(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_LOADER];return typeof e=="function"?e:void 0}o(resolveEmbeddedCodeBuddyLoader,"resolveEmbeddedCodeBuddyLoader");export function resolveEmbeddedCodeBuddyRuntime(){const e=globalThis[AGENT_HARNESS_EMBEDDED_CODEBUDDY_RUNTIME];if(!(typeof e!="object"||e===null||!("binPath"in e)||typeof e.binPath!="string"||!("packageJsonPath"in e)||typeof e.packageJsonPath!="string"||!("version"in e)||typeof e.version!="string"))return e}o(resolveEmbeddedCodeBuddyRuntime,"resolveEmbeddedCodeBuddyRuntime");export function createPrivateRuntimeLaunchSpec({args:e=[],currentExecutable:n=process.execPath,entryPath:t,nodeRuntime:a,role:s,standaloneBinary:i=isAgentHarnessStandaloneBinary()}){const r=i;return Object.freeze({args:Object.freeze(r?[s,...e]:[t,...e]),command:r?n:a.executable})}o(createPrivateRuntimeLaunchSpec,"createPrivateRuntimeLaunchSpec");
|
|
@@ -3,6 +3,7 @@ import type { QueryOptions } from '#agent-harness-codebuddy/server';
|
|
|
3
3
|
import { AgentServer } from './agent-server.js';
|
|
4
4
|
import { SessionConfigStore } from './config-store.js';
|
|
5
5
|
import { type SessionOpenOptions, SessionRuntime } from './runtime.js';
|
|
6
|
+
import { type SessionConfigDefaults } from './server-config.js';
|
|
6
7
|
export interface AgentBackendOptions<R = never> {
|
|
7
8
|
/** Host application headers forwarded through the Agent query boundary. */
|
|
8
9
|
readonly headers?: Readonly<Record<string, string>>;
|
|
@@ -12,6 +13,8 @@ export interface AgentBackendOptions<R = never> {
|
|
|
12
13
|
readonly resolveOptions?: (options: SessionOpenOptions) => Effect.Effect<QueryOptions, unknown, R>;
|
|
13
14
|
/** Ensure the process-owned sandbox center is ready for this run's Account. */
|
|
14
15
|
readonly prepareSandboxCenter?: (options: QueryOptions, signal: AbortSignal) => Promise<void>;
|
|
16
|
+
/** Host-owned effective defaults used only to project ACP selectors. */
|
|
17
|
+
readonly resolveConfigDefaults?: (options: SessionOpenOptions) => Effect.Effect<SessionConfigDefaults, unknown, R>;
|
|
15
18
|
}
|
|
16
19
|
export declare function workspaceQueryOptions(open: SessionOpenOptions): Effect.Effect<QueryOptions, Error>;
|
|
17
20
|
/** Shared Agent service, scoped session instances. No child process or prewarm protocol. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var se=Object.defineProperty;var n=(p,l)=>se(p,"name",{value:l,configurable:!0});import{randomUUID as ie}from"node:crypto";import{isAbsolute as oe}from"node:path";import{Effect as d,Layer as re}from"effect";import{abortReason as ae}from"../internal/async.js";import{promptMetadata as ce}from"../protocol/prompt.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as X,AgentHarnessInvalidParamsError as K,AgentHarnessJsonRpcError as V}from"../server/errors.js";import{readSessionTree as de}from"../subagent/history.js";import{AgentServer as le}from"./agent-server.js";import{SessionConfigStore as ue}from"./config-store.js";import{replayCodecs as F,replaySession as fe}from"./replay.js";import{SessionRuntime as W,SessionRuntimeClosedError as G}from"./runtime.js";import{ServerSessionConfig as Y}from"./server-config.js";import{ServerSessionEvents as ge}from"./server-events.js";import{serverCanUseTool as we}from"./server-interactions.js";import{ServerSessionMcp as pe}from"./server-mcp.js";import{serverPromptInput as he}from"./server-prompt.js";export function workspaceQueryOptions(p){if(!p.workspace?.product)return d.fail(new Error("In-process Agent backend requires a resolved workspace Product"));const l=p.workspace.product;return d.succeed({product:{...l,skills:l.skills??[],commands:l.commands??[]},persistSession:!0,tools:{type:"preset",preset:"default"},freezeToolsDuringRun:!0,...process.platform==="win32"?{usePty:!1}:{},settings:{enabledPlugins:{...p.pluginSettings.enabledPlugins}}})}n(workspaceQueryOptions,"workspaceQueryOptions");const Z={compact:!0,configReload:!0,promptSteer:!0},q={session:{additionalDirectories:{},delete:{},fork:{},mcp:{acp:{},http:{},stdio:{}},prompt:{image:{},embeddedContext:{}}}};export function AgentBackend(p={}){return re.effect(W,d.gen(function*(){const l=yield*le,x=yield*ue,T=yield*d.context();yield*d.tryPromise({try:F,catch:n(r=>r,"catch")});const k=new AbortController;return yield*d.addFinalizer(()=>d.sync(()=>k.abort(new G))),W.of({profile:{capabilities:q,supports:Z,checkpoints:p.checkpoints===!0},prepare:d.void,readCatalog:n((r,a)=>d.gen(function*(){const c=yield*(p.resolveOptions??workspaceQueryOptions)(a).pipe(d.provideContext(T)),I=yield*d.tryPromise({try:n(()=>Y.create(c,a.workspace?.sessionModelConfigOption,a.clientCapabilities),"try"),catch:n(b=>b,"catch")}),o=a.cwd??c.cwd??process.cwd();I.restore(yield*x.read({sessionId:r,cwd:o}));const{fs:w,settings:_,product:h,agents:f,agent:m}={...c,...I.queryOptions};return yield*d.tryPromise({try:n(async()=>{const b=AbortSignal.any([k.signal,a.signal]),S=await l.readSessionCatalog({cwd:o,fs:w,settings:_,product:h,agents:f,agent:m,signal:b});return b.throwIfAborted(),(await F()).projectAgentEvent({type:"agent_event",session_id:r,event:{type:"catalog",data:S}})},"try"),catch:n(b=>b,"catch")})}),"readCatalog"),rewind:n((r,a)=>d.tryPromise({try:n(async()=>{const c=await l.readSession(r.sessionId,a);if(!c)throw new K("Session history was not found");const{selectRewindMessage:I}=await F();let o;try{o=I(c,r._meta)}catch(w){throw w instanceof Error&&"code"in w&&["invalid_history","invalid_boundary","cursor_not_found"].includes(String(w.code))?new K(w.message):w}return await l.rewind(r.sessionId,{...a,to:o}),{}},"try"),catch:n(c=>c,"catch")}),"rewind"),open:n(r=>d.acquireRelease(d.gen(function*(){let a=yield*(p.resolveOptions??workspaceQueryOptions)(r).pipe(d.provideContext(T));const c=yield*d.tryPromise({try:n(()=>Y.create(a,r.workspace?.sessionModelConfigOption,r.clientCapabilities),"try"),catch:n(e=>e,"catch")}),I=AbortSignal.any([r.signal,k.signal]);I.throwIfAborted();let o,w={},_,h,f,m=-1,b=0,S,E,D,H,U=!1;const z=n((e,t,s)=>d.runPromise(x.write({sessionId:e,cwd:t},s.selections())),"saveConfig"),M=n(e=>{U||D||(U=!0,H=e,E?.abort(e),h?.fail(e),r.onFailure(e))},"fail"),L=new pe(r.callbacks,()=>E?.signal??k.signal),y=n(()=>{if(D||k.signal.aborted)throw new G;if(U)throw H},"assertOpen"),O=n(e=>{if(y(),e!==o)throw new Error("Session does not belong to this execution")},"assertSession"),P=n((e,t)=>{if(y(),S)throw new Error("Session is already running");const s=new AbortController;E=s;const i=AbortSignal.any([s.signal,k.signal,...e?.signal?[e.signal]:[]]),u=n(()=>s.abort(ae(i)),"abort");i.addEventListener("abort",u,{once:!0}),i.aborted&&u();const A=Promise.resolve().then(()=>(i.throwIfAborted(),t(s))).finally(()=>{i.removeEventListener("abort",u),S=void 0,E=void 0});return S=A,A},"run"),N=n(()=>D??=(async()=>{E?.abort(new G);try{if(!o)return;await l.interrupt(o),await S?.catch(()=>{})}finally{try{o&&await l.close(o)}finally{_?.unsubscribe(),await L.close()}}})(),"dispose"),$=a.canUseTool??we(r,()=>({id:o,meta:h?.meta??{}}),(e,t)=>h?.interaction(e,t)??Promise.resolve()),ee=n(async({signal:e})=>{e.throwIfAborted(),y();const t=f;if(!t||!r.callbacks.refreshAuthentication)throw new Error("Authentication required");const s=await r.callbacks.refreshAuthentication({accountId:t.account.id,generation:t.generation},{signal:e});if(e.throwIfAborted(),y(),!f||s.account.id!==t.account.id||m>s.generation)throw new Error("Authentication changed during refresh");return f=s,m=s.generation,{accessToken:s.credential.accessToken,method:s.credential.type}},"refreshAuthentication"),Q=n(()=>({...a,...w,...c.queryOptions,includePartialMessages:!0,...!r.clientCapabilities.elicitation?.form&&!a.canUseTool?{disallowedTools:[...new Set([...a.disallowedTools??[],"AskUserQuestion"])]}:{},headers:{...p.headers,...f?.credential.domain?{"X-Domain":f.credential.domain}:{},...f?.account.organization?.id?{"X-Tenant-Id":f.account.organization.id}:{},...a.headers},auth:f?{accessToken:f.credential.accessToken,method:f.credential.type,...r.callbacks.refreshAuthentication?{refresh:ee}:{}}:m<0?a.auth:void 0,account:f?{uid:f.account.id,...f.account.organization?.id?{enterpriseId:f.account.organization.id}:{}}:m<0?a.account:void 0,canUseTool:$}),"runOptions"),j=n((e,t,s)=>{const i=Promise.withResolvers();let u=!1;return P(s,async g=>{const C=Q();await p.prepareSandboxCenter?.(C,g.signal),g.signal.throwIfAborted();const v=l.query(o,e,{...C,_meta:t,abortController:g});c.lockAgent(),v.catch(()=>{});try{const R=h.begin(v.runId);u=!0,i.resolve({_meta:{"codebuddy.ai/requestId":v.runId}}),await R;const te=await h.waitForCompletion(v.runId);await v.catch(ne=>{if(te.stopReason!=="error")throw ne}),y()}catch(R){throw g.abort(R),await l.interrupt(o),await v.catch(()=>{}),R}}).catch(g=>{u?M(g):i.reject(g)}),i.promise},"acceptQuery"),B=n((e,t,s)=>{if(y(),s?.signal?.throwIfAborted(),o)throw new Error("Execution is already bound to a session");if(!oe(t.cwd))throw new Error("Session cwd must be an absolute path");const i=L.configure(t.mcpServers??[],a.mcpServers),u=new ge(e,async g=>{try{await r.callbacks.sessionUpdate(g)}catch(C){throw M(C),C}},c,g=>z(e,t.cwd,g)),A=l.subscribe(e,g=>u.accept(g));o=e,w={cwd:t.cwd,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:a.additionalDirectories,mcpServers:i},h=u,_=A,_.closed.then(g=>{g.reason==="failed"&&M(g.error)}).catch(()=>{})},"bindSession"),J=n(e=>P(e,async t=>{const{cwd:s,fs:i,settings:u,product:A,agents:g,agent:C}=Q(),v=await l.readSessionCatalog({cwd:s,fs:i,settings:u,product:A,agents:g,agent:C,signal:t.signal});t.signal.throwIfAborted(),y(),await h.accept({type:"agent_event",session_id:o,origin:{},event:{type:"catalog",data:v}})}),"publishCatalog");return{capabilities:{...q,session:{...q.session,mcp:{...q.session.mcp,acp:{}}}},supports:Z,dispose:N,newSession:n(async(e,t)=>{if(y(),o)throw new Error("Execution is already bound to a session");t?.signal?.throwIfAborted(),c.initializeBlank();const s=ie();return await l.createSession(s,{cwd:e.cwd,signal:t?.signal?AbortSignal.any([I,t.signal]):I}),await z(s,e.cwd,c),B(s,e,t),await h.restoreUsage([]),await J(t),{sessionId:o,configOptions:c.snapshot()}},"newSession"),resumeSession:n(async(e,t)=>{if(y(),o){if(O(e.sessionId),w.cwd!==e.cwd)throw new Error("Session cwd cannot change");if(S)throw new Error("Session is already running")}o||c.restore(await d.runPromise(x.read({sessionId:e.sessionId,cwd:e.cwd})));const s=e.replayFrom?await P(t,i=>fe(l.readSession,e,{signal:i.signal,onUpdate:r.callbacks.sessionUpdate,config:c})):{};if(o)w.additionalDirectories=e.additionalDirectories?[...e.additionalDirectories]:w.additionalDirectories;else{const i=await P(t,u=>de(l.readSession,e,u.signal));B(e.sessionId,e,t),await h.restoreUsage(i.find(u=>u.snapshot.sessionId===e.sessionId)?.snapshot.history??[],i)}return await J(t),c.lockAgent(),{...s,configOptions:c.snapshot()}},"resumeSession"),prompt:n(async(e,t)=>{O(e.sessionId);const s=await he(e),i=ce(e._meta);if(i?.mode==="steer"){const u=await l.steer(e.sessionId,s,{expectedRunId:i.expectedRequestId,signal:t?.signal});if(!u.steered)throw new V(X.invalidRequest,u.reason==="stale"?"Active query does not match expectedRequestId":"Session has no active query accepting steer");return{_meta:{"codebuddy.ai/requestId":u.runId}}}return j(s,e._meta,t)},"prompt"),compactSession:n(async(e,t)=>(O(e.sessionId),j({type:"compact"},e._meta,t)),"compactSession"),cancelSession:n(async e=>{O(e.sessionId),E?.abort(),await l.interrupt(e.sessionId),await S?.catch(()=>{})},"cancelSession"),closeSession:n(async e=>(O(e.sessionId),await N(),{}),"closeSession"),setAuthentication:n(async e=>e.generation<m?{applied:!1}:(f=e,m=e.generation,{applied:!0}),"setAuthentication"),clearAuthentication:n(async e=>e.generation<m?{applied:!1}:(f=void 0,m=e.generation,{applied:!0}),"clearAuthentication"),refreshUserConfig:n(async(e,t)=>{y(),t?.signal?.throwIfAborted();const s=++b,i=await d.runPromise((p.resolveOptions??workspaceQueryOptions)(r).pipe(d.provideContext(T)),{signal:t?.signal});y(),t?.signal?.throwIfAborted(),s===b&&(o&&l.reload(o,{settings:i.settings??{},agents:i.agents??{}}),a={...a,settings:i.settings,agents:i.agents})},"refreshUserConfig"),setSessionConfigOption:n(async(e,t)=>{if(O(e.sessionId),t?.signal?.throwIfAborted(),S)throw new V(X.invalidParams,"Cannot change Agent configuration during a prompt");const s=c.copy();s.set(e),await z(e.sessionId,w.cwd,s),c.replace(s);const i=c.snapshot();return await h.configuration(i),{configOptions:i}},"setSessionConfigOption")}}),a=>d.promise(()=>a.dispose())),"open")})}))}n(AgentBackend,"AgentBackend");
|
|
1
|
+
var re=Object.defineProperty;var n=(w,a)=>re(w,"name",{value:a,configurable:!0});import{randomUUID as ae}from"node:crypto";import{isAbsolute as ce}from"node:path";import{Effect as i,Layer as de}from"effect";import{abortReason as le}from"../internal/async.js";import{promptMetadata as ue}from"../protocol/prompt.js";import{AGENT_HARNESS_JSON_RPC_ERROR_CODES as V,AgentHarnessInvalidParamsError as W,AgentHarnessJsonRpcError as Y}from"../server/errors.js";import{readSessionTree as fe}from"../subagent/history.js";import{AgentServer as ge}from"./agent-server.js";import{SessionConfigStore as we}from"./config-store.js";import{replayCodecs as H,replaySession as pe}from"./replay.js";import{SessionRuntime as Z,SessionRuntimeClosedError as L}from"./runtime.js";import{ServerSessionConfig as $}from"./server-config.js";import{ServerSessionEvents as he}from"./server-events.js";import{serverCanUseTool as ye}from"./server-interactions.js";import{ServerSessionMcp as me}from"./server-mcp.js";import{serverPromptInput as be}from"./server-prompt.js";export function workspaceQueryOptions(w){if(!w.workspace?.product)return i.fail(new Error("In-process Agent backend requires a resolved workspace Product"));const a=w.workspace.product;return i.succeed({product:{...a,skills:a.skills??[],commands:a.commands??[]},persistSession:!0,tools:{type:"preset",preset:"default"},freezeToolsDuringRun:!0,...process.platform==="win32"?{usePty:!1}:{},settings:{enabledPlugins:{...w.pluginSettings.enabledPlugins}}})}n(workspaceQueryOptions,"workspaceQueryOptions");const ee={compact:!0,configReload:!0,promptSteer:!0},T={session:{additionalDirectories:{},delete:{},fork:{},mcp:{acp:{},http:{},stdio:{}},prompt:{image:{},embeddedContext:{}}}};export function AgentBackend(w={}){return de.effect(Z,i.gen(function*(){const a=yield*ge,U=yield*we,R=yield*i.context();yield*i.tryPromise({try:H,catch:n(r=>r,"catch")});const E=new AbortController;return yield*i.addFinalizer(()=>i.sync(()=>E.abort(new L))),Z.of({profile:{capabilities:T,supports:ee,checkpoints:w.checkpoints===!0},prepare:i.void,readCatalog:n((r,h)=>i.gen(function*(){const c=yield*(w.resolveOptions??workspaceQueryOptions)(h).pipe(i.provideContext(R)),A=yield*i.tryPromise({try:n(()=>$.create(c,h.workspace?.sessionModelConfigOption,h.clientCapabilities),"try"),catch:n(p=>p,"catch")}),d=h.cwd??c.cwd??process.cwd();A.restore(yield*U.read({sessionId:r,cwd:d}));const b=yield*i.tryPromise(()=>a.readSession(r,{cwd:d,signal:h.signal}));b?.mainAgent&&A.update({agent:b.mainAgent});const{fs:l,settings:v,product:_,agents:y,agent:u}={...c,...A.queryOptions};return yield*i.tryPromise({try:n(async()=>{const p=AbortSignal.any([E.signal,h.signal]),x=await a.readSessionCatalog({cwd:d,fs:l,settings:v,product:_,agents:y,agent:u,signal:p});return p.throwIfAborted(),(await H()).projectAgentEvent({type:"agent_event",session_id:r,event:{type:"catalog",data:x}})},"try"),catch:n(p=>p,"catch")})}),"readCatalog"),rewind:n((r,h)=>i.tryPromise({try:n(async()=>{const c=await a.readSession(r.sessionId,h);if(!c)throw new W("Session history was not found");const{selectRewindMessage:A}=await H();let d;try{d=A(c,r._meta)}catch(b){throw b instanceof Error&&"code"in b&&["invalid_history","invalid_boundary","cursor_not_found"].includes(String(b.code))?new W(b.message):b}return await a.rewind(r.sessionId,{...h,to:d}),{}},"try"),catch:n(c=>c,"catch")}),"rewind"),open:n(r=>i.acquireRelease(i.gen(function*(){const h=yield*i.all([(w.resolveOptions??workspaceQueryOptions)(r).pipe(i.provideContext(R)),w.resolveConfigDefaults?w.resolveConfigDefaults(r).pipe(i.provideContext(R)):i.succeed({})],{concurrency:"unbounded"});let c=h[0];const A=h[1],d=yield*i.tryPromise({try:n(()=>$.create(c,r.workspace?.sessionModelConfigOption,r.clientCapabilities,A),"try"),catch:n(e=>e,"catch")}),b=AbortSignal.any([r.signal,E.signal]);b.throwIfAborted();let l,v={},_,y,u,p=-1,x=0,C,P,z,N,M=!1;const Q=n((e,t,s)=>i.runPromise(U.write({sessionId:e,cwd:t},s.selections())),"saveConfig"),F=n(e=>{M||z||(M=!0,N=e,P?.abort(e),y?.fail(e),r.onFailure(e))},"fail"),G=new me(r.callbacks,()=>P?.signal??E.signal),S=n(()=>{if(z||E.signal.aborted)throw new L;if(M)throw N},"assertOpen"),O=n(e=>{if(S(),e!==l)throw new Error("Session does not belong to this execution")},"assertSession"),D=n((e,t)=>{if(S(),C)throw new Error("Session is already running");const s=new AbortController;P=s;const o=AbortSignal.any([s.signal,E.signal,...e?.signal?[e.signal]:[]]),f=n(()=>s.abort(le(o)),"abort");o.addEventListener("abort",f,{once:!0}),o.aborted&&f();const m=Promise.resolve().then(()=>(o.throwIfAborted(),t(s))).finally(()=>{o.removeEventListener("abort",f),C=void 0,P=void 0});return C=m,m},"run"),j=n(()=>z??=(async()=>{P?.abort(new L);try{if(!l)return;await a.interrupt(l),await C?.catch(()=>{})}finally{try{l&&await a.close(l)}finally{_?.unsubscribe(),await G.close()}}})(),"dispose"),te=c.canUseTool??ye(r,()=>({id:l,meta:y?.meta??{}}),(e,t)=>y?.interaction(e,t)??Promise.resolve()),ne=n(async({signal:e})=>{e.throwIfAborted(),S();const t=u;if(!t||!r.callbacks.refreshAuthentication)throw new Error("Authentication required");const s=await r.callbacks.refreshAuthentication({accountId:t.account.id,generation:t.generation},{signal:e});if(e.throwIfAborted(),S(),!u||s.account.id!==t.account.id||p>s.generation)throw new Error("Authentication changed during refresh");return u=s,p=s.generation,{accessToken:s.credential.accessToken,method:s.credential.type}},"refreshAuthentication"),se=n(async e=>{if(!w.resolveConfigDefaults)return;const t=await i.runPromise(w.resolveConfigDefaults({...r,signal:e}).pipe(i.provideContext(R)),{signal:e});S(),e.throwIfAborted(),d.refreshDefaults(t)&&y&&await y.configuration(d.snapshot())},"refreshDefaults"),B=n(()=>({...c,...v,...d.queryOptions,includePartialMessages:!0,...!r.clientCapabilities.elicitation?.form&&!c.canUseTool?{disallowedTools:[...new Set([...c.disallowedTools??[],"AskUserQuestion"])]}:{},headers:{...w.headers,...u?.credential.domain?{"X-Domain":u.credential.domain}:{},...u?.account.organization?.id?{"X-Tenant-Id":u.account.organization.id}:{},...c.headers},auth:u?{accessToken:u.credential.accessToken,method:u.credential.type,...r.callbacks.refreshAuthentication?{refresh:ne}:{}}:p<0?c.auth:void 0,account:u?{uid:u.account.id,...u.account.organization?.id?{enterpriseId:u.account.organization.id}:{}}:p<0?c.account:void 0,canUseTool:te}),"runOptions"),J=n((e,t,s)=>{const o=Promise.withResolvers();let f=!1;return D(s,async g=>{const k=B();await w.prepareSandboxCenter?.(k,g.signal),g.signal.throwIfAborted();const I=a.query(l,e,{...k,_meta:t,abortController:g});d.lockAgent(),I.catch(()=>{});try{const q=y.begin(I.runId);f=!0,o.resolve({_meta:{"codebuddy.ai/requestId":I.runId}}),await q;const oe=await y.waitForCompletion(I.runId);await I.catch(ie=>{if(oe.stopReason!=="error")throw ie}),S()}catch(q){throw g.abort(q),await a.interrupt(l),await I.catch(()=>{}),q}}).catch(g=>{f?F(g):o.reject(g)}),o.promise},"acceptQuery"),X=n((e,t,s)=>{if(S(),s?.signal?.throwIfAborted(),l)throw new Error("Execution is already bound to a session");if(!ce(t.cwd))throw new Error("Session cwd must be an absolute path");const o=G.configure(t.mcpServers??[],c.mcpServers),f=new he(e,async g=>{try{await r.callbacks.sessionUpdate(g)}catch(k){throw F(k),k}},d,g=>Q(e,t.cwd,g)),m=a.subscribe(e,g=>f.accept(g),{format:"acp-v2"});l=e,v={cwd:t.cwd,additionalDirectories:t.additionalDirectories?[...t.additionalDirectories]:c.additionalDirectories,mcpServers:o},y=f,_=m,_.closed.then(g=>{g.reason==="failed"&&F(g.error)}).catch(()=>{})},"bindSession"),K=n(e=>D(e,async t=>{const{cwd:s,fs:o,settings:f,product:m,agents:g,agent:k}=B(),I=await a.readSessionCatalog({cwd:s,fs:o,settings:f,product:m,agents:g,agent:k,signal:t.signal});t.signal.throwIfAborted(),S(),await y.catalog(I)}),"publishCatalog");return{capabilities:{...T,session:{...T.session,mcp:{...T.session.mcp,acp:{}}}},supports:ee,dispose:j,newSession:n(async(e,t)=>{if(S(),l)throw new Error("Execution is already bound to a session");t?.signal?.throwIfAborted(),d.initializeBlank();const s=ae();return await a.createSession(s,{cwd:e.cwd,signal:t?.signal?AbortSignal.any([b,t.signal]):b}),X(s,e,t),await y.restoreUsage([]),await K(t),{sessionId:l,configOptions:d.snapshot()}},"newSession"),resumeSession:n(async(e,t)=>{if(S(),l){if(O(e.sessionId),v.cwd!==e.cwd)throw new Error("Session cwd cannot change");if(C)throw new Error("Session is already running")}l||d.restore(await i.runPromise(U.read({sessionId:e.sessionId,cwd:e.cwd})));const s=e.replayFrom?await D(t,o=>pe(a.readSession,e,{signal:o.signal,onUpdate:r.callbacks.sessionUpdate,config:d})):{};if(l)v={...v,additionalDirectories:[...e.additionalDirectories??[]],mcpServers:G.configure(e.mcpServers??[],c.mcpServers)};else{const o=await D(t,m=>fe(a.readSession,e,m.signal)),f=o.find(m=>m.snapshot.sessionId===e.sessionId)?.snapshot;f?.mainAgent&&d.update({agent:f.mainAgent}),X(e.sessionId,e,t),await y.restoreUsage(o.find(m=>m.snapshot.sessionId===e.sessionId)?.snapshot.history??[],o)}return await K(t),d.lockAgent(),{...s,configOptions:d.snapshot()}},"resumeSession"),prompt:n(async(e,t)=>{O(e.sessionId);const s=await be(e),o=ue(e._meta);if(o?.mode==="steer"){const f=await a.steer(e.sessionId,s,{expectedRunId:o.expectedRequestId,signal:t?.signal});if(!f.steered)throw new Y(V.invalidRequest,f.reason==="stale"?"Active query does not match expectedRequestId":"Session has no active query accepting steer");return{_meta:{"codebuddy.ai/requestId":f.runId}}}return J(s,e._meta,t)},"prompt"),compactSession:n(async(e,t)=>(O(e.sessionId),J({type:"compact"},e._meta,t)),"compactSession"),cancelSession:n(async e=>{O(e.sessionId),P?.abort(),await a.interrupt(e.sessionId),await C?.catch(()=>{})},"cancelSession"),closeSession:n(async e=>(O(e.sessionId),await j(),{}),"closeSession"),setAuthentication:n(async e=>e.generation<p?{applied:!1}:(u=e,p=e.generation,{applied:!0}),"setAuthentication"),clearAuthentication:n(async e=>e.generation<p?{applied:!1}:(u=void 0,p=e.generation,{applied:!0}),"clearAuthentication"),refreshUserConfig:n(async(e,t)=>{S(),t?.signal?.throwIfAborted();const s=++x,o=await i.runPromise((w.resolveOptions??workspaceQueryOptions)(r).pipe(i.provideContext(R)),{signal:t?.signal});S(),t?.signal?.throwIfAborted(),s===x&&(l&&a.reload(l,{settings:o.settings??{},agents:o.agents??{}}),c={...c,settings:o.settings,agents:o.agents},await se(t?.signal??r.signal))},"refreshUserConfig"),setSessionConfigOption:n(async(e,t)=>{if(O(e.sessionId),t?.signal?.throwIfAborted(),C)throw new Y(V.invalidParams,"Cannot change Agent configuration during a prompt");const s=d.copy();s.set(e),await Q(e.sessionId,v.cwd,s),d.replace(s);const o=d.snapshot();return await y.configuration(o),{configOptions:o}},"setSessionConfigOption")}}),h=>i.promise(()=>h.dispose())),"open")})}))}n(AgentBackend,"AgentBackend");
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { ConfigReader } from '../config/types.js';
|
|
2
|
+
import type { SessionConfigDefaults } from './server-config.js';
|
|
3
|
+
/** Read the Host's effective workspace setting for ACP display, without adding an Agent execution override. */
|
|
4
|
+
export declare function readSessionConfigDefaults(config: ConfigReader, cwd: string, signal: AbortSignal): Promise<SessionConfigDefaults>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var d=Object.defineProperty;var a=(e,t)=>d(e,"name",{value:t,configurable:!0});import{isRecord as b}from"../internal/guards.js";export async function readSessionConfigDefaults(e,t,o){o.throwIfAborted();let n;try{n=await e.readConfig({cwd:t},{signal:o})}catch{return o.throwIfAborted(),{readFailed:!0}}o.throwIfAborted();const r=n.config.sandbox;return b(r)&&typeof r.enabled=="boolean"?{sandboxEnabled:r.enabled}:{}}a(readSessionConfigDefaults,"readSessionConfigDefaults");
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Context, Effect, Layer, Schema } from 'effect';
|
|
2
2
|
declare const document: Schema.Struct<{
|
|
3
|
-
readonly version: Schema.Literal<
|
|
3
|
+
readonly version: Schema.Literal<2>;
|
|
4
4
|
readonly values: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Boolean]>>;
|
|
5
5
|
}>;
|
|
6
6
|
export type SessionConfigValues = typeof document.Type['values'];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var p=Object.defineProperty;var r=(c,s)=>p(c,"name",{value:s,configurable:!0});import{createHash as v,randomUUID as g}from"node:crypto";import{mkdir as x,open as N,readFile as f,rename as S,rm as O}from"node:fs/promises";import{join as l,resolve as U}from"node:path";import{Context as E,Effect as i,Layer as y,Schema as t}from"effect";const w=t.Record(t.String,t.Union([t.String,t.Boolean])),$=t.Struct({version:t.Literal(1),values:w}),h=t.Struct({version:t.Literal(2),values:w});function a(c){return v("sha256").update(JSON.stringify([U(c.cwd),c.sessionId])).digest("hex")}r(a,"keyOf");export class SessionConfigStore extends E.Service()("@genie/agent-harness/session/SessionConfigStore"){static{r(this,"SessionConfigStore")}static layer(s){return y.succeed(SessionConfigStore,SessionConfigStore.of({read:r(o=>i.tryPromise({try:r(async()=>{try{const e=t.decodeUnknownSync(t.Union([$,h]))(JSON.parse(await f(l(s,`${a(o)}.selections.json`),"utf8").catch(n=>{if(n.code!=="ENOENT")throw n;return f(l(s,`${a(o)}.json`),"utf8")})));if(e.version===1){const n={...e.values};return n.sandbox===!1&&delete n.sandbox,n}return e.values}catch(e){if(e.code==="ENOENT")return{};throw e}},"try"),catch:r(e=>e,"catch")}),"read"),write:r((o,e)=>i.tryPromise({try:r(async()=>{const n=JSON.stringify(t.decodeUnknownSync(h)({version:2,values:e}));await x(s,{recursive:!0,mode:448});const m=l(s,`${a(o)}.selections.json`),d=`${m}.${g()}.tmp`;try{const u=await N(d,"wx",384);try{await u.writeFile(n),await u.sync()}finally{await u.close()}await S(d,m)}finally{await O(d,{force:!0})}},"try"),catch:r(n=>n,"catch")}),"write")}))}static{this.memory=y.sync(SessionConfigStore,()=>{const s=new Map;return SessionConfigStore.of({read:r(o=>i.sync(()=>structuredClone(s.get(a(o))??{})),"read"),write:r((o,e)=>i.sync(()=>{s.set(a(o),structuredClone(e))}),"write")})})}}
|
package/lib/session/replay.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { AcpV2ResumeSessionRequest, AcpV2UpdateSessionNotification } from '
|
|
|
4
4
|
import { type SessionHistoryReader, type SubagentHistory } from '../subagent/history.js';
|
|
5
5
|
import { SessionConfigStore } from './config-store.js';
|
|
6
6
|
import type { SessionOpenOptions } from './runtime.js';
|
|
7
|
-
import { ServerSessionConfig } from './server-config.js';
|
|
7
|
+
import { ServerSessionConfig, type SessionConfigDefaults } from './server-config.js';
|
|
8
8
|
import { type AgentHarnessResumeSessionRequest, type AgentHarnessResumeSessionResponse } from './turn.js';
|
|
9
9
|
export interface SessionReplayOptions {
|
|
10
10
|
readonly signal: AbortSignal;
|
|
@@ -37,7 +37,7 @@ export interface SessionReplayProjection {
|
|
|
37
37
|
readonly response: AgentHarnessResumeSessionResponse;
|
|
38
38
|
}
|
|
39
39
|
/** Pure projection seam; the implementation reuses agent-cli's ACP codecs. */
|
|
40
|
-
export type SessionReplayProjector = (snapshot: SessionSnapshot, replayFrom: AgentHarnessResumeSessionRequest['replayFrom'], readFile?: (path: string) => Promise<Uint8Array
|
|
40
|
+
export type SessionReplayProjector = (snapshot: SessionSnapshot, replayFrom: AgentHarnessResumeSessionRequest['replayFrom'], readFile?: (path: string) => Promise<Uint8Array>, contextSize?: (modelId?: string) => number | undefined) => Promise<SessionReplayProjection>;
|
|
41
41
|
export type AgentItemProjector = (sessionId: string, item: SessionSnapshot['history'][number]) => Promise<AcpV2UpdateSessionNotification[]>;
|
|
42
42
|
export type AgentEventProjector = (frame: import('#agent-harness-codebuddy/server').AgentEvent) => Promise<AcpV2UpdateSessionNotification[]>;
|
|
43
43
|
export declare const replayCodecs: () => Promise<typeof import('#agent-harness-components/session-replay')>;
|
|
@@ -48,6 +48,6 @@ declare const SessionReplay_base: Context.ServiceClass<SessionReplay, "@genie/ag
|
|
|
48
48
|
}>;
|
|
49
49
|
/** Reads transcripts and Host selections; uses the admitted Product without acquiring an executor. */
|
|
50
50
|
export declare class SessionReplay extends SessionReplay_base {
|
|
51
|
-
static layer(options?: ReadSessionOptions, readFile?: (path: string) => Promise<Uint8Array>): Layer.Layer<SessionReplay, never, SessionConfigStore>;
|
|
51
|
+
static layer(options?: ReadSessionOptions, readFile?: (path: string) => Promise<Uint8Array>, readDefaults?: (cwd: string, signal: AbortSignal) => Promise<SessionConfigDefaults>): Layer.Layer<SessionReplay, never, SessionConfigStore>;
|
|
52
52
|
}
|
|
53
53
|
export {};
|
package/lib/session/replay.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var r=(l,o)=>h(l,"name",{value:o,configurable:!0});import{Context as b,Effect as y,Layer as x}from"effect";import{isRecord as A}from"../internal/guards.js";import{loadAgentServerModule as I}from"../runtime/private-runtime-role.js";import{AgentHarnessInvalidParamsError as p}from"../server/errors.js";import{createSubagentHistory as v,readSessionTree as C}from"../subagent/history.js";import{SessionConfigStore as R}from"./config-store.js";import{ServerSessionConfig as S}from"./server-config.js";import{turnReplayValidationError as U}from"./turn.js";let _;export const replayCodecs=r(()=>_??=import("#agent-harness-components/session-replay"),"replayCodecs");export async function replaySession(l,o,s,g={},w){s.signal.throwIfAborted();const t=U(o.replayFrom);if(t)throw new p(t);const e=await l(o.sessionId,{...g,cwd:o.cwd,signal:s.signal,includeSubagents:!0});if(!e)throw new p(`Session '${o.sessionId}' was not found in the requested cwd`);if(s.signal.throwIfAborted(),e.mainAgent&&s.config?.update({agent:e.mainAgent}),o.replayFrom==null)return{};const{projectSessionReplay:d,createSessionUsage:f}=await replayCodecs(),c=s.config?f(e.sessionId,e.history,await C(l,o,s.signal,g,e)):void 0,i=o.replayFrom,u=await d(e,i,w,n=>s.config?.contextSize(n)).catch(n=>{throw n instanceof Error&&"code"in n&&typeof n.code=="string"&&["invalid_history","invalid_replay","cursor_not_found"].includes(n.code)?new p(n.message):n});for(const n of u.events){s.signal.throwIfAborted();const a=n.update._meta;if(A(a)){const m=a["codebuddy.ai/requestId"];typeof m=="string"&&a["codebuddy.ai/rootRequestId"]===void 0&&(n.update._meta={...a,"codebuddy.ai/rootRequestId":m})}await s.onUpdate(n)}if(s.config){const n=c?.context,a=s.config.contextSize();s.signal.throwIfAborted(),n&&a!==void 0&&await s.onUpdate({sessionId:e.sessionId,update:{sessionUpdate:"usage_update",used:n.used,size:a,...c?.cost?{cost:c.cost}:{}}})}return s.signal.throwIfAborted(),u.response}r(replaySession,"replaySession");export class SessionReplay extends b.Service()("@genie/agent-harness/session/SessionReplay"){static{r(this,"SessionReplay")}static layer(o={},s,g){return x.effect(SessionReplay,y.gen(function*(){const w=yield*R;return SessionReplay.of({subagents:v(async(t,e)=>(await I()).readSession(t,e),async(...t)=>(await replayCodecs()).projectSessionReplay(...t),o,s,async(t,e,d,f)=>{const c=await S.create({product:t.workspace?.product});c.restore(await y.runPromise(w.read(t)));const i=(await replayCodecs()).createSessionUsage(t.sessionId,[],d).snapshot(e),u=c.contextSize(i.context?.modelId);return f.throwIfAborted(),i.context&&u!==void 0?{sessionId:e,update:{sessionUpdate:"usage_update",used:i.context.used,size:u,...i.cost?{cost:i.cost}:{}}}:void 0}),resume:r((t,e)=>y.tryPromise({try:r(async()=>{const d=await I(),[f,c]=await Promise.all([g?.(t.cwd,e.signal),y.runPromise(w.read({sessionId:t.sessionId,cwd:t.cwd}))]),i=await S.create({product:e.workspace?.product},e.workspace?.sessionModelConfigOption,e.clientCapabilities,f);return i.restore(c),{...await replaySession(d.readSession,t,{...e,config:i},o,s),configOptions:i.snapshot()}},"try"),catch:r(d=>d,"catch")}),"resume")})}))}}
|
|
@@ -5,6 +5,10 @@ import type { WorkspaceSessionModelConfigOption } from '../runtime/product-manag
|
|
|
5
5
|
import type { SessionConfigValues } from './config-store.js';
|
|
6
6
|
export type SessionConfigProjector = (options: QueryOptions, catalog?: WorkspaceSessionModelConfigOption) => SessionConfigOption[];
|
|
7
7
|
type ConfigQueryOptions = Pick<QueryOptions, 'model' | 'permissionMode' | 'thinking' | 'effort' | 'contextWindow' | 'agent' | 'multitask' | 'sandboxEnabled'>;
|
|
8
|
+
export interface SessionConfigDefaults {
|
|
9
|
+
readonly sandboxEnabled?: boolean;
|
|
10
|
+
readonly readFailed?: boolean;
|
|
11
|
+
}
|
|
8
12
|
/** Session selections are validated against the same projection sent to clients. */
|
|
9
13
|
export declare class ServerSessionConfig {
|
|
10
14
|
private readonly options;
|
|
@@ -13,10 +17,13 @@ export declare class ServerSessionConfig {
|
|
|
13
17
|
private readonly restoreProject;
|
|
14
18
|
private readonly projectContextSize;
|
|
15
19
|
private readonly values;
|
|
20
|
+
/** Explicit Host choices and subsequent Agent configuration transitions survive resume. */
|
|
21
|
+
private explicitSelections;
|
|
16
22
|
private agentLocked;
|
|
17
23
|
private modelExplicit;
|
|
18
24
|
private constructor();
|
|
19
|
-
static create(options: QueryOptions, catalog?: WorkspaceSessionModelConfigOption, capabilities?: AcpV2ClientCapabilities): Promise<ServerSessionConfig>;
|
|
25
|
+
static create(options: QueryOptions, catalog?: WorkspaceSessionModelConfigOption, capabilities?: AcpV2ClientCapabilities, defaults?: SessionConfigDefaults): Promise<ServerSessionConfig>;
|
|
26
|
+
refreshDefaults(defaults: SessionConfigDefaults): boolean;
|
|
20
27
|
get queryOptions(): ConfigQueryOptions;
|
|
21
28
|
copy(): ServerSessionConfig;
|
|
22
29
|
replace(config: ServerSessionConfig): void;
|
|
@@ -24,10 +31,12 @@ export declare class ServerSessionConfig {
|
|
|
24
31
|
restore(values: SessionConfigValues): void;
|
|
25
32
|
snapshot(): SessionConfigOption[];
|
|
26
33
|
contextSize(modelId?: string): number | undefined;
|
|
27
|
-
update(values: Pick<ConfigQueryOptions, 'permissionMode' | 'agent' | 'multitask'
|
|
34
|
+
update(values: Pick<ConfigQueryOptions, 'permissionMode' | 'agent' | 'multitask'>, rememberChanges?: boolean): boolean;
|
|
28
35
|
lockAgent(): void;
|
|
29
36
|
initializeBlank(): void;
|
|
30
37
|
set(params: AcpV2SetSessionConfigOptionRequest): void;
|
|
38
|
+
private reconcileSelections;
|
|
39
|
+
private remember;
|
|
31
40
|
private apply;
|
|
32
41
|
}
|
|
33
42
|
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var h=Object.defineProperty;var r=(c,e)=>h(c,"name",{value:e,configurable:!0});import{AgentHarnessInvalidParamsError as l}from"../server/errors.js";function d(c){return c?.type==="select"&&Array.isArray(c.options)}r(d,"isSelect");export class ServerSessionConfig{static{r(this,"ServerSessionConfig")}constructor(e,i,n,s,t){this.options=e,this.catalog=i,this.project=n,this.restoreProject=s,this.projectContextSize=t,this.explicitSelections={},this.agentLocked=!1;const o=e.model??i?.currentValue;if(this.modelExplicit=e.model!==void 0,o&&i&&!i.options.some(a=>a.value===o))throw new l("Agent model is outside the admitted Harness catalog");this.values={model:o,permissionMode:e.permissionMode??e.settings?.permissions?.defaultMode??"default",...e.thinking?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.contextWindow!==void 0?{contextWindow:e.contextWindow}:{},...e.agent!==void 0?{agent:e.agent}:{},...e.multitask!==void 0?{multitask:e.multitask}:{},...e.sandboxEnabled!==void 0?{sandboxEnabled:e.sandboxEnabled}:{}}}static async create(e,i,n={},s={}){const{createSessionConfigProjector:t,projectSessionContextSize:o}=await import("#agent-harness-components/session-config"),a=s.sandboxEnabled===void 0?{...e}:{...e,settings:{...e.settings,sandbox:{...e.settings?.sandbox,enabled:s.sandboxEnabled}}},u=await t(a,{_meta:{"codebuddy.ai":{mainAgentSupport:!0}}});return new ServerSessionConfig(a,i,await t(a,n),u,o)}refreshDefaults(e){if(e.readFailed)return!1;const i=JSON.stringify(this.snapshot());return this.options.settings={...this.options.settings,sandbox:{...this.options.settings?.sandbox,enabled:e.sandboxEnabled}},i!==JSON.stringify(this.snapshot())}get queryOptions(){return{...this.values}}copy(){const e=new ServerSessionConfig(this.options,this.catalog,this.project,this.restoreProject,this.projectContextSize);return e.replace(this),e}replace(e){for(const i of Object.keys(this.values))delete this.values[i];Object.assign(this.values,structuredClone(e.values)),this.explicitSelections=structuredClone(e.explicitSelections),this.agentLocked=e.agentLocked,this.modelExplicit=e.modelExplicit}selections(){return structuredClone(this.explicitSelections)}restore(e){const i=e.model,n=typeof i=="string"&&this.catalog!==void 0&&!this.catalog.options.some(s=>s.value===i);for(const s of["multitask","sandbox","agent","model","mode","context_window","thought_level"]){if(n&&["model","context_window","thought_level"].includes(s))continue;const t=e[s];if(t!==void 0)try{this.apply(typeof t=="boolean"?{sessionId:"",configId:s,type:"boolean",value:t}:{sessionId:"",configId:s,type:"id",value:t},this.restoreProject),this.remember(s)}catch(o){if(!(o instanceof l))throw o}}}snapshot(){return this.project({...this.options,...this.values},this.catalog)}contextSize(e){return this.projectContextSize({...this.options,...this.values},e)}update(e,i=!1){const n=Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0));if(Object.entries(n).every(([t,o])=>this.values[t]===o))return!1;const s=Object.keys(n).filter(t=>this.values[t]!==n[t]);if(Object.assign(this.values,n),i)for(const t of s)this.remember(t==="permissionMode"?"mode":t);return!0}lockAgent(){this.agentLocked=!0}initializeBlank(){const e=this.snapshot().find(i=>i.configId==="agent");d(e)&&!this.values.agent&&this.apply({sessionId:"",configId:"agent",type:"id",value:e.currentValue},this.project)}set(e){this.apply(e,this.project),this.remember(e.configId)}reconcileSelections(){const e=new Map(this.restoreProject({...this.options,...this.values},this.catalog).map(i=>[i.configId,i.currentValue]));for(const[i,n]of Object.entries(this.explicitSelections))e.get(i)!==n&&delete this.explicitSelections[i]}remember(e){this.reconcileSelections();const i=this.restoreProject({...this.options,...this.values},this.catalog).find(n=>n.configId===e);(typeof i?.currentValue=="string"||typeof i?.currentValue=="boolean")&&(this.explicitSelections[e]=i.currentValue)}apply(e,i){const n=i({...this.options,...this.values},this.catalog).find(t=>t.configId===e.configId);if(!n)throw new l(`Unknown Agent configuration option: ${e.configId}`);if(n.type==="boolean"){if(e.type!=="boolean"||typeof e.value!="boolean")throw new l("Agent boolean configuration requires a boolean value");if(e.configId==="multitask"){this.values.multitask=e.value;return}if(e.configId==="sandbox"){this.values.sandboxEnabled=e.value;return}throw new l(`Unsupported Agent configuration option: ${e.configId}`)}if(e.type!=="id"||typeof e.value!="string")throw new l("Agent select configuration requires an option id");if(!(d(n)?n.options.flatMap(t=>"options"in t?t.options:[t]):[]).some(t=>t.value===e.value))throw new l(`Unknown Agent configuration option: ${e.configId}=${e.value}`);switch(e.configId){case"agent":if(this.agentLocked)throw new l("Main Agent can only change in a blank session");if(e.value==="minimal"&&this.values.multitask)throw new l("Disable Multitask before selecting Minimal");if(this.values.agent=e.value,!this.modelExplicit){const t=this.options.product?.agents?.find(o=>o.name===e.value)?.declaredModel;t&&(!this.catalog||this.catalog.options.some(o=>o.value===t))&&(this.values.model=t)}e.value==="minimal"&&this.values.permissionMode==="plan"&&(this.values.permissionMode="default");return;case"mode":this.values.permissionMode=e.value;return;case"model":{this.modelExplicit=!0,this.values.model=e.value,(this.values.thinking!==void 0||this.values.effort!==void 0)&&(this.values.thinking={type:"adaptive"},this.values.effort=null);const t=this.snapshot().find(o=>o.configId==="context_window");this.values.contextWindow!=null&&(!d(t)||!t.options.some(o=>"value"in o&&o.value===String(this.values.contextWindow)))&&(this.values.contextWindow=null);return}case"thought_level":this.values.thinking={type:e.value==="disabled"?"disabled":"adaptive"},this.values.effort=e.value==="disabled"||e.value==="enabled"?null:e.value;return;case"context_window":this.values.contextWindow=Number(e.value);return;default:throw new l(`Unsupported Agent configuration option: ${e.configId}`)}}}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AgentEvent, FormattedSessionEvent, QueryResult } from '#agent-harness-codebuddy/server';
|
|
2
2
|
import type { AcpV2SetSessionConfigOptionResponse, AcpV2UpdateSessionNotification } from '../protocol/acp-v2.js';
|
|
3
3
|
import { type SessionUsageHistory } from './replay.js';
|
|
4
4
|
import type { ServerSessionConfig } from './server-config.js';
|
|
5
|
-
/**
|
|
5
|
+
/** Host policy and delivery for Server-projected ACP; no stream-json conversion. */
|
|
6
6
|
export declare class ServerSessionEvents {
|
|
7
7
|
private readonly sessionId;
|
|
8
8
|
private readonly deliver;
|
|
9
9
|
private readonly config?;
|
|
10
|
-
private readonly
|
|
10
|
+
private readonly persistConfig?;
|
|
11
11
|
private requestId?;
|
|
12
12
|
private delivery;
|
|
13
13
|
private completion?;
|
|
@@ -15,12 +15,10 @@ export declare class ServerSessionEvents {
|
|
|
15
15
|
private accounting?;
|
|
16
16
|
private foregroundError?;
|
|
17
17
|
private resultError?;
|
|
18
|
-
|
|
19
|
-
constructor(sessionId: string, deliver: (update: AcpV2UpdateSessionNotification) => Promise<void>, config?: ServerSessionConfig | undefined, persistConfiguration?: ((candidate: ServerSessionConfig) => Promise<void>) | undefined);
|
|
18
|
+
constructor(sessionId: string, deliver: (update: AcpV2UpdateSessionNotification) => Promise<void>, config?: ServerSessionConfig | undefined, persistConfig?: ((config: ServerSessionConfig) => Promise<void>) | undefined);
|
|
20
19
|
get meta(): Record<string, string>;
|
|
20
|
+
private configurationObserved;
|
|
21
21
|
private readonly interactions;
|
|
22
|
-
private readonly toolStreams;
|
|
23
|
-
private readonly toolParsers;
|
|
24
22
|
private readonly pendingTools;
|
|
25
23
|
interaction(waiting: boolean, meta: Record<string, unknown>): Promise<void>;
|
|
26
24
|
begin(requestId: string): Promise<void>;
|
|
@@ -33,6 +31,10 @@ export declare class ServerSessionEvents {
|
|
|
33
31
|
private send;
|
|
34
32
|
private finishTools;
|
|
35
33
|
private usage;
|
|
36
|
-
|
|
34
|
+
/** Catalog reads are host operations outside the Agent subscription. */
|
|
35
|
+
catalog(data: Extract<AgentEvent['event'], {
|
|
36
|
+
type: 'catalog';
|
|
37
|
+
}>['data']): Promise<void>;
|
|
38
|
+
accept(frame: FormattedSessionEvent<'acp-v2'>): Promise<void>;
|
|
37
39
|
private completeToolInvocation;
|
|
38
40
|
}
|