@scitrera/aether-client 0.1.60 → 0.2.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/kv.ts","../src/checkpoint.ts","../src/tunnel.ts","../src/authority-cache.ts","../src/client.ts","../src/admin.ts","../src/topics.ts","../src/agents.ts","../src/tasks.ts","../src/users.ts","../src/orchestrator.ts","../src/workflow.ts","../src/metrics.ts","../src/metrics-builder.ts","../src/bridge.ts","../src/proxy.ts"],"sourcesContent":["/**\n * @scitrera/aether-client - TypeScript SDK for the Aether distributed control plane.\n *\n * Aether is a distributed control plane for routing structured messages,\n * tracking tasks, and managing connection lifecycles. This SDK provides\n * TypeScript/JavaScript clients for agents, users, and other principal types.\n *\n * Key architectural principle: The connection itself IS the distributed lock\n * AND the heartbeat. When the gRPC stream closes, the identity lock is\n * immediately released. No separate heartbeat API exists.\n *\n * Principal Types:\n * - {@link AgentClient}: For persistent agents with workspace/impl/spec identity\n * - {@link TaskClient}: For task connections (unique or non-unique)\n * - {@link UserClient}: For user connections with userId/windowId identity\n * - {@link OrchestratorClient}: For orchestrating agent/task lifecycle\n * - {@link WorkflowEngineClient}: For event processing (singleton)\n * - {@link MetricsBridgeClient}: For telemetry collection (singleton, receive-only)\n * - {@link AetherClient}: Base client for custom principal types\n *\n * @example\n * ```typescript\n * import { AgentClient, MessageType } from \"@scitrera/aether-client\";\n *\n * const agent = new AgentClient({\n * address: \"localhost:50051\",\n * workspace: \"production\",\n * implementation: \"my-agent\",\n * specifier: \"instance-1\",\n * });\n *\n * agent.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * agent.onConnect((ack) => {\n * console.log(`Connected with session ${ack.sessionId}`);\n * });\n *\n * await agent.connect();\n * ```\n *\n * @packageDocumentation\n */\n\n// Client classes\nexport { AetherClient } from \"./client.js\";\nexport type { AetherClientOptions } from \"./client.js\";\n\nexport { AdminClient } from \"./admin.js\";\nexport type {\n AdminQueryResponse,\n AdminQueryResponseHandler,\n AdminTimeoutOptions,\n CreateTokenOptions,\n RevokeTokenOptions,\n ListTokensOptions,\n CreateACLRuleOptions,\n DeleteACLRuleOptions,\n ListACLRulesOptions,\n ListWorkspacesOptions,\n CreateWorkspaceOptions,\n UpdateWorkspaceOptions,\n DeleteWorkspaceOptions,\n ListAgentsOptions,\n GetAgentOptions,\n ListConnectionsOptions,\n DisconnectSessionOptions,\n} from \"./admin.js\";\n\nexport { AgentClient } from \"./agents.js\";\nexport type { AgentClientOptions, CreateTaskOptions } from \"./agents.js\";\n\nexport { TaskClient } from \"./tasks.js\";\nexport type { TaskClientOptions } from \"./tasks.js\";\n\nexport { UserClient } from \"./users.js\";\nexport type { UserClientOptions } from \"./users.js\";\n\nexport { OrchestratorClient, BaseOrchestrator } from \"./orchestrator.js\";\nexport type { OrchestratorClientOptions, BaseOrchestratorOptions } from \"./orchestrator.js\";\n\nexport { WorkflowEngineClient } from \"./workflow.js\";\nexport type { WorkflowEngineClientOptions } from \"./workflow.js\";\n\nexport { MetricsBridgeClient } from \"./metrics.js\";\nexport type { MetricsBridgeClientOptions } from \"./metrics.js\";\n\nexport { MetricBuilder, newMetric } from \"./metrics-builder.js\";\nexport type { Metric, MetricEntry } from \"./metrics-builder.js\";\n\nexport { BridgeClient } from \"./bridge.js\";\nexport type { BridgeClientOptions } from \"./bridge.js\";\n\nexport { KVClient } from \"./kv.js\";\n\nexport { CheckpointClient } from \"./checkpoint.js\";\nexport type {\n CheckpointSaveOptions,\n CheckpointLoadOptions,\n CheckpointDeleteOptions,\n CheckpointListOptions,\n} from \"./checkpoint.js\";\n\n// Types and enums\nexport {\n PrincipalType,\n MessageType,\n KVScope,\n TaskAssignmentMode,\n SignalType,\n} from \"./types.js\";\n\nexport type {\n // Message structures\n IncomingMessage,\n OutgoingMessage,\n ConfigSnapshot,\n Signal,\n ErrorResponse,\n ConnectionAck,\n TaskAssignment,\n // KV types\n KVResponse,\n KVGetOptions,\n KVPutOptions,\n KVListOptions,\n KVDeleteOptions,\n KVIncrementOptions,\n KVDecrementOptions,\n KVIncrementIfOptions,\n KVDecrementIfOptions,\n // Checkpoint types\n CheckpointResponse,\n // Progress types\n ProgressUpdate,\n ProgressStep,\n ReportProgressOptions,\n // Task management types\n TaskInfo,\n TaskQueryResponse,\n TaskOperationResponse,\n TaskQueryOptions,\n TaskQueryResponseHandler,\n TaskOperationResponseHandler,\n // Workspace/Agent/ACL/Workflow response types\n WorkspaceResponse,\n AgentResponse,\n ACLResponse,\n AuthorityGrantPrincipalRef,\n AuthorityGrantResourceScope,\n AuthorityGrantInfo,\n AuthorityGrantResponse,\n AuthorityGrantRevocation,\n WorkflowResponse,\n // Token management types\n TokenInfo,\n TokenResponse,\n // Callback types\n MessageHandler,\n ConfigHandler,\n SignalHandler,\n ErrorHandler,\n KVResponseHandler,\n TaskAssignmentHandler,\n CheckpointResponseHandler,\n ProgressHandler,\n ConnectHandler,\n DisconnectHandler,\n ReconnectingHandler,\n WorkspaceResponseHandler,\n AgentResponseHandler,\n ACLResponseHandler,\n AuthorityGrantResponseHandler,\n AuthorityGrantRevocationHandler,\n WorkflowResponseHandler,\n TokenResponseHandler,\n AuditSubmitResponse,\n AuditSubmitResponseHandler,\n // Configuration types\n TLSOptions,\n ConnectionOptions,\n Credentials,\n} from \"./types.js\";\n\n// Credential helpers\nexport {\n withAPIKey,\n withToken,\n withTaskToken,\n withTenant,\n} from \"./types.js\";\n\n// Error classes\nexport {\n AetherError,\n ConnectionError,\n ConnectionClosedError,\n ReconnectionError,\n AuthenticationError,\n PermissionDeniedError,\n DuplicateIdentityError,\n TimeoutError,\n InvalidArgumentError,\n NotFoundError,\n UnimplementedError,\n MessageError,\n KVOperationError,\n CheckpointError,\n // Error classification utilities\n isRecoverable,\n isConnectionError,\n isTimeoutError,\n} from \"./errors.js\";\n\n// Proxy HTTP support\nexport { proxyHttp, AetherFetchTransport, ProxyErrorKind, ProxyHttpError } from \"./proxy.js\";\nexport type { ProxyHttpResponse, ProxyHttpOptions, ProxyError } from \"./proxy.js\";\n\n// Tunnel support\nexport { tunnelDial, TunnelClosedError } from \"./tunnel.js\";\nexport type { TunnelProtocol, TunnelDialOptions, TunnelStream } from \"./tunnel.js\";\n\n// Authority-grant cache (Phase 4 of the ACL/grant cleanup)\nexport { AuthorityGrantCache } from \"./authority-cache.js\";\nexport type { AuthorityGrantCacheOptions, AuthorityCacheClient } from \"./authority-cache.js\";\n\n// Topic construction helpers\nexport {\n agentTopic,\n globalAgentsTopic,\n uniqueTaskTopic,\n taskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n globalUsersTopic,\n eventTopic,\n eventWildcardTopic,\n metricTopic,\n metricWildcardTopic,\n progressTopic,\n bridgeTopic,\n // Topic prefix constants\n TOPIC_PREFIX_AGENT,\n TOPIC_PREFIX_UNIQUE_TASK,\n TOPIC_PREFIX_TASK,\n TOPIC_PREFIX_TASK_BROADCAST,\n TOPIC_PREFIX_USER,\n TOPIC_PREFIX_USER_WORKSPACE,\n TOPIC_PREFIX_GLOBAL_AGENTS,\n TOPIC_PREFIX_GLOBAL_USERS,\n TOPIC_PREFIX_EVENT,\n TOPIC_PREFIX_METRIC,\n TOPIC_PREFIX_PROGRESS,\n TOPIC_PREFIX_BRIDGE,\n} from \"./topics.js\";\n","/**\n * Type definitions for the Aether TypeScript SDK.\n *\n * This module provides comprehensive type definitions for principal types,\n * message types, KV scopes, topic construction, and callback handlers.\n * These types mirror the protobuf definitions in api/proto/aether.proto\n * and match the patterns established by the Go and Python SDKs.\n *\n * @module types\n */\n\n// =============================================================================\n// Principal Types\n// =============================================================================\n\n/**\n * Principal types supported by the Aether gateway.\n *\n * Each principal type has different routing rules and permissions:\n * - Agent: Persistent entity with workspace/impl/spec identity\n * - UniqueTask: Named task with persistent identity\n * - NonUniqueTask: Ephemeral task with server-assigned ID\n * - User: Browser/session-based identity with userId/windowId\n * - WorkflowEngine: Event processor (singleton per gateway)\n * - MetricsBridge: Telemetry collector (singleton per gateway)\n * - Orchestrator: Compute provisioner for lazy-loading agents/tasks\n */\nexport enum PrincipalType {\n Agent = \"agent\",\n UniqueTask = \"unique_task\",\n NonUniqueTask = \"non_unique_task\",\n\tUser = \"user\",\n\tWorkflowEngine = \"workflow_engine\",\n\tMetricsBridge = \"metrics_bridge\",\n\tOrchestrator = \"orchestrator\",\n\tService = \"service\",\n}\n\n// =============================================================================\n// Message Types\n// =============================================================================\n\n/**\n * Message types for the Aether messaging protocol.\n *\n * - Chat: Conversational messages between principals\n * - Control: Control/command messages for state changes\n * - ToolCall: Tool invocation messages\n * - Event: Broadcast events processed by WorkflowEngine\n * - Metric: Telemetry data collected by MetricsBridge\n */\nexport enum MessageType {\n Unspecified = 0,\n Chat = 1,\n Control = 2,\n ToolCall = 3,\n Event = 4,\n Metric = 5,\n Opaque = 6,\n}\n\n// =============================================================================\n// KV Scope\n// =============================================================================\n\n/**\n * Scopes for KV store operations.\n *\n * - Global: Accessible to all entities across all workspaces\n * - Workspace: Accessible within a specific workspace\n * - User: Accessible to a specific user across all workspaces\n * - UserWorkspace: Accessible to a specific user within a specific workspace\n * - GlobalExclusive: Global scope with exclusive (single-owner) write semantics\n * - WorkspaceExclusive: Workspace scope with exclusive (single-owner) write semantics\n * - UserShared: User scope shared across all agent implementations\n * - UserWorkspaceShared: User-workspace scope shared across all agent implementations\n */\nexport enum KVScope {\n Unspecified = 0,\n Global = 1,\n Workspace = 2,\n User = 3,\n UserWorkspace = 4,\n GlobalExclusive = 5,\n WorkspaceExclusive = 6,\n UserShared = 7,\n UserWorkspaceShared = 8,\n}\n\n// =============================================================================\n// Task Assignment Mode\n// =============================================================================\n\n/**\n * Modes for task assignment.\n *\n * - SelfAssign: Caller self-assigns the task (default)\n * - Targeted: Task is assigned to a specific agent (may trigger orchestration)\n * - Pool: Any matching worker can claim the task\n */\nexport enum TaskAssignmentMode {\n SelfAssign = 0,\n Targeted = 1,\n Pool = 2,\n}\n\n// =============================================================================\n// Signal Types\n// =============================================================================\n\n/**\n * Signal types from the gateway.\n */\nexport enum SignalType {\n ForceDisconnect = 0,\n GracefulDisconnect = 1,\n}\n\n// =============================================================================\n// Message Structures\n// =============================================================================\n\n/**\n * An incoming message received from the Aether gateway.\n */\nexport interface IncomingMessage {\n /** The topic from which the message originated (identifies the sender). */\n readonly sourceTopic: string;\n /** The raw message payload. */\n readonly payload: Uint8Array;\n /** The type of the message (Chat, Control, ToolCall, Event, Metric). */\n readonly messageType?: number;\n /** Local timestamp when the message was received. */\n readonly receivedAt: Date;\n}\n\n/**\n * An outgoing message to send through the Aether gateway.\n */\nexport interface OutgoingMessage {\n /** The destination topic string. */\n targetTopic: string;\n /** The message payload (bytes). */\n payload: Uint8Array;\n /** The type of message. Defaults to Chat. */\n messageType?: MessageType;\n}\n\n/**\n * A configuration snapshot received upon connection.\n * Contains KV store data for the client's workspace.\n */\nexport interface ConfigSnapshot {\n /** Workspace-scoped key-value pairs (opaque bytes; decode with msgpack/TextDecoder as needed). */\n readonly kv: Record<string, Uint8Array>;\n /** Global-scoped key-value pairs (opaque bytes; decode with msgpack/TextDecoder as needed). */\n readonly globalKv: Record<string, Uint8Array>;\n /** Workspace-exclusive-scoped key-value pairs (opaque bytes). */\n readonly workspaceExclusiveKv: Record<string, Uint8Array>;\n /** Global-exclusive-scoped key-value pairs (opaque bytes). */\n readonly globalExclusiveKv: Record<string, Uint8Array>;\n}\n\n/**\n * A signal from the gateway (e.g., force disconnect).\n */\nexport interface Signal {\n /** The signal type. */\n readonly type: SignalType;\n /** Additional context for the signal. */\n readonly reason: string;\n}\n\n/**\n * An error response from the gateway.\n */\nexport interface ErrorResponse {\n /** Error code string. */\n readonly code: string;\n /** Human-readable error message. */\n readonly message: string;\n /** Whether the client should retry this request. */\n readonly retryable: boolean;\n /** Suggested retry delay in milliseconds (0 = use default backoff). */\n readonly retryAfterMs: number;\n}\n\n/**\n * Connection acknowledgment received after successful connection.\n */\nexport interface ConnectionAck {\n /** Server-assigned session identifier. Store for session resumption. */\n readonly sessionId: string;\n /** Whether this was a resumed session. */\n readonly resumed: boolean;\n /** For non-unique tasks: the server-assigned task instance ID. Empty otherwise. */\n readonly assignedId: string;\n}\n\n/**\n * A task assignment received by orchestrators.\n */\nexport interface TaskAssignment {\n readonly taskId: string;\n readonly taskType: string;\n readonly assignedTo: string;\n readonly metadata: Record<string, string>;\n readonly assignedAt: number;\n readonly profile: string;\n readonly launchParams: Record<string, string>;\n readonly targetImplementation: string;\n readonly workspace: string;\n readonly specifier: string;\n}\n\n// =============================================================================\n// KV Types\n// =============================================================================\n\n/**\n * Response from a KV store operation.\n */\nexport interface KVResponse {\n readonly success: boolean;\n /** Retrieved value (for GET operations). */\n readonly value: Uint8Array;\n /** List of keys (for LIST operations). */\n readonly keys: string[];\n /** Key-value pairs (for LIST with values). */\n readonly kvMap: Record<string, string>;\n /** Correlation ID echoed from the request. */\n readonly requestId: string;\n /** Result of INCREMENT/DECREMENT operations. */\n readonly counterValue?: number;\n /** Whether the guarded increment/decrement was applied (INCREMENT_IF/DECREMENT_IF). */\n readonly applied?: boolean;\n}\n\n/**\n * Parameters for a KV GET operation.\n */\nexport interface KVGetOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV PUT operation.\n */\nexport interface KVPutOptions {\n key: string;\n value: Uint8Array;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** TTL in seconds (0 = no expiration). */\n ttl?: number;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV LIST operation.\n */\nexport interface KVListOptions {\n keyPrefix?: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV DELETE operation.\n */\nexport interface KVDeleteOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV INCREMENT operation.\n */\nexport interface KVIncrementOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV DECREMENT operation.\n */\nexport interface KVDecrementOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV INCREMENT_IF operation (increment only if counter is below ceiling).\n */\nexport interface KVIncrementIfOptions {\n key: string;\n /** Amount to increment. Default: 1. */\n delta?: bigint | number;\n /** Ceiling guard: increment only if the current value is strictly below this. */\n ceiling: bigint | number;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV DECREMENT_IF operation (decrement only if counter is above floor).\n */\nexport interface KVDecrementIfOptions {\n key: string;\n /** Amount to decrement. Default: 1. */\n delta?: bigint | number;\n /** Floor guard: decrement only if the current value is strictly above this. */\n floor: bigint | number;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n// =============================================================================\n// Progress Types\n// =============================================================================\n\n/**\n * A progress update received from an agent or task.\n * Delivered via the pg.{workspace} RabbitMQ stream with server-side filtering.\n */\nexport interface ProgressUpdate {\n /** The identity of the reporting agent/task (topic format). */\n readonly source: string;\n /** Task or correlation ID this progress relates to. */\n readonly taskId: string;\n /** Current state (e.g., \"running\", \"finishing\", \"idle\"). */\n readonly state: string;\n /** Completion fraction 0.0-1.0, or -1 for indeterminate. */\n readonly completion: number;\n /** Human-readable summary of current activity. */\n readonly summary: string;\n /** Structured step information for multi-step operations. */\n readonly step?: ProgressStep;\n /** Server timestamp when progress was received (Unix milliseconds). */\n readonly timestampMs: number;\n /** Workspace the progress originated from. */\n readonly workspace: string;\n /** Correlation ID from the originating request. */\n readonly requestId: string;\n /** Arbitrary metadata from the reporter. */\n readonly metadata: Record<string, string>;\n /** Target recipient identity topic (empty = broadcast). */\n readonly recipient: string;\n}\n\n/**\n * A discrete step within a multi-step progress operation.\n */\nexport interface ProgressStep {\n /** Step name/title. */\n readonly name: string;\n /** Detailed description of what this step is doing. */\n readonly detail: string;\n /** Step sequence number (1-based). */\n readonly sequence: number;\n /** Total number of steps (0 = unknown). */\n readonly totalSteps: number;\n /** Step type hint for UI rendering (e.g., \"llm_call\", \"tool_use\"). */\n readonly stepType: string;\n}\n\n/**\n * Options for reporting progress from an agent or task.\n */\nexport interface ReportProgressOptions {\n /** Task or correlation ID this progress relates to. Required. */\n taskId: string;\n /** Current state (e.g., \"running\", \"finishing\", \"idle\"). */\n state?: string;\n /** Completion fraction 0.0-1.0, or -1 for indeterminate. Default: -1. */\n completion?: number;\n /** Human-readable summary of current activity. */\n summary?: string;\n /** Step name for multi-step progress. */\n stepName?: string;\n /** Step detail description. */\n stepDetail?: string;\n /** Step sequence number (1-based). */\n stepSequence?: number;\n /** Total number of steps (0 = unknown). */\n stepTotal?: number;\n /** Step type hint for UI rendering. */\n stepType?: string;\n /** Target identity topic to receive updates (empty = broadcast). */\n recipient?: string;\n /** Correlation ID for the originating request. */\n requestId?: string;\n /** Arbitrary key-value metadata. */\n metadata?: Record<string, string>;\n}\n\n// =============================================================================\n// Checkpoint Types\n// =============================================================================\n\n/**\n * Response from a checkpoint operation.\n */\nexport interface CheckpointResponse {\n readonly success: boolean;\n readonly data: Uint8Array;\n readonly keys: string[];\n readonly error: string;\n readonly savedAt: number;\n readonly requestId: string;\n}\n\n// =============================================================================\n// Task Management Types\n// =============================================================================\n\n/**\n * Represents a task's information from the server.\n */\nexport interface TaskInfo {\n taskId: string;\n taskType: string;\n status: string;\n workspace: string;\n targetTopic: string;\n assignedTo: string;\n createdAt: number;\n startedAt: number;\n completedAt: number;\n attempt: number;\n maxAttempts: number;\n error: string;\n metadata: Record<string, string>;\n}\n\n/**\n * Response to a task query (list or get).\n */\nexport interface TaskQueryResponse {\n success: boolean;\n error: string;\n task?: TaskInfo;\n tasks: TaskInfo[];\n totalCount: number;\n /** Correlation ID echoed from the request. */\n requestId?: string;\n}\n\n/**\n * Response to a task operation (cancel or retry).\n */\nexport interface TaskOperationResponse {\n success: boolean;\n message: string;\n error: string;\n task?: TaskInfo;\n /** Correlation ID echoed from the request. */\n requestId?: string;\n}\n\n/**\n * Response to a CreateTaskRequest that carried a non-empty request_id.\n * Gives the creator the server-assigned task_id for later COMPLETE/FAIL/CANCEL.\n */\nexport interface CreateTaskResponse {\n /** Whether the task was created successfully. */\n success: boolean;\n /** Server-assigned task ID on success. */\n taskId: string;\n /** Initial task status, e.g., \"pending\", \"assigned\", \"pending_pool\". */\n status: string;\n /** Error code on failure, e.g., \"ERR_PERMISSION_DENIED\". */\n errorCode: string;\n /** Human-readable error description. */\n errorMessage: string;\n /** Echoed from the originating CreateTaskRequest for correlation. */\n requestId: string;\n /** For TARGETED tasks successfully delivered: the receiving identity string. */\n assignedTo: string;\n}\n\n// =============================================================================\n// Workspace / Agent / ACL / Workflow Response Types\n// =============================================================================\n\n/**\n * Generic workspace operation response.\n */\nexport interface WorkspaceResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly totalCount: number;\n readonly requestId?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Generic agent operation response.\n */\nexport interface AgentResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly totalCount: number;\n readonly requestId?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Generic ACL operation response.\n */\nexport interface ACLResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly requestId?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Stable principal reference attached to an authority grant.\n */\nexport interface AuthorityGrantPrincipalRef {\n readonly principalType: string;\n readonly principalId: string;\n}\n\n/**\n * Resource-specific scope entry attached to an authority grant.\n */\nexport interface AuthorityGrantResourceScope {\n readonly resourceType: string;\n readonly patterns: string[];\n}\n\n/**\n * Authority grant details returned by runtime or admin grant APIs.\n */\nexport interface AuthorityGrantInfo {\n readonly grantId: string;\n readonly rootGrantId: string;\n readonly subject?: AuthorityGrantPrincipalRef;\n readonly delegate?: AuthorityGrantPrincipalRef;\n readonly issuedBy?: AuthorityGrantPrincipalRef;\n readonly rootSubject?: AuthorityGrantPrincipalRef;\n readonly parentGrantId: string;\n readonly mayDelegate: boolean;\n readonly remainingHops: number;\n readonly workspaceScope: string[];\n readonly resourceScope: AuthorityGrantResourceScope[];\n readonly operationScope: string[];\n readonly maxAccessLevel: number;\n readonly accessLevelName: string;\n readonly audienceType: string;\n readonly audienceId: string;\n readonly validWhileAudienceActive: boolean;\n readonly expiresAt: number;\n readonly renewableUntil: number;\n readonly renewedAt: number;\n readonly revoked: boolean;\n readonly revokedAt: number;\n readonly reason: string;\n readonly metadata: Record<string, string>;\n readonly createdAt: number;\n}\n\n/**\n * Runtime authority-grant operation response.\n */\nexport interface AuthorityGrantResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly grant?: AuthorityGrantInfo;\n readonly requestId: string;\n /**\n * For LIST_MY_GRANTS / LIST_GRANTS_ON_ME / BATCH_EXCHANGE results.\n */\n readonly grants?: AuthorityGrantInfo[];\n /**\n * Total matching rows ignoring pagination (LIST_*) or count of returned\n * grants (BATCH_EXCHANGE).\n */\n readonly total?: number;\n /**\n * Server's hint to clients on how often to revalidate cached grants\n * (seconds). Zero means \"no hint\" — clients fall back to their own policy.\n */\n readonly cacheHintTtlSeconds?: number;\n}\n\n/**\n * Server-pushed AuthorityGrantRevocation event. Sent on the downstream\n * stream when a grant the connected client holds is revoked, directly or\n * via cascade from a parent revocation.\n */\nexport interface AuthorityGrantRevocation {\n readonly grantId: string;\n readonly rootGrantId: string;\n readonly reason: string;\n readonly revokedAt: number;\n readonly cascade: boolean;\n}\n\n/**\n * Workflow operation response.\n */\nexport interface WorkflowResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly data?: Uint8Array;\n readonly totalCount: number;\n readonly requestId?: string;\n}\n\n/**\n * Options for querying tasks.\n */\nexport interface TaskQueryOptions {\n workspace?: string;\n status?: string;\n taskType?: string;\n limit?: number;\n offset?: number;\n timeout?: number;\n}\n\n// =============================================================================\n// Token Management Types\n// =============================================================================\n\n/**\n * Information about an API token.\n */\nexport interface TokenInfo {\n readonly id: string;\n readonly name: string;\n readonly principalType: string;\n readonly workspacePatterns: string[];\n readonly scopes: string[];\n readonly createdBy: string;\n readonly expiresAt: number;\n readonly lastUsedAt: number;\n readonly revoked: boolean;\n readonly revokedAt: number;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\n/**\n * Response to a token operation.\n */\nexport interface TokenResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly token?: TokenInfo;\n readonly tokens: TokenInfo[];\n readonly totalCount: number;\n readonly plaintextToken: string;\n readonly createdToken?: TokenInfo;\n readonly requestId: string;\n}\n\n// =============================================================================\n// Callback Types\n// =============================================================================\n\n/** Handler for incoming messages. */\nexport type MessageHandler = (message: IncomingMessage) => void | Promise<void>;\n\n/** Handler for configuration snapshots. */\nexport type ConfigHandler = (config: ConfigSnapshot) => void | Promise<void>;\n\n/** Handler for signals from the gateway. */\nexport type SignalHandler = (signal: Signal) => void | Promise<void>;\n\n/** Handler for error responses from the gateway. */\nexport type ErrorHandler = (error: ErrorResponse) => void | Promise<void>;\n\n/** Handler for KV operation responses. */\nexport type KVResponseHandler = (response: KVResponse) => void | Promise<void>;\n\n/** Handler for task assignments (used by orchestrators). */\nexport type TaskAssignmentHandler = (assignment: TaskAssignment) => void | Promise<void>;\n\n/** Handler for checkpoint responses. */\nexport type CheckpointResponseHandler = (response: CheckpointResponse) => void | Promise<void>;\n\n/** Handler for create task responses. */\nexport type CreateTaskResponseHandler = (response: CreateTaskResponse) => void | Promise<void>;\n\n/** Handler for task query responses. */\nexport type TaskQueryResponseHandler = (response: TaskQueryResponse) => void;\n\n/** Handler for task operation responses. */\nexport type TaskOperationResponseHandler = (response: TaskOperationResponse) => void;\n\n/** Handler for workspace operation responses. */\nexport type WorkspaceResponseHandler = (response: WorkspaceResponse) => void | Promise<void>;\n\n/** Handler for agent operation responses. */\nexport type AgentResponseHandler = (response: AgentResponse) => void | Promise<void>;\n\n/** Handler for ACL operation responses. */\nexport type ACLResponseHandler = (response: ACLResponse) => void | Promise<void>;\n\n/** Handler for runtime authority-grant responses. */\nexport type AuthorityGrantResponseHandler = (response: AuthorityGrantResponse) => void | Promise<void>;\n\n/** Handler for server-pushed authority-grant revocation events. */\nexport type AuthorityGrantRevocationHandler = (event: AuthorityGrantRevocation) => void | Promise<void>;\n\n/** Handler for workflow operation responses. */\nexport type WorkflowResponseHandler = (response: WorkflowResponse) => void | Promise<void>;\n\n/** Handler for token operation responses. */\nexport type TokenResponseHandler = (response: TokenResponse) => void;\n\n// ---------------------------------------------------------------------------\n// Audit submit types\n// ---------------------------------------------------------------------------\n\n/** Response type for submitAuditEvent requests. */\nexport type AuditSubmitResponse = import(\"./proto/aether/v1/SubmitAuditEventResponse.js\").SubmitAuditEventResponse__Output;\n\n/** Handler for audit-submit responses. */\nexport type AuditSubmitResponseHandler = (response: AuditSubmitResponse) => void;\n\n/** Handler for progress updates from agents/tasks. */\nexport type ProgressHandler = (update: ProgressUpdate) => void | Promise<void>;\n\n/** Handler for successful connection. */\nexport type ConnectHandler = (ack: ConnectionAck) => void | Promise<void>;\n\n/** Handler for disconnection events. */\nexport type DisconnectHandler = (reason: string) => void | Promise<void>;\n\n/** Handler for reconnection attempts. */\nexport type ReconnectingHandler = (attempt: number) => void | Promise<void>;\n\n// =============================================================================\n// Connection Options\n// =============================================================================\n\n/**\n * TLS configuration for secure connections.\n */\nexport interface TLSOptions {\n /** PEM-encoded root CA certificates for server verification. */\n rootCerts?: Buffer;\n /** PEM-encoded client private key (for mTLS). */\n privateKey?: Buffer;\n /** PEM-encoded client certificate chain (for mTLS). */\n certChain?: Buffer;\n /** Override server hostname for certificate validation. */\n serverNameOverride?: string;\n}\n\n/**\n * Connection behavior configuration.\n */\nexport interface ConnectionOptions {\n /** Maximum number of connection attempts (0 = infinite for reconnection). Default: 5. */\n maxRetries?: number;\n /** Initial backoff delay in milliseconds. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff delay in milliseconds. Default: 30000. */\n maxBackoff?: number;\n /** Multiplier for exponential backoff. Default: 2.0. */\n backoffMultiplier?: number;\n /** Whether to automatically reconnect on connection loss. Default: true. */\n autoReconnect?: boolean;\n /** Timeout for establishing a connection in milliseconds. Default: 30000. */\n connectTimeout?: number;\n /**\n * When true, if the gateway returns a DuplicateIdentityError (ALREADY_EXISTS)\n * during connection, the client will wait briefly and retry. Useful when a\n * previous instance may still be releasing its distributed lock.\n * Default: false.\n */\n retryOnDuplicate?: boolean;\n /**\n * How long to wait (ms) before retrying after a DuplicateIdentityError.\n * Only used when retryOnDuplicate is true. Default: 5000.\n */\n retryOnDuplicateDelay?: number;\n /**\n * Maximum number of duplicate-identity retries before giving up.\n * Only used when retryOnDuplicate is true. Default: 5.\n */\n retryOnDuplicateMaxAttempts?: number;\n}\n\n/**\n * Authentication credentials passed to the gateway.\n */\nexport interface Credentials {\n [key: string]: string;\n}\n\n// =============================================================================\n// Credential Helpers\n// =============================================================================\n\n/**\n * Creates a credentials object with an API key.\n *\n * @param key - The long-lived API key for authentication\n * @returns Credentials map with the API key header\n */\nexport function withAPIKey(key: string): Credentials {\n return { \"x-api-key\": key };\n}\n\n/**\n * Creates a credentials object with a bearer token.\n *\n * @param token - The OAuth/JWT bearer token\n * @returns Credentials map with the authorization header\n */\nexport function withToken(token: string): Credentials {\n return { authorization: `Bearer ${token}` };\n}\n\n/**\n * Creates a credentials object with a task token.\n *\n * @param token - The short-lived task authentication token\n * @returns Credentials map with the token header\n */\nexport function withTaskToken(token: string): Credentials {\n return { token };\n}\n\n/**\n * Creates a credentials object with a tenant ID.\n *\n * @param tenantId - The tenant identifier\n * @returns Credentials map with the tenant ID header\n */\nexport function withTenant(tenantId: string): Credentials {\n return { \"x-tenant-id\": tenantId };\n}\n","/**\n * Error hierarchy for the Aether TypeScript SDK.\n *\n * This module provides a structured set of error classes that map to common\n * error scenarios in Aether client operations, mirroring the error hierarchies\n * in the Go SDK (errors.go) and Python SDK (exceptions.py).\n *\n * All errors extend the base AetherError class, making it easy to catch all\n * SDK-related errors with a single catch clause.\n *\n * @module errors\n */\n\n// =============================================================================\n// Base Error\n// =============================================================================\n\n/**\n * Base error class for all Aether SDK errors.\n *\n * All Aether-specific errors extend this class.\n */\nexport class AetherError extends Error {\n /** Optional error code (e.g., gRPC status code name). */\n readonly code: string;\n /** Optional additional error details. */\n readonly details: string;\n /** The underlying cause, if any. */\n readonly cause?: Error;\n\n constructor(message: string, code = \"\", details = \"\", cause?: Error) {\n const parts: string[] = [];\n if (code) parts.push(`[${code}]`);\n parts.push(message);\n if (details) parts.push(`(${details})`);\n super(parts.join(\" \"));\n\n this.name = \"AetherError\";\n this.code = code;\n this.details = details;\n this.cause = cause;\n }\n}\n\n// =============================================================================\n// Connection Errors\n// =============================================================================\n\n/**\n * Indicates a connection to the Aether gateway failed.\n *\n * This includes initial connection failures, network errors, and\n * disconnection events that cannot be automatically recovered.\n */\nexport class ConnectionError extends AetherError {\n constructor(message = \"Failed to connect to Aether gateway\", code = \"\", details = \"\", cause?: Error) {\n super(message, code, details, cause);\n this.name = \"ConnectionError\";\n }\n}\n\n/**\n * Indicates the connection was unexpectedly closed.\n *\n * This can happen due to network issues, server restarts, or\n * force disconnect signals from the server.\n */\nexport class ConnectionClosedError extends AetherError {\n /** Reason for the disconnection. */\n readonly reason: string;\n\n constructor(reason = \"\", code = \"\", cause?: Error) {\n super(\"Connection closed unexpectedly\", code, reason, cause);\n this.name = \"ConnectionClosedError\";\n this.reason = reason;\n }\n}\n\n/**\n * Indicates automatic reconnection failed after exhausting all retries.\n */\nexport class ReconnectionError extends AetherError {\n /** Number of reconnection attempts made. */\n readonly attempts: number;\n\n constructor(attempts: number, cause?: Error) {\n super(\"Failed to reconnect after maximum retries\", \"\", `attempts=${attempts}`, cause);\n this.name = \"ReconnectionError\";\n this.attempts = attempts;\n }\n}\n\n// =============================================================================\n// Authentication and Authorization Errors\n// =============================================================================\n\n/**\n * Indicates authentication failed.\n *\n * Maps to gRPC UNAUTHENTICATED status code. Authentication errors\n * are non-recoverable and will not trigger automatic reconnection.\n */\nexport class AuthenticationError extends AetherError {\n constructor(message = \"Authentication failed\", details = \"\", cause?: Error) {\n super(message, \"UNAUTHENTICATED\", details, cause);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Indicates the client lacks permission to perform an operation.\n *\n * Maps to gRPC PERMISSION_DENIED status code. Permission errors\n * are non-recoverable and will not trigger automatic reconnection.\n */\nexport class PermissionDeniedError extends AetherError {\n constructor(message = \"Permission denied\", details = \"\", cause?: Error) {\n super(message, \"PERMISSION_DENIED\", details, cause);\n this.name = \"PermissionDeniedError\";\n }\n}\n\n// =============================================================================\n// Identity Errors\n// =============================================================================\n\n/**\n * Indicates an identity is already in use.\n *\n * In Aether, each agent or unique task identity can only have one active\n * connection at a time (Connection = Lock paradigm). This error indicates\n * another client is already connected with the same identity.\n *\n * Maps to gRPC ALREADY_EXISTS status code.\n */\nexport class DuplicateIdentityError extends AetherError {\n /** The conflicting identity string. */\n readonly identity: string;\n\n constructor(identity = \"\", details = \"\", cause?: Error) {\n super(\"Identity already connected\", \"ALREADY_EXISTS\", details, cause);\n this.name = \"DuplicateIdentityError\";\n this.identity = identity;\n }\n}\n\n// =============================================================================\n// Timeout Errors\n// =============================================================================\n\n/**\n * Indicates an operation timed out.\n *\n * This can occur during connection attempts, message sends, or\n * synchronous KV/checkpoint operations.\n *\n * Maps to gRPC DEADLINE_EXCEEDED status code.\n */\nexport class TimeoutError extends AetherError {\n /** The operation that timed out. */\n readonly operation: string;\n /** The timeout duration that was exceeded, in seconds. */\n readonly timeoutSeconds: number;\n\n constructor(operation = \"\", timeoutSeconds = 0, cause?: Error) {\n const details = timeoutSeconds > 0 ? `timeout=${timeoutSeconds.toFixed(2)}s` : \"\";\n super(\"Operation timed out\", \"DEADLINE_EXCEEDED\", details, cause);\n this.name = \"TimeoutError\";\n this.operation = operation;\n this.timeoutSeconds = timeoutSeconds;\n }\n}\n\n// =============================================================================\n// Request/Response Errors\n// =============================================================================\n\n/**\n * Indicates an invalid argument was provided to an operation.\n *\n * Maps to gRPC INVALID_ARGUMENT status code.\n */\nexport class InvalidArgumentError extends AetherError {\n /** The name of the invalid argument. */\n readonly argument: string;\n\n constructor(message = \"Invalid argument\", argument = \"\", cause?: Error) {\n super(message, \"INVALID_ARGUMENT\", \"\", cause);\n this.name = \"InvalidArgumentError\";\n this.argument = argument;\n }\n}\n\n/**\n * Indicates a requested resource was not found.\n *\n * Maps to gRPC NOT_FOUND status code.\n */\nexport class NotFoundError extends AetherError {\n /** The resource that was not found. */\n readonly resource: string;\n\n constructor(resource = \"\", cause?: Error) {\n const message = resource ? `${resource} not found` : \"Resource not found\";\n super(message, \"NOT_FOUND\", \"\", cause);\n this.name = \"NotFoundError\";\n this.resource = resource;\n }\n}\n\n/**\n * Indicates an operation is not implemented by the server.\n *\n * Maps to gRPC UNIMPLEMENTED status code.\n */\nexport class UnimplementedError extends AetherError {\n /** The unimplemented operation name. */\n readonly operation: string;\n\n constructor(operation = \"\", cause?: Error) {\n const message = operation ? `Operation '${operation}' not implemented` : \"Operation not implemented\";\n super(message, \"UNIMPLEMENTED\", \"\", cause);\n this.name = \"UnimplementedError\";\n this.operation = operation;\n }\n}\n\n// =============================================================================\n// Message and Protocol Errors\n// =============================================================================\n\n/**\n * Indicates an error with message handling.\n *\n * This includes serialization errors, invalid message formats,\n * or protocol violations.\n */\nexport class MessageError extends AetherError {\n constructor(message = \"Message error\", cause?: Error) {\n super(message, \"\", \"\", cause);\n this.name = \"MessageError\";\n }\n}\n\n/**\n * Indicates a KV store operation failed.\n */\nexport class KVOperationError extends AetherError {\n /** The KV operation that failed. */\n readonly operation: string;\n /** The key involved in the failed operation. */\n readonly key: string;\n\n constructor(operation = \"\", key = \"\", cause?: Error) {\n let message = \"KV operation failed\";\n if (operation) message = `KV ${operation} operation failed`;\n if (key) message = `${message} for key '${key}'`;\n super(message, \"\", \"\", cause);\n this.name = \"KVOperationError\";\n this.operation = operation;\n this.key = key;\n }\n}\n\n/**\n * Indicates a checkpoint operation failed.\n */\nexport class CheckpointError extends AetherError {\n /** The checkpoint operation that failed. */\n readonly operation: string;\n /** The checkpoint key involved. */\n readonly key: string;\n\n constructor(operation = \"\", key = \"\", cause?: Error) {\n let message = \"Checkpoint operation failed\";\n if (operation) message = `Checkpoint ${operation} operation failed`;\n if (key) message = `${message} for key '${key}'`;\n super(message, \"\", \"\", cause);\n this.name = \"CheckpointError\";\n this.operation = operation;\n this.key = key;\n }\n}\n\n// =============================================================================\n// Error Classification\n// =============================================================================\n\n/**\n * Checks if an error is recoverable (should trigger reconnection).\n *\n * Non-recoverable errors include authentication failures, permission denials,\n * and other terminal error conditions.\n *\n * @param error - The error to check\n * @returns true if the error is recoverable, false otherwise\n */\nexport function isRecoverable(error: Error): boolean {\n if (\n error instanceof AuthenticationError ||\n error instanceof PermissionDeniedError ||\n error instanceof DuplicateIdentityError ||\n error instanceof InvalidArgumentError ||\n error instanceof NotFoundError ||\n error instanceof UnimplementedError\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Checks if an error is a connection-related error.\n *\n * @param error - The error to check\n * @returns true if the error is connection-related\n */\nexport function isConnectionError(error: Error): boolean {\n return (\n error instanceof ConnectionError ||\n error instanceof ConnectionClosedError ||\n error instanceof ReconnectionError\n );\n}\n\n/**\n * Checks if an error is a timeout-related error.\n *\n * @param error - The error to check\n * @returns true if the error is timeout-related\n */\nexport function isTimeoutError(error: Error): boolean {\n return error instanceof TimeoutError;\n}\n","/**\n * KV (key-value) store operations for the Aether TypeScript SDK.\n *\n * This module provides the KVClient class for interacting with the\n * hierarchical KV store through the Aether gateway connection.\n *\n * KV operations support four scopes:\n * - Global: Accessible to all entities across all workspaces\n * - Workspace: Accessible within a specific workspace\n * - User: Accessible to a specific user across all workspaces\n * - UserWorkspace: Accessible to a specific user within a specific workspace\n *\n * @module kv\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport type { KVGetOptions, KVPutOptions, KVDeleteOptions, KVListOptions, KVIncrementOptions, KVDecrementOptions, KVIncrementIfOptions, KVDecrementIfOptions, KVResponse } from \"./types.js\";\nimport { KVScope } from \"./types.js\";\nimport { TimeoutError } from \"./errors.js\";\n\n/** Default timeout for synchronous KV operations (5 seconds). */\nconst DEFAULT_KV_TIMEOUT = 5000;\n\n/**\n * KVClient provides KV store operations over an Aether connection.\n *\n * Access this through `client.kv()` rather than constructing directly.\n *\n * Supports both async (fire-and-forget with callback) and sync (Promise-based)\n * operation modes.\n *\n * @example\n * ```typescript\n * const kv = client.kv();\n *\n * // Async put (fire-and-forget)\n * kv.put({ key: \"my-key\", value: encode(\"my-value\"), scope: KVScope.Global });\n *\n * // Sync get (returns a Promise)\n * const response = await kv.getSync({ key: \"my-key\", scope: KVScope.Global });\n * if (response.success) {\n * console.log(\"Value:\", response.value);\n * }\n * ```\n */\nexport class KVClient {\n private _client: AetherClient;\n\n /** @internal */\n constructor(client: AetherClient) {\n this._client = client;\n }\n\n // ===========================================================================\n // Async Operations (fire-and-forget, responses via onKVResponse callback)\n // ===========================================================================\n\n /**\n * Retrieves a value from the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link getSync}.\n *\n * @param opts - Get operation options\n */\n get(opts: KVGetOptions): void {\n this._client.sendKVOperation({\n op: \"GET\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Stores a value in the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link putSync}.\n *\n * @param opts - Put operation options\n */\n put(opts: KVPutOptions): void {\n this._client.sendKVOperation({\n op: \"PUT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n value: opts.value,\n userId: opts.userId,\n workspace: opts.workspace,\n ttl: opts.ttl,\n });\n }\n\n /**\n * Removes a key from the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link deleteSync}.\n *\n * @param opts - Delete operation options\n */\n delete(opts: KVDeleteOptions): void {\n this._client.sendKVOperation({\n op: \"DELETE\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Lists keys from the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link listSync}.\n *\n * @param opts - List operation options\n */\n list(opts?: KVListOptions): void {\n this._client.sendKVOperation({\n op: \"LIST\",\n scope: opts?.scope ?? KVScope.Global,\n key: opts?.keyPrefix,\n userId: opts?.userId,\n workspace: opts?.workspace,\n });\n }\n\n // ===========================================================================\n // Synchronous Operations (Promise-based with timeout)\n // ===========================================================================\n\n /**\n * Retrieves a value from the KV store and waits for the response.\n *\n * @param opts - Get operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async getSync(opts: KVGetOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"GET\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Stores a value in the KV store and waits for the response.\n *\n * @param opts - Put operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async putSync(opts: KVPutOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"PUT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n value: opts.value,\n userId: opts.userId,\n workspace: opts.workspace,\n ttl: opts.ttl,\n requestId,\n });\n });\n }\n\n /**\n * Removes a key from the KV store and waits for the response.\n *\n * @param opts - Delete operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async deleteSync(opts: KVDeleteOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"DELETE\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Lists keys from the KV store and waits for the response.\n *\n * @param opts - List operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async listSync(opts?: KVListOptions): Promise<KVResponse> {\n const timeout = opts?.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"LIST\",\n scope: opts?.scope ?? KVScope.Global,\n key: opts?.keyPrefix,\n userId: opts?.userId,\n workspace: opts?.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Increments a counter in the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link incrementSync}.\n *\n * @param opts - Increment operation options\n */\n increment(opts: KVIncrementOptions): void {\n this._client.sendKVOperation({\n op: \"INCREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Decrements a counter in the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link decrementSync}.\n *\n * @param opts - Decrement operation options\n */\n decrement(opts: KVDecrementOptions): void {\n this._client.sendKVOperation({\n op: \"DECREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Increments a counter in the KV store and waits for the response.\n *\n * @param opts - Increment operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with counterValue set\n * @throws {@link TimeoutError} if the operation times out\n */\n async incrementSync(opts: KVIncrementOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"INCREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Decrements a counter in the KV store and waits for the response.\n *\n * @param opts - Decrement operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with counterValue set\n * @throws {@link TimeoutError} if the operation times out\n */\n async decrementSync(opts: KVDecrementOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"DECREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Increments a counter only if it is strictly below `ceiling` (async).\n *\n * The response (with `applied` and `counterValue`) is delivered via the onKVResponse callback.\n * For synchronous operation, use {@link incrementIfSync}.\n *\n * @param opts - IncrementIf operation options\n */\n incrementIf(opts: KVIncrementIfOptions): void {\n this._client.sendKVOperation({\n op: \"INCREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.ceiling),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n });\n }\n\n /**\n * Decrements a counter only if it is strictly above `floor` (async).\n *\n * The response (with `applied` and `counterValue`) is delivered via the onKVResponse callback.\n * For synchronous operation, use {@link decrementIfSync}.\n *\n * @param opts - DecrementIf operation options\n */\n decrementIf(opts: KVDecrementIfOptions): void {\n this._client.sendKVOperation({\n op: \"DECREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.floor),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n });\n }\n\n /**\n * Increments a counter only if it is strictly below `ceiling`, and waits for the response.\n *\n * @param opts - IncrementIf operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with `counterValue` and `applied` set\n * @throws {@link TimeoutError} if the operation times out\n */\n async incrementIfSync(opts: KVIncrementIfOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"INCREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.ceiling),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n requestId,\n });\n });\n }\n\n /**\n * Decrements a counter only if it is strictly above `floor`, and waits for the response.\n *\n * @param opts - DecrementIf operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with `counterValue` and `applied` set\n * @throws {@link TimeoutError} if the operation times out\n */\n async decrementIfSync(opts: KVDecrementIfOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"DECREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.floor),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n requestId,\n });\n });\n }\n\n // ===========================================================================\n // Convenience Methods\n // ===========================================================================\n\n /**\n * Retrieves a value from the global scope (async).\n *\n * @param key - The key to retrieve\n */\n getGlobal(key: string): void {\n this.get({ key, scope: KVScope.Global });\n }\n\n /**\n * Stores a value in the global scope (async).\n *\n * @param key - The key to store\n * @param value - The value to store\n */\n putGlobal(key: string, value: Uint8Array): void {\n this.put({ key, value, scope: KVScope.Global });\n }\n\n /**\n * Removes a key from the global scope (async).\n *\n * @param key - The key to delete\n */\n deleteGlobal(key: string): void {\n this.delete({ key, scope: KVScope.Global });\n }\n\n /**\n * Lists keys from the global scope (async).\n *\n * @param keyPrefix - Prefix to filter keys (empty for all)\n */\n listGlobal(keyPrefix = \"\"): void {\n this.list({ keyPrefix, scope: KVScope.Global });\n }\n\n // ===========================================================================\n // Private Helpers\n // ===========================================================================\n\n /**\n * Waits for a correlated KV response with timeout.\n * @internal\n */\n private _waitForResponse(\n requestId: string,\n timeout: number,\n sendFn: () => void,\n ): Promise<KVResponse> {\n return new Promise<KVResponse>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._client.removePendingRequest(requestId);\n reject(new TimeoutError(\"KV operation timed out\", timeout / 1000));\n }, timeout);\n\n this._client.registerPendingKVRequest(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n sendFn();\n });\n }\n}\n","/**\n * Checkpoint operations for the Aether TypeScript SDK.\n *\n * Checkpoints allow agents/tasks to persist arbitrary state that survives\n * restarts. This is separate from message offset tracking (handled\n * automatically by RabbitMQ Streams).\n *\n * @module checkpoint\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport type { CheckpointResponse } from \"./types.js\";\nimport { TimeoutError } from \"./errors.js\";\n\n/** Default timeout for synchronous checkpoint operations (5 seconds). */\nconst DEFAULT_CHECKPOINT_TIMEOUT = 5000;\n\n/**\n * Options for a checkpoint save operation.\n */\nexport interface CheckpointSaveOptions {\n /** The checkpoint data to save. */\n data: Uint8Array;\n /** Checkpoint key. Allows multiple named checkpoints per identity. Default: \"default\". */\n key?: string;\n /** TTL in seconds (-1 = server default, 0 = no expiration). */\n ttl?: number;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Options for a checkpoint load operation.\n */\nexport interface CheckpointLoadOptions {\n /** Checkpoint key to load. Default: \"default\". */\n key?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Options for a checkpoint delete operation.\n */\nexport interface CheckpointDeleteOptions {\n /** Checkpoint key to delete. Default: \"default\". */\n key?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Options for a checkpoint list operation.\n */\nexport interface CheckpointListOptions {\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * CheckpointClient provides checkpoint operations over an Aether connection.\n *\n * Access this through `client.checkpoint()` rather than constructing directly.\n *\n * Supports both async (fire-and-forget with callback) and sync (Promise-based)\n * operation modes.\n *\n * @example\n * ```typescript\n * const cp = client.checkpoint();\n *\n * // Save state\n * const encoder = new TextEncoder();\n * await cp.saveSync({ data: encoder.encode(JSON.stringify(myState)) });\n *\n * // Load state\n * const response = await cp.loadSync({});\n * if (response.success && response.data.length > 0) {\n * const state = JSON.parse(new TextDecoder().decode(response.data));\n * }\n *\n * // List checkpoints\n * const listResponse = await cp.listSync({});\n * console.log(\"Checkpoint keys:\", listResponse.keys);\n * ```\n */\nexport class CheckpointClient {\n private _client: AetherClient;\n\n /** @internal */\n constructor(client: AetherClient) {\n this._client = client;\n }\n\n // ===========================================================================\n // Async Operations (fire-and-forget, responses via onCheckpointResponse)\n // ===========================================================================\n\n /**\n * Saves checkpoint data (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n save(opts: CheckpointSaveOptions): void {\n this._client.sendCheckpointOperation({\n op: \"SAVE\",\n key: opts.key ?? \"\",\n data: opts.data,\n ttl: opts.ttl ?? -1,\n });\n }\n\n /**\n * Loads checkpoint data (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n load(opts?: CheckpointLoadOptions): void {\n this._client.sendCheckpointOperation({\n op: \"LOAD\",\n key: opts?.key ?? \"\",\n });\n }\n\n /**\n * Deletes a checkpoint (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n delete(opts?: CheckpointDeleteOptions): void {\n this._client.sendCheckpointOperation({\n op: \"DELETE\",\n key: opts?.key ?? \"\",\n });\n }\n\n /**\n * Lists checkpoint keys (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n list(): void {\n this._client.sendCheckpointOperation({\n op: \"LIST\",\n });\n }\n\n // ===========================================================================\n // Synchronous Operations (Promise-based with timeout)\n // ===========================================================================\n\n /**\n * Saves checkpoint data and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async saveSync(opts: CheckpointSaveOptions): Promise<CheckpointResponse> {\n const timeout = opts.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"SAVE\",\n key: opts.key ?? \"\",\n data: opts.data,\n ttl: opts.ttl ?? -1,\n requestId,\n });\n });\n }\n\n /**\n * Loads checkpoint data and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async loadSync(opts?: CheckpointLoadOptions): Promise<CheckpointResponse> {\n const timeout = opts?.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"LOAD\",\n key: opts?.key ?? \"\",\n requestId,\n });\n });\n }\n\n /**\n * Deletes a checkpoint and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async deleteSync(opts?: CheckpointDeleteOptions): Promise<CheckpointResponse> {\n const timeout = opts?.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"DELETE\",\n key: opts?.key ?? \"\",\n requestId,\n });\n });\n }\n\n /**\n * Lists checkpoint keys and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async listSync(opts?: CheckpointListOptions): Promise<CheckpointResponse> {\n const timeout = opts?.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"LIST\",\n requestId,\n });\n });\n }\n\n // ===========================================================================\n // Private Helpers\n // ===========================================================================\n\n private _waitForResponse(\n requestId: string,\n timeout: number,\n sendFn: () => void,\n ): Promise<CheckpointResponse> {\n return new Promise<CheckpointResponse>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._client.removePendingRequest(requestId);\n reject(new TimeoutError(\"Checkpoint operation timed out\", timeout / 1000));\n }, timeout);\n\n this._client.registerPendingCheckpointRequest(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n sendFn();\n });\n }\n}\n","/**\n * Tunnel (tunnelDial) support for the Aether TypeScript SDK.\n *\n * Provides `tunnelDial()` on AetherClient for opening a bidirectional byte-stream\n * tunnel through the Aether gRPC connection to a remote service.\n *\n * Uses the Web Streams API (ReadableStream / WritableStream) so callers work\n * in both Node ≥18 and browser environments.\n *\n * @module tunnel\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport { ConnectionError } from \"./errors.js\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst TUNNEL_CHUNK_SIZE = 256 * 1024; // 256 KiB per TunnelData frame\nconst INBOUND_ACK_THRESHOLD = 256 * 1024; // send TunnelAck after consuming this many bytes\nconst DEFAULT_INITIAL_CREDITS = 16;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Wire protocol for the tunnel. */\nexport type TunnelProtocol = \"tcp\" | \"udp\" | \"ws\" | \"websocket\";\n\n/** Options for tunnelDial(). */\nexport interface TunnelDialOptions {\n /** Hint passed to the remote sidecar (e.g. \"host:port\"). */\n remoteHint?: string;\n /** Idle timeout in ms (server-side enforcement). */\n idleTimeoutMs?: number;\n /** Byte quota (server-side enforcement). */\n maxBytes?: number;\n /** Arbitrary metadata forwarded in TunnelOpen (e.g. WS sub-protocols). */\n metadata?: Record<string, string>;\n /** Reserved for v2 reconnect/resume; ignored in v1. */\n sessionToken?: string;\n /** Initial outbound credit window (default: 16). */\n initialCredits?: number;\n /**\n * Pin the tunnel to a named terminator backend. The backend's allow-list\n * still applies — explicit naming selects which backend's ACL is consulted,\n * not whether the tunnel is allowed.\n */\n backend?: string;\n}\n\n/** Reason string from a remote TunnelClose frame. */\nexport type TunnelCloseReason = \"NORMAL\" | \"PEER_RESET\" | \"IDLE_TIMEOUT\" | \"QUOTA\" | \"ERROR\" | string;\n\n/** Error thrown when the remote side sends a TunnelClose frame. */\nexport class TunnelClosedError extends Error {\n readonly reason: TunnelCloseReason;\n readonly detail: string;\n constructor(reason: TunnelCloseReason, detail: string) {\n super(`Aether tunnel closed: ${reason}: ${detail}`);\n this.name = \"TunnelClosedError\";\n this.reason = reason;\n this.detail = detail;\n }\n}\n\n/**\n * Duplex tunnel object returned by tunnelDial().\n *\n * - `readable`: incoming bytes from the remote end.\n * - `writable`: outgoing bytes to the remote end.\n * - `close()`: send a NORMAL TunnelClose and clean up.\n */\nexport interface TunnelStream {\n /** Readable stream of inbound Uint8Array chunks from the remote end. */\n readonly readable: ReadableStream<Uint8Array>;\n /** Writable stream; write Uint8Array chunks to send to the remote end. */\n readonly writable: WritableStream<Uint8Array>;\n /** Sends TunnelClose{NORMAL} and tears down both streams. */\n close(): void;\n /** Resolves when the tunnel is fully closed (either side). */\n readonly closed: Promise<void>;\n}\n\n// =============================================================================\n// Internal per-tunnel state (registered in _pendingTunnels on the client)\n// =============================================================================\n\n/** @internal */\nexport interface TunnelInflight {\n /** Push inbound data (from downstream TunnelData) into the readable side. */\n pushData(data: Uint8Array, fin: boolean): void;\n /** Replenish outbound credits (from downstream TunnelAck). */\n addCredits(n: number): void;\n /** Signal that the remote closed the tunnel. */\n closeWithError(err: TunnelClosedError): void;\n}\n\n// =============================================================================\n// tunnelDial — main entry point\n// =============================================================================\n\n/**\n * Opens a byte-stream tunnel through the Aether connection.\n *\n * @param client - Connected AetherClient instance.\n * @param target - Target topic (e.g. \"sv::proxy::default\").\n * @param protocol - Wire protocol: \"tcp\", \"udp\", \"ws\", or \"websocket\".\n * @param options - Optional dial parameters.\n * @returns A TunnelStream with readable/writable Web Streams and a close() method.\n * @throws {@link ConnectionError} if not connected.\n */\nexport function tunnelDial(\n client: AetherClient,\n target: string,\n protocol: TunnelProtocol,\n options: TunnelDialOptions = {},\n): TunnelStream {\n if (!(client as unknown as { _connected: boolean })._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n if (!target) {\n throw new ConnectionError(\"tunnelDial: target topic is required\");\n }\n\n const tunnelId = (client as unknown as { nextRequestId(): string }).nextRequestId();\n const initialCredits = options.initialCredits ?? DEFAULT_INITIAL_CREDITS;\n\n // ---- outbound credit tracking ----\n let outCredits = initialCredits;\n // Waiters blocked on credits: each entry is a resolve fn for one credit slot.\n const creditWaiters: Array<() => void> = [];\n\n function consumeCredit(): Promise<void> {\n if (outCredits > 0) {\n outCredits--;\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => { creditWaiters.push(resolve); });\n }\n\n function addCredits(n: number): void {\n outCredits += n;\n // Wake blocked writers one credit at a time.\n while (outCredits > 0 && creditWaiters.length > 0) {\n outCredits--;\n const waiter = creditWaiters.shift()!;\n waiter();\n }\n }\n\n // ---- inbound flow control ----\n let inboundBytesConsumed = 0;\n\n // ---- closed state ----\n let closed = false;\n let closedError: TunnelClosedError | undefined;\n let closedResolve!: () => void;\n const closedPromise = new Promise<void>((resolve) => { closedResolve = resolve; });\n\n // ---- ReadableStream for inbound bytes ----\n let readableController!: ReadableStreamDefaultController<Uint8Array>;\n const readable = new ReadableStream<Uint8Array>({\n start(controller) {\n readableController = controller;\n },\n cancel() {\n doClose(\"NORMAL\");\n },\n });\n\n // ---- WritableStream for outbound bytes ----\n const writable = new WritableStream<Uint8Array>({\n async write(chunk) {\n if (closed) {\n throw closedError ?? new TunnelClosedError(\"NORMAL\", \"tunnel closed\");\n }\n let offset = 0;\n while (offset < chunk.length) {\n await consumeCredit();\n if (closed) {\n throw closedError ?? new TunnelClosedError(\"NORMAL\", \"tunnel closed\");\n }\n const end = Math.min(offset + TUNNEL_CHUNK_SIZE, chunk.length);\n const slice = chunk.slice(offset, end);\n offset = end;\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelData: {\n tunnelId,\n data: slice,\n fin: false,\n },\n });\n }\n },\n close() {\n // WritableStream closed by caller — send FIN frame then tear down.\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelData: {\n tunnelId,\n data: new Uint8Array(0),\n fin: true,\n },\n });\n doClose(\"NORMAL\");\n },\n abort(_reason) {\n doClose(\"NORMAL\");\n },\n });\n\n // ---- inflight registration ----\n const inflight: TunnelInflight = {\n pushData(data: Uint8Array, fin: boolean) {\n if (closed) return;\n if (data.length > 0) {\n readableController.enqueue(data);\n // Track consumed bytes and send TunnelAck when threshold crossed.\n inboundBytesConsumed += data.length;\n if (inboundBytesConsumed >= INBOUND_ACK_THRESHOLD) {\n const credits = Math.floor(inboundBytesConsumed / INBOUND_ACK_THRESHOLD) * 16;\n inboundBytesConsumed = inboundBytesConsumed % INBOUND_ACK_THRESHOLD;\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelAck: {\n tunnelId,\n credits,\n },\n });\n }\n }\n if (fin) {\n readableController.close();\n doClose(\"NORMAL\");\n }\n },\n addCredits,\n closeWithError(err: TunnelClosedError) {\n if (closed) return;\n closedError = err;\n try { readableController.error(err); } catch { /* already closed */ }\n // Wake all pending writers with an error.\n closed = true;\n while (creditWaiters.length > 0) {\n const waiter = creditWaiters.shift()!;\n waiter(); // they will see `closed === true` and throw\n }\n const pendingMap = (client as unknown as { _pendingTunnels: Map<string, TunnelInflight> })._pendingTunnels;\n pendingMap.delete(tunnelId);\n closedResolve();\n },\n };\n\n const pendingMap = (client as unknown as { _pendingTunnels: Map<string, TunnelInflight> })._pendingTunnels;\n pendingMap.set(tunnelId, inflight);\n\n // ---- send TunnelOpen ----\n const openMsg: Record<string, unknown> = {\n tunnelId,\n targetTopic: target,\n protocol: (protocol === \"ws\" || protocol === \"websocket\") ? \"WEBSOCKET\" : protocol.toUpperCase(),\n remoteHint: options.remoteHint ?? \"\",\n metadata: options.metadata ?? {},\n sessionToken: options.sessionToken ?? \"\",\n backendName: options.backend ?? \"\",\n };\n if (options.idleTimeoutMs != null) {\n openMsg[\"idleTimeoutMs\"] = options.idleTimeoutMs;\n }\n if (options.maxBytes != null) {\n openMsg[\"maxBytes\"] = options.maxBytes;\n }\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelOpen: openMsg,\n });\n\n // ---- close helper ----\n function doClose(_reason: TunnelCloseReason): void {\n if (closed) return;\n closed = true;\n // Wake any blocked writers.\n while (creditWaiters.length > 0) {\n const waiter = creditWaiters.shift()!;\n waiter();\n }\n pendingMap.delete(tunnelId);\n closedResolve();\n }\n\n return {\n readable,\n writable,\n closed: closedPromise,\n close() {\n if (closed) return;\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelClose: {\n tunnelId,\n reason: \"NORMAL\",\n detail: \"\",\n },\n });\n doClose(\"NORMAL\");\n },\n };\n}\n","/**\n * Authority grant cache for the Aether TypeScript client.\n *\n * Mirrors the Python `AuthorityGrantCache` (see\n * `sdk/python-client/scitrera_aether_client/authority_cache.py`):\n *\n * - Caches grants per `(sourceSessionId, audienceType, audienceId)`.\n * - Soft-renews at `expiresAt - softRenewSkewMs` (configurable).\n * - Honors server `cacheHintTtlSeconds` from `AuthorityGrantResponse` as\n * an upper bound on the cached lifetime.\n * - Listens for `AuthorityGrantRevocation` push events and invalidates\n * matching entries by `grantId` OR `rootGrantId` (cascade).\n * - `deriveForTask(...)` uses the idempotent `DERIVE_FOR_TARGET` op so\n * repeated calls return the same grant rather than minting new ones.\n *\n * Concurrency: per-key in-flight Promise dedupe collapses concurrent\n * `getOrExchange` / `deriveForTask` calls so only one network round-trip\n * happens per cache key at a time.\n *\n * @module authority-cache\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport type { AuthorityGrantInfo, AuthorityGrantResponse, AuthorityGrantRevocation } from \"./types.js\";\n\n/**\n * Configuration for {@link AuthorityGrantCache}.\n */\nexport interface AuthorityGrantCacheOptions {\n /**\n * Soft-renew skew, in milliseconds. Re-exchange a grant this long\n * before its server-side `expiresAt`. Default: 30000 (30 s) to match\n * the connection-lock heartbeat cadence.\n */\n softRenewSkewMs?: number;\n\n /**\n * Default per-op timeout (ms) passed through to the underlying client\n * when the cache issues exchange / derive / revoke calls. Default:\n * 10000.\n */\n opTimeoutMs?: number;\n\n /**\n * Wall-clock provider, returning unix-ms. Pluggable for tests.\n * Default: `Date.now`.\n */\n clock?: () => number;\n\n /**\n * When true the cache treats `AuthorityGrantInfo.expiresAt` as\n * unix-MILLISECONDS rather than unix-seconds. The proto comment on\n * `AuthorityGrantInfo` says \"Unix seconds\" but the runtime\n * `ACLAuthorityGrantInfo` uses milliseconds in practice — pick the\n * unit your gateway emits. Default: `false` (seconds).\n */\n expiresAtInMillis?: boolean;\n}\n\n/** Subset of {@link AetherClient} the cache depends on. */\nexport interface AuthorityCacheClient {\n exchangeAuthorityGrant(opts: Record<string, unknown>): Promise<AuthorityGrantResponse>;\n deriveAuthorityGrantForTarget(opts: Record<string, unknown>): Promise<AuthorityGrantResponse>;\n revokeAuthorityGrant(grantId: string, timeout?: number): Promise<AuthorityGrantResponse>;\n _removeAuthorityCache?(cache: AuthorityGrantCache): void;\n}\n\n/** Composite cache key. */\ntype CacheKey = string;\n\ninterface CacheEntry {\n grant: AuthorityGrantInfo;\n /** Absolute deadline (unix-ms) at which this entry is considered stale. */\n effectiveDeadlineMs: number;\n /** Absolute server-side expires_at, in proto units (see {@link AuthorityGrantCacheOptions.expiresAtInMillis}). */\n rawExpiresAt: number;\n cacheHintTtlS: number;\n fetchedAtMs: number;\n}\n\n/**\n * Per-actor cache of runtime authority grants. See module docstring for\n * the behavioural contract.\n */\nexport class AuthorityGrantCache {\n private readonly _client: AuthorityCacheClient;\n private readonly _softRenewSkewMs: number;\n private readonly _opTimeoutMs: number;\n private readonly _clock: () => number;\n private readonly _expiresAtInMillis: boolean;\n\n private readonly _entries = new Map<CacheKey, CacheEntry>();\n /** grantId -> set of cache keys, for fast revocation lookup. */\n private readonly _grantIdIndex = new Map<string, Set<CacheKey>>();\n /** rootGrantId -> set of cache keys, for cascade invalidation. */\n private readonly _rootGrantIdIndex = new Map<string, Set<CacheKey>>();\n /** In-flight per-key fetch promises, for single-flight de-dupe. */\n private readonly _inflight = new Map<CacheKey, Promise<AuthorityGrantInfo | null>>();\n\n private _closed = false;\n\n constructor(client: AuthorityCacheClient, opts: AuthorityGrantCacheOptions = {}) {\n if (opts.softRenewSkewMs !== undefined && opts.softRenewSkewMs < 0) {\n throw new Error(\"softRenewSkewMs must be non-negative\");\n }\n this._client = client;\n this._softRenewSkewMs = opts.softRenewSkewMs ?? 30_000;\n this._opTimeoutMs = opts.opTimeoutMs ?? 10_000;\n this._clock = opts.clock ?? (() => Date.now());\n this._expiresAtInMillis = opts.expiresAtInMillis ?? false;\n }\n\n // ===========================================================================\n // Public API\n // ===========================================================================\n\n /**\n * Return a cached grant for the (sourceSessionId, audienceType,\n * audienceId) triplet, or exchange a fresh one. Callers MUST keep the\n * rest of the request shape stable for a given key.\n *\n * Returns `null` when the gateway response is missing, has\n * `success === false`, or carries no grant — callers should fall back\n * to direct invocation or surface the error.\n */\n async getOrExchange(opts: {\n sourceSessionId: string;\n audienceType?: string;\n audienceId?: string;\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n }): Promise<AuthorityGrantInfo | null> {\n const audienceType = opts.audienceType ?? \"\";\n const audienceId = opts.audienceId ?? \"\";\n const key = makeKey(opts.sourceSessionId, audienceType, audienceId);\n\n const cached = this._getUnexpired(key);\n if (cached !== null) {\n return cached;\n }\n\n return this._withInflight(key, async () => {\n const cachedAfterLock = this._getUnexpired(key);\n if (cachedAfterLock !== null) {\n return cachedAfterLock;\n }\n const response = await this._client.exchangeAuthorityGrant({\n sourceSessionId: opts.sourceSessionId,\n audienceType,\n audienceId,\n workspaceScope: opts.workspaceScope,\n resourceScope: opts.resourceScope,\n operationScope: opts.operationScope,\n maxAccessLevel: opts.maxAccessLevel,\n validWhileAudienceActive: opts.validWhileAudienceActive,\n expiresAt: opts.expiresAt,\n renewableUntil: opts.renewableUntil,\n mayDelegate: opts.mayDelegate,\n remainingHops: opts.remainingHops,\n reason: opts.reason,\n metadata: opts.metadata,\n timeout: opts.timeout ?? this._opTimeoutMs,\n });\n const grant = extractGrant(response);\n if (!grant) {\n return null;\n }\n this._store(key, grant, response);\n return grant;\n });\n }\n\n /**\n * Idempotent derive for a target task: returns an existing visible\n * grant matching (parentGrantId, taskId, audience) when one is in\n * place, otherwise mints a new one via `DERIVE_FOR_TARGET`. Safe to\n * call repeatedly without leaking grants.\n */\n async deriveForTask(opts: {\n parentGrantId: string;\n taskId: string;\n audienceType?: string;\n audienceId?: string;\n operationScope?: string[];\n maxAccessLevel?: number;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n timeout?: number;\n }): Promise<AuthorityGrantInfo | null> {\n return this.deriveForTarget({\n parentGrantId: opts.parentGrantId,\n targetType: \"task\",\n targetId: opts.taskId,\n audienceType: opts.audienceType,\n audienceId: opts.audienceId,\n operationScope: opts.operationScope,\n maxAccessLevel: opts.maxAccessLevel,\n expiresAt: opts.expiresAt,\n renewableUntil: opts.renewableUntil,\n mayDelegate: opts.mayDelegate,\n remainingHops: opts.remainingHops,\n reason: opts.reason,\n timeout: opts.timeout,\n });\n }\n\n /** General form of {@link deriveForTask} for arbitrary target principals. */\n async deriveForTarget(opts: {\n parentGrantId: string;\n targetType: string;\n targetId: string;\n audienceType?: string;\n audienceId?: string;\n operationScope?: string[];\n maxAccessLevel?: number;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n timeout?: number;\n }): Promise<AuthorityGrantInfo | null> {\n const audienceType = opts.audienceType ?? \"\";\n const audienceId = opts.audienceId ?? \"\";\n const key = makeKey(\n `derive::${opts.parentGrantId}::${opts.targetType}::${opts.targetId}`,\n audienceType,\n audienceId,\n );\n\n const cached = this._getUnexpired(key);\n if (cached !== null) {\n return cached;\n }\n\n return this._withInflight(key, async () => {\n const cachedAfterLock = this._getUnexpired(key);\n if (cachedAfterLock !== null) {\n return cachedAfterLock;\n }\n const response = await this._client.deriveAuthorityGrantForTarget({\n parentGrantId: opts.parentGrantId,\n targetType: opts.targetType,\n targetId: opts.targetId,\n audienceType,\n audienceId,\n operationScope: opts.operationScope,\n maxAccessLevel: opts.maxAccessLevel,\n expiresAt: opts.expiresAt,\n renewableUntil: opts.renewableUntil,\n mayDelegate: opts.mayDelegate,\n remainingHops: opts.remainingHops,\n reason: opts.reason,\n timeout: opts.timeout ?? this._opTimeoutMs,\n });\n const grant = extractGrant(response);\n if (!grant) {\n return null;\n }\n this._store(key, grant, response);\n return grant;\n });\n }\n\n /**\n * Drop every cache entry whose grant ID OR root grant ID matches.\n * Returns the number of entries dropped. Safe to call from any\n * context.\n */\n invalidate(grantIdOrRoot: string): number {\n let dropped = 0;\n for (const idx of [this._grantIdIndex, this._rootGrantIdIndex]) {\n const keys = idx.get(grantIdOrRoot);\n if (!keys) {\n continue;\n }\n // Snapshot the keys because _drop mutates the index.\n for (const key of [...keys]) {\n if (this._drop(key)) {\n dropped++;\n }\n }\n idx.delete(grantIdOrRoot);\n }\n return dropped;\n }\n\n /**\n * Best-effort revoke every cached grant on the gateway, then clear.\n * Per-grant errors are caught and logged via `console.warn`.\n */\n async revokeAll(): Promise<void> {\n const entries = [...this._entries.values()];\n this._entries.clear();\n this._grantIdIndex.clear();\n this._rootGrantIdIndex.clear();\n\n await Promise.all(\n entries.map(async (entry) => {\n const grantId = entry.grant.grantId;\n if (!grantId) {\n return;\n }\n try {\n await this._client.revokeAuthorityGrant(grantId, this._opTimeoutMs);\n } catch (err) {\n console.warn(`AuthorityGrantCache.revokeAll: revoke ${grantId} failed`, err);\n }\n }),\n );\n }\n\n /**\n * Invalidate cache entries matching a server-pushed revocation event.\n * Returns the number of entries dropped. Wired into the client\n * dispatch loop by {@link AetherClient.makeAuthorityCache}; tests may\n * also call this directly.\n */\n handleRevocationEvent(evt: AuthorityGrantRevocation): number {\n let dropped = 0;\n if (evt.grantId) {\n dropped += this.invalidate(evt.grantId);\n }\n if (evt.rootGrantId && evt.rootGrantId !== evt.grantId) {\n dropped += this.invalidate(evt.rootGrantId);\n }\n return dropped;\n }\n\n /** Cache stats for observability tests. */\n stats(): { size: number; grantIdsIndexed: number; rootGrantIdsIndexed: number } {\n return {\n size: this._entries.size,\n grantIdsIndexed: this._grantIdIndex.size,\n rootGrantIdsIndexed: this._rootGrantIdIndex.size,\n };\n }\n\n // ===========================================================================\n // High-level convenience helpers (Phase 4)\n // ===========================================================================\n\n /**\n * Report whether `grantId` is currently cached and fresh (not revoked,\n * not past its soft-renew deadline). Cache-only — never round-trips to\n * the gateway. Stale/revoked entries observed here are evicted as a\n * side-effect.\n */\n isValid(grantId: string): boolean {\n if (!grantId) {\n return false;\n }\n const keys = this._grantIdIndex.get(grantId);\n if (!keys || keys.size === 0) {\n return false;\n }\n // Snapshot — `_getUnexpired` mutates the index when it evicts.\n for (const key of [...keys]) {\n if (this._getUnexpired(key) !== null) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return a snapshot of every cached grant that is currently fresh,\n * de-duplicated by `grantId`. Stale/revoked entries observed during\n * the snapshot are evicted as a side-effect.\n */\n listActive(): AuthorityGrantInfo[] {\n const out: AuthorityGrantInfo[] = [];\n const seen = new Set<string>();\n // Snapshot keys first so eviction during iteration is safe.\n for (const key of [...this._entries.keys()]) {\n const grant = this._getUnexpired(key);\n if (!grant || !grant.grantId || seen.has(grant.grantId)) {\n continue;\n }\n seen.add(grant.grantId);\n out.push(grant);\n }\n return out;\n }\n\n /**\n * Drop `grantId` from the cache without calling the gateway. Alias of\n * {@link invalidate} with a name that telegraphs the local-only\n * semantics; the matching server-side revoke is\n * {@link AetherClient.revokeAuthorityGrant}. Returns the number of\n * entries dropped.\n */\n revokeLocal(grantId: string): number {\n return this.invalidate(grantId);\n }\n\n /**\n * Force-drop a cached grant and re-exchange it.\n *\n * Returns `null` when the cache does not know `grantId`, the matching\n * entry was originally derived (those cannot be refreshed via\n * exchange — re-derive explicitly), or the underlying exchange fails.\n */\n async refresh(\n grantId: string,\n opts: {\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n } = {},\n ): Promise<AuthorityGrantInfo | null> {\n if (!grantId) {\n return null;\n }\n const keys = this._grantIdIndex.get(grantId);\n if (!keys || keys.size === 0) {\n return null;\n }\n // Pick the first key — all keys for a given grantId share the same\n // grant payload.\n const [firstKey] = keys;\n const [sourceSessionId, audienceType, audienceId] = firstKey.split(\"|||\");\n this.invalidate(grantId);\n if (sourceSessionId.startsWith(\"derive::\")) {\n return null;\n }\n return this.getOrExchange({\n sourceSessionId,\n audienceType,\n audienceId,\n ...opts,\n });\n }\n\n /**\n * Deregister this cache from its parent client so it stops receiving\n * AuthorityGrantRevocation events. Idempotent.\n */\n close(): void {\n if (this._closed) {\n return;\n }\n this._closed = true;\n this._entries.clear();\n this._grantIdIndex.clear();\n this._rootGrantIdIndex.clear();\n this._client._removeAuthorityCache?.(this);\n }\n\n // ===========================================================================\n // Internals\n // ===========================================================================\n\n private _getUnexpired(key: CacheKey): AuthorityGrantInfo | null {\n const entry = this._entries.get(key);\n if (!entry) {\n return null;\n }\n if (entry.grant.revoked) {\n this._drop(key);\n return null;\n }\n const now = this._clock();\n if (entry.effectiveDeadlineMs > 0 && now >= entry.effectiveDeadlineMs) {\n this._drop(key);\n return null;\n }\n return entry.grant;\n }\n\n private _store(\n key: CacheKey,\n grant: AuthorityGrantInfo,\n response: AuthorityGrantResponse,\n ): void {\n // Drop any prior entry under this key first.\n const prior = this._entries.get(key);\n if (prior) {\n this._unindex(key, prior.grant);\n }\n\n const fetchedAt = this._clock();\n const cacheHintTtlS = response.cacheHintTtlSeconds ?? 0;\n const rawExpiresAt = grant.expiresAt ?? 0;\n const deadlines: number[] = [];\n if (rawExpiresAt > 0) {\n const expiresAtMs = this._expiresAtInMillis ? rawExpiresAt : rawExpiresAt * 1000;\n deadlines.push(expiresAtMs - this._softRenewSkewMs);\n }\n if (cacheHintTtlS > 0) {\n deadlines.push(fetchedAt + cacheHintTtlS * 1000);\n }\n const effectiveDeadlineMs = deadlines.length === 0 ? 0 : Math.min(...deadlines);\n\n this._entries.set(key, {\n grant,\n effectiveDeadlineMs,\n rawExpiresAt,\n cacheHintTtlS,\n fetchedAtMs: fetchedAt,\n });\n this._index(key, grant);\n }\n\n private _drop(key: CacheKey): boolean {\n const entry = this._entries.get(key);\n if (!entry) {\n return false;\n }\n this._entries.delete(key);\n this._unindex(key, entry.grant);\n return true;\n }\n\n private _index(key: CacheKey, grant: AuthorityGrantInfo): void {\n if (grant.grantId) {\n let set = this._grantIdIndex.get(grant.grantId);\n if (!set) {\n set = new Set<CacheKey>();\n this._grantIdIndex.set(grant.grantId, set);\n }\n set.add(key);\n }\n if (grant.rootGrantId && grant.rootGrantId !== grant.grantId) {\n let set = this._rootGrantIdIndex.get(grant.rootGrantId);\n if (!set) {\n set = new Set<CacheKey>();\n this._rootGrantIdIndex.set(grant.rootGrantId, set);\n }\n set.add(key);\n }\n }\n\n private _unindex(key: CacheKey, grant: AuthorityGrantInfo): void {\n if (grant.grantId) {\n const set = this._grantIdIndex.get(grant.grantId);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n this._grantIdIndex.delete(grant.grantId);\n }\n }\n }\n if (grant.rootGrantId) {\n const set = this._rootGrantIdIndex.get(grant.rootGrantId);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n this._rootGrantIdIndex.delete(grant.rootGrantId);\n }\n }\n }\n }\n\n private _withInflight(\n key: CacheKey,\n fetcher: () => Promise<AuthorityGrantInfo | null>,\n ): Promise<AuthorityGrantInfo | null> {\n const existing = this._inflight.get(key);\n if (existing) {\n return existing;\n }\n const promise = fetcher().finally(() => {\n this._inflight.delete(key);\n });\n this._inflight.set(key, promise);\n return promise;\n }\n}\n\nfunction makeKey(sourceSessionId: string, audienceType: string, audienceId: string): CacheKey {\n // Triple-pipe is a delimiter that is illegal in any valid principal id /\n // audience identifier today. Mirror the Python tuple-key encoding.\n return `${sourceSessionId}|||${audienceType}|||${audienceId}`;\n}\n\nfunction extractGrant(response: AuthorityGrantResponse | undefined | null): AuthorityGrantInfo | null {\n if (!response || !response.success) {\n return null;\n }\n const grant = response.grant;\n if (!grant || !grant.grantId) {\n return null;\n }\n return grant;\n}\n","/**\n * Base client implementation for the Aether TypeScript SDK.\n *\n * This module provides the AetherClient class that handles gRPC connection\n * management, TLS configuration, message queue infrastructure, and automatic\n * reconnection with exponential backoff. Specific client types (AgentClient,\n * UserClient, etc.) extend this base client.\n *\n * Key architectural principle: The connection itself IS the distributed lock\n * AND the heartbeat. When the gRPC stream closes, the identity lock is\n * immediately released. No separate heartbeat API exists.\n *\n * @module client\n */\n\nimport type {\n ConnectionOptions,\n TLSOptions,\n Credentials,\n MessageHandler,\n ConfigHandler,\n SignalHandler,\n ErrorHandler,\n KVResponseHandler,\n TaskAssignmentHandler,\n CheckpointResponseHandler,\n ProgressHandler,\n ConnectHandler,\n DisconnectHandler,\n ReconnectingHandler,\n WorkspaceResponseHandler,\n AgentResponseHandler,\n ACLResponseHandler,\n AuthorityGrantResponseHandler,\n AuthorityGrantRevocation,\n AuthorityGrantRevocationHandler,\n WorkflowResponseHandler,\n TokenResponseHandler,\n OutgoingMessage,\n IncomingMessage,\n ConfigSnapshot,\n Signal,\n ErrorResponse,\n ConnectionAck,\n TaskAssignment,\n KVResponse,\n CheckpointResponse,\n ProgressUpdate,\n ReportProgressOptions,\n TaskQueryResponse,\n TaskOperationResponse,\n TaskInfo,\n TaskQueryOptions,\n TaskQueryResponseHandler,\n TaskOperationResponseHandler,\n CreateTaskResponse,\n CreateTaskResponseHandler,\n WorkspaceResponse,\n AgentResponse,\n ACLResponse,\n AuthorityGrantResponse,\n AuthorityGrantInfo,\n WorkflowResponse,\n TokenResponse,\n TokenInfo,\n AuditSubmitResponse,\n AuditSubmitResponseHandler,\n} from \"./types.js\";\nimport { MessageType, KVScope, SignalType } from \"./types.js\";\nimport {\n ConnectionError,\n DuplicateIdentityError,\n ReconnectionError,\n InvalidArgumentError,\n isRecoverable,\n} from \"./errors.js\";\nimport { KVClient } from \"./kv.js\";\nimport { CheckpointClient } from \"./checkpoint.js\";\nimport type { TunnelInflight } from \"./tunnel.js\";\nimport { TunnelClosedError } from \"./tunnel.js\";\nimport type { AuthorityGrantCacheOptions } from \"./authority-cache.js\";\nimport { AuthorityGrantCache } from \"./authority-cache.js\";\nimport type { ProxyHttpResponse } from \"./proxy.js\";\n\n// =============================================================================\n// Client Options\n// =============================================================================\n\n/**\n * Configuration options for the base Aether client.\n */\nexport interface AetherClientOptions {\n /** Gateway address in host:port format. Required. */\n address: string;\n /** Optional TLS configuration for secure connections. */\n tls?: TLSOptions;\n /** Connection behavior configuration. */\n connection?: ConnectionOptions;\n /** Authentication credentials. */\n credentials?: Credentials;\n /** Whether to automatically reconnect on connection loss. Default: true. */\n reconnect?: boolean;\n /** Initial delay in ms between reconnect attempts. Default: 1000. */\n reconnectDelay?: number;\n /** Maximum delay in ms between reconnect attempts. Default: 30000. */\n maxReconnectDelay?: number;\n /**\n * When true, if the gateway returns a DuplicateIdentityError (ALREADY_EXISTS)\n * during connection, the client will wait and retry automatically.\n * Shorthand for connection.retryOnDuplicate. Default: false.\n */\n retryOnDuplicate?: boolean;\n /**\n * How long to wait (ms) before retrying after a DuplicateIdentityError.\n * Shorthand for connection.retryOnDuplicateDelay. Default: 5000.\n */\n retryOnDuplicateDelay?: number;\n}\n\n// =============================================================================\n// Internal KV Operation Type\n// =============================================================================\n\n/** @internal */\nexport interface KVOperationParams {\n op: \"GET\" | \"PUT\" | \"LIST\" | \"DELETE\" | \"INCREMENT\" | \"DECREMENT\" | \"INCREMENT_IF\" | \"DECREMENT_IF\";\n scope: KVScope;\n key?: string;\n value?: Uint8Array;\n userId?: string;\n workspace?: string;\n ttl?: number;\n requestId?: string;\n /** Guard value for INCREMENT_IF (ceiling) and DECREMENT_IF (floor) operations. */\n guardValue?: bigint;\n /** Step size for INCREMENT_IF / DECREMENT_IF. When omitted the server defaults to 1. */\n deltaValue?: bigint;\n}\n\n// =============================================================================\n// Internal Checkpoint Operation Type\n// =============================================================================\n\n/** @internal */\nexport interface CheckpointOperationParams {\n op: \"SAVE\" | \"LOAD\" | \"DELETE\" | \"LIST\";\n key?: string;\n data?: Uint8Array;\n ttl?: number;\n requestId?: string;\n}\n\n// =============================================================================\n// Default Connection Options\n// =============================================================================\n\nconst DEFAULT_CONNECTION: Required<ConnectionOptions> = {\n maxRetries: 5,\n initialBackoff: 1000,\n maxBackoff: 30000,\n backoffMultiplier: 2.0,\n autoReconnect: true,\n connectTimeout: 30000,\n retryOnDuplicate: false,\n retryOnDuplicateDelay: 5000,\n retryOnDuplicateMaxAttempts: 5,\n};\n\n// =============================================================================\n// AetherClient\n// =============================================================================\n\n/**\n * Base client for connecting to the Aether distributed control plane.\n *\n * AetherClient manages the gRPC bidirectional streaming connection,\n * handles automatic reconnection with exponential backoff, and provides\n * the message send/receive infrastructure.\n *\n * This class is not typically used directly. Instead, use one of the\n * specialized client types:\n * - {@link AgentClient} for agent connections\n * - {@link UserClient} for user/browser connections\n *\n * @example\n * ```typescript\n * import { AetherClient } from \"@scitrera/aether-client\";\n *\n * const client = new AetherClient({ address: \"localhost:50051\" });\n *\n * client.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await client.connect();\n * ```\n */\nexport class AetherClient {\n // Configuration\n protected readonly _address: string;\n protected readonly _tls: TLSOptions | undefined;\n protected readonly _connectionOpts: Required<ConnectionOptions>;\n protected readonly _credentials: Credentials;\n\n // Connection state\n protected _connected = false;\n protected _connecting = false;\n protected _sessionId = \"\";\n protected _resumeSessionId = \"\";\n private _requestCounter = 0;\n\n // Handler registry\n private _onMessage: MessageHandler = () => {};\n private _onConfig: ConfigHandler = () => {};\n private _onSignal: SignalHandler = () => {};\n private _onError: ErrorHandler = () => {};\n private _onKVResponse: KVResponseHandler = () => {};\n private _onTaskAssignment: TaskAssignmentHandler = () => {};\n private _onCheckpointResponse: CheckpointResponseHandler = () => {};\n private _onProgress: ProgressHandler = () => {};\n private _onConnect: ConnectHandler = () => {};\n private _onDisconnect: DisconnectHandler = () => {};\n private _onReconnecting: ReconnectingHandler = () => {};\n\n // Task management handlers\n private _onTaskQueryResponse: TaskQueryResponseHandler = () => {};\n private _onTaskOperationResponse: TaskOperationResponseHandler = () => {};\n private _onCreateTaskResponse: CreateTaskResponseHandler = () => {};\n\n // Workspace/Agent/ACL/Workflow handlers\n private _onWorkspaceResponse: WorkspaceResponseHandler = () => {};\n private _onAgentResponse: AgentResponseHandler = () => {};\n private _onACLResponse: ACLResponseHandler = () => {};\n private _onAuthorityGrantResponse: AuthorityGrantResponseHandler = () => {};\n private _onAuthorityGrantRevocation: AuthorityGrantRevocationHandler = () => {};\n private _onAuditSubmitResponse: AuditSubmitResponseHandler = () => {};\n\n // Registered authority-grant caches receive AuthorityGrantRevocation\n // push events before the user-supplied handler. @internal\n private _authorityGrantCaches: AuthorityGrantCache[] = [];\n private _onWorkflowResponse: WorkflowResponseHandler = () => {};\n private _onTokenResponse: TokenResponseHandler = () => {};\n\n // Typed message handlers\n private _onChatMessage: MessageHandler | null = null;\n private _onControlMessage: MessageHandler | null = null;\n private _onToolCallMessage: MessageHandler | null = null;\n private _onEventMessage: MessageHandler | null = null;\n private _onMetricMessage: MessageHandler | null = null;\n\n // Pending request correlation maps\n private _pendingKVRequests = new Map<string, (response: KVResponse) => void>();\n private _pendingCheckpointRequests = new Map<string, (response: CheckpointResponse) => void>();\n private _pendingTaskQueryRequests = new Map<string, (response: TaskQueryResponse) => void>();\n private _pendingTaskOpRequests = new Map<string, (response: TaskOperationResponse) => void>();\n private _pendingCreateTaskRequests = new Map<string, (response: CreateTaskResponse) => void>();\n private _pendingWorkspaceRequests = new Map<string, (response: WorkspaceResponse) => void>();\n private _pendingAgentRequests = new Map<string, (response: AgentResponse) => void>();\n private _pendingACLRequests = new Map<string, (response: ACLResponse) => void>();\n private _pendingAuthorityGrantRequests = new Map<string, (response: AuthorityGrantResponse) => void>();\n private _pendingWorkflowRequests = new Map<string, (response: WorkflowResponse) => void>();\n private _pendingAuditSubmitRequests = new Map<string, (response: AuditSubmitResponse) => void>();\n private _pendingTokenRequests = new Map<string, (response: TokenResponse) => void>();\n\n // Proxy HTTP pending requests: request_id → resolver\n // @internal\n _pendingProxyHttpRequests = new Map<string, (response: ProxyHttpResponse) => void>();\n // Accumulated body chunks keyed by request_id, for chunked responses\n // @internal\n _pendingProxyHttpChunks = new Map<string, Uint8Array[]>();\n // Active streaming proxy responses: request_id → controller. Set by\n // proxyHttp() when streamResponse=true; populated as ProxyHttpBodyChunk\n // frames arrive so the caller's ReadableStream<Uint8Array> can yield them\n // incrementally.\n // @internal\n _pendingProxyHttpStreams = new Map<\n string,\n {\n controller: ReadableStreamDefaultController<Uint8Array>;\n headerResolved: boolean;\n }\n >();\n\n // Tunnel inflight map: tunnel_id → TunnelInflight handler\n // @internal\n _pendingTunnels = new Map<string, TunnelInflight>();\n\n // KV client instance (lazy)\n private _kvClient: KVClient | undefined;\n\n // Checkpoint client instance (lazy)\n private _checkpointClient: CheckpointClient | undefined;\n\n // RetryOnDuplicate configuration\n private readonly _retryOnDuplicate: boolean;\n private readonly _retryOnDuplicateDelay: number;\n private readonly _retryOnDuplicateMaxAttempts: number;\n\n // gRPC connection objects (populated when @grpc/grpc-js is available)\n private _grpcClient: unknown = null;\n private _stream: unknown = null;\n private _disconnectRequested = false;\n private _reconnecting = false;\n\n // Loaded proto package definition — stored for sub-message encoding (e.g. Metric)\n private _packageDefinition: Record<string, unknown> | null = null;\n\n /**\n * Creates a new AetherClient.\n *\n * The client is created but not connected. Call {@link connect} to establish\n * the connection to the gateway.\n *\n * @param options - Client configuration options\n * @throws {@link InvalidArgumentError} if the address is not provided\n */\n constructor(options: AetherClientOptions) {\n if (!options.address) {\n throw new InvalidArgumentError(\"Gateway address is required\", \"address\");\n }\n\n this._address = options.address;\n this._tls = options.tls;\n this._credentials = options.credentials ?? {};\n\n // Merge connection options with defaults\n const connOpts = options.connection ?? {};\n\n // RetryOnDuplicate: top-level shorthand takes precedence over connection sub-object\n this._retryOnDuplicate =\n options.retryOnDuplicate ?? connOpts.retryOnDuplicate ?? false;\n this._retryOnDuplicateDelay =\n options.retryOnDuplicateDelay ?? connOpts.retryOnDuplicateDelay ?? 5000;\n this._retryOnDuplicateMaxAttempts =\n connOpts.retryOnDuplicateMaxAttempts ?? 5;\n\n this._connectionOpts = {\n maxRetries: connOpts.maxRetries ?? DEFAULT_CONNECTION.maxRetries,\n initialBackoff: options.reconnectDelay ?? connOpts.initialBackoff ?? DEFAULT_CONNECTION.initialBackoff,\n maxBackoff: options.maxReconnectDelay ?? connOpts.maxBackoff ?? DEFAULT_CONNECTION.maxBackoff,\n backoffMultiplier: connOpts.backoffMultiplier ?? DEFAULT_CONNECTION.backoffMultiplier,\n autoReconnect: options.reconnect ?? connOpts.autoReconnect ?? DEFAULT_CONNECTION.autoReconnect,\n connectTimeout: connOpts.connectTimeout ?? DEFAULT_CONNECTION.connectTimeout,\n retryOnDuplicate: this._retryOnDuplicate,\n retryOnDuplicateDelay: this._retryOnDuplicateDelay,\n retryOnDuplicateMaxAttempts: this._retryOnDuplicateMaxAttempts,\n };\n }\n\n // ===========================================================================\n // Connection Lifecycle\n // ===========================================================================\n\n /**\n * Establishes a connection to the Aether gateway.\n *\n * Opens a gRPC bidirectional stream and sends the InitConnection message.\n * If auto-reconnect is enabled, the client will automatically attempt to\n * reconnect on connection loss.\n *\n * If `retryOnDuplicate` is enabled and the gateway responds with a\n * DuplicateIdentityError (ALREADY_EXISTS), the client will wait briefly\n * and retry up to `retryOnDuplicateMaxAttempts` times. This handles the\n * race condition where a previous instance's lock has not yet expired.\n *\n * @throws {@link ConnectionError} if the connection cannot be established\n * @throws {@link DuplicateIdentityError} if identity is already connected\n * and retryOnDuplicate is disabled or exhausted\n */\n async connect(): Promise<void> {\n if (this._connected) {\n return;\n }\n if (this._connecting) {\n return;\n }\n\n this._connecting = true;\n this._disconnectRequested = false;\n\n try {\n if (this._retryOnDuplicate) {\n await this._connectWithDuplicateRetry();\n } else {\n await this._establishConnection();\n }\n this._connected = true;\n } finally {\n this._connecting = false;\n }\n }\n\n /**\n * Attempts connection, retrying on DuplicateIdentityError.\n * @internal\n */\n private async _connectWithDuplicateRetry(): Promise<void> {\n const maxAttempts = this._retryOnDuplicateMaxAttempts;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Reset any partial connection state before each attempt\n await this._closeConnection();\n\n // Track whether a duplicate error was received during this attempt.\n // We listen for it via a one-shot error handler shim.\n let duplicateReceived = false;\n const prevOnError = this._onError;\n this._onError = (errResp) => {\n if (errResp.code === \"ALREADY_EXISTS\" || errResp.code === \"DUPLICATE_IDENTITY\") {\n duplicateReceived = true;\n }\n prevOnError(errResp);\n };\n\n try {\n await this._establishConnection();\n // Connection succeeded — restore handler and return\n this._onError = prevOnError;\n return;\n } catch (err) {\n this._onError = prevOnError;\n lastError = err instanceof Error ? err : new Error(String(err));\n\n // Check if the error is a DuplicateIdentityError or the flag was set\n const isDuplicate =\n duplicateReceived ||\n err instanceof DuplicateIdentityError ||\n (err instanceof Error && err.message.toLowerCase().includes(\"already_exists\"));\n\n if (!isDuplicate || attempt >= maxAttempts) {\n throw err;\n }\n\n // Wait before retrying\n await new Promise<void>((resolve) => setTimeout(resolve, this._retryOnDuplicateDelay));\n }\n }\n\n throw lastError ?? new DuplicateIdentityError(\"\", \"exhausted retryOnDuplicate attempts\");\n }\n\n /**\n * Gracefully disconnects from the Aether gateway.\n *\n * Closes the gRPC stream and releases the identity lock on the server.\n * Automatic reconnection is suppressed for this disconnection.\n */\n async disconnect(): Promise<void> {\n this._disconnectRequested = true;\n this._connected = false;\n await this._closeConnection();\n }\n\n /**\n * Returns whether the client is currently connected to the gateway.\n */\n get connected(): boolean {\n return this._connected;\n }\n\n /**\n * Returns the current session ID assigned by the gateway.\n * Empty string if not connected.\n */\n get sessionId(): string {\n return this._sessionId;\n }\n\n // ===========================================================================\n // Message Sending\n // ===========================================================================\n\n /**\n * Sends a message through the Aether gateway.\n *\n * @param message - The outgoing message to send\n * @throws {@link ConnectionError} if not connected\n */\n async send(message: OutgoingMessage): Promise<void> {\n if (!this._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n this._sendUpstream({\n send: {\n targetTopic: message.targetTopic,\n payload: message.payload,\n messageType: message.messageType ?? MessageType.Opaque,\n },\n });\n }\n\n /**\n * Sends a KV operation through the gateway.\n * @internal Used by KVClient.\n */\n sendKVOperation(params: KVOperationParams): void {\n this._sendUpstream({\n kvOp: {\n op: params.op,\n scope: params.scope,\n key: params.key ?? \"\",\n value: params.value,\n userId: params.userId ?? \"\",\n workspace: params.workspace ?? \"\",\n ttl: params.ttl ?? 0,\n requestId: params.requestId ?? \"\",\n guardValue: params.guardValue,\n deltaValue: params.deltaValue,\n },\n });\n }\n\n /**\n * Sends a checkpoint operation through the gateway.\n * @internal Used by CheckpointClient.\n */\n sendCheckpointOperation(params: CheckpointOperationParams): void {\n this._sendUpstream({\n checkpointOp: {\n op: params.op,\n key: params.key ?? \"\",\n data: params.data,\n ttl: params.ttl ?? -1,\n requestId: params.requestId ?? \"\",\n },\n });\n }\n\n // ===========================================================================\n // Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for incoming messages.\n *\n * @param handler - Function called when a message is received\n *\n * @example\n * ```typescript\n * client.onMessage((msg) => {\n * console.log(`From ${msg.sourceTopic}: ${new TextDecoder().decode(msg.payload)}`);\n * });\n * ```\n */\n onMessage(handler: MessageHandler): void {\n this._onMessage = handler;\n }\n\n /**\n * Registers a handler for configuration snapshots.\n *\n * Called once when the connection is established, providing the initial\n * KV store state for the workspace.\n *\n * @param handler - Function called when a config snapshot is received\n */\n onConfig(handler: ConfigHandler): void {\n this._onConfig = handler;\n }\n\n /**\n * Registers a handler for signals from the gateway.\n *\n * @param handler - Function called when a signal is received\n */\n onSignal(handler: SignalHandler): void {\n this._onSignal = handler;\n }\n\n /**\n * Registers a handler for error responses from the gateway.\n *\n * @param handler - Function called when an error response is received\n */\n onError(handler: ErrorHandler): void {\n this._onError = handler;\n }\n\n /**\n * Registers a handler for KV operation responses.\n *\n * @param handler - Function called when a KV response is received\n */\n onKVResponse(handler: KVResponseHandler): void {\n this._onKVResponse = handler;\n }\n\n /**\n * Registers a handler for task assignments.\n *\n * Used by orchestrators to receive task assignments that require\n * starting new agent or task instances.\n *\n * @param handler - Function called when a task assignment is received\n */\n onTaskAssignment(handler: TaskAssignmentHandler): void {\n this._onTaskAssignment = handler;\n }\n\n /**\n * Registers a handler for checkpoint operation responses.\n *\n * @param handler - Function called when a checkpoint response is received\n */\n onCheckpointResponse(handler: CheckpointResponseHandler): void {\n this._onCheckpointResponse = handler;\n }\n\n /**\n * Registers a handler for progress updates from agents/tasks.\n *\n * Progress updates are delivered via the pg.{workspace} stream with\n * server-side recipient filtering.\n *\n * @param handler - Function called when a progress update is received\n */\n onProgress(handler: ProgressHandler): void {\n this._onProgress = handler;\n }\n\n /**\n * Registers a handler for successful connections.\n *\n * Called both for initial connection and reconnections.\n *\n * @param handler - Function called with the connection acknowledgment\n */\n onConnect(handler: ConnectHandler): void {\n this._onConnect = handler;\n }\n\n /**\n * Registers a handler for disconnection events.\n *\n * Called before any automatic reconnection attempt.\n *\n * @param handler - Function called with the disconnection reason\n */\n onDisconnect(handler: DisconnectHandler): void {\n this._onDisconnect = handler;\n }\n\n /**\n * Registers a handler for reconnection attempts.\n *\n * @param handler - Function called with the attempt number\n */\n onReconnecting(handler: ReconnectingHandler): void {\n this._onReconnecting = handler;\n }\n\n /**\n * Registers a handler for task query responses.\n *\n * @param handler - Function called when a task query response is received\n */\n onTaskQueryResponse(handler: TaskQueryResponseHandler): void {\n this._onTaskQueryResponse = handler;\n }\n\n /**\n * Registers a handler for task operation responses.\n *\n * @param handler - Function called when a task operation response is received\n */\n onTaskOperationResponse(handler: TaskOperationResponseHandler): void {\n this._onTaskOperationResponse = handler;\n }\n\n /**\n * Registers a handler for create-task responses (fire-and-forget path,\n * i.e. when no request_id is supplied or a response arrives without a\n * matching pending entry).\n *\n * @param handler - Function called when a create-task response is received\n */\n onCreateTaskResponse(handler: CreateTaskResponseHandler): void {\n this._onCreateTaskResponse = handler;\n }\n\n /**\n * Registers a handler for Chat messages.\n *\n * @param handler - Function called when a Chat message is received\n */\n onChatMessage(handler: MessageHandler): void {\n this._onChatMessage = handler;\n }\n\n /**\n * Registers a handler for Control messages.\n *\n * @param handler - Function called when a Control message is received\n */\n onControlMessage(handler: MessageHandler): void {\n this._onControlMessage = handler;\n }\n\n /**\n * Registers a handler for ToolCall messages.\n *\n * @param handler - Function called when a ToolCall message is received\n */\n onToolCallMessage(handler: MessageHandler): void {\n this._onToolCallMessage = handler;\n }\n\n /**\n * Registers a handler for Event messages.\n *\n * @param handler - Function called when an Event message is received\n */\n onEventMessage(handler: MessageHandler): void {\n this._onEventMessage = handler;\n }\n\n /**\n * Registers a handler for Metric messages.\n *\n * @param handler - Function called when a Metric message is received\n */\n onMetricMessage(handler: MessageHandler): void {\n this._onMetricMessage = handler;\n }\n\n // ===========================================================================\n // KV Client Access\n // ===========================================================================\n\n /**\n * Returns the KV operations client.\n *\n * @returns The KVClient instance for performing KV store operations\n *\n * @example\n * ```typescript\n * const kv = client.kv();\n * const response = await kv.getSync({ key: \"my-key\", scope: KVScope.Global });\n * ```\n */\n kv(): KVClient {\n if (!this._kvClient) {\n this._kvClient = new KVClient(this);\n }\n return this._kvClient;\n }\n\n /**\n * Returns the checkpoint operations client.\n *\n * @returns The CheckpointClient instance for checkpoint save/load/delete/list\n *\n * @example\n * ```typescript\n * const cp = client.checkpoint();\n * const response = await cp.loadSync({ key: \"my-state\" });\n * ```\n */\n checkpoint(): CheckpointClient {\n if (!this._checkpointClient) {\n this._checkpointClient = new CheckpointClient(this);\n }\n return this._checkpointClient;\n }\n\n // ===========================================================================\n // Request Correlation (internal)\n // ===========================================================================\n\n /**\n * Generates a unique request ID for correlating responses.\n * @internal\n */\n nextRequestId(): string {\n this._requestCounter++;\n return `req-${Date.now()}-${this._requestCounter}`;\n }\n\n /**\n * Registers a pending KV request for response correlation.\n * @internal\n */\n registerPendingKVRequest(requestId: string, callback: (response: KVResponse) => void): void {\n this._pendingKVRequests.set(requestId, callback);\n }\n\n /**\n * Registers a pending checkpoint request for response correlation.\n * @internal\n */\n registerPendingCheckpointRequest(requestId: string, callback: (response: CheckpointResponse) => void): void {\n this._pendingCheckpointRequests.set(requestId, callback);\n }\n\n /**\n * Removes a pending request (used on timeout cleanup).\n * @internal\n */\n removePendingRequest(requestId: string): void {\n this._pendingKVRequests.delete(requestId);\n this._pendingCheckpointRequests.delete(requestId);\n }\n\n // ===========================================================================\n // Init Message (overridden by subclasses)\n // ===========================================================================\n\n /**\n * Builds the InitConnection message for the connection handshake.\n * Subclasses override this to provide their specific identity.\n * @internal\n */\n protected _buildInitMessage(): Record<string, unknown> {\n return {\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // gRPC Connection Management\n // ===========================================================================\n\n /**\n * Establishes the gRPC connection and starts the message loop.\n * @internal\n */\n private async _establishConnection(): Promise<void> {\n try {\n // Dynamic import of @grpc/grpc-js (Node.js only)\n const grpc = await import(\"@grpc/grpc-js\");\n const protoLoader = await import(\"@grpc/proto-loader\");\n\n // Resolve proto file path\n const path = await import(\"path\");\n const url = await import(\"url\");\n const dirname = path.dirname(url.fileURLToPath(import.meta.url));\n const protoPath = path.resolve(dirname, \"../../api/proto/aether.proto\");\n\n // Load proto definition\n const packageDefinition = await protoLoader.load(protoPath, {\n keepCase: false,\n longs: Number,\n enums: Number,\n defaults: true,\n oneofs: true,\n });\n\n // Store package definition for sub-message encoding (e.g. Metric)\n this._packageDefinition = packageDefinition as Record<string, unknown>;\n\n const protoDescriptor = grpc.loadPackageDefinition(packageDefinition) as Record<string, unknown>;\n const aetherV1 = (protoDescriptor[\"aether\"] as Record<string, unknown>)?.[\"v1\"] as Record<string, unknown>;\n\n if (!aetherV1) {\n throw new ConnectionError(\"Failed to load aether.v1 proto package\");\n }\n\n // Create gRPC channel credentials\n let channelCredentials: ReturnType<typeof grpc.credentials.createInsecure>;\n if (this._tls) {\n channelCredentials = grpc.credentials.createSsl(\n this._tls.rootCerts ?? null,\n this._tls.privateKey ?? null,\n this._tls.certChain ?? null,\n );\n } else {\n channelCredentials = grpc.credentials.createInsecure();\n }\n\n // Create client\n const ServiceClient = aetherV1[\"AetherGateway\"] as new (\n address: string,\n credentials: ReturnType<typeof grpc.credentials.createInsecure>,\n ) => Record<string, unknown>;\n this._grpcClient = new ServiceClient(this._address, channelCredentials);\n\n // Open bidirectional stream\n const client = this._grpcClient as Record<string, (...args: unknown[]) => unknown>;\n this._stream = client[\"connect\"]() as Record<string, unknown>;\n\n const stream = this._stream as {\n write: (msg: unknown) => void;\n on: (event: string, handler: (...args: unknown[]) => void) => void;\n end: () => void;\n };\n\n // Set up message handler\n stream.on(\"data\", (...args: unknown[]) => {\n this._handleDownstreamMessage(args[0] as Record<string, unknown>);\n });\n\n // Set up error handler\n stream.on(\"error\", (...args: unknown[]) => {\n this._handleStreamError(args[0] as Error);\n });\n\n // Set up end handler\n stream.on(\"end\", () => {\n this._handleStreamEnd();\n });\n\n // Send init message\n const initMsg = this._buildInitMessage();\n stream.write({ init: initMsg });\n\n } catch (err) {\n if (err instanceof ConnectionError) {\n throw err;\n }\n throw new ConnectionError(\n `Failed to connect to gateway at ${this._address}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n /**\n * Closes the gRPC connection.\n * @internal\n */\n private async _closeConnection(): Promise<void> {\n if (this._stream) {\n const stream = this._stream as { end: () => void; removeAllListeners?: () => void };\n try {\n // Remove event listeners before ending to prevent stale handlers\n // from firing during reconnection and triggering duplicate attempts\n stream.removeAllListeners?.();\n stream.end();\n } catch {\n // Ignore errors during close\n }\n this._stream = null;\n }\n\n if (this._grpcClient) {\n const client = this._grpcClient as { close?: () => void };\n try {\n client.close?.();\n } catch {\n // Ignore errors during close\n }\n this._grpcClient = null;\n }\n }\n\n /**\n * Sends an upstream message on the gRPC stream.\n * @internal\n */\n protected _sendUpstream(message: Record<string, unknown>): void {\n if (!this._stream) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n const stream = this._stream as { write: (msg: unknown) => void };\n stream.write(message);\n }\n\n // ===========================================================================\n // Downstream Message Handling\n // ===========================================================================\n\n /**\n * Routes a downstream message to the appropriate handler.\n * @internal\n */\n private _handleDownstreamMessage(data: Record<string, unknown>): void {\n // Detect which payload field is set (oneof)\n if (data[\"connectionAck\"] || data[\"connection_ack\"]) {\n const ack = (data[\"connectionAck\"] ?? data[\"connection_ack\"]) as Record<string, unknown>;\n this._sessionId = String(ack[\"sessionId\"] ?? ack[\"session_id\"] ?? \"\");\n this._resumeSessionId = this._sessionId;\n const connAck: ConnectionAck = {\n sessionId: this._sessionId,\n resumed: Boolean(ack[\"resumed\"]),\n assignedId: String(ack[\"assignedId\"] ?? ack[\"assigned_id\"] ?? \"\"),\n };\n this._onConnect(connAck);\n return;\n }\n\n if (data[\"msg\"]) {\n const msg = data[\"msg\"] as Record<string, unknown>;\n const incoming: IncomingMessage = {\n sourceTopic: String(msg[\"sourceTopic\"] ?? msg[\"source_topic\"] ?? \"\"),\n payload: msg[\"payload\"] instanceof Uint8Array ? msg[\"payload\"] : new Uint8Array(),\n messageType: Number(msg[\"messageType\"] ?? msg[\"message_type\"] ?? 0),\n receivedAt: new Date(),\n };\n this._onMessage(incoming);\n\n // Dispatch to typed message handler\n switch (incoming.messageType) {\n case MessageType.Chat:\n this._onChatMessage?.(incoming);\n break;\n case MessageType.Control:\n this._onControlMessage?.(incoming);\n break;\n case MessageType.ToolCall:\n this._onToolCallMessage?.(incoming);\n break;\n case MessageType.Event:\n this._onEventMessage?.(incoming);\n break;\n case MessageType.Metric:\n this._onMetricMessage?.(incoming);\n break;\n case MessageType.Opaque:\n // No typed handler — falls through to onMessage catch-all above\n break;\n }\n return;\n }\n\n if (data[\"config\"]) {\n const cfg = data[\"config\"] as Record<string, unknown>;\n const rawKv = (cfg[\"kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const rawGlobalKv = (cfg[\"globalKv\"] ?? cfg[\"global_kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const rawWsExclKv = (cfg[\"workspaceExclusiveKv\"] ?? cfg[\"workspace_exclusive_kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const rawGlobalExclKv = (cfg[\"globalExclusiveKv\"] ?? cfg[\"global_exclusive_kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const config: ConfigSnapshot = {\n kv: Object.fromEntries(Object.entries(rawKv).map(([k, v]) => [k, new Uint8Array(v)])),\n globalKv: Object.fromEntries(Object.entries(rawGlobalKv).map(([k, v]) => [k, new Uint8Array(v)])),\n workspaceExclusiveKv: Object.fromEntries(Object.entries(rawWsExclKv).map(([k, v]) => [k, new Uint8Array(v)])),\n globalExclusiveKv: Object.fromEntries(Object.entries(rawGlobalExclKv).map(([k, v]) => [k, new Uint8Array(v)])),\n };\n this._onConfig(config);\n return;\n }\n\n if (data[\"signal\"]) {\n const sig = data[\"signal\"] as Record<string, unknown>;\n const signal: Signal = {\n type: Number(sig[\"type\"]) as SignalType,\n reason: String(sig[\"reason\"] ?? \"\"),\n };\n this._onSignal(signal);\n\n if (signal.type === SignalType.ForceDisconnect) {\n this._connected = false;\n this._disconnectRequested = true; // Terminal — do not auto-reconnect\n this._onDisconnect(signal.reason || \"Force disconnect signal received\");\n } else if (signal.type === SignalType.GracefulDisconnect) {\n this._connected = false;\n // Do NOT set _disconnectRequested — allow auto-reconnect\n this._onDisconnect(signal.reason || \"Graceful disconnect signal received\");\n }\n return;\n }\n\n if (data[\"error\"]) {\n const err = data[\"error\"] as Record<string, unknown>;\n const errorResponse: ErrorResponse = {\n code: String(err[\"code\"] ?? \"\"),\n message: String(err[\"message\"] ?? \"\"),\n retryable: Boolean(err[\"retryable\"]),\n retryAfterMs: Number(err[\"retryAfterMs\"] ?? err[\"retry_after_ms\"] ?? 0),\n };\n this._onError(errorResponse);\n return;\n }\n\n if (data[\"kv\"]) {\n const kv = data[\"kv\"] as Record<string, unknown>;\n const rawCounter = kv[\"counterValue\"] ?? kv[\"counter_value\"];\n const rawApplied = kv[\"applied\"];\n const response: KVResponse = {\n success: Boolean(kv[\"success\"]),\n value: kv[\"value\"] instanceof Uint8Array ? kv[\"value\"] : new Uint8Array(),\n keys: (kv[\"keys\"] ?? []) as string[],\n kvMap: (kv[\"kvMap\"] ?? kv[\"kv_map\"] ?? {}) as Record<string, string>,\n requestId: String(kv[\"requestId\"] ?? kv[\"request_id\"] ?? \"\"),\n counterValue: rawCounter !== undefined ? Number(rawCounter) : undefined,\n applied: rawApplied !== undefined ? Boolean(rawApplied) : undefined,\n };\n\n // Route to correlated request if available\n const pending = this._pendingKVRequests.get(response.requestId);\n if (pending) {\n this._pendingKVRequests.delete(response.requestId);\n pending(response);\n } else {\n this._onKVResponse(response);\n }\n return;\n }\n\n if (data[\"taskAssignment\"] || data[\"task_assignment\"]) {\n const ta = (data[\"taskAssignment\"] ?? data[\"task_assignment\"]) as Record<string, unknown>;\n const assignment: TaskAssignment = {\n taskId: String(ta[\"taskId\"] ?? ta[\"task_id\"] ?? \"\"),\n taskType: String(ta[\"taskType\"] ?? ta[\"task_type\"] ?? \"\"),\n assignedTo: String(ta[\"assignedTo\"] ?? ta[\"assigned_to\"] ?? \"\"),\n metadata: (ta[\"metadata\"] ?? {}) as Record<string, string>,\n assignedAt: Number(ta[\"assignedAt\"] ?? ta[\"assigned_at\"] ?? 0),\n profile: String(ta[\"profile\"] ?? \"\"),\n launchParams: (ta[\"launchParams\"] ?? ta[\"launch_params\"] ?? {}) as Record<string, string>,\n targetImplementation: String(ta[\"targetImplementation\"] ?? ta[\"target_implementation\"] ?? \"\"),\n workspace: String(ta[\"workspace\"] ?? \"\"),\n specifier: String(ta[\"specifier\"] ?? \"\"),\n };\n this._onTaskAssignment(assignment);\n return;\n }\n\n if (data[\"progressUpdate\"] || data[\"progress_update\"]) {\n const pu = (data[\"progressUpdate\"] ?? data[\"progress_update\"]) as Record<string, unknown>;\n const step = pu[\"step\"] as Record<string, unknown> | undefined;\n const update: ProgressUpdate = {\n source: String(pu[\"source\"] ?? \"\"),\n taskId: String(pu[\"taskId\"] ?? pu[\"task_id\"] ?? \"\"),\n state: String(pu[\"state\"] ?? \"\"),\n completion: Number(pu[\"completion\"] ?? -1),\n summary: String(pu[\"summary\"] ?? \"\"),\n step: step ? {\n name: String(step[\"name\"] ?? \"\"),\n detail: String(step[\"detail\"] ?? \"\"),\n sequence: Number(step[\"sequence\"] ?? 0),\n totalSteps: Number(step[\"totalSteps\"] ?? step[\"total_steps\"] ?? 0),\n stepType: String(step[\"stepType\"] ?? step[\"step_type\"] ?? \"\"),\n } : undefined,\n timestampMs: Number(pu[\"timestampMs\"] ?? pu[\"timestamp_ms\"] ?? 0),\n workspace: String(pu[\"workspace\"] ?? \"\"),\n requestId: String(pu[\"requestId\"] ?? pu[\"request_id\"] ?? \"\"),\n metadata: (pu[\"metadata\"] ?? {}) as Record<string, string>,\n recipient: String(pu[\"recipient\"] ?? \"\"),\n };\n this._onProgress(update);\n return;\n }\n\n if (data[\"checkpoint\"]) {\n const cp = data[\"checkpoint\"] as Record<string, unknown>;\n const response: CheckpointResponse = {\n success: Boolean(cp[\"success\"]),\n data: cp[\"data\"] instanceof Uint8Array ? cp[\"data\"] : new Uint8Array(),\n keys: (cp[\"keys\"] ?? []) as string[],\n error: String(cp[\"error\"] ?? \"\"),\n savedAt: Number(cp[\"savedAt\"] ?? cp[\"saved_at\"] ?? 0),\n requestId: String(cp[\"requestId\"] ?? cp[\"request_id\"] ?? \"\"),\n };\n\n // Route to correlated request if available\n const pending = this._pendingCheckpointRequests.get(response.requestId);\n if (pending) {\n this._pendingCheckpointRequests.delete(response.requestId);\n pending(response);\n } else {\n this._onCheckpointResponse(response);\n }\n return;\n }\n\n if (data[\"taskQuery\"] || data[\"task_query\"]) {\n const tq = (data[\"taskQuery\"] ?? data[\"task_query\"]) as Record<string, unknown>;\n const requestId = String(tq[\"requestId\"] ?? tq[\"request_id\"] ?? \"\");\n const response: TaskQueryResponse = {\n success: Boolean(tq[\"success\"]),\n error: String(tq[\"error\"] ?? \"\"),\n task: tq[\"task\"] ? this._parseTaskInfo(tq[\"task\"] as Record<string, unknown>) : undefined,\n tasks: ((tq[\"tasks\"] ?? []) as Record<string, unknown>[]).map(t => this._parseTaskInfo(t)),\n totalCount: Number(tq[\"totalCount\"] ?? tq[\"total_count\"] ?? 0),\n requestId,\n };\n\n const pending = this._pendingTaskQueryRequests.get(requestId);\n if (pending) {\n this._pendingTaskQueryRequests.delete(requestId);\n pending(response);\n } else {\n this._onTaskQueryResponse(response);\n }\n return;\n }\n\n if (data[\"taskOp\"] || data[\"task_op\"]) {\n const to = (data[\"taskOp\"] ?? data[\"task_op\"]) as Record<string, unknown>;\n const requestId = String(to[\"requestId\"] ?? to[\"request_id\"] ?? \"\");\n const response: TaskOperationResponse = {\n success: Boolean(to[\"success\"]),\n message: String(to[\"message\"] ?? \"\"),\n error: String(to[\"error\"] ?? \"\"),\n task: to[\"task\"] ? this._parseTaskInfo(to[\"task\"] as Record<string, unknown>) : undefined,\n requestId,\n };\n\n const pending = this._pendingTaskOpRequests.get(requestId);\n if (pending) {\n this._pendingTaskOpRequests.delete(requestId);\n pending(response);\n } else {\n this._onTaskOperationResponse(response);\n }\n return;\n }\n\n if (data[\"workspace\"]) {\n const ws = data[\"workspace\"] as Record<string, unknown>;\n const requestId = String(ws[\"requestId\"] ?? ws[\"request_id\"] ?? \"\");\n const response: WorkspaceResponse = {\n success: Boolean(ws[\"success\"]),\n error: String(ws[\"error\"] ?? \"\"),\n message: String(ws[\"message\"] ?? \"\"),\n totalCount: Number(ws[\"totalCount\"] ?? ws[\"total_count\"] ?? 0),\n requestId,\n ...ws,\n };\n\n const pending = this._pendingWorkspaceRequests.get(requestId);\n if (pending) {\n this._pendingWorkspaceRequests.delete(requestId);\n pending(response);\n } else {\n this._onWorkspaceResponse(response);\n }\n return;\n }\n\n if (data[\"agent\"]) {\n const ag = data[\"agent\"] as Record<string, unknown>;\n const requestId = String(ag[\"requestId\"] ?? ag[\"request_id\"] ?? \"\");\n const response: AgentResponse = {\n success: Boolean(ag[\"success\"]),\n error: String(ag[\"error\"] ?? \"\"),\n message: String(ag[\"message\"] ?? \"\"),\n totalCount: Number(ag[\"totalCount\"] ?? ag[\"total_count\"] ?? 0),\n requestId,\n ...ag,\n };\n\n const pending = this._pendingAgentRequests.get(requestId);\n if (pending) {\n this._pendingAgentRequests.delete(requestId);\n pending(response);\n } else {\n this._onAgentResponse(response);\n }\n return;\n }\n\n if (data[\"acl\"]) {\n const acl = data[\"acl\"] as Record<string, unknown>;\n const requestId = String(acl[\"requestId\"] ?? acl[\"request_id\"] ?? \"\");\n const response: ACLResponse = {\n success: Boolean(acl[\"success\"]),\n error: String(acl[\"error\"] ?? \"\"),\n message: String(acl[\"message\"] ?? \"\"),\n requestId,\n ...acl,\n };\n\n const pending = this._pendingACLRequests.get(requestId);\n if (pending) {\n this._pendingACLRequests.delete(requestId);\n pending(response);\n } else {\n this._onACLResponse(response);\n }\n return;\n }\n\n if (data[\"authorityGrant\"] || data[\"authority_grant\"]) {\n const ag = (data[\"authorityGrant\"] ?? data[\"authority_grant\"]) as Record<string, unknown>;\n const requestId = String(ag[\"requestId\"] ?? ag[\"request_id\"] ?? \"\");\n const rawGrant = ag[\"grant\"] as Record<string, unknown> | null | undefined;\n const rawGrants = ag[\"grants\"];\n\n const response: AuthorityGrantResponse = {\n success: Boolean(ag[\"success\"]),\n error: String(ag[\"error\"] ?? \"\"),\n message: String(ag[\"message\"] ?? \"\"),\n grant: rawGrant ? this._parseAuthorityGrantInfo(rawGrant) : undefined,\n requestId,\n grants: Array.isArray(rawGrants)\n ? (rawGrants as Record<string, unknown>[]).map((g) => this._parseAuthorityGrantInfo(g))\n : undefined,\n total: Number(ag[\"total\"] ?? 0),\n cacheHintTtlSeconds: Number(ag[\"cacheHintTtlSeconds\"] ?? ag[\"cache_hint_ttl_seconds\"] ?? 0),\n };\n\n const pending = this._pendingAuthorityGrantRequests.get(requestId);\n if (pending) {\n this._pendingAuthorityGrantRequests.delete(requestId);\n pending(response);\n } else {\n this._onAuthorityGrantResponse(response);\n }\n return;\n }\n\n if (data[\"authorityGrantRevocation\"] || data[\"authority_grant_revocation\"]) {\n const raw = (data[\"authorityGrantRevocation\"] ?? data[\"authority_grant_revocation\"]) as Record<string, unknown>;\n const evt: AuthorityGrantRevocation = {\n grantId: String(raw[\"grantId\"] ?? raw[\"grant_id\"] ?? \"\"),\n rootGrantId: String(raw[\"rootGrantId\"] ?? raw[\"root_grant_id\"] ?? \"\"),\n reason: String(raw[\"reason\"] ?? \"\"),\n revokedAt: Number(raw[\"revokedAt\"] ?? raw[\"revoked_at\"] ?? 0),\n cascade: Boolean(raw[\"cascade\"]),\n };\n\n // Dispatch to every registered cache before firing the user handler.\n for (const cache of this._authorityGrantCaches) {\n try {\n cache.handleRevocationEvent(evt);\n } catch {\n // Best-effort: cache errors are isolated from each other and\n // from the user handler.\n }\n }\n this._onAuthorityGrantRevocation(evt);\n return;\n }\n\n if (data[\"createTask\"] || data[\"create_task\"]) {\n const ct = (data[\"createTask\"] ?? data[\"create_task\"]) as Record<string, unknown>;\n const requestId = String(ct[\"requestId\"] ?? ct[\"request_id\"] ?? \"\");\n const response: CreateTaskResponse = {\n success: Boolean(ct[\"success\"]),\n taskId: String(ct[\"taskId\"] ?? ct[\"task_id\"] ?? \"\"),\n status: String(ct[\"status\"] ?? \"\"),\n errorCode: String(ct[\"errorCode\"] ?? ct[\"error_code\"] ?? \"\"),\n errorMessage: String(ct[\"errorMessage\"] ?? ct[\"error_message\"] ?? \"\"),\n requestId,\n assignedTo: String(ct[\"assignedTo\"] ?? ct[\"assigned_to\"] ?? \"\"),\n };\n\n const pending = this._pendingCreateTaskRequests.get(requestId);\n if (pending) {\n this._pendingCreateTaskRequests.delete(requestId);\n pending(response);\n } else {\n this._onCreateTaskResponse(response);\n }\n return;\n }\n\n if (data[\"workflowResponse\"] || data[\"workflow_response\"]) {\n const wf = (data[\"workflowResponse\"] ?? data[\"workflow_response\"]) as Record<string, unknown>;\n const requestId = String(wf[\"requestId\"] ?? wf[\"request_id\"] ?? \"\");\n const response: WorkflowResponse = {\n success: Boolean(wf[\"success\"]),\n error: String(wf[\"error\"] ?? \"\"),\n message: String(wf[\"message\"] ?? \"\"),\n data: wf[\"data\"] instanceof Uint8Array ? wf[\"data\"] : undefined,\n totalCount: Number(wf[\"totalCount\"] ?? wf[\"total_count\"] ?? 0),\n requestId,\n };\n\n const pending = this._pendingWorkflowRequests.get(requestId);\n if (pending) {\n this._pendingWorkflowRequests.delete(requestId);\n pending(response);\n } else {\n this._onWorkflowResponse(response);\n }\n return;\n }\n\n if (data[\"submitAuditEventResponse\"] || data[\"submit_audit_event_response\"]) {\n const ar = (data[\"submitAuditEventResponse\"] ?? data[\"submit_audit_event_response\"]) as Record<string, unknown>;\n const clientRequestId = String(ar[\"clientRequestId\"] ?? ar[\"client_request_id\"] ?? \"\");\n const response: AuditSubmitResponse = {\n clientRequestId,\n success: Boolean(ar[\"success\"]),\n errorCode: String(ar[\"errorCode\"] ?? ar[\"error_code\"] ?? \"\"),\n errorMessage: String(ar[\"errorMessage\"] ?? ar[\"error_message\"] ?? \"\"),\n };\n const pending = this._pendingAuditSubmitRequests.get(clientRequestId);\n if (pending) {\n this._pendingAuditSubmitRequests.delete(clientRequestId);\n pending(response);\n } else {\n this._onAuditSubmitResponse(response);\n }\n return;\n }\n\n if (data[\"token\"] || data[\"tokenResponse\"] || data[\"token_response\"]) {\n const tr = (data[\"token\"] ?? data[\"tokenResponse\"] ?? data[\"token_response\"]) as Record<string, unknown>;\n const requestId = String(tr[\"requestId\"] ?? tr[\"request_id\"] ?? \"\");\n\n const parseTokenInfo = (t: Record<string, unknown>): TokenInfo => ({\n id: String(t[\"id\"] ?? \"\"),\n name: String(t[\"name\"] ?? \"\"),\n principalType: String(t[\"principalType\"] ?? t[\"principal_type\"] ?? \"\"),\n workspacePatterns: Array.isArray(t[\"workspacePatterns\"] ?? t[\"workspace_patterns\"])\n ? ((t[\"workspacePatterns\"] ?? t[\"workspace_patterns\"]) as unknown[]).map(String)\n : [],\n scopes: Array.isArray(t[\"scopes\"]) ? (t[\"scopes\"] as unknown[]).map(String) : [],\n createdBy: String(t[\"createdBy\"] ?? t[\"created_by\"] ?? \"\"),\n expiresAt: Number(t[\"expiresAt\"] ?? t[\"expires_at\"] ?? 0),\n lastUsedAt: Number(t[\"lastUsedAt\"] ?? t[\"last_used_at\"] ?? 0),\n revoked: Boolean(t[\"revoked\"]),\n revokedAt: Number(t[\"revokedAt\"] ?? t[\"revoked_at\"] ?? 0),\n createdAt: Number(t[\"createdAt\"] ?? t[\"created_at\"] ?? 0),\n updatedAt: Number(t[\"updatedAt\"] ?? t[\"updated_at\"] ?? 0),\n });\n\n const rawToken = tr[\"token\"] as Record<string, unknown> | null | undefined;\n const rawCreated = tr[\"createdToken\"] ?? tr[\"created_token\"] as Record<string, unknown> | null | undefined;\n const rawTokens = tr[\"tokens\"];\n\n const response: TokenResponse = {\n success: Boolean(tr[\"success\"]),\n error: String(tr[\"error\"] ?? \"\"),\n message: String(tr[\"message\"] ?? \"\"),\n token: rawToken ? parseTokenInfo(rawToken) : undefined,\n tokens: Array.isArray(rawTokens) ? (rawTokens as Record<string, unknown>[]).map(parseTokenInfo) : [],\n totalCount: Number(tr[\"totalCount\"] ?? tr[\"total_count\"] ?? 0),\n plaintextToken: String(tr[\"plaintextToken\"] ?? tr[\"plaintext_token\"] ?? \"\"),\n createdToken: rawCreated ? parseTokenInfo(rawCreated as Record<string, unknown>) : undefined,\n requestId,\n };\n\n const pending = this._pendingTokenRequests.get(requestId);\n if (pending) {\n this._pendingTokenRequests.delete(requestId);\n pending(response);\n } else {\n this._onTokenResponse(response);\n }\n return;\n }\n\n if (data[\"proxyHttpResponse\"] || data[\"proxy_http_response\"]) {\n const raw = (data[\"proxyHttpResponse\"] ?? data[\"proxy_http_response\"]) as Record<string, unknown>;\n const requestId = String(raw[\"requestId\"] ?? raw[\"request_id\"] ?? \"\");\n const rawErr = raw[\"error\"] as Record<string, unknown> | null | undefined;\n const response = {\n requestId,\n statusCode: Number(raw[\"statusCode\"] ?? raw[\"status_code\"] ?? 0),\n headers: (raw[\"headers\"] ?? {}) as Record<string, string>,\n body: raw[\"body\"] instanceof Uint8Array ? raw[\"body\"] : new Uint8Array(),\n bodyChunked: Boolean(raw[\"bodyChunked\"] ?? raw[\"body_chunked\"]),\n error: rawErr ? { kind: Number(rawErr[\"kind\"] ?? 0), message: String(rawErr[\"message\"] ?? \"\") } : undefined,\n };\n\n // Streaming path: a header lands first (resolves the request), then a\n // post-header header frame is treated as a terminal mid-stream error.\n const streamSlot = this._pendingProxyHttpStreams.get(requestId);\n if (streamSlot) {\n if (streamSlot.headerResolved) {\n // Mid-stream error — close the stream with an error.\n if (response.error) {\n streamSlot.controller.error(new Error(`${response.error.message}`));\n } else {\n streamSlot.controller.close();\n }\n this._pendingProxyHttpStreams.delete(requestId);\n return;\n }\n streamSlot.headerResolved = true;\n const pending = this._pendingProxyHttpRequests.get(requestId);\n if (pending) {\n this._pendingProxyHttpRequests.delete(requestId);\n pending(response);\n }\n // If header already carries a terminal error (TTFB failure), close.\n if (response.error) {\n streamSlot.controller.error(new Error(`${response.error.message}`));\n this._pendingProxyHttpStreams.delete(requestId);\n }\n return;\n }\n\n if (response.bodyChunked) {\n // Store partial response — body will be assembled from chunks\n this._pendingProxyHttpChunks.set(requestId, []);\n // Stash the response shell to reuse when fin arrives\n // We reuse the pending map entry itself once fin arrives; store the shell alongside chunks\n (this._pendingProxyHttpChunks as Map<string, unknown>).set(requestId + \":shell\", response);\n } else {\n const pending = this._pendingProxyHttpRequests.get(requestId);\n if (pending) {\n this._pendingProxyHttpRequests.delete(requestId);\n pending(response);\n }\n }\n return;\n }\n\n if (data[\"proxyHttpBodyChunk\"] || data[\"proxy_http_body_chunk\"]) {\n const raw = (data[\"proxyHttpBodyChunk\"] ?? data[\"proxy_http_body_chunk\"]) as Record<string, unknown>;\n const requestId = String(raw[\"requestId\"] ?? raw[\"request_id\"] ?? \"\");\n const isRequest = Boolean(raw[\"isRequest\"] ?? raw[\"is_request\"]);\n if (isRequest) return; // sent by us; ignore echoes\n\n const data_ = raw[\"data\"] instanceof Uint8Array ? raw[\"data\"] : new Uint8Array();\n const fin = Boolean(raw[\"fin\"]);\n\n // Streaming-body path: enqueue directly into the caller's\n // ReadableStream<Uint8Array> controller.\n const streamSlot = this._pendingProxyHttpStreams.get(requestId);\n if (streamSlot) {\n if (data_.length > 0) {\n streamSlot.controller.enqueue(data_);\n }\n if (fin) {\n streamSlot.controller.close();\n this._pendingProxyHttpStreams.delete(requestId);\n }\n return;\n }\n\n const chunks = this._pendingProxyHttpChunks.get(requestId);\n if (chunks && Array.isArray(chunks)) {\n chunks.push(data_);\n if (fin) {\n // Assemble body\n const totalLen = chunks.reduce((s, c) => s + c.length, 0);\n const body = new Uint8Array(totalLen);\n let offset = 0;\n for (const c of chunks) { body.set(c, offset); offset += c.length; }\n\n this._pendingProxyHttpChunks.delete(requestId);\n const shell = (this._pendingProxyHttpChunks as Map<string, unknown>).get(requestId + \":shell\") as Record<string, unknown> | undefined;\n (this._pendingProxyHttpChunks as Map<string, unknown>).delete(requestId + \":shell\");\n\n const pending = this._pendingProxyHttpRequests.get(requestId);\n if (pending) {\n this._pendingProxyHttpRequests.delete(requestId);\n pending({ ...(shell ?? {}), body } as Parameters<typeof pending>[0]);\n }\n }\n }\n return;\n }\n\n if (data[\"tunnelData\"] || data[\"tunnel_data\"]) {\n const raw = (data[\"tunnelData\"] ?? data[\"tunnel_data\"]) as Record<string, unknown>;\n const tunnelId = String(raw[\"tunnelId\"] ?? raw[\"tunnel_id\"] ?? \"\");\n const rawData = raw[\"data\"];\n const bytes = rawData instanceof Uint8Array ? rawData : (Buffer.isBuffer(rawData) ? new Uint8Array(rawData) : new Uint8Array());\n const fin = Boolean(raw[\"fin\"]);\n const inflight = this._pendingTunnels.get(tunnelId);\n if (inflight) {\n inflight.pushData(bytes, fin);\n }\n return;\n }\n\n if (data[\"tunnelAck\"] || data[\"tunnel_ack\"]) {\n const raw = (data[\"tunnelAck\"] ?? data[\"tunnel_ack\"]) as Record<string, unknown>;\n const tunnelId = String(raw[\"tunnelId\"] ?? raw[\"tunnel_id\"] ?? \"\");\n const credits = Number(raw[\"credits\"] ?? 0);\n const inflight = this._pendingTunnels.get(tunnelId);\n if (inflight) {\n inflight.addCredits(credits);\n }\n return;\n }\n\n if (data[\"tunnelClose\"] || data[\"tunnel_close\"]) {\n const raw = (data[\"tunnelClose\"] ?? data[\"tunnel_close\"]) as Record<string, unknown>;\n const tunnelId = String(raw[\"tunnelId\"] ?? raw[\"tunnel_id\"] ?? \"\");\n const reason = String(raw[\"reason\"] ?? \"NORMAL\");\n const detail = String(raw[\"detail\"] ?? \"\");\n const inflight = this._pendingTunnels.get(tunnelId);\n if (inflight) {\n inflight.closeWithError(new TunnelClosedError(reason, detail));\n }\n return;\n }\n }\n\n // ===========================================================================\n // Error and Stream End Handling\n // ===========================================================================\n\n /**\n * Handles gRPC stream errors.\n * @internal\n */\n private _handleStreamError(err: Error): void {\n const wasConnected = this._connected;\n this._connected = false;\n\n if (this._disconnectRequested) {\n return;\n }\n\n if (wasConnected) {\n this._onDisconnect(err.message);\n }\n\n // Attempt reconnection if the error is recoverable\n if (this._connectionOpts.autoReconnect && isRecoverable(err)) {\n this._attemptReconnection();\n }\n }\n\n /**\n * Handles gRPC stream end.\n * @internal\n */\n private _handleStreamEnd(): void {\n const wasConnected = this._connected;\n this._connected = false;\n\n if (this._disconnectRequested) {\n return;\n }\n\n if (wasConnected) {\n this._onDisconnect(\"Stream ended\");\n }\n\n if (this._connectionOpts.autoReconnect) {\n this._attemptReconnection();\n }\n }\n\n /**\n * Attempts automatic reconnection with exponential backoff.\n * @internal\n */\n private async _attemptReconnection(): Promise<void> {\n // Prevent concurrent reconnection loops (e.g. both error and end handlers fire)\n if (this._reconnecting) {\n return;\n }\n this._reconnecting = true;\n\n try {\n let delay = this._connectionOpts.initialBackoff;\n const maxRetries = this._connectionOpts.maxRetries;\n\n for (let attempt = 1; maxRetries === 0 || attempt <= maxRetries; attempt++) {\n if (this._disconnectRequested) {\n return;\n }\n\n this._onReconnecting(attempt);\n\n // Wait with backoff\n await new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n if (this._disconnectRequested) {\n return;\n }\n\n try {\n // Clean up old connection before establishing new one\n await this._closeConnection();\n await this._establishConnection();\n this._connected = true;\n\n // Re-send init message is handled inside _establishConnection\n return;\n } catch {\n // Calculate next backoff delay\n delay = Math.min(\n delay * this._connectionOpts.backoffMultiplier,\n this._connectionOpts.maxBackoff,\n );\n // Add jitter (10% random variation)\n delay = delay * (0.9 + Math.random() * 0.2);\n }\n }\n\n // Exhausted all retries\n const err = new ReconnectionError(maxRetries);\n this._onDisconnect(err.message);\n } finally {\n this._reconnecting = false;\n }\n }\n\n // ===========================================================================\n // Progress Reporting\n // ===========================================================================\n\n /**\n * Reports progress for a task through the Aether gateway.\n *\n * Progress updates are routed through RabbitMQ Streams via the pg.{workspace}\n * topic with server-side recipient filtering.\n *\n * @param opts - Progress report options\n * @throws {@link ConnectionError} if not connected\n */\n reportProgress(opts: ReportProgressOptions): void {\n if (!this._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n\n const report: Record<string, unknown> = {\n taskId: opts.taskId,\n state: opts.state ?? \"\",\n completion: opts.completion ?? -1,\n summary: opts.summary ?? \"\",\n recipient: opts.recipient ?? \"\",\n requestId: opts.requestId ?? \"\",\n metadata: opts.metadata ?? {},\n };\n\n if (opts.stepName) {\n report[\"step\"] = {\n name: opts.stepName,\n detail: opts.stepDetail ?? \"\",\n sequence: opts.stepSequence ?? 0,\n totalSteps: opts.stepTotal ?? 0,\n stepType: opts.stepType ?? \"\",\n };\n }\n\n this._sendUpstream({ progressReport: report });\n }\n\n // ===========================================================================\n // Internal Send Helper\n // ===========================================================================\n\n /**\n * Encodes a Metric object to protobuf bytes using the loaded proto descriptor.\n *\n * Uses the `aether.v1.Metric` type from the package definition stored at\n * connection time. Throws if the descriptor is not yet available — sending\n * JSON-encoded bytes here would silently fail on the gateway with\n * ERR_METRIC_INVALID, so we eagerly surface the misuse.\n *\n * @param metric - The metric object to encode\n * @returns Encoded bytes\n * @internal\n */\n protected _encodeMetric(metric: Record<string, unknown>): Uint8Array {\n const pkgDef = this._packageDefinition;\n if (!pkgDef) {\n throw new Error(\"Cannot encode metric: proto descriptor not loaded — call connect() first\");\n }\n const metricType = pkgDef[\"aether.v1.Metric\"] as { encode: (obj: unknown) => { finish: () => Uint8Array } } | undefined;\n if (!metricType?.encode) {\n throw new Error(\"Cannot encode metric: aether.v1.Metric not present in loaded proto descriptor\");\n }\n return metricType.encode(metric).finish();\n }\n\n /**\n * Low-level message send helper used by subclasses.\n * @internal\n */\n protected _sendMessage(targetTopic: string, payload: Uint8Array, messageType: MessageType): void {\n this._sendUpstream({\n send: {\n targetTopic,\n payload,\n messageType,\n },\n });\n }\n\n // ===========================================================================\n // Task Management\n // ===========================================================================\n\n /**\n * Parses a raw task info object from the server into a TaskInfo.\n * @internal\n */\n private _parseTaskInfo(t: Record<string, unknown>): TaskInfo {\n return {\n taskId: String(t[\"taskId\"] ?? t[\"task_id\"] ?? \"\"),\n taskType: String(t[\"taskType\"] ?? t[\"task_type\"] ?? \"\"),\n status: String(t[\"status\"] ?? \"\"),\n workspace: String(t[\"workspace\"] ?? \"\"),\n targetTopic: String(t[\"targetTopic\"] ?? t[\"target_topic\"] ?? \"\"),\n assignedTo: String(t[\"assignedTo\"] ?? t[\"assigned_to\"] ?? \"\"),\n createdAt: Number(t[\"createdAt\"] ?? t[\"created_at\"] ?? 0),\n startedAt: Number(t[\"startedAt\"] ?? t[\"started_at\"] ?? 0),\n completedAt: Number(t[\"completedAt\"] ?? t[\"completed_at\"] ?? 0),\n attempt: Number(t[\"attempt\"] ?? 0),\n maxAttempts: Number(t[\"maxAttempts\"] ?? t[\"max_attempts\"] ?? 0),\n error: String(t[\"error\"] ?? \"\"),\n metadata: (t[\"metadata\"] ?? {}) as Record<string, string>,\n };\n }\n\n /**\n * Parses a raw authority grant object from the server into an AuthorityGrantInfo.\n * @internal\n */\n private _parseAuthorityGrantInfo(g: Record<string, unknown>): AuthorityGrantInfo {\n const parsePrincipalRef = (ref: unknown) => {\n if (!ref || typeof ref !== \"object\") {\n return undefined;\n }\n const value = ref as Record<string, unknown>;\n return {\n principalType: String(value[\"principalType\"] ?? value[\"principal_type\"] ?? \"\"),\n principalId: String(value[\"principalId\"] ?? value[\"principal_id\"] ?? \"\"),\n };\n };\n\n const parseResourceScope = (entry: unknown) => {\n const value = (entry ?? {}) as Record<string, unknown>;\n return {\n resourceType: String(value[\"resourceType\"] ?? value[\"resource_type\"] ?? \"\"),\n patterns: Array.isArray(value[\"patterns\"]) ? (value[\"patterns\"] as unknown[]).map(String) : [],\n };\n };\n\n return {\n grantId: String(g[\"grantId\"] ?? g[\"grant_id\"] ?? \"\"),\n rootGrantId: String(g[\"rootGrantId\"] ?? g[\"root_grant_id\"] ?? \"\"),\n subject: parsePrincipalRef(g[\"subject\"]),\n delegate: parsePrincipalRef(g[\"delegate\"]),\n issuedBy: parsePrincipalRef(g[\"issuedBy\"] ?? g[\"issued_by\"]),\n rootSubject: parsePrincipalRef(g[\"rootSubject\"] ?? g[\"root_subject\"]),\n parentGrantId: String(g[\"parentGrantId\"] ?? g[\"parent_grant_id\"] ?? \"\"),\n mayDelegate: Boolean(g[\"mayDelegate\"] ?? g[\"may_delegate\"]),\n remainingHops: Number(g[\"remainingHops\"] ?? g[\"remaining_hops\"] ?? 0),\n workspaceScope: Array.isArray(g[\"workspaceScope\"] ?? g[\"workspace_scope\"])\n ? ((g[\"workspaceScope\"] ?? g[\"workspace_scope\"]) as unknown[]).map(String)\n : [],\n resourceScope: Array.isArray(g[\"resourceScope\"] ?? g[\"resource_scope\"])\n ? ((g[\"resourceScope\"] ?? g[\"resource_scope\"]) as unknown[]).map(parseResourceScope)\n : [],\n operationScope: Array.isArray(g[\"operationScope\"] ?? g[\"operation_scope\"])\n ? ((g[\"operationScope\"] ?? g[\"operation_scope\"]) as unknown[]).map(String)\n : [],\n maxAccessLevel: Number(g[\"maxAccessLevel\"] ?? g[\"max_access_level\"] ?? 0),\n accessLevelName: String(g[\"accessLevelName\"] ?? g[\"access_level_name\"] ?? \"\"),\n audienceType: String(g[\"audienceType\"] ?? g[\"audience_type\"] ?? \"\"),\n audienceId: String(g[\"audienceId\"] ?? g[\"audience_id\"] ?? \"\"),\n validWhileAudienceActive: Boolean(g[\"validWhileAudienceActive\"] ?? g[\"valid_while_audience_active\"]),\n expiresAt: Number(g[\"expiresAt\"] ?? g[\"expires_at\"] ?? 0),\n renewableUntil: Number(g[\"renewableUntil\"] ?? g[\"renewable_until\"] ?? 0),\n renewedAt: Number(g[\"renewedAt\"] ?? g[\"renewed_at\"] ?? 0),\n revoked: Boolean(g[\"revoked\"]),\n revokedAt: Number(g[\"revokedAt\"] ?? g[\"revoked_at\"] ?? 0),\n reason: String(g[\"reason\"] ?? \"\"),\n metadata: (g[\"metadata\"] ?? {}) as Record<string, string>,\n createdAt: Number(g[\"createdAt\"] ?? g[\"created_at\"] ?? 0),\n };\n }\n\n /**\n * Lists tasks with optional filters.\n */\n queryTasks(opts: TaskQueryOptions = {}): Promise<TaskQueryResponse> {\n const timeout = opts.timeout ?? 10000;\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskQueryRequests.delete(requestId);\n reject(new Error(\"queryTasks timed out\"));\n }, timeout);\n\n this._pendingTaskQueryRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskQuery: {\n op: 0, // LIST\n requestId,\n filter: {\n status: opts.status ?? \"\",\n workspace: opts.workspace ?? \"\",\n taskType: opts.taskType ?? \"\",\n limit: opts.limit ?? 0,\n offset: opts.offset ?? 0,\n },\n },\n });\n });\n }\n\n /**\n * Gets a specific task by ID.\n */\n getTask(taskId: string, timeout = 10000): Promise<TaskQueryResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskQueryRequests.delete(requestId);\n reject(new Error(\"getTask timed out\"));\n }, timeout);\n\n this._pendingTaskQueryRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskQuery: {\n op: 1, // GET\n taskId,\n requestId,\n },\n });\n });\n }\n\n /**\n * Cancels a running or queued task.\n */\n cancelTask(taskId: string, reason = \"\", timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"cancelTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 1, // CANCEL\n taskId,\n reason,\n requestId,\n },\n });\n });\n }\n\n /**\n * Retries a failed task.\n */\n retryTask(taskId: string, timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"retryTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 0, // RETRY\n taskId,\n requestId,\n },\n });\n });\n }\n\n /**\n * Completes a task (for POOL workers).\n */\n completeTask(taskId: string, timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"completeTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 2, // COMPLETE\n taskId,\n requestId,\n },\n });\n });\n }\n\n /**\n * Marks a task as failed (for POOL workers).\n */\n failTask(taskId: string, reason = \"\", timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"failTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 3, // FAIL\n taskId,\n reason,\n requestId,\n },\n });\n });\n }\n\n // ===========================================================================\n // Create Task (blocking)\n // ===========================================================================\n\n /**\n * Sends a CreateTaskRequest and waits for the server's CreateTaskResponse.\n *\n * A unique request_id is injected automatically so the response can be\n * correlated. Unlike the fire-and-forget `createTask` override in subclasses,\n * this method blocks until the gateway echoes back the assigned task_id.\n *\n * @param op - CreateTaskRequest fields (task_type, workspace, assignment_mode, etc.)\n * @param timeout - Timeout in ms (default 10 000)\n * @returns Promise resolving to the CreateTaskResponse\n */\n createTaskBlocking(op: Record<string, unknown>, timeout = 10000): Promise<CreateTaskResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingCreateTaskRequests.delete(requestId);\n reject(new Error(\"createTaskBlocking timed out\"));\n }, timeout);\n\n this._pendingCreateTaskRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n createTask: { ...op, requestId },\n });\n });\n }\n\n // ===========================================================================\n // Workspace / Agent / ACL / Workflow Operations\n // ===========================================================================\n\n /**\n * Sends a workspace operation upstream.\n *\n * @param op - The workspace operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the workspace response\n */\n sendWorkspaceOperation(op: Record<string, unknown>, timeout = 10000): Promise<WorkspaceResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingWorkspaceRequests.delete(requestId);\n reject(new Error(\"workspace operation timed out\"));\n }, timeout);\n\n this._pendingWorkspaceRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n workspaceOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Sends an agent operation upstream.\n *\n * @param op - The agent operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the agent response\n */\n sendAgentOperation(op: Record<string, unknown>, timeout = 10000): Promise<AgentResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingAgentRequests.delete(requestId);\n reject(new Error(\"agent operation timed out\"));\n }, timeout);\n\n this._pendingAgentRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n agentOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Sends an ACL operation upstream.\n *\n * @param op - The ACL operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the ACL response\n */\n sendACLOperation(op: Record<string, unknown>, timeout = 10000): Promise<ACLResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingACLRequests.delete(requestId);\n reject(new Error(\"ACL operation timed out\"));\n }, timeout);\n\n this._pendingACLRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n aclOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Sends a runtime authority-grant operation upstream.\n *\n * @param op - The authority grant operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the authority-grant response\n */\n sendAuthorityGrantOperation(op: Record<string, unknown>, timeout = 10000): Promise<AuthorityGrantResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingAuthorityGrantRequests.delete(requestId);\n reject(new Error(\"authority grant operation timed out\"));\n }, timeout);\n\n this._pendingAuthorityGrantRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n authorityGrantOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Submits a foreign audit event to the gateway's audit pipeline.\n *\n * @param opts - Audit event fields\n * @param timeout - Timeout in ms (default 10 000)\n * @returns Promise resolving to the audit-submit response\n */\n submitAuditEvent(\n opts: {\n eventType: string;\n operation?: string;\n resourceType?: string;\n resourceId?: string;\n workspace?: string;\n success?: boolean;\n errorMessage?: string;\n metadata?: Record<string, string>;\n },\n timeout = 10000,\n ): Promise<AuditSubmitResponse> {\n const clientRequestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingAuditSubmitRequests.delete(clientRequestId);\n reject(new Error(\"submit audit event timed out\"));\n }, timeout);\n this._pendingAuditSubmitRequests.set(clientRequestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n this._sendUpstream({\n submitAuditEvent: {\n clientRequestId,\n eventType: opts.eventType,\n operation: opts.operation ?? \"\",\n resourceType: opts.resourceType ?? \"\",\n resourceId: opts.resourceId ?? \"\",\n workspace: opts.workspace ?? \"\",\n success: opts.success ?? true,\n errorMessage: opts.errorMessage ?? \"\",\n metadata: opts.metadata ?? {},\n },\n });\n });\n }\n\n /**\n * Sends a workflow operation upstream.\n *\n * @param op - The workflow operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the workflow response\n */\n sendWorkflowOperation(op: Record<string, unknown>, timeout = 10000): Promise<WorkflowResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingWorkflowRequests.delete(requestId);\n reject(new Error(\"workflow operation timed out\"));\n }, timeout);\n\n this._pendingWorkflowRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n workflowOp: { ...op, requestId },\n });\n });\n }\n\n // ===========================================================================\n // Workspace / Agent / ACL / Workflow Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for workspace operation responses.\n *\n * @param handler - Function called when a workspace response is received\n */\n onWorkspaceResponse(handler: WorkspaceResponseHandler): void {\n this._onWorkspaceResponse = handler;\n }\n\n /**\n * Registers a handler for agent operation responses.\n *\n * @param handler - Function called when an agent response is received\n */\n onAgentResponse(handler: AgentResponseHandler): void {\n this._onAgentResponse = handler;\n }\n\n /**\n * Registers a handler for ACL operation responses.\n *\n * @param handler - Function called when an ACL response is received\n */\n onACLResponse(handler: ACLResponseHandler): void {\n this._onACLResponse = handler;\n }\n\n /**\n * Registers a handler for runtime authority-grant responses.\n *\n * @param handler - Function called when an authority-grant response is received\n */\n onAuthorityGrantResponse(handler: AuthorityGrantResponseHandler): void {\n this._onAuthorityGrantResponse = handler;\n }\n\n /**\n * Registers a handler for unsolicited audit-submit responses (i.e. responses\n * not correlated to a pending {@link submitAuditEvent} call).\n *\n * @param handler - Function called when an audit-submit response is received\n */\n onAuditSubmitResponse(handler: AuditSubmitResponseHandler): void {\n this._onAuditSubmitResponse = handler;\n }\n\n /**\n * Registers a handler for server-pushed AuthorityGrantRevocation events.\n * Caches registered via {@link makeAuthorityCache} are invoked first; the\n * user handler runs after every cache has been notified.\n */\n onAuthorityGrantRevocation(handler: AuthorityGrantRevocationHandler): void {\n this._onAuthorityGrantRevocation = handler;\n }\n\n // =========================================================================\n // Authority Grant High-Level Wrappers\n //\n // Low-level: one method per AuthorityGrantOperation op. For ergonomic\n // caching, soft-renew, and revocation invalidation use\n // {@link makeAuthorityCache} and its high-level helpers\n // (getOrExchange / deriveForTask / isValid / listActive /\n // revokeLocal / refresh).\n // =========================================================================\n\n /**\n * Bootstrap a runtime authority grant for the current actor.\n *\n * If `sourceSessionId` is empty, only a user may self-exchange. When it\n * is set, the caller must hold the `_perm:exchange_authority_grants`\n * permission and the referenced session must belong to an active user.\n */\n exchangeAuthorityGrant(\n opts: {\n sourceSessionId?: string;\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n audienceType?: string;\n audienceId?: string;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n } = {},\n ): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"EXCHANGE\",\n exchangeRequest: {\n sourceSessionId: opts.sourceSessionId ?? \"\",\n workspaceScope: opts.workspaceScope ?? [],\n resourceScope: opts.resourceScope ?? [],\n operationScope: opts.operationScope ?? [],\n maxAccessLevel: opts.maxAccessLevel ?? 0,\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n validWhileAudienceActive: opts.validWhileAudienceActive ?? false,\n expiresAt: opts.expiresAt ?? 0,\n renewableUntil: opts.renewableUntil ?? 0,\n mayDelegate: opts.mayDelegate ?? false,\n remainingHops: opts.remainingHops ?? 0,\n reason: opts.reason ?? \"\",\n metadata: opts.metadata ?? {},\n },\n },\n opts.timeout,\n );\n }\n\n /**\n * Derive a child runtime authority grant for a downstream delegate.\n */\n deriveAuthorityGrant(opts: {\n parentGrantId: string;\n delegateType: string;\n delegateId: string;\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n audienceType?: string;\n audienceId?: string;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"DERIVE\",\n deriveRequest: {\n parentGrantId: opts.parentGrantId,\n delegate: { principalType: opts.delegateType, principalId: opts.delegateId },\n workspaceScope: opts.workspaceScope ?? [],\n resourceScope: opts.resourceScope ?? [],\n operationScope: opts.operationScope ?? [],\n maxAccessLevel: opts.maxAccessLevel ?? 0,\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n validWhileAudienceActive: opts.validWhileAudienceActive ?? false,\n expiresAt: opts.expiresAt ?? 0,\n renewableUntil: opts.renewableUntil ?? 0,\n mayDelegate: opts.mayDelegate ?? false,\n remainingHops: opts.remainingHops ?? 0,\n reason: opts.reason ?? \"\",\n metadata: opts.metadata ?? {},\n },\n },\n opts.timeout,\n );\n }\n\n /** Get a runtime authority grant by ID. */\n getAuthorityGrant(grantId: string, timeout?: number): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation({ op: \"GET\", grantId }, timeout);\n }\n\n /**\n * Renew a runtime authority grant lease. `expiresAt` (proto units) takes\n * precedence; `extendSeconds` extends the current expiry by N seconds\n * server-side and is ignored when `expiresAt` is non-zero.\n */\n renewAuthorityGrant(opts: {\n grantId: string;\n expiresAt?: number;\n extendSeconds?: number;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"RENEW\",\n grantId: opts.grantId,\n renewRequest: {\n grantId: opts.grantId,\n expiresAt: opts.expiresAt ?? 0,\n extendSeconds: opts.extendSeconds ?? 0,\n },\n },\n opts.timeout,\n );\n }\n\n /** Revoke a runtime authority grant by ID. */\n revokeAuthorityGrant(grantId: string, timeout?: number): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation({ op: \"REVOKE\", grantId }, timeout);\n }\n\n /** List grants where the actor is delegate or subject. */\n listMyAuthorityGrants(opts: {\n audienceType?: string;\n audienceId?: string;\n includeRevoked?: boolean;\n limit?: number;\n offset?: number;\n timeout?: number;\n } = {}): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"LIST_MY_GRANTS\",\n listRequest: {\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n includeRevoked: opts.includeRevoked ?? false,\n limit: opts.limit ?? 0,\n offset: opts.offset ?? 0,\n },\n },\n opts.timeout,\n );\n }\n\n /** List grants where the actor is the subject (i.e., grants OTHERS hold on me). */\n listAuthorityGrantsOnMe(opts: {\n audienceType?: string;\n audienceId?: string;\n includeRevoked?: boolean;\n limit?: number;\n offset?: number;\n timeout?: number;\n } = {}): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"LIST_GRANTS_ON_ME\",\n listRequest: {\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n includeRevoked: opts.includeRevoked ?? false,\n limit: opts.limit ?? 0,\n offset: opts.offset ?? 0,\n },\n },\n opts.timeout,\n );\n }\n\n /** Exchange multiple authority grants in a single round-trip. */\n batchExchangeAuthorityGrants(opts: {\n requests: Record<string, unknown>[];\n stopOnFirstError?: boolean;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"BATCH_EXCHANGE\",\n batchExchangeRequest: {\n requests: opts.requests,\n stopOnFirstError: opts.stopOnFirstError ?? false,\n },\n },\n opts.timeout,\n );\n }\n\n /**\n * Idempotent derive: returns existing visible grant matching\n * (parentGrantId, target, audience) or mints a new one.\n *\n * Safe to call repeatedly without leaking grants.\n */\n deriveAuthorityGrantForTarget(opts: {\n parentGrantId: string;\n targetType: string;\n targetId: string;\n audienceType?: string;\n audienceId?: string;\n operationScope?: string[];\n maxAccessLevel?: number;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"DERIVE_FOR_TARGET\",\n deriveForTargetRequest: {\n parentGrantId: opts.parentGrantId,\n target: { principalType: opts.targetType, principalId: opts.targetId },\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n operationScope: opts.operationScope ?? [],\n maxAccessLevel: opts.maxAccessLevel ?? 0,\n expiresAt: opts.expiresAt ?? 0,\n renewableUntil: opts.renewableUntil ?? 0,\n mayDelegate: opts.mayDelegate ?? false,\n remainingHops: opts.remainingHops ?? 0,\n reason: opts.reason ?? \"\",\n },\n },\n opts.timeout,\n );\n }\n\n /**\n * Construct a new {@link AuthorityGrantCache} wired into this client.\n * AuthorityGrantRevocation push events on the downstream stream are\n * dispatched to the cache automatically. Call {@link AuthorityGrantCache.close}\n * to deregister it.\n */\n makeAuthorityCache(opts: AuthorityGrantCacheOptions = {}): AuthorityGrantCache {\n const cache = new AuthorityGrantCache(this, opts);\n this._authorityGrantCaches.push(cache);\n return cache;\n }\n\n /** @internal */\n _removeAuthorityCache(cache: AuthorityGrantCache): void {\n this._authorityGrantCaches = this._authorityGrantCaches.filter((c) => c !== cache);\n }\n\n /**\n * Registers a handler for workflow operation responses.\n *\n * @param handler - Function called when a workflow response is received\n */\n onWorkflowResponse(handler: WorkflowResponseHandler): void {\n this._onWorkflowResponse = handler;\n }\n\n /**\n * Sends a token management operation to the gateway.\n *\n * @param op - The token operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the token response\n */\n sendTokenOperation(op: Record<string, unknown>, timeout = 10000): Promise<TokenResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTokenRequests.delete(requestId);\n reject(new Error(\"token operation timed out\"));\n }, timeout);\n\n this._pendingTokenRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n tokenOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Registers a handler for token operation responses.\n *\n * @param handler - Function called when a token response is received\n */\n onTokenResponse(handler: TokenResponseHandler): void {\n this._onTokenResponse = handler;\n }\n}\n","/**\n * Admin client for the Aether TypeScript SDK.\n *\n * AdminClient wraps a connected AetherClient and provides named helper methods\n * for all administrative operations exposed through the gRPC streaming protocol:\n * token management, ACL rules, workspace CRUD, agent registry, and gateway\n * health / connection queries.\n *\n * The underlying AetherClient must already be connected before calling any\n * AdminClient method. All methods return Promises that resolve when the\n * gateway sends the correlated response, or reject on timeout.\n *\n * @module admin\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type {\n TokenResponse,\n ACLResponse,\n WorkspaceResponse,\n AgentResponse,\n} from \"./types.js\";\n\n// =============================================================================\n// Shared option types\n// =============================================================================\n\n/** Timeout option shared by all admin methods. */\nexport interface AdminTimeoutOptions {\n /** Operation timeout in milliseconds. Default: 10000. */\n timeout?: number;\n}\n\n// =============================================================================\n// Token operation types\n// =============================================================================\n\n/** Options for creating an API token. */\nexport interface CreateTokenOptions extends AdminTimeoutOptions {\n /** Human-readable name for the token. Required. */\n name: string;\n /** Principal type this token authenticates (e.g., \"agent\", \"user\"). */\n principalType?: string;\n /** Glob patterns for workspaces this token may access. */\n workspacePatterns?: string[];\n /** Permission scopes granted by this token. */\n scopes?: string[];\n /** Expiry duration in seconds from now (0 = no expiry). */\n expiresInSeconds?: number;\n}\n\n/** Options for revoking an API token. */\nexport interface RevokeTokenOptions extends AdminTimeoutOptions {\n /** Token ID to revoke. Required. */\n tokenId: string;\n}\n\n/** Options for listing API tokens. */\nexport interface ListTokensOptions extends AdminTimeoutOptions {\n /** Filter by principal type. */\n principalType?: string;\n /** If true, include revoked tokens in results. */\n includeRevoked?: boolean;\n /** Maximum number of results to return. */\n limit?: number;\n}\n\n// =============================================================================\n// ACL operation types\n// =============================================================================\n\n/** Options for creating an ACL rule (granting access). */\nexport interface CreateACLRuleOptions extends AdminTimeoutOptions {\n /** Principal type being granted access (e.g., \"agent\", \"user\"). Required. */\n principalType: string;\n /** Principal ID being granted access. Required. */\n principalId: string;\n /** Resource type the access applies to (e.g., \"workspace\"). Required. */\n resourceType: string;\n /** Resource ID the access applies to. Required. */\n resourceId: string;\n /** Permission level (e.g., \"read\", \"write\", \"admin\"). Required. */\n permission: string;\n /** Optional expiry as Unix timestamp (seconds). 0 = no expiry. */\n expiresAt?: number;\n /** Arbitrary metadata to attach to the rule. */\n metadata?: Record<string, string>;\n}\n\n/** Options for deleting an ACL rule. */\nexport interface DeleteACLRuleOptions extends AdminTimeoutOptions {\n /** Rule ID to delete. Required. */\n ruleId: string;\n}\n\n/** Options for listing ACL rules. */\nexport interface ListACLRulesOptions extends AdminTimeoutOptions {\n /** Filter by principal type. */\n principalType?: string;\n /** Filter by principal ID. */\n principalId?: string;\n /** Filter by resource type. */\n resourceType?: string;\n /** Filter by resource ID. */\n resourceId?: string;\n}\n\n/** Options for reading a fallback policy by category. */\nexport interface GetFallbackPolicyOptions extends AdminTimeoutOptions {\n /**\n * Rule category, formatted as \"{principal_type}_{resource_type}\" (e.g.,\n * \"user_workspace\", \"agent_kv_scope\", \"service_kv_scope\").\n */\n ruleCategory: string;\n}\n\n/** Options for upserting a fallback policy. */\nexport interface SetFallbackPolicyOptions extends AdminTimeoutOptions {\n /** Rule category to upsert. */\n ruleCategory: string;\n /**\n * Default access level when no explicit acl_rules row matches. Use the\n * numeric tiers from internal/acl/types.go: 0=NONE, 10=READ, 20=READWRITE,\n * 30=MANAGE, 40=ADMIN, 50=SUPERADMIN.\n */\n fallbackAccessLevel: number;\n}\n\n/** Principal reference used by authority-grant admin operations. */\nexport interface AuthorityGrantPrincipalRef {\n principalType: string;\n principalId: string;\n}\n\n/** Resource-specific scope entry for authority grants. */\nexport interface AuthorityGrantResourceScope {\n resourceType: string;\n patterns: string[];\n}\n\n// NOTE: ListAuthorityGrantsOptions / GetAuthorityGrantOptions /\n// CreateAuthorityGrantOptions / RenewAuthorityGrantOptions /\n// RevokeAuthorityGrantOptions were removed alongside the corresponding\n// streaming-admin methods. The streaming ACLOperation no longer carries\n// authority-grant ops; use the runtime AuthorityGrantOperation surface\n// (Phase 4 SDK cache helpers) or the REST admin endpoints for management.\n\n// =============================================================================\n// Workspace operation types\n// =============================================================================\n\n/** Options for listing workspaces. */\nexport interface ListWorkspacesOptions extends AdminTimeoutOptions {\n /** Maximum number of results to return. */\n limit?: number;\n /** Offset for pagination. */\n offset?: number;\n}\n\n/** Data for creating a workspace. */\nexport interface CreateWorkspaceOptions extends AdminTimeoutOptions {\n /** Workspace ID (the string identifier). Required. */\n workspaceId: string;\n /** Human-readable display name. */\n displayName?: string;\n /** Arbitrary metadata. */\n metadata?: Record<string, string>;\n}\n\n/** Data for updating a workspace. */\nexport interface UpdateWorkspaceOptions extends AdminTimeoutOptions {\n /** Workspace ID to update. Required. */\n workspaceId: string;\n /** New display name. */\n displayName?: string;\n /** Updated metadata. */\n metadata?: Record<string, string>;\n}\n\n/** Options for deleting a workspace. */\nexport interface DeleteWorkspaceOptions extends AdminTimeoutOptions {\n /** Workspace ID to delete. Required. */\n workspaceId: string;\n}\n\n// =============================================================================\n// Agent operation types\n// =============================================================================\n\n/** Options for listing registered agent types. */\nexport interface ListAgentsOptions extends AdminTimeoutOptions {\n /** Filter by workspace. */\n workspace?: string;\n /** Maximum number of results to return. */\n limit?: number;\n}\n\n/** Options for getting a specific agent registration. */\nexport interface GetAgentOptions extends AdminTimeoutOptions {\n /** The agent implementation name. Required. */\n implementation: string;\n}\n\n// =============================================================================\n// Admin query types\n// =============================================================================\n\n/** Response from admin queries. Loosely typed to accommodate the AdminResponse oneof. */\nexport interface AdminQueryResponse {\n readonly success: boolean;\n readonly error: string;\n readonly health?: Record<string, unknown>;\n readonly info?: Record<string, unknown>;\n readonly stats?: Record<string, unknown>;\n readonly connection?: Record<string, unknown>;\n readonly connections?: Record<string, unknown>[];\n readonly totalCount: number;\n}\n\n/** Handler type for admin query responses. */\nexport type AdminQueryResponseHandler = (response: AdminQueryResponse) => void | Promise<void>;\n\n/** Options for listing connections. */\nexport interface ListConnectionsOptions extends AdminTimeoutOptions {\n /** Filter by workspace. */\n workspace?: string;\n /** Filter by principal type. */\n principalType?: string;\n}\n\n/** Options for disconnecting a session. */\nexport interface DisconnectSessionOptions extends AdminTimeoutOptions {\n /** Session ID to disconnect. Required. */\n sessionId: string;\n /** Optional reason message sent to the disconnected client. */\n reason?: string;\n}\n\n// =============================================================================\n// AdminClient\n// =============================================================================\n\n/**\n * Administrative client for managing an Aether gateway.\n *\n * AdminClient wraps any connected {@link AetherClient} (typically an\n * AgentClient or UserClient) and exposes named helper methods for the full\n * set of administrative operations that are available through the gRPC\n * streaming protocol.\n *\n * @example\n * ```typescript\n * import { AgentClient, AdminClient } from \"@scitrera/aether-client\";\n *\n * const agent = new AgentClient({\n * address: \"localhost:50051\",\n * workspace: \"default\",\n * implementation: \"admin-agent\",\n * specifier: \"ops-1\",\n * credentials: { \"x-api-key\": \"my-admin-key\" },\n * });\n * await agent.connect();\n *\n * const admin = new AdminClient(agent);\n *\n * // List workspaces\n * const wsr = await admin.listWorkspaces();\n * console.log(wsr);\n *\n * // Create a token\n * const tr = await admin.createToken({ name: \"ci-token\", principalType: \"agent\" });\n * console.log(tr.plaintextToken);\n * ```\n */\nexport class AdminClient {\n private readonly _client: AetherClient;\n\n /**\n * Creates an AdminClient backed by the given AetherClient.\n *\n * The AetherClient must be connected before calling any method.\n *\n * @param client - A connected AetherClient instance\n */\n constructor(client: AetherClient) {\n this._client = client;\n }\n\n // ===========================================================================\n // Token Operations\n // ===========================================================================\n\n /**\n * Creates a new API token.\n *\n * @param opts - Token creation parameters\n * @returns Promise resolving to the token response (includes plaintextToken)\n */\n createToken(opts: CreateTokenOptions): Promise<TokenResponse> {\n const { timeout, name, principalType, workspacePatterns, scopes, expiresInSeconds } = opts;\n return this._client.sendTokenOperation(\n {\n op: \"CREATE\",\n createRequest: {\n name,\n principalType: principalType ?? \"\",\n workspacePatterns: workspacePatterns ?? [],\n scopes: scopes ?? [],\n expiresInSeconds: expiresInSeconds ?? 0,\n },\n },\n timeout,\n );\n }\n\n /**\n * Revokes an API token by ID.\n *\n * @param opts - Revoke options containing the token ID\n * @returns Promise resolving to the token response\n */\n revokeToken(opts: RevokeTokenOptions): Promise<TokenResponse> {\n const { timeout, tokenId } = opts;\n return this._client.sendTokenOperation({ op: \"REVOKE\", tokenId }, timeout);\n }\n\n /**\n * Lists API tokens with optional filters.\n *\n * @param opts - List options\n * @returns Promise resolving to the token response (tokens array)\n */\n listTokens(opts: ListTokensOptions = {}): Promise<TokenResponse> {\n const { timeout, principalType, includeRevoked, limit } = opts;\n return this._client.sendTokenOperation(\n {\n op: \"LIST\",\n filter: {\n principalType: principalType ?? \"\",\n includeRevoked: includeRevoked ?? false,\n limit: limit ?? 0,\n },\n },\n timeout,\n );\n }\n\n // ===========================================================================\n // ACL Operations\n // ===========================================================================\n\n /**\n * Creates an ACL rule granting access.\n *\n * @param opts - ACL rule creation parameters\n * @returns Promise resolving to the ACL response\n */\n createACLRule(opts: CreateACLRuleOptions): Promise<ACLResponse> {\n const { timeout, principalType, principalId, resourceType, resourceId, permission, expiresAt, metadata } = opts;\n return this._client.sendACLOperation(\n {\n op: \"GRANT\",\n grantRequest: {\n principalType,\n principalId,\n resourceType,\n resourceId,\n permission,\n expiresAt: expiresAt ?? 0,\n metadata: metadata ?? {},\n },\n },\n timeout,\n );\n }\n\n /**\n * Deletes an ACL rule by ID.\n *\n * @param opts - Delete options containing the rule ID\n * @returns Promise resolving to the ACL response\n */\n deleteACLRule(opts: DeleteACLRuleOptions): Promise<ACLResponse> {\n const { timeout, ruleId } = opts;\n return this._client.sendACLOperation({ op: \"REVOKE\", ruleId }, timeout);\n }\n\n /**\n * Lists ACL rules with optional filters.\n *\n * @param opts - List options\n * @returns Promise resolving to the ACL response (rules array in response)\n */\n listACLRules(opts: ListACLRulesOptions = {}): Promise<ACLResponse> {\n const { timeout, principalType, principalId, resourceType, resourceId } = opts;\n return this._client.sendACLOperation(\n {\n op: \"LIST_RULES\",\n ruleFilter: {\n principalType: principalType ?? \"\",\n principalId: principalId ?? \"\",\n resourceType: resourceType ?? \"\",\n resourceId: resourceId ?? \"\",\n },\n },\n timeout,\n );\n }\n\n /**\n * Reads the fallback policy for a rule category.\n *\n * Fallback policies decide the default ACL outcome when no explicit\n * `acl_rules` row matches the (principal_type, resource_type) pair.\n * The `ruleCategory` is the catonical\n * `{principal_type}_{resource_type}` slug — e.g., \"agent_kv_scope\".\n */\n getFallbackPolicy(opts: GetFallbackPolicyOptions): Promise<ACLResponse> {\n const { timeout, ruleCategory } = opts;\n return this._client.sendACLOperation(\n { op: \"GET_FALLBACK_POLICY\", ruleCategory },\n timeout,\n );\n }\n\n /**\n * Upserts a fallback policy for a rule category.\n *\n * Use ``fallbackAccessLevel: 0`` to flip a category to default-deny.\n */\n setFallbackPolicy(opts: SetFallbackPolicyOptions): Promise<ACLResponse> {\n const { timeout, ruleCategory, fallbackAccessLevel } = opts;\n return this._client.sendACLOperation(\n {\n op: \"SET_FALLBACK_POLICY\",\n ruleCategory,\n fallbackRequest: {\n ruleCategory,\n fallbackAccessLevel,\n },\n },\n timeout,\n );\n }\n\n // NOTE: listAuthorityGrants / getAuthorityGrant / createAuthorityGrant /\n // renewAuthorityGrant / revokeAuthorityGrant were removed alongside the\n // corresponding streaming ACLOperation cases. Use the runtime\n // AuthorityGrantOperation surface (Phase 4 SDK cache helpers) or the\n // REST admin endpoints for management.\n\n // ===========================================================================\n // Workspace Operations\n // ===========================================================================\n\n /**\n * Lists workspaces.\n *\n * @param opts - List options\n * @returns Promise resolving to the workspace response\n */\n listWorkspaces(opts: ListWorkspacesOptions = {}): Promise<WorkspaceResponse> {\n const { timeout, limit, offset } = opts;\n return this._client.sendWorkspaceOperation(\n {\n op: \"LIST\",\n filter: { limit: limit ?? 0, offset: offset ?? 0 },\n },\n timeout,\n );\n }\n\n /**\n * Creates a new workspace.\n *\n * @param opts - Workspace creation parameters\n * @returns Promise resolving to the workspace response\n */\n createWorkspace(opts: CreateWorkspaceOptions): Promise<WorkspaceResponse> {\n const { timeout, workspaceId, displayName, metadata } = opts;\n return this._client.sendWorkspaceOperation(\n {\n op: \"CREATE\",\n workspace: {\n workspaceId,\n displayName: displayName ?? \"\",\n metadata: metadata ?? {},\n },\n },\n timeout,\n );\n }\n\n /**\n * Updates an existing workspace.\n *\n * @param opts - Workspace update parameters\n * @returns Promise resolving to the workspace response\n */\n updateWorkspace(opts: UpdateWorkspaceOptions): Promise<WorkspaceResponse> {\n const { timeout, workspaceId, displayName, metadata } = opts;\n return this._client.sendWorkspaceOperation(\n {\n op: \"UPDATE\",\n workspaceId,\n workspace: {\n workspaceId,\n displayName: displayName ?? \"\",\n metadata: metadata ?? {},\n },\n },\n timeout,\n );\n }\n\n /**\n * Deletes a workspace by ID.\n *\n * @param opts - Delete options containing the workspace ID\n * @returns Promise resolving to the workspace response\n */\n deleteWorkspace(opts: DeleteWorkspaceOptions): Promise<WorkspaceResponse> {\n const { timeout, workspaceId } = opts;\n return this._client.sendWorkspaceOperation({ op: \"DELETE\", workspaceId }, timeout);\n }\n\n // ===========================================================================\n // Agent Operations\n // ===========================================================================\n\n /**\n * Lists registered agent types.\n *\n * @param opts - List options\n * @returns Promise resolving to the agent response\n */\n listAgents(opts: ListAgentsOptions = {}): Promise<AgentResponse> {\n const { timeout, workspace, limit } = opts;\n return this._client.sendAgentOperation(\n {\n op: \"LIST\",\n filter: {\n workspace: workspace ?? \"\",\n limit: limit ?? 0,\n },\n },\n timeout,\n );\n }\n\n /**\n * Gets the registration details for a specific agent implementation.\n *\n * @param opts - Options including the implementation name\n * @returns Promise resolving to the agent response\n */\n getAgent(opts: GetAgentOptions): Promise<AgentResponse> {\n const { timeout, implementation } = opts;\n return this._client.sendAgentOperation({ op: \"GET\", implementation }, timeout);\n }\n\n // ===========================================================================\n // Admin Queries (health, connections)\n // ===========================================================================\n\n /**\n * Queries gateway health, including component status for Redis, RabbitMQ,\n * and PostgreSQL.\n *\n * Note: This sends a GET_HEALTH admin query through the gRPC stream.\n * The gateway must have admin-over-stream enabled.\n *\n * @param timeout - Timeout in milliseconds (default: 10000)\n * @returns Promise resolving to the admin query response\n */\n getHealth(timeout?: number): Promise<AdminQueryResponse> {\n return this._client\n .sendWorkspaceOperation({ _adminQuery: \"GET_HEALTH\" }, timeout)\n .then((r) => ({\n success: r.success,\n error: r.error,\n health: r[\"health\"] as Record<string, unknown> | undefined,\n info: undefined,\n stats: undefined,\n connection: undefined,\n connections: undefined,\n totalCount: 0,\n }));\n }\n\n /**\n * Lists active connections on the gateway.\n *\n * @param opts - Optional filter and timeout options\n * @returns Promise resolving to the admin query response (connections array)\n */\n getConnections(opts: ListConnectionsOptions = {}): Promise<AdminQueryResponse> {\n const { timeout, workspace, principalType } = opts;\n return this._client\n .sendWorkspaceOperation(\n {\n _adminQuery: \"LIST_CONNECTIONS\",\n filter: {\n workspace: workspace ?? \"\",\n principalType: principalType ?? \"\",\n },\n },\n timeout,\n )\n .then((r) => ({\n success: r.success,\n error: r.error,\n health: undefined,\n info: undefined,\n stats: undefined,\n connection: undefined,\n connections: r[\"connections\"] as Record<string, unknown>[] | undefined,\n totalCount: r.totalCount,\n }));\n }\n\n /**\n * Forcibly disconnects a session by session ID.\n *\n * @param opts - Options containing the session ID and optional reason\n * @returns Promise resolving to the workspace response\n */\n disconnectSession(opts: DisconnectSessionOptions): Promise<WorkspaceResponse> {\n const { timeout, sessionId, reason } = opts;\n return this._client.sendWorkspaceOperation(\n {\n _sessionOp: \"DISCONNECT\",\n sessionId,\n reason: reason ?? \"\",\n },\n timeout,\n );\n }\n}\n","/**\n * Topic construction helpers for the Aether TypeScript SDK.\n *\n * This module provides helper functions for constructing topic strings used\n * for message routing in the Aether system. Topics follow a structured\n * format that identifies the principal type and location.\n *\n * Segment separator is \"::\" (not \".\") so field values can legitimately\n * contain \".\" — e.g. Python FQN implementations\n * (\"scitrera_ai_runtime.cowork.aether_bridge.CoworkAgent\") or email-style\n * user_ids (\"alice@example.com\") — without the parser ambiguity that a\n * dotted separator would create.\n *\n * Topic Schema:\n * - ag::{workspace}::{impl}::{spec} - Specific agent instance\n * - tu::{workspace}::{impl}::{spec} - Unique task (named)\n * - ta::{workspace}::{impl}::{id} - Non-unique task instance (server-assigned ID)\n * - tb::{workspace}::{impl} - Task broadcast (load-balancing)\n * - us::{user_id}::{window_id} - User window-specific messages\n * - uw::{user_id}::{workspace} - User workspace-scoped messages\n * - ga::{workspace} - Global agent broadcast in workspace\n * - gu::{workspace} - Global user broadcast in workspace\n * - event::* - Workflow Engine only (broadcast events)\n * - metric::* - Metrics Bridge only (telemetry ingestion)\n *\n * @module topics\n */\n\n// =============================================================================\n// Identity Separator\n// =============================================================================\n\n/**\n * Segment separator for all identity / topic strings. Must match\n * server/pkg/models/topics.go::IdentitySep and the Python SDK's IDENTITY_SEP.\n */\nexport const IDENTITY_SEP = \"::\";\n\n// =============================================================================\n// Topic Prefixes\n// =============================================================================\n\n/** Prefix for agent topics. */\nexport const TOPIC_PREFIX_AGENT = \"ag\";\n\n/** Prefix for unique task topics. */\nexport const TOPIC_PREFIX_UNIQUE_TASK = \"tu\";\n\n/** Prefix for non-unique task topics. */\nexport const TOPIC_PREFIX_TASK = \"ta\";\n\n/** Prefix for task broadcast topics. */\nexport const TOPIC_PREFIX_TASK_BROADCAST = \"tb\";\n\n/** Prefix for user session topics. */\nexport const TOPIC_PREFIX_USER = \"us\";\n\n/** Prefix for user workspace topics. */\nexport const TOPIC_PREFIX_USER_WORKSPACE = \"uw\";\n\n/** Prefix for global agent broadcast topics. */\nexport const TOPIC_PREFIX_GLOBAL_AGENTS = \"ga\";\n\n/** Prefix for global user broadcast topics. */\nexport const TOPIC_PREFIX_GLOBAL_USERS = \"gu\";\n\n/** Prefix for event topics (workflow engine). */\nexport const TOPIC_PREFIX_EVENT = \"event\";\n\n/** Prefix for metric topics (metrics bridge). */\nexport const TOPIC_PREFIX_METRIC = \"metric\";\n\n/** Prefix for progress stream topics. */\nexport const TOPIC_PREFIX_PROGRESS = \"pg\";\n\n/** Prefix for bridge topics. */\nexport const TOPIC_PREFIX_BRIDGE = \"br\";\n\n// =============================================================================\n// Topic Construction Helpers - Agents\n// =============================================================================\n\n/**\n * Creates a topic string for a specific agent.\n *\n * @param workspace - The agent's workspace\n * @param implementation - The agent's implementation type\n * @param specifier - The agent's unique specifier\n * @returns Topic string in format: ag::{workspace}::{implementation}::{specifier}\n *\n * @example\n * ```typescript\n * const topic = agentTopic(\"prod\", \"data-processor\", \"instance-1\");\n * // Returns: \"ag::prod::data-processor::instance-1\"\n * ```\n */\nexport function agentTopic(workspace: string, implementation: string, specifier: string): string {\n return `${TOPIC_PREFIX_AGENT}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${specifier}`;\n}\n\n/**\n * Creates a broadcast topic for all agents in a workspace.\n *\n * @param workspace - The workspace to broadcast to\n * @returns Topic string in format: ga::{workspace}\n */\nexport function globalAgentsTopic(workspace: string): string {\n return `${TOPIC_PREFIX_GLOBAL_AGENTS}${IDENTITY_SEP}${workspace}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - Tasks\n// =============================================================================\n\n/**\n * Creates a topic string for a unique (named) task.\n *\n * @param workspace - The task's workspace\n * @param implementation - The task's implementation type\n * @param specifier - The task's unique specifier\n * @returns Topic string in format: tu::{workspace}::{implementation}::{specifier}\n */\nexport function uniqueTaskTopic(workspace: string, implementation: string, specifier: string): string {\n return `${TOPIC_PREFIX_UNIQUE_TASK}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${specifier}`;\n}\n\n/**\n * Creates a topic string for a non-unique task instance.\n *\n * @param workspace - The task's workspace\n * @param implementation - The task's implementation type\n * @param id - The server-assigned task instance ID\n * @returns Topic string in format: ta::{workspace}::{implementation}::{id}\n */\nexport function taskTopic(workspace: string, implementation: string, id: string): string {\n return `${TOPIC_PREFIX_TASK}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${id}`;\n}\n\n/**\n * Creates a broadcast topic for task load balancing.\n *\n * Non-unique tasks subscribe to this topic to receive work items that can\n * be claimed by any available worker of that implementation type.\n *\n * @param workspace - The task's workspace\n * @param implementation - The task's implementation type\n * @returns Topic string in format: tb::{workspace}::{implementation}\n */\nexport function taskBroadcastTopic(workspace: string, implementation: string): string {\n return `${TOPIC_PREFIX_TASK_BROADCAST}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - Users\n// =============================================================================\n\n/**\n * Creates a topic string for a user session.\n *\n * @param userId - The user's unique identifier\n * @param windowId - The window/session identifier\n * @returns Topic string in format: us::{userId}::{windowId}\n */\nexport function userTopic(userId: string, windowId: string): string {\n return `${TOPIC_PREFIX_USER}${IDENTITY_SEP}${userId}${IDENTITY_SEP}${windowId}`;\n}\n\n/**\n * Creates a topic string for user workspace messages.\n *\n * Messages sent to this topic reach a specific user regardless of which\n * window/tab they are using.\n *\n * @param userId - The user's unique identifier\n * @param workspace - The workspace\n * @returns Topic string in format: uw::{userId}::{workspace}\n */\nexport function userWorkspaceTopic(userId: string, workspace: string): string {\n return `${TOPIC_PREFIX_USER_WORKSPACE}${IDENTITY_SEP}${userId}${IDENTITY_SEP}${workspace}`;\n}\n\n/**\n * Creates a broadcast topic for all users in a workspace.\n *\n * @param workspace - The workspace to broadcast to\n * @returns Topic string in format: gu::{workspace}\n */\nexport function globalUsersTopic(workspace: string): string {\n return `${TOPIC_PREFIX_GLOBAL_USERS}${IDENTITY_SEP}${workspace}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - System Topics\n// =============================================================================\n\n/**\n * Creates a topic string for broadcast events.\n *\n * @param eventType - The event type identifier\n * @returns Topic string in format: event::{eventType}\n */\nexport function eventTopic(eventType: string): string {\n return `${TOPIC_PREFIX_EVENT}${IDENTITY_SEP}${eventType}`;\n}\n\n/**\n * Returns the wildcard pattern for all events.\n *\n * This is the topic that Workflow Engines subscribe to.\n *\n * @returns \"event::*\"\n */\nexport function eventWildcardTopic(): string {\n return `${TOPIC_PREFIX_EVENT}${IDENTITY_SEP}*`;\n}\n\n/**\n * Creates a topic string for telemetry/metrics.\n *\n * @param metricType - The metric type identifier\n * @returns Topic string in format: metric::{metricType}\n */\nexport function metricTopic(metricType: string): string {\n return `${TOPIC_PREFIX_METRIC}${IDENTITY_SEP}${metricType}`;\n}\n\n/**\n * Returns the wildcard pattern for all metrics.\n *\n * This is the topic that Metrics Bridges subscribe to.\n *\n * @returns \"metric::*\"\n */\nexport function metricWildcardTopic(): string {\n return `${TOPIC_PREFIX_METRIC}${IDENTITY_SEP}*`;\n}\n\n/**\n * Creates a topic string for workspace progress updates.\n *\n * Progress updates from agents and tasks in a workspace are published to this\n * topic. Users and agents subscribe to it with server-side recipient filtering.\n *\n * @param workspace - The workspace\n * @returns Topic string in format: pg::{workspace}\n */\nexport function progressTopic(workspace: string): string {\n return `${TOPIC_PREFIX_PROGRESS}${IDENTITY_SEP}${workspace}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - Bridges\n// =============================================================================\n\n/**\n * Creates a topic string for a specific bridge instance.\n *\n * Bridges are cross-workspace principals identified only by implementation\n * and specifier (no workspace component).\n *\n * @param implementation - The bridge implementation type (e.g., \"aether-msgbridge\")\n * @param specifier - The bridge's unique specifier (e.g., \"discord-1\")\n * @returns Topic string in format: br::{implementation}::{specifier}\n *\n * @example\n * ```typescript\n * const topic = bridgeTopic(\"aether-msgbridge\", \"discord-1\");\n * // Returns: \"br::aether-msgbridge::discord-1\"\n * ```\n */\nexport function bridgeTopic(implementation: string, specifier: string): string {\n return `${TOPIC_PREFIX_BRIDGE}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${specifier}`;\n}","/**\n * Agent client implementation for the Aether TypeScript SDK.\n *\n * This module provides the AgentClient class for connecting to the Aether\n * gateway as an agent. Agents are persistent entities with\n * workspace/implementation/specifier identity that can send and receive\n * messages, manage state, and participate in task orchestration.\n *\n * @module agents\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType, TaskAssignmentMode } from \"./types.js\";\nimport type { MessageHandler } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n globalAgentsTopic,\n globalUsersTopic,\n eventWildcardTopic,\n metricWildcardTopic,\n} from \"./topics.js\";\nimport type { Metric } from \"./metrics-builder.js\";\n\n// =============================================================================\n// Agent Client Options\n// =============================================================================\n\n/**\n * Configuration options for the AgentClient.\n */\nexport interface AgentClientOptions extends AetherClientOptions {\n /** The workspace to connect to. Required. */\n workspace: string;\n /** The agent implementation type. Required. */\n implementation: string;\n /** The unique specifier for this agent instance. Required. */\n specifier: string;\n}\n\n// =============================================================================\n// Task Creation Options\n// =============================================================================\n\n/**\n * Options for creating a task.\n */\nexport interface CreateTaskOptions {\n /** The type of task to create. Required. */\n taskType: string;\n /** The workspace for the task. If empty, uses the agent's workspace. */\n workspace?: string;\n /** For TARGETED mode: the agent to assign to. */\n targetAgentId?: string;\n /** For POOL mode: the agent implementation type to match. */\n targetImplementation?: string;\n /** Optional parameter overrides for orchestration. */\n launchParamOverrides?: Record<string, string>;\n /** Optional task metadata. */\n metadata?: Record<string, string>;\n /** Assignment mode. Default: SelfAssign. */\n assignmentMode?: TaskAssignmentMode;\n}\n\n// =============================================================================\n// AgentClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as an agent.\n *\n * Agents are persistent entities identified by workspace, implementation,\n * and specifier. Each agent identity can only have one active connection\n * at a time (Connection = Lock paradigm).\n *\n * AgentClient extends AetherClient and adds agent-specific functionality:\n * - Identity management (workspace, implementation, specifier)\n * - Messaging helpers (sendToAgent, sendToUser, sendToTask, broadcast)\n * - Event and metric publishing\n * - Workspace switching\n * - Task creation\n *\n * @example\n * ```typescript\n * import { AgentClient } from \"@scitrera/aether-client\";\n *\n * const agent = new AgentClient({\n * address: \"localhost:50051\",\n * workspace: \"prod\",\n * implementation: \"data-processor\",\n * specifier: \"instance-1\",\n * });\n *\n * agent.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await agent.connect();\n * ```\n */\nexport class AgentClient extends AetherClient {\n private _workspace: string;\n private readonly _implementation: string;\n private readonly _specifier: string;\n\n /**\n * Creates a new AgentClient.\n *\n * @param options - Agent client configuration\n * @throws {@link InvalidArgumentError} if required fields are missing\n */\n constructor(options: AgentClientOptions) {\n super(options);\n\n if (!options.workspace) {\n throw new InvalidArgumentError(\"Workspace is required\", \"workspace\");\n }\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n if (!options.specifier) {\n throw new InvalidArgumentError(\"Specifier is required\", \"specifier\");\n }\n\n this._workspace = options.workspace;\n this._implementation = options.implementation;\n this._specifier = options.specifier;\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n /** Returns the agent's current workspace. */\n get workspace(): string {\n return this._workspace;\n }\n\n /** Returns the agent's implementation type. */\n get implementation(): string {\n return this._implementation;\n }\n\n /** Returns the agent's specifier (instance identifier). */\n get specifier(): string {\n return this._specifier;\n }\n\n /**\n * Returns this agent's topic address.\n *\n * Format: ag.{workspace}.{implementation}.{specifier}\n */\n get topic(): string {\n return agentTopic(this._workspace, this._implementation, this._specifier);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n agent: {\n workspace: this._workspace,\n implementation: this._implementation,\n specifier: this._specifier,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Workspace Management\n // ===========================================================================\n\n /**\n * Switches the agent's workspace.\n *\n * Sends a SwitchWorkspace message to the gateway, which will update\n * the agent's topic subscription and optionally send a new ConfigSnapshot.\n *\n * @param newWorkspace - The new workspace to switch to\n * @throws {@link InvalidArgumentError} if the workspace is empty\n */\n switchWorkspace(newWorkspace: string): void {\n if (!newWorkspace) {\n throw new InvalidArgumentError(\"Workspace cannot be empty\", \"newWorkspace\");\n }\n\n this._sendUpstream({\n switchWorkspace: {\n newWorkspaceId: newWorkspace,\n },\n });\n\n this._workspace = newWorkspace;\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = agentTopic(workspace, implementation, specifier);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific task.\n *\n * For unique tasks (with specifier), uses tu.{workspace}.{impl}.{spec} topic.\n * For non-unique tasks (empty specifier), uses tb.{workspace}.{impl} broadcast topic.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n *\n * @param userId - Target user's ID\n * @param windowId - Target user's window/session ID\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userTopic(userId, windowId);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a user's workspace scope.\n *\n * This reaches the user regardless of which window/tab they are using.\n *\n * @param userId - Target user's ID\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUserWorkspace(\n userId: string,\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userWorkspaceTopic(userId, workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n // ===========================================================================\n // Broadcast Helpers\n // ===========================================================================\n\n /**\n * Sends a message to all agents in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToAgents(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = globalAgentsTopic(workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to all users in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToUsers(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = globalUsersTopic(workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n // ===========================================================================\n // Event and Metric Publishing\n // ===========================================================================\n\n /**\n * Publishes an event to the workflow engine.\n *\n * @param payload - Event payload (bytes)\n */\n sendEvent(payload: Uint8Array): void {\n this._sendMessage(eventWildcardTopic(), payload, MessageType.Event);\n }\n\n /**\n * Publishes a metric to the metrics bridge.\n *\n * @param metric - Structured metric to publish. Use {@link newMetric} to construct one.\n */\n sendMetric(metric: Metric): void {\n const payload = this._encodeMetric(metric as Record<string, unknown>);\n this._sendMessage(metricWildcardTopic(), payload, MessageType.Metric);\n }\n\n // ===========================================================================\n // Task Creation\n // ===========================================================================\n\n /**\n * Creates a new task with the specified parameters.\n *\n * @param opts - Task creation options\n * @throws {@link InvalidArgumentError} if task type is missing\n */\n createTask(opts: CreateTaskOptions): void {\n if (!opts.taskType) {\n throw new InvalidArgumentError(\"Task type is required\", \"taskType\");\n }\n\n const workspace = opts.workspace || this._workspace;\n let assignmentMode = opts.assignmentMode ?? TaskAssignmentMode.SelfAssign;\n\n // Auto-set TARGETED mode if target is specified\n if (opts.targetAgentId && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Targeted;\n }\n\n // Auto-set POOL mode if target implementation is specified\n if (opts.targetImplementation && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Pool;\n }\n\n this._sendUpstream({\n createTask: {\n taskType: opts.taskType,\n workspace,\n assignmentMode,\n targetAgentId: opts.targetAgentId ?? \"\",\n targetImplementation: opts.targetImplementation ?? \"\",\n launchParamOverrides: opts.launchParamOverrides ?? {},\n metadata: opts.metadata ?? {},\n },\n });\n }\n\n // ===========================================================================\n // Convenience Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler specifically for task-related messages.\n *\n * Filters incoming messages to only those from task topics (tu.* or ta.*).\n *\n * @param handler - Function called when a task message is received\n */\n onTaskMessage(handler: MessageHandler): void {\n const existingHandler = this[\"_onMessage\" as keyof this] as MessageHandler;\n this.onMessage((msg) => {\n if (msg.sourceTopic.startsWith(\"tu.\") || msg.sourceTopic.startsWith(\"ta.\") || msg.sourceTopic.startsWith(\"tb.\")) {\n handler(msg);\n } else if (existingHandler) {\n existingHandler(msg);\n }\n });\n }\n\n /**\n * Registers a handler specifically for control messages.\n *\n * Note: Since the base protocol delivers all messages through a single\n * stream, this filters based on source topic prefixes. For more granular\n * filtering, use onMessage directly and inspect the payload.\n *\n * @param handler - Function called when a control message is received\n */\n onControlMessage(handler: MessageHandler): void {\n const existingHandler = this[\"_onMessage\" as keyof this] as MessageHandler;\n this.onMessage((msg) => {\n // Control messages can come from any source; delegate to user handler\n // for inspection. This provides a simple hook point.\n handler(msg);\n if (existingHandler) {\n existingHandler(msg);\n }\n });\n }\n}\n","/**\n * Task client implementation for the Aether TypeScript SDK.\n *\n * This module provides the TaskClient class for connecting to the Aether\n * gateway as a task. Tasks can be unique (named, with a specifier) or\n * non-unique (server-assigned ID, load-balanced via broadcast topic).\n *\n * @module tasks\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType, TaskAssignmentMode } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n eventWildcardTopic,\n metricWildcardTopic,\n} from \"./topics.js\";\nimport type { CreateTaskOptions } from \"./agents.js\";\nimport type { Metric } from \"./metrics-builder.js\";\n\n// =============================================================================\n// Task Client Options\n// =============================================================================\n\n/**\n * Configuration options for the TaskClient.\n */\nexport interface TaskClientOptions extends AetherClientOptions {\n /** The workspace to connect to. Required. */\n workspace: string;\n /** The task implementation type. Required. */\n implementation: string;\n /** Unique specifier for this task. Empty for non-unique tasks. */\n uniqueSpecifier?: string;\n}\n\n// =============================================================================\n// TaskClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a task.\n *\n * Tasks come in two flavors:\n * - **Unique tasks** (with specifier): Persistent identity like agents,\n * only one connection at a time. Topic: tu.{workspace}.{impl}.{spec}\n * - **Non-unique tasks** (empty specifier): Server-assigned ID, multiple\n * instances allowed. Subscribe to both ta.{workspace}.{impl}.{id} and\n * the shared tb.{workspace}.{impl} broadcast for work claiming.\n *\n * @example\n * ```typescript\n * // Unique task\n * const task = new TaskClient({\n * address: \"localhost:50051\",\n * workspace: \"prod\",\n * implementation: \"report-gen\",\n * uniqueSpecifier: \"daily-report\",\n * });\n *\n * // Non-unique task (worker pool)\n * const worker = new TaskClient({\n * address: \"localhost:50051\",\n * workspace: \"prod\",\n * implementation: \"data-processor\",\n * });\n * ```\n */\nexport class TaskClient extends AetherClient {\n private _workspace: string;\n private readonly _implementation: string;\n private readonly _uniqueSpecifier: string;\n\n constructor(options: TaskClientOptions) {\n super(options);\n\n if (!options.workspace) {\n throw new InvalidArgumentError(\"Workspace is required\", \"workspace\");\n }\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n\n this._workspace = options.workspace;\n this._implementation = options.implementation;\n this._uniqueSpecifier = options.uniqueSpecifier ?? \"\";\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n get workspace(): string {\n return this._workspace;\n }\n\n get implementation(): string {\n return this._implementation;\n }\n\n get uniqueSpecifier(): string {\n return this._uniqueSpecifier;\n }\n\n /** Whether this is a unique (named) task. */\n get isUnique(): boolean {\n return this._uniqueSpecifier !== \"\";\n }\n\n /**\n * Returns this task's topic address.\n * For unique tasks: tu.{workspace}.{impl}.{spec}\n * For non-unique tasks: returns the broadcast topic tb.{workspace}.{impl}\n * (the actual instance topic is assigned by the server).\n */\n get topic(): string {\n if (this._uniqueSpecifier) {\n return uniqueTaskTopic(this._workspace, this._implementation, this._uniqueSpecifier);\n }\n return taskBroadcastTopic(this._workspace, this._implementation);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n task: {\n workspace: this._workspace,\n implementation: this._implementation,\n uniqueSpecifier: this._uniqueSpecifier,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Workspace Management\n // ===========================================================================\n\n /**\n * Switches the task's workspace.\n *\n * @param newWorkspace - The new workspace to switch to\n * @throws {@link InvalidArgumentError} if the workspace is empty\n */\n switchWorkspace(newWorkspace: string): void {\n if (!newWorkspace) {\n throw new InvalidArgumentError(\"Workspace cannot be empty\", \"newWorkspace\");\n }\n this._sendUpstream({\n switchWorkspace: {\n newWorkspaceId: newWorkspace,\n },\n });\n this._workspace = newWorkspace;\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent.\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a message to a specific task.\n * For unique tasks (with specifier), uses tu.* topic.\n * For non-unique tasks (empty specifier), uses tb.* broadcast topic.\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userTopic(userId, windowId), payload, messageType);\n }\n\n // ===========================================================================\n // Event and Metric Publishing\n // ===========================================================================\n\n /**\n * Publishes an event to the workflow engine.\n */\n sendEvent(payload: Uint8Array): void {\n this._sendMessage(eventWildcardTopic(), payload, MessageType.Event);\n }\n\n /**\n * Publishes a metric to the metrics bridge.\n *\n * @param metric - Structured metric to publish. Use {@link newMetric} to construct one.\n */\n sendMetric(metric: Metric): void {\n const payload = this._encodeMetric(metric as Record<string, unknown>);\n this._sendMessage(metricWildcardTopic(), payload, MessageType.Metric);\n }\n\n // ===========================================================================\n // Task Creation\n // ===========================================================================\n\n /**\n * Creates a new task with the specified parameters.\n *\n * @param opts - Task creation options\n * @throws {@link InvalidArgumentError} if task type is missing\n */\n createTask(opts: CreateTaskOptions): void {\n if (!opts.taskType) {\n throw new InvalidArgumentError(\"Task type is required\", \"taskType\");\n }\n\n const workspace = opts.workspace || this._workspace;\n let assignmentMode = opts.assignmentMode ?? TaskAssignmentMode.SelfAssign;\n\n // Auto-set TARGETED mode if target is specified\n if (opts.targetAgentId && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Targeted;\n }\n\n // Auto-set POOL mode if target implementation is specified\n if (opts.targetImplementation && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Pool;\n }\n\n this._sendUpstream({\n createTask: {\n taskType: opts.taskType,\n workspace,\n assignmentMode,\n targetAgentId: opts.targetAgentId ?? \"\",\n targetImplementation: opts.targetImplementation ?? \"\",\n launchParamOverrides: opts.launchParamOverrides ?? {},\n metadata: opts.metadata ?? {},\n },\n });\n }\n}\n","/**\n * User client implementation for the Aether TypeScript SDK.\n *\n * This module provides the UserClient class for connecting to the Aether\n * gateway as a user. Users are identified by userId and windowId, allowing\n * multiple browser tabs or sessions per user.\n *\n * Per the Aether specification, users can only send direct messages.\n * They cannot publish events or metrics like agents and tasks can.\n *\n * @module users\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType, TaskAssignmentMode } from \"./types.js\";\nimport type { MessageHandler } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n} from \"./topics.js\";\nimport type { CreateTaskOptions } from \"./agents.js\";\n\n// =============================================================================\n// User Client Options\n// =============================================================================\n\n/**\n * Configuration options for the UserClient.\n */\nexport interface UserClientOptions extends AetherClientOptions {\n /** The user's unique identifier. Required. */\n userId: string;\n /** The window/session identifier. Required. */\n windowId: string;\n /** Optional initial workspace association. */\n workspace?: string;\n}\n\n// =============================================================================\n// UserClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a user.\n *\n * Users are identified by userId and windowId, allowing multiple browser\n * tabs or sessions per user. Each user session (userId + windowId combination)\n * is unique and can only have one active connection at a time.\n *\n * UserClient extends AetherClient and adds user-specific functionality:\n * - Identity management (userId, windowId)\n * - Messaging helpers (sendToAgent, sendToUser, sendToTask)\n * - Optional workspace association\n *\n * Note: Per the Aether specification, users can only send direct messages.\n * They cannot publish events or metrics.\n *\n * @example\n * ```typescript\n * import { UserClient } from \"@scitrera/aether-client\";\n *\n * const user = new UserClient({\n * address: \"localhost:50051\",\n * userId: \"alice\",\n * windowId: \"tab-1\",\n * });\n *\n * user.onIncomingMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await user.connect();\n *\n * // Send a message to an agent\n * const encoder = new TextEncoder();\n * user.sendToAgent(\"prod\", \"data-processor\", \"instance-1\",\n * encoder.encode(JSON.stringify({ action: \"process\" }))\n * );\n * ```\n */\nexport class UserClient extends AetherClient {\n private readonly _userId: string;\n private readonly _windowId: string;\n private _workspace: string;\n\n /**\n * Creates a new UserClient.\n *\n * @param options - User client configuration\n * @throws {@link InvalidArgumentError} if required fields are missing\n */\n constructor(options: UserClientOptions) {\n super(options);\n\n if (!options.userId) {\n throw new InvalidArgumentError(\"User ID is required\", \"userId\");\n }\n if (!options.windowId) {\n throw new InvalidArgumentError(\"Window ID is required\", \"windowId\");\n }\n\n this._userId = options.userId;\n this._windowId = options.windowId;\n this._workspace = options.workspace ?? \"\";\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n /** Returns the user's unique identifier. */\n get userId(): string {\n return this._userId;\n }\n\n /** Returns the user's window/session identifier. */\n get windowId(): string {\n return this._windowId;\n }\n\n /** Returns the user's current workspace (if set). */\n get workspace(): string {\n return this._workspace;\n }\n\n /**\n * Returns this user's topic address.\n *\n * Format: us.{userId}.{windowId}\n */\n get topic(): string {\n return userTopic(this._userId, this._windowId);\n }\n\n /**\n * Returns this user's workspace-scoped topic address.\n *\n * Format: uw.{userId}.{workspace}\n *\n * Returns empty string if no workspace is set.\n */\n get workspaceTopic(): string {\n if (!this._workspace) return \"\";\n return userWorkspaceTopic(this._userId, this._workspace);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n user: {\n userId: this._userId,\n windowId: this._windowId,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Workspace Management\n // ===========================================================================\n\n /**\n * Sets the user's current workspace for workspace-scoped operations.\n *\n * This is a local operation that does not notify the gateway.\n *\n * @param workspace - The workspace to associate with\n */\n setWorkspace(workspace: string): void {\n this._workspace = workspace;\n }\n\n /**\n * Switches the user's workspace on the gateway.\n *\n * Sends a SwitchWorkspace message to the gateway, which will update\n * topic subscriptions (including progress) and send a new ConfigSnapshot.\n *\n * @param newWorkspace - The new workspace to switch to\n * @throws {@link InvalidArgumentError} if the workspace is empty\n */\n switchWorkspace(newWorkspace: string): void {\n if (!newWorkspace) {\n throw new InvalidArgumentError(\"Workspace cannot be empty\", \"newWorkspace\");\n }\n this._sendUpstream({\n switchWorkspace: {\n newWorkspaceId: newWorkspace,\n },\n });\n this._workspace = newWorkspace;\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = agentTopic(workspace, implementation, specifier);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific task.\n *\n * For unique tasks (with specifier), uses tu.{workspace}.{impl}.{spec} topic.\n * For non-unique tasks (empty specifier), uses tb.{workspace}.{impl} broadcast topic.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n *\n * @param userId - Target user's ID\n * @param windowId - Target user's window/session ID\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userTopic(userId, windowId);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a user's workspace scope.\n *\n * @param userId - Target user's ID\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUserWorkspace(\n userId: string,\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userWorkspaceTopic(userId, workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n // ===========================================================================\n // Task Creation\n // ===========================================================================\n\n /**\n * Creates a new task with the specified parameters.\n *\n * Users can create tasks targeting agents or task pools.\n *\n * @param opts - Task creation options\n * @throws {@link InvalidArgumentError} if task type is missing\n */\n createTask(opts: CreateTaskOptions): void {\n if (!opts.taskType) {\n throw new InvalidArgumentError(\"Task type is required\", \"taskType\");\n }\n\n const workspace = opts.workspace || this._workspace;\n let assignmentMode = opts.assignmentMode ?? TaskAssignmentMode.SelfAssign;\n\n // Auto-set TARGETED mode if target is specified\n if (opts.targetAgentId && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Targeted;\n }\n\n // Auto-set POOL mode if target implementation is specified\n if (opts.targetImplementation && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Pool;\n }\n\n this._sendUpstream({\n createTask: {\n taskType: opts.taskType,\n workspace,\n assignmentMode,\n targetAgentId: opts.targetAgentId ?? \"\",\n targetImplementation: opts.targetImplementation ?? \"\",\n launchParamOverrides: opts.launchParamOverrides ?? {},\n metadata: opts.metadata ?? {},\n },\n });\n }\n\n // ===========================================================================\n // Convenience Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for all incoming messages.\n *\n * This is an alias for onMessage, provided for API clarity in the\n * user context.\n *\n * @param handler - Function called when a message is received\n */\n onIncomingMessage(handler: MessageHandler): void {\n this.onMessage(handler);\n }\n}\n","/**\n * Orchestrator client implementation for the Aether TypeScript SDK.\n *\n * Orchestrators manage agent/task lifecycle: receiving startup requests\n * when targeted agents are offline, launching compute resources, and\n * managing agent pools and scaling.\n *\n * @module orchestrator\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\nimport type { TaskAssignment, ConnectionAck } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n} from \"./topics.js\";\n\n// =============================================================================\n// Orchestrator Client Options\n// =============================================================================\n\n/**\n * Configuration options for the OrchestratorClient.\n */\nexport interface OrchestratorClientOptions extends AetherClientOptions {\n /** The orchestrator implementation type (e.g., \"kubernetes-orchestrator\"). Required. */\n implementation: string;\n /** Profiles this orchestrator supports (e.g., [\"kubernetes\", \"docker\"]). Required, at least one. */\n supportedProfiles: string[];\n /** Unique specifier for this instance. Auto-generated if not provided. */\n specifier?: string;\n}\n\n// =============================================================================\n// OrchestratorClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as an orchestrator.\n *\n * Orchestrators receive task assignments via the onTaskAssignment handler\n * and are responsible for launching the appropriate compute resources.\n *\n * @example\n * ```typescript\n * const orchestrator = new OrchestratorClient({\n * address: \"localhost:50051\",\n * implementation: \"k8s-orchestrator\",\n * supportedProfiles: [\"kubernetes\"],\n * });\n *\n * orchestrator.onTaskAssignment((assignment) => {\n * console.log(`Starting ${assignment.targetImplementation} for task ${assignment.taskId}`);\n * // Launch container based on assignment.launchParams\n * });\n *\n * await orchestrator.connect();\n * ```\n */\nexport class OrchestratorClient extends AetherClient {\n private readonly _implementation: string;\n private readonly _specifier: string;\n private readonly _supportedProfiles: string[];\n\n constructor(options: OrchestratorClientOptions) {\n super(options);\n\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n if (!options.supportedProfiles || options.supportedProfiles.length === 0) {\n throw new InvalidArgumentError(\"At least one supported profile is required\", \"supportedProfiles\");\n }\n\n this._implementation = options.implementation;\n this._specifier = options.specifier ?? crypto.randomUUID().slice(0, 8);\n this._supportedProfiles = options.supportedProfiles;\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n get implementation(): string {\n return this._implementation;\n }\n\n get specifier(): string {\n return this._specifier;\n }\n\n get supportedProfiles(): string[] {\n return [...this._supportedProfiles];\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n orchestrator: {\n implementation: this._implementation,\n specifier: this._specifier,\n supportedProfiles: this._supportedProfiles,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a status/control message to an agent.\n */\n sendStatusToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a status/control message to a task.\n * For unique tasks (with specifier), uses tu.* topic.\n * For non-unique tasks (empty specifier), uses tb.* broadcast topic.\n */\n sendStatusToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n}\n\n// =============================================================================\n// BaseOrchestrator Options\n// =============================================================================\n\n/**\n * Configuration options for BaseOrchestrator subclasses.\n */\nexport interface BaseOrchestratorOptions extends OrchestratorClientOptions {\n /**\n * Whether to log task assignment details to the console.\n * Default: false.\n */\n logAssignments?: boolean;\n}\n\n// =============================================================================\n// BaseOrchestrator\n// =============================================================================\n\n/**\n * Abstract base class for building orchestrators.\n *\n * BaseOrchestrator wraps {@link OrchestratorClient} and provides a structured\n * framework for managing agent/task lifecycle. Subclasses implement the\n * abstract {@link launchTask} method to handle task assignments with their\n * specific compute backend (Docker, Kubernetes, subprocess, etc.).\n *\n * The class manages the full orchestrator lifecycle:\n * - Connecting to the Aether gateway as an Orchestrator principal\n * - Receiving {@link TaskAssignment} messages and dispatching to launchTask\n * - Error handling and logging hooks\n *\n * @example\n * ```typescript\n * import { BaseOrchestrator, TaskAssignment } from \"@scitrera/aether-client\";\n *\n * class MyOrchestrator extends BaseOrchestrator {\n * async launchTask(assignment: TaskAssignment): Promise<void> {\n * console.log(`Launching task ${assignment.taskId} (profile: ${assignment.profile})`);\n * // Start a subprocess, container, etc. using assignment.launchParams\n * }\n * }\n *\n * const orch = new MyOrchestrator({\n * address: \"localhost:50051\",\n * implementation: \"my-orchestrator\",\n * supportedProfiles: [\"my-profile\"],\n * });\n *\n * orch.onConnect((ack) => {\n * console.log(`Connected with session ${ack.sessionId}`);\n * });\n *\n * await orch.connect();\n * ```\n */\nexport abstract class BaseOrchestrator {\n /** The underlying OrchestratorClient for direct gateway access. */\n readonly client: OrchestratorClient;\n\n private readonly _logAssignments: boolean;\n\n /**\n * Creates a new BaseOrchestrator.\n *\n * @param options - Orchestrator configuration options\n */\n constructor(options: BaseOrchestratorOptions) {\n this._logAssignments = options.logAssignments ?? false;\n this.client = new OrchestratorClient(options);\n\n // Wire task assignment handler to launchTask\n this.client.onTaskAssignment((assignment) => {\n return this._handleAssignment(assignment);\n });\n }\n\n // ===========================================================================\n // Abstract Interface\n // ===========================================================================\n\n /**\n * Called when the gateway assigns a task to this orchestrator.\n *\n * Subclasses must implement this method to launch the appropriate compute\n * resource (container, process, VM, etc.) based on the assignment details.\n *\n * The assignment includes:\n * - `taskId`: Unique task identifier\n * - `profile`: The profile that matched (from supportedProfiles)\n * - `targetImplementation`: The agent/task implementation to launch\n * - `workspace`: The workspace this task belongs to\n * - `specifier`: Optional unique specifier for the agent/task\n * - `launchParams`: Key-value launch parameters (image, command, env vars, etc.)\n * - `metadata`: Arbitrary task metadata\n *\n * @param assignment - The task assignment received from the gateway\n */\n abstract launchTask(assignment: TaskAssignment): void | Promise<void>;\n\n // ===========================================================================\n // Lifecycle\n // ===========================================================================\n\n /**\n * Connects to the Aether gateway.\n *\n * Must be called before the orchestrator can receive task assignments.\n */\n async connect(): Promise<void> {\n await this.client.connect();\n }\n\n /**\n * Disconnects from the Aether gateway.\n */\n async disconnect(): Promise<void> {\n await this.client.disconnect();\n }\n\n /**\n * Returns whether the orchestrator is currently connected.\n */\n get connected(): boolean {\n return this.client.connected;\n }\n\n /**\n * Returns the current session ID assigned by the gateway.\n * Empty string if not connected.\n */\n get sessionId(): string {\n return this.client.sessionId;\n }\n\n /**\n * Returns the orchestrator's implementation type.\n */\n get implementation(): string {\n return this.client.implementation;\n }\n\n /**\n * Returns the orchestrator's specifier.\n */\n get specifier(): string {\n return this.client.specifier;\n }\n\n /**\n * Returns the list of profiles this orchestrator supports.\n */\n get supportedProfiles(): string[] {\n return this.client.supportedProfiles;\n }\n\n // ===========================================================================\n // Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for successful connection events.\n *\n * @param handler - Called with the ConnectionAck when connected\n */\n onConnect(handler: (ack: ConnectionAck) => void | Promise<void>): void {\n this.client.onConnect(handler);\n }\n\n /**\n * Registers a handler for disconnection events.\n *\n * @param handler - Called with the reason string when disconnected\n */\n onDisconnect(handler: (reason: string) => void | Promise<void>): void {\n this.client.onDisconnect(handler);\n }\n\n /**\n * Registers a handler for reconnection attempts.\n *\n * @param handler - Called with the attempt number on each reconnect try\n */\n onReconnecting(handler: (attempt: number) => void | Promise<void>): void {\n this.client.onReconnecting(handler);\n }\n\n // ===========================================================================\n // Message Sending\n // ===========================================================================\n\n /**\n * Sends a status/control message to an agent.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload\n * @param messageType - Message type. Default: Control\n */\n sendStatusToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this.client.sendStatusToAgent(workspace, implementation, specifier, payload, messageType);\n }\n\n /**\n * Sends a status/control message to a task.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload\n * @param messageType - Message type. Default: Control\n */\n sendStatusToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this.client.sendStatusToTask(workspace, implementation, specifier, payload, messageType);\n }\n\n // ===========================================================================\n // Internal\n // ===========================================================================\n\n /**\n * Internal handler that logs and dispatches to launchTask.\n * @internal\n */\n private async _handleAssignment(assignment: TaskAssignment): Promise<void> {\n if (this._logAssignments) {\n console.log(\n `[BaseOrchestrator] Task assignment received: taskId=${assignment.taskId}` +\n ` profile=${assignment.profile} impl=${assignment.targetImplementation}` +\n ` workspace=${assignment.workspace}`,\n );\n }\n await this.launchTask(assignment);\n }\n}\n","/**\n * Workflow engine client implementation for the Aether TypeScript SDK.\n *\n * The workflow engine is the sole subscriber to event.* topics and processes\n * broadcast events to trigger downstream actions by sending commands to\n * agents/tasks. It is a singleton per gateway deployment.\n *\n * @module workflow\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n globalAgentsTopic,\n globalUsersTopic,\n userTopic,\n metricWildcardTopic,\n} from \"./topics.js\";\nimport type { Metric } from \"./metrics-builder.js\";\n\n// =============================================================================\n// Workflow Engine Client Options\n// =============================================================================\n\n/**\n * Configuration options for the WorkflowEngineClient.\n *\n * No additional identity fields are needed — the workflow engine is\n * identified by its principal type alone (singleton per gateway).\n */\nexport type WorkflowEngineClientOptions = AetherClientOptions;\n\n// =============================================================================\n// WorkflowEngineClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a workflow engine.\n *\n * The workflow engine receives all events (event.*) and can send commands\n * to any principal type. It is the central event processor for the system.\n *\n * @example\n * ```typescript\n * const engine = new WorkflowEngineClient({\n * address: \"localhost:50051\",\n * });\n *\n * engine.onMessage((msg) => {\n * // Process incoming events\n * const event = JSON.parse(new TextDecoder().decode(msg.payload));\n * console.log(`Event from ${msg.sourceTopic}:`, event);\n * });\n *\n * await engine.connect();\n * ```\n */\nexport class WorkflowEngineClient extends AetherClient {\n constructor(options: WorkflowEngineClientOptions) {\n super(options);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n workflowEngine: {},\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a command to a specific agent.\n */\n sendCommandToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a command to a specific task.\n * For unique tasks (with specifier), uses tu.* topic.\n * For non-unique tasks (empty specifier), uses tb.* broadcast topic.\n */\n sendCommandToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a broadcast to all agents in a workspace.\n */\n broadcastToAgents(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this._sendMessage(globalAgentsTopic(workspace), payload, messageType);\n }\n\n /**\n * Sends a broadcast to all users in a workspace.\n */\n broadcastToUsers(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(globalUsersTopic(workspace), payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userTopic(userId, windowId), payload, messageType);\n }\n\n /**\n * Publishes a metric to the metrics bridge.\n *\n * @param metric - Structured metric to publish. Use {@link newMetric} to construct one.\n */\n sendMetric(metric: Metric): void {\n const payload = this._encodeMetric(metric as Record<string, unknown>);\n this._sendMessage(metricWildcardTopic(), payload, MessageType.Metric);\n }\n}\n","/**\n * Metrics bridge client implementation for the Aether TypeScript SDK.\n *\n * The metrics bridge is a receive-only client that subscribes to metric.*\n * topics to collect telemetry data from agents and tasks. It is a singleton\n * per gateway deployment.\n *\n * @module metrics\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\n\n// =============================================================================\n// Metrics Bridge Client Options\n// =============================================================================\n\n/**\n * Configuration options for the MetricsBridgeClient.\n *\n * No additional identity fields are needed — the metrics bridge is\n * identified by its principal type alone (singleton per gateway).\n */\nexport type MetricsBridgeClientOptions = AetherClientOptions;\n\n// =============================================================================\n// MetricsBridgeClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a metrics bridge.\n *\n * The metrics bridge is receive-only: it subscribes to metric.* topics\n * to collect telemetry data published by agents and tasks. It does not\n * send messages to other principals.\n *\n * @example\n * ```typescript\n * const bridge = new MetricsBridgeClient({\n * address: \"localhost:50051\",\n * });\n *\n * bridge.onMessage((msg) => {\n * // Process incoming metrics\n * const metric = JSON.parse(new TextDecoder().decode(msg.payload));\n * console.log(`Metric from ${msg.sourceTopic}:`, metric);\n * });\n *\n * await bridge.connect();\n * ```\n */\nexport class MetricsBridgeClient extends AetherClient {\n constructor(options: MetricsBridgeClientOptions) {\n super(options);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n metricsBridge: {},\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Messaging\n // ===========================================================================\n\n /**\n * Sends an acknowledgment to a source topic.\n *\n * @param targetTopic - The topic to send the acknowledgment to\n * @param payload - The acknowledgment payload\n */\n sendAcknowledgment(targetTopic: string, payload: Uint8Array): void {\n this._sendMessage(targetTopic, payload, MessageType.Control);\n }\n}\n","/**\n * Fluent builder for constructing Metric payloads.\n *\n * Metric is the canonical payload for SendMessage when message_type == METRIC.\n * All entries are interpreted as additive deltas; negative qty values require\n * the `capability/metric_credit` ACL permission on the sender.\n *\n * @module metrics-builder\n *\n * @example\n * ```typescript\n * import { newMetric } from \"@scitrera/aether-client\";\n *\n * const metric = newMetric()\n * .trace(\"req-abc-123\")\n * .add(\"tokens_in\", \"modelA\", 512)\n * .add(\"tokens_out\", \"modelA\", 128)\n * .tag(\"source.version\", \"1.0.0\")\n * .clientTimestampMs(Date.now())\n * .build();\n *\n * agent.sendMetric(metric);\n * ```\n */\n\nimport type { Metric } from './proto/aether/v1/Metric.js';\nimport type { MetricEntry } from './proto/aether/v1/MetricEntry.js';\n\nexport type { Metric, MetricEntry };\n\n/**\n * Fluent builder for constructing a {@link Metric}.\n */\nexport class MetricBuilder {\n private m: Metric;\n\n constructor() {\n this.m = {\n traceId: '',\n entries: [],\n metadata: {},\n clientTimestampMs: 0,\n };\n }\n\n /**\n * Sets the optional correlation/trace ID tying these entries to upstream work.\n */\n trace(id: string): this {\n this.m.traceId = id;\n return this;\n }\n\n /**\n * Adds a metric entry (additive delta).\n *\n * @param name - Counter name, e.g. \"tokens_in\", \"time_seconds\"\n * @param kind - Sub-classifier, e.g. \"modelA\" (may be empty)\n * @param qty - Additive delta; negative requires `capability/metric_credit`\n */\n add(name: string, kind: string, qty: number): this {\n if (!this.m.entries) {\n this.m.entries = [];\n }\n this.m.entries.push({ name, kind, qty });\n return this;\n }\n\n /**\n * Adds a free-form metadata tag.\n *\n * Well-known keys: lifecycle (\"startup\" | \"shutdown\"),\n * source.version, source.region, source.host, ...\n */\n tag(key: string, value: string): this {\n if (!this.m.metadata) {\n this.m.metadata = {};\n }\n this.m.metadata[key] = value;\n return this;\n }\n\n /**\n * Sets the optional client-side timestamp (ms since epoch).\n *\n * The server always stamps its own authoritative timestamp on the\n * MessageEnvelope; this field is an advisory ordering hint only.\n *\n * Accepts `number` or `string` to support int64 values that exceed\n * `Number.MAX_SAFE_INTEGER` (the generated proto type allows both,\n * driven by `--longs=String` in compile_protos.sh).\n */\n clientTimestampMs(ts: number | string): this {\n this.m.clientTimestampMs = ts;\n return this;\n }\n\n /**\n * Returns the constructed Metric object.\n */\n build(): Metric {\n return this.m;\n }\n}\n\n/**\n * Creates a new {@link MetricBuilder}.\n *\n * @example\n * ```typescript\n * const metric = newMetric()\n * .add(\"tokens_in\", \"gpt4\", 512)\n * .build();\n * ```\n */\nexport function newMetric(): MetricBuilder {\n return new MetricBuilder();\n}\n","/**\n * Bridge client implementation for the Aether TypeScript SDK.\n *\n * This module provides the BridgeClient class for connecting to the Aether\n * gateway as a cross-workspace message bridge. Bridges relay messages across\n * workspace boundaries and can send to any principal type in any workspace.\n *\n * Unlike workspace-scoped principals (agents, tasks, users), bridges have no\n * workspace field in their identity — allowing them to send to targets in any\n * workspace. Each bridge identity can only have one active connection at a time\n * (Connection = Lock paradigm).\n *\n * @module bridge\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n bridgeTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n globalAgentsTopic,\n globalUsersTopic,\n} from \"./topics.js\";\n\n// =============================================================================\n// Bridge Client Options\n// =============================================================================\n\n/**\n * Configuration options for the BridgeClient.\n */\nexport interface BridgeClientOptions extends AetherClientOptions {\n /** The bridge implementation type (e.g., \"aether-msgbridge\", \"webhook-bridge\"). Required. */\n implementation: string;\n /** The unique specifier for this bridge instance (e.g., \"default\", \"discord-1\"). Required. */\n specifier: string;\n}\n\n// =============================================================================\n// BridgeClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a cross-workspace message bridge.\n *\n * Bridges are identified by implementation and specifier with no workspace field,\n * allowing them to operate across workspace boundaries. Each bridge identity can\n * only have one active connection at a time (Connection = Lock paradigm).\n *\n * BridgeClient extends AetherClient and adds bridge-specific functionality:\n * - Identity management (implementation, specifier)\n * - Messaging helpers to any workspace (sendToAgent, sendToUser, sendToTask, broadcast)\n *\n * Topic format: br.{implementation}.{specifier}\n *\n * @example\n * ```typescript\n * import { BridgeClient } from \"@scitrera/aether-client\";\n *\n * const bridge = new BridgeClient({\n * address: \"localhost:50051\",\n * implementation: \"aether-msgbridge\",\n * specifier: \"discord-1\",\n * });\n *\n * bridge.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await bridge.connect();\n *\n * // Send to any workspace — bridges are cross-workspace\n * const encoder = new TextEncoder();\n * bridge.sendToAgent(\"prod\", \"my-agent\", \"instance-1\", encoder.encode(\"Hello!\"));\n * bridge.sendToUser(\"alice\", \"tab-1\", encoder.encode(\"Notification from Discord\"));\n * ```\n */\nexport class BridgeClient extends AetherClient {\n private readonly _implementation: string;\n private readonly _specifier: string;\n\n /**\n * Creates a new BridgeClient.\n *\n * @param options - Bridge client configuration\n * @throws {@link InvalidArgumentError} if required fields are missing\n */\n constructor(options: BridgeClientOptions) {\n super(options);\n\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n if (!options.specifier) {\n throw new InvalidArgumentError(\"Specifier is required\", \"specifier\");\n }\n\n this._implementation = options.implementation;\n this._specifier = options.specifier;\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n /** Returns the bridge's implementation type. */\n get implementation(): string {\n return this._implementation;\n }\n\n /** Returns the bridge's specifier (instance identifier). */\n get specifier(): string {\n return this._specifier;\n }\n\n /**\n * Returns this bridge's topic address.\n *\n * Format: br.{implementation}.{specifier}\n */\n get topic(): string {\n return bridgeTopic(this._implementation, this._specifier);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n bridge: {\n implementation: this._implementation,\n specifier: this._specifier,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent in any workspace.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a message to a specific task in any workspace.\n *\n * For unique tasks (with specifier), uses tu.{workspace}.{impl}.{spec} topic.\n * For non-unique tasks (empty specifier), uses tb.{workspace}.{impl} broadcast topic.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n *\n * @param userId - Target user's ID\n * @param windowId - Target user's window/session ID\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userTopic(userId, windowId), payload, messageType);\n }\n\n /**\n * Sends a message to a user's workspace scope.\n *\n * This reaches the user regardless of which window/tab they are using.\n *\n * @param userId - Target user's ID\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUserWorkspace(\n userId: string,\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userWorkspaceTopic(userId, workspace), payload, messageType);\n }\n\n // ===========================================================================\n // Broadcast Helpers\n // ===========================================================================\n\n /**\n * Sends a message to all agents in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToAgents(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(globalAgentsTopic(workspace), payload, messageType);\n }\n\n /**\n * Sends a message to all users in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToUsers(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(globalUsersTopic(workspace), payload, messageType);\n }\n}\n","/**\n * Proxy HTTP support for the Aether TypeScript SDK.\n *\n * Provides `proxyHttp()` on AetherClient for tunneling HTTP requests through\n * the Aether gRPC stream, and `AetherFetchTransport` as a drop-in replacement\n * for the Web Fetch API transport layer.\n *\n * Bodies larger than CHUNK_THRESHOLD (256 KB) are split into\n * ProxyHttpBodyChunk frames and reassembled on the response side.\n *\n * @module proxy\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport { ConnectionError, TimeoutError } from \"./errors.js\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst CHUNK_THRESHOLD = 256 * 1024; // 256 KB\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Transport-layer error kinds from the gateway. */\nexport enum ProxyErrorKind {\n Unknown = 0,\n DialFailed = 1,\n Timeout = 2,\n UpstreamReset = 3,\n AclDenied = 4,\n SidecarUnavailable = 5,\n PayloadTooLarge = 6,\n DecodeFailed = 7,\n}\n\n/** Transport-layer error from the gateway (not an HTTP error). */\nexport interface ProxyError {\n readonly kind: ProxyErrorKind;\n readonly message: string;\n}\n\n/** Structured response from a proxied HTTP request. */\nexport interface ProxyHttpResponse {\n readonly requestId: string;\n readonly statusCode: number;\n readonly headers: Record<string, string>;\n readonly body: Uint8Array;\n readonly bodyChunked: boolean;\n readonly error?: ProxyError;\n}\n\n/** Options for proxyHttp(). */\nexport interface ProxyHttpOptions {\n /** Request headers to send. */\n headers?: Record<string, string>;\n /** Request body (raw bytes). */\n body?: Uint8Array;\n /** Timeout in milliseconds (default: 30 000). */\n timeoutMs?: number;\n /** Whether to follow HTTP redirects (default: true). */\n followRedirects?: boolean;\n /**\n * Pin the request to a named terminator backend. The backend's allow-list\n * still applies — explicit naming selects which backend's ACL is consulted,\n * not whether the request is allowed.\n */\n backend?: string;\n /**\n * Opt into unbounded response streaming (SSE / log tails / model token\n * streams). When true, ``timeoutMs`` becomes the time-to-first-byte\n * deadline only; subsequent body bytes are governed by\n * ``streamIdleTimeoutMs``. The response body is delivered as a real\n * ``ReadableStream<Uint8Array>`` so consumers can iterate chunks as they\n * arrive without buffering the whole response.\n */\n streamResponse?: boolean;\n /**\n * Idle deadline (ms) between body bytes when ``streamResponse=true``.\n * Default 30 000 (30s) when unset. Exceeding closes the stream with\n * ``ProxyError{TIMEOUT}``.\n */\n streamIdleTimeoutMs?: number;\n /**\n * Maximum total response body bytes when ``streamResponse=true``. 0 (the\n * default) means \"use the per-backend cap\". Exceeding closes the stream\n * with ``ProxyError{PAYLOAD_TOO_LARGE}``.\n */\n maxResponseBodyBytes?: number;\n}\n\n/** Error thrown when the proxy transport layer fails. */\nexport class ProxyHttpError extends Error {\n readonly proxyError: ProxyError;\n constructor(err: ProxyError) {\n super(`Proxy transport error [${ProxyErrorKind[err.kind]}]: ${err.message}`);\n this.name = \"ProxyHttpError\";\n this.proxyError = err;\n }\n}\n\n// =============================================================================\n// proxyHttp — callable as client.proxyHttp(...)\n// =============================================================================\n\n/**\n * Sends an HTTP request through the Aether gRPC stream to a service principal\n * and returns a fetch-compatible `Response` object.\n *\n * @param client - Connected AetherClient instance\n * @param target - Target topic, e.g. `\"sv::memorylayer::default\"` or wildcard `\"sv::memorylayer\"`\n * @param method - HTTP method, e.g. `\"GET\"`, `\"POST\"`\n * @param path - Path including query string, e.g. `\"/v1/memories/abc\"`\n * @param opts - Optional headers, body, timeout, followRedirects\n * @returns A `Response`-compatible object (standard Web API Response)\n * @throws {@link ProxyHttpError} on transport-layer failure\n * @throws {@link TimeoutError} if the request times out\n * @throws {@link ConnectionError} if not connected\n */\nexport async function proxyHttp(\n client: AetherClient,\n target: string,\n method: string,\n path: string,\n opts: ProxyHttpOptions = {},\n): Promise<Response> {\n if (!(client as unknown as { _connected: boolean })._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n\n const requestId = (client as { nextRequestId(): string }).nextRequestId();\n const timeoutMs = opts.timeoutMs ?? 30_000;\n const body = opts.body ?? new Uint8Array(0);\n const headers = opts.headers ?? {};\n const followRedirects = opts.followRedirects ?? true;\n const backendName = opts.backend ?? \"\";\n const streamResponse = opts.streamResponse ?? false;\n const streamIdleTimeoutMs = opts.streamIdleTimeoutMs ?? 0;\n const maxResponseBodyBytes = opts.maxResponseBodyBytes ?? 0;\n const bodyChunked = body.length > CHUNK_THRESHOLD;\n\n // For streaming responses, we wire a ReadableStream<Uint8Array> whose\n // controller is fed by the client's chunk dispatcher. The promise resolves\n // as soon as the header (TTFB) lands so the caller gets a real Response\n // back without waiting for fin.\n let streamingController: ReadableStreamDefaultController<Uint8Array> | null = null;\n const streamSlotMap = (client as {\n _pendingProxyHttpStreams: Map<\n string,\n { controller: ReadableStreamDefaultController<Uint8Array>; headerResolved: boolean }\n >;\n })._pendingProxyHttpStreams;\n const readable = streamResponse\n ? new ReadableStream<Uint8Array>({\n start(controller) {\n streamingController = controller;\n streamSlotMap.set(requestId, { controller, headerResolved: false });\n },\n cancel() {\n streamSlotMap.delete(requestId);\n },\n })\n : null;\n\n return new Promise<Response>((resolve, reject) => {\n const timer = setTimeout(() => {\n (client as { _pendingProxyHttpRequests: Map<string, unknown> })._pendingProxyHttpRequests.delete(requestId);\n (client as { _pendingProxyHttpChunks: Map<string, unknown> })._pendingProxyHttpChunks.delete(requestId);\n (client as { _pendingProxyHttpChunks: Map<string, unknown> })._pendingProxyHttpChunks.delete(requestId + \":shell\");\n if (streamResponse) {\n streamSlotMap.delete(requestId);\n if (streamingController) {\n try { streamingController.error(new TimeoutError(`proxyHttp timed out after ${timeoutMs}ms`)); } catch { /* already closed */ }\n }\n }\n reject(new TimeoutError(`proxyHttp timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n const pendingMap = (client as { _pendingProxyHttpRequests: Map<string, (r: ProxyHttpResponse) => void> })._pendingProxyHttpRequests;\n pendingMap.set(requestId, (resp: ProxyHttpResponse) => {\n clearTimeout(timer);\n if (resp.error && resp.error.kind !== ProxyErrorKind.Unknown) {\n if (streamResponse && streamingController) {\n try { streamingController.error(new ProxyHttpError(resp.error)); } catch { /* */ }\n }\n reject(new ProxyHttpError(resp.error));\n return;\n }\n // Streaming responses surface the ReadableStream<Uint8Array> body so\n // chunks arrive incrementally; bounded responses keep the legacy\n // buffered shape.\n if (streamResponse && readable) {\n const responseHeaders = new Headers(resp.headers);\n resolve(new Response(readable, {\n status: resp.statusCode,\n headers: responseHeaders,\n }));\n return;\n }\n const responseHeaders = new Headers(resp.headers);\n resolve(new Response(resp.body.length > 0 ? resp.body : null, {\n status: resp.statusCode,\n headers: responseHeaders,\n }));\n });\n\n // Send the request envelope\n const upstream = client as unknown as { _sendUpstream(msg: Record<string, unknown>): void };\n\n if (!bodyChunked) {\n upstream._sendUpstream({\n proxyHttpRequest: {\n requestId,\n targetTopic: target,\n method,\n path,\n headers,\n body,\n bodyChunked: false,\n timeoutMs,\n followRedirects,\n backendName,\n streamResponseIndefinitely: streamResponse,\n streamIdleTimeoutMs,\n maxResponseBodyBytes,\n },\n });\n } else {\n // Send header envelope first with bodyChunked=true, empty body\n upstream._sendUpstream({\n proxyHttpRequest: {\n requestId,\n targetTopic: target,\n method,\n path,\n headers,\n body: new Uint8Array(0),\n bodyChunked: true,\n timeoutMs,\n followRedirects,\n backendName,\n streamResponseIndefinitely: streamResponse,\n streamIdleTimeoutMs,\n maxResponseBodyBytes,\n },\n });\n // Send body as chunks\n let seq = 0;\n let offset = 0;\n while (offset < body.length) {\n const end = Math.min(offset + CHUNK_THRESHOLD, body.length);\n const chunk = body.slice(offset, end);\n const fin = end >= body.length;\n upstream._sendUpstream({\n proxyHttpBodyChunk: {\n requestId,\n isRequest: true,\n seq,\n data: chunk,\n fin,\n },\n });\n seq++;\n offset = end;\n }\n }\n });\n}\n\n// =============================================================================\n// AetherFetchTransport — drop-in for the Web Fetch API\n// =============================================================================\n\n/**\n * A drop-in transport for the Web Fetch API that routes requests through\n * an Aether gRPC connection to a service principal.\n *\n * @example\n * ```typescript\n * const transport = new AetherFetchTransport(agentClient, \"sv::memorylayer::default\");\n * const response = await transport.fetch(\"/v1/memories/abc\");\n * ```\n */\nexport class AetherFetchTransport {\n private readonly _client: AetherClient;\n private readonly _target: string;\n private readonly _defaultTimeoutMs: number;\n private readonly _defaultBackend: string;\n\n /**\n * @param client - Connected AetherClient\n * @param target - Default target topic (e.g. `\"sv::memorylayer::default\"`)\n * @param timeoutMs - Default request timeout in ms (default: 30 000)\n * @param backend - Optional default terminator backend name applied to\n * every request. The backend's allow-list still applies — explicit\n * naming selects which backend's ACL is consulted.\n */\n constructor(client: AetherClient, target: string, timeoutMs = 30_000, backend = \"\") {\n this._client = client;\n this._target = target;\n this._defaultTimeoutMs = timeoutMs;\n this._defaultBackend = backend;\n }\n\n /**\n * Fetch-compatible method. Accepts a URL string or Request object plus\n * optional RequestInit overrides.\n *\n * The URL hostname/protocol is ignored — requests are routed to the\n * configured target topic. Only the pathname + search are used as the path.\n *\n * @returns Web API `Response`\n */\n async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n let method = \"GET\";\n let path = \"/\";\n let reqHeaders: Record<string, string> = {};\n let reqBody: Uint8Array | undefined;\n\n if (typeof input === \"string\" || input instanceof URL) {\n const url = typeof input === \"string\" ? new URL(input, \"http://placeholder\") : input;\n path = url.pathname + url.search;\n method = (init?.method ?? \"GET\").toUpperCase();\n } else {\n // Request object\n const url = new URL(input.url, \"http://placeholder\");\n path = url.pathname + url.search;\n method = input.method.toUpperCase();\n // Copy headers from Request object\n input.headers.forEach((value, key) => { reqHeaders[key] = value; });\n }\n\n // Merge init headers\n if (init?.headers) {\n if (init.headers instanceof Headers) {\n init.headers.forEach((v, k) => { reqHeaders[k] = v; });\n } else if (Array.isArray(init.headers)) {\n for (const [k, v] of init.headers) { reqHeaders[k] = v; }\n } else {\n Object.assign(reqHeaders, init.headers);\n }\n }\n\n // Resolve body\n const rawBody = init?.body ?? (input instanceof Request ? input.body : null);\n if (rawBody != null) {\n if (rawBody instanceof Uint8Array) {\n reqBody = rawBody;\n } else if (rawBody instanceof ArrayBuffer) {\n reqBody = new Uint8Array(rawBody);\n } else if (typeof rawBody === \"string\") {\n reqBody = new TextEncoder().encode(rawBody);\n } else if (rawBody instanceof ReadableStream) {\n // Drain the stream\n const reader = rawBody.getReader();\n const parts: Uint8Array[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) parts.push(value instanceof Uint8Array ? value : new Uint8Array(value as ArrayBuffer));\n }\n const total = parts.reduce((s, p) => s + p.length, 0);\n reqBody = new Uint8Array(total);\n let off = 0;\n for (const p of parts) { reqBody.set(p, off); off += p.length; }\n }\n }\n\n return proxyHttp(this._client, this._target, method, path, {\n headers: reqHeaders,\n body: reqBody,\n timeoutMs: this._defaultTimeoutMs,\n backend: this._defaultBackend || undefined,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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Mode","SignalType","pendingMap","ProxyErrorKind","responseHeaders"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/errors.ts","../src/kv.ts","../src/checkpoint.ts","../src/tunnel.ts","../src/authority-cache.ts","../package.json","../src/version-meta.ts","../src/client.ts","../src/admin.ts","../src/topics.ts","../src/agents.ts","../src/tasks.ts","../src/users.ts","../src/orchestrator.ts","../src/workflow.ts","../src/metrics.ts","../src/metrics-builder.ts","../src/bridge.ts","../src/proxy.ts"],"sourcesContent":["/**\n * @scitrera/aether-client - TypeScript SDK for the Aether distributed control plane.\n *\n * Aether is a distributed control plane for routing structured messages,\n * tracking tasks, and managing connection lifecycles. This SDK provides\n * TypeScript/JavaScript clients for agents, users, and other principal types.\n *\n * Key architectural principle: The connection itself IS the distributed lock\n * AND the heartbeat. When the gRPC stream closes, the identity lock is\n * immediately released. No separate heartbeat API exists.\n *\n * Principal Types:\n * - {@link AgentClient}: For persistent agents with workspace/impl/spec identity\n * - {@link TaskClient}: For task connections (unique or non-unique)\n * - {@link UserClient}: For user connections with userId/windowId identity\n * - {@link OrchestratorClient}: For orchestrating agent/task lifecycle\n * - {@link WorkflowEngineClient}: For event processing (singleton)\n * - {@link MetricsBridgeClient}: For telemetry collection (singleton, receive-only)\n * - {@link AetherClient}: Base client for custom principal types\n *\n * @example\n * ```typescript\n * import { AgentClient, MessageType } from \"@scitrera/aether-client\";\n *\n * const agent = new AgentClient({\n * address: \"localhost:50051\",\n * workspace: \"production\",\n * implementation: \"my-agent\",\n * specifier: \"instance-1\",\n * });\n *\n * agent.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * agent.onConnect((ack) => {\n * console.log(`Connected with session ${ack.sessionId}`);\n * });\n *\n * await agent.connect();\n * ```\n *\n * @packageDocumentation\n */\n\n// Client classes\nexport { AetherClient } from \"./client.js\";\nexport type { AetherClientOptions } from \"./client.js\";\n\nexport { AdminClient } from \"./admin.js\";\nexport type {\n AdminQueryResponse,\n AdminQueryResponseHandler,\n AdminTimeoutOptions,\n CreateTokenOptions,\n RevokeTokenOptions,\n ListTokensOptions,\n CreateACLRuleOptions,\n DeleteACLRuleOptions,\n ListACLRulesOptions,\n ListWorkspacesOptions,\n CreateWorkspaceOptions,\n UpdateWorkspaceOptions,\n DeleteWorkspaceOptions,\n ListAgentsOptions,\n GetAgentOptions,\n ListConnectionsOptions,\n DisconnectSessionOptions,\n} from \"./admin.js\";\n\nexport { AgentClient } from \"./agents.js\";\nexport type { AgentClientOptions, CreateTaskOptions } from \"./agents.js\";\n\nexport { TaskClient } from \"./tasks.js\";\nexport type { TaskClientOptions } from \"./tasks.js\";\n\nexport { UserClient } from \"./users.js\";\nexport type { UserClientOptions } from \"./users.js\";\n\nexport { OrchestratorClient, BaseOrchestrator } from \"./orchestrator.js\";\nexport type { OrchestratorClientOptions, BaseOrchestratorOptions } from \"./orchestrator.js\";\n\nexport { WorkflowEngineClient } from \"./workflow.js\";\nexport type { WorkflowEngineClientOptions } from \"./workflow.js\";\n\nexport { MetricsBridgeClient } from \"./metrics.js\";\nexport type { MetricsBridgeClientOptions } from \"./metrics.js\";\n\nexport { MetricBuilder, newMetric } from \"./metrics-builder.js\";\nexport type { Metric, MetricEntry } from \"./metrics-builder.js\";\n\nexport { BridgeClient } from \"./bridge.js\";\nexport type { BridgeClientOptions } from \"./bridge.js\";\n\nexport { KVClient } from \"./kv.js\";\n\nexport { CheckpointClient } from \"./checkpoint.js\";\nexport type {\n CheckpointSaveOptions,\n CheckpointLoadOptions,\n CheckpointDeleteOptions,\n CheckpointListOptions,\n} from \"./checkpoint.js\";\n\n// Types and enums\nexport {\n PrincipalType,\n MessageType,\n KVScope,\n TaskAssignmentMode,\n SignalType,\n} from \"./types.js\";\n\nexport type {\n // Message structures\n IncomingMessage,\n OutgoingMessage,\n ConfigSnapshot,\n Signal,\n ErrorResponse,\n ConnectionAck,\n TaskAssignment,\n // KV types\n KVResponse,\n KVGetOptions,\n KVPutOptions,\n KVListOptions,\n KVDeleteOptions,\n KVIncrementOptions,\n KVDecrementOptions,\n KVIncrementIfOptions,\n KVDecrementIfOptions,\n // Checkpoint types\n CheckpointResponse,\n // Progress types\n ProgressUpdate,\n ProgressStep,\n ReportProgressOptions,\n // Task management types\n TaskInfo,\n TaskQueryResponse,\n TaskOperationResponse,\n TaskQueryOptions,\n TaskQueryResponseHandler,\n TaskOperationResponseHandler,\n // Workspace/Agent/ACL/Workflow response types\n WorkspaceResponse,\n AgentResponse,\n ACLResponse,\n AuthorityGrantPrincipalRef,\n AuthorityGrantResourceScope,\n AuthorityGrantInfo,\n AuthorityGrantResponse,\n AuthorityGrantRevocation,\n WorkflowResponse,\n // Token management types\n TokenInfo,\n TokenResponse,\n // Callback types\n MessageHandler,\n ConfigHandler,\n SignalHandler,\n ErrorHandler,\n KVResponseHandler,\n TaskAssignmentHandler,\n CheckpointResponseHandler,\n ProgressHandler,\n ConnectHandler,\n DisconnectHandler,\n ReconnectingHandler,\n WorkspaceResponseHandler,\n AgentResponseHandler,\n ACLResponseHandler,\n AuthorityGrantResponseHandler,\n AuthorityGrantRevocationHandler,\n WorkflowResponseHandler,\n TokenResponseHandler,\n AuditSubmitResponse,\n AuditSubmitResponseHandler,\n // Configuration types\n TLSOptions,\n ConnectionOptions,\n Credentials,\n} from \"./types.js\";\n\n// Credential helpers\nexport {\n withAPIKey,\n withToken,\n withTaskToken,\n withTenant,\n} from \"./types.js\";\n\n// Error classes\nexport {\n AetherError,\n ConnectionError,\n ConnectionClosedError,\n ReconnectionError,\n AuthenticationError,\n PermissionDeniedError,\n DuplicateIdentityError,\n TimeoutError,\n InvalidArgumentError,\n NotFoundError,\n UnimplementedError,\n MessageError,\n KVOperationError,\n CheckpointError,\n // Error classification utilities\n isRecoverable,\n isConnectionError,\n isTimeoutError,\n} from \"./errors.js\";\n\n// Proxy HTTP support\nexport { proxyHttp, AetherFetchTransport, ProxyErrorKind, ProxyHttpError } from \"./proxy.js\";\nexport type { ProxyHttpResponse, ProxyHttpOptions, ProxyError } from \"./proxy.js\";\n\n// Tunnel support\nexport { tunnelDial, TunnelClosedError } from \"./tunnel.js\";\nexport type { TunnelProtocol, TunnelDialOptions, TunnelStream } from \"./tunnel.js\";\n\n// Authority-grant cache (Phase 4 of the ACL/grant cleanup)\nexport { AuthorityGrantCache } from \"./authority-cache.js\";\nexport type { AuthorityGrantCacheOptions, AuthorityCacheClient } from \"./authority-cache.js\";\n\n// Topic construction helpers\nexport {\n agentTopic,\n globalAgentsTopic,\n uniqueTaskTopic,\n taskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n globalUsersTopic,\n eventTopic,\n eventWildcardTopic,\n metricTopic,\n metricWildcardTopic,\n progressTopic,\n bridgeTopic,\n // Topic prefix constants\n TOPIC_PREFIX_AGENT,\n TOPIC_PREFIX_UNIQUE_TASK,\n TOPIC_PREFIX_TASK,\n TOPIC_PREFIX_TASK_BROADCAST,\n TOPIC_PREFIX_USER,\n TOPIC_PREFIX_USER_WORKSPACE,\n TOPIC_PREFIX_GLOBAL_AGENTS,\n TOPIC_PREFIX_GLOBAL_USERS,\n TOPIC_PREFIX_EVENT,\n TOPIC_PREFIX_METRIC,\n TOPIC_PREFIX_PROGRESS,\n TOPIC_PREFIX_BRIDGE,\n} from \"./topics.js\";\n","/**\n * Type definitions for the Aether TypeScript SDK.\n *\n * This module provides comprehensive type definitions for principal types,\n * message types, KV scopes, topic construction, and callback handlers.\n * These types mirror the protobuf definitions in api/proto/aether.proto\n * and match the patterns established by the Go and Python SDKs.\n *\n * @module types\n */\n\n// =============================================================================\n// Principal Types\n// =============================================================================\n\n/**\n * Principal types supported by the Aether gateway.\n *\n * Each principal type has different routing rules and permissions:\n * - Agent: Persistent entity with workspace/impl/spec identity\n * - UniqueTask: Named task with persistent identity\n * - NonUniqueTask: Ephemeral task with server-assigned ID\n * - User: Browser/session-based identity with userId/windowId\n * - WorkflowEngine: Event processor (singleton per gateway)\n * - MetricsBridge: Telemetry collector (singleton per gateway)\n * - Orchestrator: Compute provisioner for lazy-loading agents/tasks\n */\nexport enum PrincipalType {\n Agent = \"agent\",\n UniqueTask = \"unique_task\",\n NonUniqueTask = \"non_unique_task\",\n\tUser = \"user\",\n\tWorkflowEngine = \"workflow_engine\",\n\tMetricsBridge = \"metrics_bridge\",\n\tOrchestrator = \"orchestrator\",\n\tService = \"service\",\n}\n\n// =============================================================================\n// Message Types\n// =============================================================================\n\n/**\n * Message types for the Aether messaging protocol.\n *\n * - Chat: Conversational messages between principals\n * - Control: Control/command messages for state changes\n * - ToolCall: Tool invocation messages\n * - Event: Broadcast events processed by WorkflowEngine\n * - Metric: Telemetry data collected by MetricsBridge\n */\nexport enum MessageType {\n Unspecified = 0,\n Chat = 1,\n Control = 2,\n ToolCall = 3,\n Event = 4,\n Metric = 5,\n Opaque = 6,\n}\n\n// =============================================================================\n// KV Scope\n// =============================================================================\n\n/**\n * Scopes for KV store operations.\n *\n * - Global: Accessible to all entities across all workspaces\n * - Workspace: Accessible within a specific workspace\n * - User: Accessible to a specific user across all workspaces\n * - UserWorkspace: Accessible to a specific user within a specific workspace\n * - GlobalExclusive: Global scope with exclusive (single-owner) write semantics\n * - WorkspaceExclusive: Workspace scope with exclusive (single-owner) write semantics\n * - UserShared: User scope shared across all agent implementations\n * - UserWorkspaceShared: User-workspace scope shared across all agent implementations\n */\nexport enum KVScope {\n Unspecified = 0,\n Global = 1,\n Workspace = 2,\n User = 3,\n UserWorkspace = 4,\n GlobalExclusive = 5,\n WorkspaceExclusive = 6,\n UserShared = 7,\n UserWorkspaceShared = 8,\n}\n\n// =============================================================================\n// Task Assignment Mode\n// =============================================================================\n\n/**\n * Modes for task assignment.\n *\n * - SelfAssign: Caller self-assigns the task (default)\n * - Targeted: Task is assigned to a specific agent (may trigger orchestration)\n * - Pool: Any matching worker can claim the task\n */\nexport enum TaskAssignmentMode {\n SelfAssign = 0,\n Targeted = 1,\n Pool = 2,\n}\n\n// =============================================================================\n// Signal Types\n// =============================================================================\n\n/**\n * Signal types from the gateway.\n */\nexport enum SignalType {\n ForceDisconnect = 0,\n GracefulDisconnect = 1,\n}\n\n// =============================================================================\n// Message Structures\n// =============================================================================\n\n/**\n * An incoming message received from the Aether gateway.\n */\nexport interface IncomingMessage {\n /** The topic from which the message originated (identifies the sender). */\n readonly sourceTopic: string;\n /** The raw message payload. */\n readonly payload: Uint8Array;\n /** The type of the message (Chat, Control, ToolCall, Event, Metric). */\n readonly messageType?: number;\n /** Local timestamp when the message was received. */\n readonly receivedAt: Date;\n}\n\n/**\n * An outgoing message to send through the Aether gateway.\n */\nexport interface OutgoingMessage {\n /** The destination topic string. */\n targetTopic: string;\n /** The message payload (bytes). */\n payload: Uint8Array;\n /** The type of message. Defaults to Chat. */\n messageType?: MessageType;\n}\n\n/**\n * A configuration snapshot received upon connection.\n * Contains KV store data for the client's workspace.\n */\nexport interface ConfigSnapshot {\n /** Workspace-scoped key-value pairs (opaque bytes; decode with msgpack/TextDecoder as needed). */\n readonly kv: Record<string, Uint8Array>;\n /** Global-scoped key-value pairs (opaque bytes; decode with msgpack/TextDecoder as needed). */\n readonly globalKv: Record<string, Uint8Array>;\n /** Workspace-exclusive-scoped key-value pairs (opaque bytes). */\n readonly workspaceExclusiveKv: Record<string, Uint8Array>;\n /** Global-exclusive-scoped key-value pairs (opaque bytes). */\n readonly globalExclusiveKv: Record<string, Uint8Array>;\n}\n\n/**\n * A signal from the gateway (e.g., force disconnect).\n */\nexport interface Signal {\n /** The signal type. */\n readonly type: SignalType;\n /** Additional context for the signal. */\n readonly reason: string;\n}\n\n/**\n * An error response from the gateway.\n */\nexport interface ErrorResponse {\n /** Error code string. */\n readonly code: string;\n /** Human-readable error message. */\n readonly message: string;\n /** Whether the client should retry this request. */\n readonly retryable: boolean;\n /** Suggested retry delay in milliseconds (0 = use default backoff). */\n readonly retryAfterMs: number;\n}\n\n/**\n * Connection acknowledgment received after successful connection.\n */\nexport interface ConnectionAck {\n /** Server-assigned session identifier. Store for session resumption. */\n readonly sessionId: string;\n /** Whether this was a resumed session. */\n readonly resumed: boolean;\n /** For non-unique tasks: the server-assigned task instance ID. Empty otherwise. */\n readonly assignedId: string;\n}\n\n/**\n * A task assignment received by orchestrators.\n */\nexport interface TaskAssignment {\n readonly taskId: string;\n readonly taskType: string;\n readonly assignedTo: string;\n readonly metadata: Record<string, string>;\n readonly assignedAt: number;\n readonly profile: string;\n readonly launchParams: Record<string, string>;\n readonly targetImplementation: string;\n readonly workspace: string;\n readonly specifier: string;\n}\n\n// =============================================================================\n// KV Types\n// =============================================================================\n\n/**\n * Response from a KV store operation.\n */\nexport interface KVResponse {\n readonly success: boolean;\n /** Retrieved value (for GET operations). */\n readonly value: Uint8Array;\n /** List of keys (for LIST operations). */\n readonly keys: string[];\n /** Key-value pairs (for LIST with values). */\n readonly kvMap: Record<string, string>;\n /** Correlation ID echoed from the request. */\n readonly requestId: string;\n /** Result of INCREMENT/DECREMENT operations. */\n readonly counterValue?: number;\n /** Whether the guarded increment/decrement was applied (INCREMENT_IF/DECREMENT_IF). */\n readonly applied?: boolean;\n}\n\n/**\n * Parameters for a KV GET operation.\n */\nexport interface KVGetOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV PUT operation.\n */\nexport interface KVPutOptions {\n key: string;\n value: Uint8Array;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** TTL in seconds (0 = no expiration). */\n ttl?: number;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV LIST operation.\n */\nexport interface KVListOptions {\n keyPrefix?: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV DELETE operation.\n */\nexport interface KVDeleteOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV INCREMENT operation.\n */\nexport interface KVIncrementOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV DECREMENT operation.\n */\nexport interface KVDecrementOptions {\n key: string;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV INCREMENT_IF operation (increment only if counter is below ceiling).\n */\nexport interface KVIncrementIfOptions {\n key: string;\n /** Amount to increment. Default: 1. */\n delta?: bigint | number;\n /** Ceiling guard: increment only if the current value is strictly below this. */\n ceiling: bigint | number;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Parameters for a KV DECREMENT_IF operation (decrement only if counter is above floor).\n */\nexport interface KVDecrementIfOptions {\n key: string;\n /** Amount to decrement. Default: 1. */\n delta?: bigint | number;\n /** Floor guard: decrement only if the current value is strictly above this. */\n floor: bigint | number;\n scope?: KVScope;\n userId?: string;\n workspace?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n// =============================================================================\n// Progress Types\n// =============================================================================\n\n/**\n * A progress update received from an agent or task.\n * Delivered via the pg::{workspace} RabbitMQ stream with server-side filtering.\n */\nexport interface ProgressUpdate {\n /** The identity of the reporting agent/task (topic format). */\n readonly source: string;\n /** Task or correlation ID this progress relates to. */\n readonly taskId: string;\n /** Current state (e.g., \"running\", \"finishing\", \"idle\"). */\n readonly state: string;\n /** Completion fraction 0.0-1.0, or -1 for indeterminate. */\n readonly completion: number;\n /** Human-readable summary of current activity. */\n readonly summary: string;\n /** Structured step information for multi-step operations. */\n readonly step?: ProgressStep;\n /** Server timestamp when progress was received (Unix milliseconds). */\n readonly timestampMs: number;\n /** Workspace the progress originated from. */\n readonly workspace: string;\n /** Correlation ID from the originating request. */\n readonly requestId: string;\n /** Arbitrary metadata from the reporter. */\n readonly metadata: Record<string, string>;\n /** Target recipient identity topic (empty = broadcast). */\n readonly recipient: string;\n}\n\n/**\n * A discrete step within a multi-step progress operation.\n */\nexport interface ProgressStep {\n /** Step name/title. */\n readonly name: string;\n /** Detailed description of what this step is doing. */\n readonly detail: string;\n /** Step sequence number (1-based). */\n readonly sequence: number;\n /** Total number of steps (0 = unknown). */\n readonly totalSteps: number;\n /** Step type hint for UI rendering (e.g., \"llm_call\", \"tool_use\"). */\n readonly stepType: string;\n}\n\n/**\n * Options for reporting progress from an agent or task.\n */\nexport interface ReportProgressOptions {\n /** Task or correlation ID this progress relates to. Required. */\n taskId: string;\n /** Current state (e.g., \"running\", \"finishing\", \"idle\"). */\n state?: string;\n /** Completion fraction 0.0-1.0, or -1 for indeterminate. Default: -1. */\n completion?: number;\n /** Human-readable summary of current activity. */\n summary?: string;\n /** Step name for multi-step progress. */\n stepName?: string;\n /** Step detail description. */\n stepDetail?: string;\n /** Step sequence number (1-based). */\n stepSequence?: number;\n /** Total number of steps (0 = unknown). */\n stepTotal?: number;\n /** Step type hint for UI rendering. */\n stepType?: string;\n /** Target identity topic to receive updates (empty = broadcast). */\n recipient?: string;\n /** Correlation ID for the originating request. */\n requestId?: string;\n /** Arbitrary key-value metadata. */\n metadata?: Record<string, string>;\n}\n\n// =============================================================================\n// Checkpoint Types\n// =============================================================================\n\n/**\n * Response from a checkpoint operation.\n */\nexport interface CheckpointResponse {\n readonly success: boolean;\n readonly data: Uint8Array;\n readonly keys: string[];\n readonly error: string;\n readonly savedAt: number;\n readonly requestId: string;\n}\n\n// =============================================================================\n// Task Management Types\n// =============================================================================\n\n/**\n * Represents a task's information from the server.\n */\nexport interface TaskInfo {\n taskId: string;\n taskType: string;\n status: string;\n workspace: string;\n targetTopic: string;\n assignedTo: string;\n createdAt: number;\n startedAt: number;\n completedAt: number;\n attempt: number;\n maxAttempts: number;\n error: string;\n metadata: Record<string, string>;\n}\n\n/**\n * Response to a task query (list or get).\n */\nexport interface TaskQueryResponse {\n success: boolean;\n error: string;\n task?: TaskInfo;\n tasks: TaskInfo[];\n totalCount: number;\n /** Correlation ID echoed from the request. */\n requestId?: string;\n}\n\n/**\n * Response to a task operation (cancel or retry).\n */\nexport interface TaskOperationResponse {\n success: boolean;\n message: string;\n error: string;\n task?: TaskInfo;\n /** Correlation ID echoed from the request. */\n requestId?: string;\n}\n\n/**\n * Response to a CreateTaskRequest that carried a non-empty request_id.\n * Gives the creator the server-assigned task_id for later COMPLETE/FAIL/CANCEL.\n */\nexport interface CreateTaskResponse {\n /** Whether the task was created successfully. */\n success: boolean;\n /** Server-assigned task ID on success. */\n taskId: string;\n /** Initial task status, e.g., \"pending\", \"assigned\", \"pending_pool\". */\n status: string;\n /** Error code on failure, e.g., \"ERR_PERMISSION_DENIED\". */\n errorCode: string;\n /** Human-readable error description. */\n errorMessage: string;\n /** Echoed from the originating CreateTaskRequest for correlation. */\n requestId: string;\n /** For TARGETED tasks successfully delivered: the receiving identity string. */\n assignedTo: string;\n}\n\n// =============================================================================\n// Workspace / Agent / ACL / Workflow Response Types\n// =============================================================================\n\n/**\n * Generic workspace operation response.\n */\nexport interface WorkspaceResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly totalCount: number;\n readonly requestId?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Generic agent operation response.\n */\nexport interface AgentResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly totalCount: number;\n readonly requestId?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Generic ACL operation response.\n */\nexport interface ACLResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly requestId?: string;\n readonly [key: string]: unknown;\n}\n\n/**\n * Stable principal reference attached to an authority grant.\n */\nexport interface AuthorityGrantPrincipalRef {\n readonly principalType: string;\n readonly principalId: string;\n}\n\n/**\n * Resource-specific scope entry attached to an authority grant.\n */\nexport interface AuthorityGrantResourceScope {\n readonly resourceType: string;\n readonly patterns: string[];\n}\n\n/**\n * Authority grant details returned by runtime or admin grant APIs.\n */\nexport interface AuthorityGrantInfo {\n readonly grantId: string;\n readonly rootGrantId: string;\n readonly subject?: AuthorityGrantPrincipalRef;\n readonly delegate?: AuthorityGrantPrincipalRef;\n readonly issuedBy?: AuthorityGrantPrincipalRef;\n readonly rootSubject?: AuthorityGrantPrincipalRef;\n readonly parentGrantId: string;\n readonly mayDelegate: boolean;\n readonly remainingHops: number;\n readonly workspaceScope: string[];\n readonly resourceScope: AuthorityGrantResourceScope[];\n readonly operationScope: string[];\n readonly maxAccessLevel: number;\n readonly accessLevelName: string;\n readonly audienceType: string;\n readonly audienceId: string;\n readonly validWhileAudienceActive: boolean;\n readonly expiresAt: number;\n readonly renewableUntil: number;\n readonly renewedAt: number;\n readonly revoked: boolean;\n readonly revokedAt: number;\n readonly reason: string;\n readonly metadata: Record<string, string>;\n readonly createdAt: number;\n}\n\n/**\n * Runtime authority-grant operation response.\n */\nexport interface AuthorityGrantResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly grant?: AuthorityGrantInfo;\n readonly requestId: string;\n /**\n * For LIST_MY_GRANTS / LIST_GRANTS_ON_ME / BATCH_EXCHANGE results.\n */\n readonly grants?: AuthorityGrantInfo[];\n /**\n * Total matching rows ignoring pagination (LIST_*) or count of returned\n * grants (BATCH_EXCHANGE).\n */\n readonly total?: number;\n /**\n * Server's hint to clients on how often to revalidate cached grants\n * (seconds). Zero means \"no hint\" — clients fall back to their own policy.\n */\n readonly cacheHintTtlSeconds?: number;\n}\n\n/**\n * Server-pushed AuthorityGrantRevocation event. Sent on the downstream\n * stream when a grant the connected client holds is revoked, directly or\n * via cascade from a parent revocation.\n */\nexport interface AuthorityGrantRevocation {\n readonly grantId: string;\n readonly rootGrantId: string;\n readonly reason: string;\n readonly revokedAt: number;\n readonly cascade: boolean;\n}\n\n/**\n * Workflow operation response.\n */\nexport interface WorkflowResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly data?: Uint8Array;\n readonly totalCount: number;\n readonly requestId?: string;\n}\n\n/**\n * Options for querying tasks.\n */\nexport interface TaskQueryOptions {\n workspace?: string;\n status?: string;\n taskType?: string;\n limit?: number;\n offset?: number;\n timeout?: number;\n}\n\n// =============================================================================\n// Token Management Types\n// =============================================================================\n\n/**\n * Information about an API token.\n */\nexport interface TokenInfo {\n readonly id: string;\n readonly name: string;\n readonly principalType: string;\n readonly workspacePatterns: string[];\n readonly scopes: string[];\n readonly createdBy: string;\n readonly expiresAt: number;\n readonly lastUsedAt: number;\n readonly revoked: boolean;\n readonly revokedAt: number;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\n/**\n * Response to a token operation.\n */\nexport interface TokenResponse {\n readonly success: boolean;\n readonly error: string;\n readonly message: string;\n readonly token?: TokenInfo;\n readonly tokens: TokenInfo[];\n readonly totalCount: number;\n readonly plaintextToken: string;\n readonly createdToken?: TokenInfo;\n readonly requestId: string;\n}\n\n// =============================================================================\n// Callback Types\n// =============================================================================\n\n/** Handler for incoming messages. */\nexport type MessageHandler = (message: IncomingMessage) => void | Promise<void>;\n\n/** Handler for configuration snapshots. */\nexport type ConfigHandler = (config: ConfigSnapshot) => void | Promise<void>;\n\n/** Handler for signals from the gateway. */\nexport type SignalHandler = (signal: Signal) => void | Promise<void>;\n\n/** Handler for error responses from the gateway. */\nexport type ErrorHandler = (error: ErrorResponse) => void | Promise<void>;\n\n/** Handler for KV operation responses. */\nexport type KVResponseHandler = (response: KVResponse) => void | Promise<void>;\n\n/** Handler for task assignments (used by orchestrators). */\nexport type TaskAssignmentHandler = (assignment: TaskAssignment) => void | Promise<void>;\n\n/** Handler for checkpoint responses. */\nexport type CheckpointResponseHandler = (response: CheckpointResponse) => void | Promise<void>;\n\n/** Handler for create task responses. */\nexport type CreateTaskResponseHandler = (response: CreateTaskResponse) => void | Promise<void>;\n\n/** Handler for task query responses. */\nexport type TaskQueryResponseHandler = (response: TaskQueryResponse) => void;\n\n/** Handler for task operation responses. */\nexport type TaskOperationResponseHandler = (response: TaskOperationResponse) => void;\n\n/** Handler for workspace operation responses. */\nexport type WorkspaceResponseHandler = (response: WorkspaceResponse) => void | Promise<void>;\n\n/** Handler for agent operation responses. */\nexport type AgentResponseHandler = (response: AgentResponse) => void | Promise<void>;\n\n/** Handler for ACL operation responses. */\nexport type ACLResponseHandler = (response: ACLResponse) => void | Promise<void>;\n\n/** Handler for runtime authority-grant responses. */\nexport type AuthorityGrantResponseHandler = (response: AuthorityGrantResponse) => void | Promise<void>;\n\n/** Handler for server-pushed authority-grant revocation events. */\nexport type AuthorityGrantRevocationHandler = (event: AuthorityGrantRevocation) => void | Promise<void>;\n\n/** Handler for workflow operation responses. */\nexport type WorkflowResponseHandler = (response: WorkflowResponse) => void | Promise<void>;\n\n/** Handler for token operation responses. */\nexport type TokenResponseHandler = (response: TokenResponse) => void;\n\n// ---------------------------------------------------------------------------\n// Audit submit types\n// ---------------------------------------------------------------------------\n\n/** Response type for submitAuditEvent requests. */\nexport type AuditSubmitResponse = import(\"./proto/aether/v1/SubmitAuditEventResponse.js\").SubmitAuditEventResponse__Output;\n\n/** Handler for audit-submit responses. */\nexport type AuditSubmitResponseHandler = (response: AuditSubmitResponse) => void;\n\n/** Handler for progress updates from agents/tasks. */\nexport type ProgressHandler = (update: ProgressUpdate) => void | Promise<void>;\n\n/** Handler for successful connection. */\nexport type ConnectHandler = (ack: ConnectionAck) => void | Promise<void>;\n\n/** Handler for disconnection events. */\nexport type DisconnectHandler = (reason: string) => void | Promise<void>;\n\n/** Handler for reconnection attempts. */\nexport type ReconnectingHandler = (attempt: number) => void | Promise<void>;\n\n// =============================================================================\n// Connection Options\n// =============================================================================\n\n/**\n * TLS configuration for secure connections.\n */\nexport interface TLSOptions {\n /** PEM-encoded root CA certificates for server verification. */\n rootCerts?: Buffer;\n /** PEM-encoded client private key (for mTLS). */\n privateKey?: Buffer;\n /** PEM-encoded client certificate chain (for mTLS). */\n certChain?: Buffer;\n /** Override server hostname for certificate validation. */\n serverNameOverride?: string;\n}\n\n/**\n * Connection behavior configuration.\n */\nexport interface ConnectionOptions {\n /** Maximum number of connection attempts (0 = infinite for reconnection). Default: 5. */\n maxRetries?: number;\n /** Initial backoff delay in milliseconds. Default: 1000. */\n initialBackoff?: number;\n /** Maximum backoff delay in milliseconds. Default: 30000. */\n maxBackoff?: number;\n /** Multiplier for exponential backoff. Default: 2.0. */\n backoffMultiplier?: number;\n /** Whether to automatically reconnect on connection loss. Default: true. */\n autoReconnect?: boolean;\n /** Timeout for establishing a connection in milliseconds. Default: 30000. */\n connectTimeout?: number;\n /**\n * When true, if the gateway returns a DuplicateIdentityError (ALREADY_EXISTS)\n * during connection, the client will wait briefly and retry. Useful when a\n * previous instance may still be releasing its distributed lock.\n * Default: false.\n */\n retryOnDuplicate?: boolean;\n /**\n * How long to wait (ms) before retrying after a DuplicateIdentityError.\n * Only used when retryOnDuplicate is true. Default: 5000.\n */\n retryOnDuplicateDelay?: number;\n /**\n * Maximum number of duplicate-identity retries before giving up.\n * Only used when retryOnDuplicate is true. Default: 5.\n */\n retryOnDuplicateMaxAttempts?: number;\n}\n\n/**\n * Authentication credentials passed to the gateway.\n */\nexport interface Credentials {\n [key: string]: string;\n}\n\n// =============================================================================\n// Credential Helpers\n// =============================================================================\n\n/**\n * Creates a credentials object with an API key.\n *\n * @param key - The long-lived API key for authentication\n * @returns Credentials map with the API key header\n */\nexport function withAPIKey(key: string): Credentials {\n return { \"x-api-key\": key };\n}\n\n/**\n * Creates a credentials object with a bearer token.\n *\n * @param token - The OAuth/JWT bearer token\n * @returns Credentials map with the authorization header\n */\nexport function withToken(token: string): Credentials {\n return { authorization: `Bearer ${token}` };\n}\n\n/**\n * Creates a credentials object with a task token.\n *\n * @param token - The short-lived task authentication token\n * @returns Credentials map with the token header\n */\nexport function withTaskToken(token: string): Credentials {\n return { token };\n}\n\n/**\n * Creates a credentials object with a tenant ID.\n *\n * @param tenantId - The tenant identifier\n * @returns Credentials map with the tenant ID header\n */\nexport function withTenant(tenantId: string): Credentials {\n return { \"x-tenant-id\": tenantId };\n}\n","/**\n * Error hierarchy for the Aether TypeScript SDK.\n *\n * This module provides a structured set of error classes that map to common\n * error scenarios in Aether client operations, mirroring the error hierarchies\n * in the Go SDK (errors.go) and Python SDK (exceptions.py).\n *\n * All errors extend the base AetherError class, making it easy to catch all\n * SDK-related errors with a single catch clause.\n *\n * @module errors\n */\n\n// =============================================================================\n// Base Error\n// =============================================================================\n\n/**\n * Base error class for all Aether SDK errors.\n *\n * All Aether-specific errors extend this class.\n */\nexport class AetherError extends Error {\n /** Optional error code (e.g., gRPC status code name). */\n readonly code: string;\n /** Optional additional error details. */\n readonly details: string;\n /** The underlying cause, if any. */\n readonly cause?: Error;\n\n constructor(message: string, code = \"\", details = \"\", cause?: Error) {\n const parts: string[] = [];\n if (code) parts.push(`[${code}]`);\n parts.push(message);\n if (details) parts.push(`(${details})`);\n super(parts.join(\" \"));\n\n this.name = \"AetherError\";\n this.code = code;\n this.details = details;\n this.cause = cause;\n }\n}\n\n// =============================================================================\n// Connection Errors\n// =============================================================================\n\n/**\n * Indicates a connection to the Aether gateway failed.\n *\n * This includes initial connection failures, network errors, and\n * disconnection events that cannot be automatically recovered.\n */\nexport class ConnectionError extends AetherError {\n constructor(message = \"Failed to connect to Aether gateway\", code = \"\", details = \"\", cause?: Error) {\n super(message, code, details, cause);\n this.name = \"ConnectionError\";\n }\n}\n\n/**\n * Indicates the connection was unexpectedly closed.\n *\n * This can happen due to network issues, server restarts, or\n * force disconnect signals from the server.\n */\nexport class ConnectionClosedError extends AetherError {\n /** Reason for the disconnection. */\n readonly reason: string;\n\n constructor(reason = \"\", code = \"\", cause?: Error) {\n super(\"Connection closed unexpectedly\", code, reason, cause);\n this.name = \"ConnectionClosedError\";\n this.reason = reason;\n }\n}\n\n/**\n * Indicates automatic reconnection failed after exhausting all retries.\n */\nexport class ReconnectionError extends AetherError {\n /** Number of reconnection attempts made. */\n readonly attempts: number;\n\n constructor(attempts: number, cause?: Error) {\n super(\"Failed to reconnect after maximum retries\", \"\", `attempts=${attempts}`, cause);\n this.name = \"ReconnectionError\";\n this.attempts = attempts;\n }\n}\n\n// =============================================================================\n// Authentication and Authorization Errors\n// =============================================================================\n\n/**\n * Indicates authentication failed.\n *\n * Maps to gRPC UNAUTHENTICATED status code. Authentication errors\n * are non-recoverable and will not trigger automatic reconnection.\n */\nexport class AuthenticationError extends AetherError {\n constructor(message = \"Authentication failed\", details = \"\", cause?: Error) {\n super(message, \"UNAUTHENTICATED\", details, cause);\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Indicates the client lacks permission to perform an operation.\n *\n * Maps to gRPC PERMISSION_DENIED status code. Permission errors\n * are non-recoverable and will not trigger automatic reconnection.\n */\nexport class PermissionDeniedError extends AetherError {\n constructor(message = \"Permission denied\", details = \"\", cause?: Error) {\n super(message, \"PERMISSION_DENIED\", details, cause);\n this.name = \"PermissionDeniedError\";\n }\n}\n\n// =============================================================================\n// Identity Errors\n// =============================================================================\n\n/**\n * Indicates an identity is already in use.\n *\n * In Aether, each agent or unique task identity can only have one active\n * connection at a time (Connection = Lock paradigm). This error indicates\n * another client is already connected with the same identity.\n *\n * Maps to gRPC ALREADY_EXISTS status code.\n */\nexport class DuplicateIdentityError extends AetherError {\n /** The conflicting identity string. */\n readonly identity: string;\n\n constructor(identity = \"\", details = \"\", cause?: Error) {\n super(\"Identity already connected\", \"ALREADY_EXISTS\", details, cause);\n this.name = \"DuplicateIdentityError\";\n this.identity = identity;\n }\n}\n\n// =============================================================================\n// Timeout Errors\n// =============================================================================\n\n/**\n * Indicates an operation timed out.\n *\n * This can occur during connection attempts, message sends, or\n * synchronous KV/checkpoint operations.\n *\n * Maps to gRPC DEADLINE_EXCEEDED status code.\n */\nexport class TimeoutError extends AetherError {\n /** The operation that timed out. */\n readonly operation: string;\n /** The timeout duration that was exceeded, in seconds. */\n readonly timeoutSeconds: number;\n\n constructor(operation = \"\", timeoutSeconds = 0, cause?: Error) {\n const details = timeoutSeconds > 0 ? `timeout=${timeoutSeconds.toFixed(2)}s` : \"\";\n super(\"Operation timed out\", \"DEADLINE_EXCEEDED\", details, cause);\n this.name = \"TimeoutError\";\n this.operation = operation;\n this.timeoutSeconds = timeoutSeconds;\n }\n}\n\n// =============================================================================\n// Request/Response Errors\n// =============================================================================\n\n/**\n * Indicates an invalid argument was provided to an operation.\n *\n * Maps to gRPC INVALID_ARGUMENT status code.\n */\nexport class InvalidArgumentError extends AetherError {\n /** The name of the invalid argument. */\n readonly argument: string;\n\n constructor(message = \"Invalid argument\", argument = \"\", cause?: Error) {\n super(message, \"INVALID_ARGUMENT\", \"\", cause);\n this.name = \"InvalidArgumentError\";\n this.argument = argument;\n }\n}\n\n/**\n * Indicates a requested resource was not found.\n *\n * Maps to gRPC NOT_FOUND status code.\n */\nexport class NotFoundError extends AetherError {\n /** The resource that was not found. */\n readonly resource: string;\n\n constructor(resource = \"\", cause?: Error) {\n const message = resource ? `${resource} not found` : \"Resource not found\";\n super(message, \"NOT_FOUND\", \"\", cause);\n this.name = \"NotFoundError\";\n this.resource = resource;\n }\n}\n\n/**\n * Indicates an operation is not implemented by the server.\n *\n * Maps to gRPC UNIMPLEMENTED status code.\n */\nexport class UnimplementedError extends AetherError {\n /** The unimplemented operation name. */\n readonly operation: string;\n\n constructor(operation = \"\", cause?: Error) {\n const message = operation ? `Operation '${operation}' not implemented` : \"Operation not implemented\";\n super(message, \"UNIMPLEMENTED\", \"\", cause);\n this.name = \"UnimplementedError\";\n this.operation = operation;\n }\n}\n\n// =============================================================================\n// Message and Protocol Errors\n// =============================================================================\n\n/**\n * Indicates an error with message handling.\n *\n * This includes serialization errors, invalid message formats,\n * or protocol violations.\n */\nexport class MessageError extends AetherError {\n constructor(message = \"Message error\", cause?: Error) {\n super(message, \"\", \"\", cause);\n this.name = \"MessageError\";\n }\n}\n\n/**\n * Indicates a KV store operation failed.\n */\nexport class KVOperationError extends AetherError {\n /** The KV operation that failed. */\n readonly operation: string;\n /** The key involved in the failed operation. */\n readonly key: string;\n\n constructor(operation = \"\", key = \"\", cause?: Error) {\n let message = \"KV operation failed\";\n if (operation) message = `KV ${operation} operation failed`;\n if (key) message = `${message} for key '${key}'`;\n super(message, \"\", \"\", cause);\n this.name = \"KVOperationError\";\n this.operation = operation;\n this.key = key;\n }\n}\n\n/**\n * Indicates a checkpoint operation failed.\n */\nexport class CheckpointError extends AetherError {\n /** The checkpoint operation that failed. */\n readonly operation: string;\n /** The checkpoint key involved. */\n readonly key: string;\n\n constructor(operation = \"\", key = \"\", cause?: Error) {\n let message = \"Checkpoint operation failed\";\n if (operation) message = `Checkpoint ${operation} operation failed`;\n if (key) message = `${message} for key '${key}'`;\n super(message, \"\", \"\", cause);\n this.name = \"CheckpointError\";\n this.operation = operation;\n this.key = key;\n }\n}\n\n// =============================================================================\n// Error Classification\n// =============================================================================\n\n/**\n * Checks if an error is recoverable (should trigger reconnection).\n *\n * Non-recoverable errors include authentication failures, permission denials,\n * and other terminal error conditions.\n *\n * @param error - The error to check\n * @returns true if the error is recoverable, false otherwise\n */\nexport function isRecoverable(error: Error): boolean {\n if (\n error instanceof AuthenticationError ||\n error instanceof PermissionDeniedError ||\n error instanceof DuplicateIdentityError ||\n error instanceof InvalidArgumentError ||\n error instanceof NotFoundError ||\n error instanceof UnimplementedError\n ) {\n return false;\n }\n return true;\n}\n\n/**\n * Checks if an error is a connection-related error.\n *\n * @param error - The error to check\n * @returns true if the error is connection-related\n */\nexport function isConnectionError(error: Error): boolean {\n return (\n error instanceof ConnectionError ||\n error instanceof ConnectionClosedError ||\n error instanceof ReconnectionError\n );\n}\n\n/**\n * Checks if an error is a timeout-related error.\n *\n * @param error - The error to check\n * @returns true if the error is timeout-related\n */\nexport function isTimeoutError(error: Error): boolean {\n return error instanceof TimeoutError;\n}\n","/**\n * KV (key-value) store operations for the Aether TypeScript SDK.\n *\n * This module provides the KVClient class for interacting with the\n * hierarchical KV store through the Aether gateway connection.\n *\n * KV operations support four scopes:\n * - Global: Accessible to all entities across all workspaces\n * - Workspace: Accessible within a specific workspace\n * - User: Accessible to a specific user across all workspaces\n * - UserWorkspace: Accessible to a specific user within a specific workspace\n *\n * @module kv\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport type { KVGetOptions, KVPutOptions, KVDeleteOptions, KVListOptions, KVIncrementOptions, KVDecrementOptions, KVIncrementIfOptions, KVDecrementIfOptions, KVResponse } from \"./types.js\";\nimport { KVScope } from \"./types.js\";\nimport { TimeoutError } from \"./errors.js\";\n\n/** Default timeout for synchronous KV operations (5 seconds). */\nconst DEFAULT_KV_TIMEOUT = 5000;\n\n/**\n * KVClient provides KV store operations over an Aether connection.\n *\n * Access this through `client.kv()` rather than constructing directly.\n *\n * Supports both async (fire-and-forget with callback) and sync (Promise-based)\n * operation modes.\n *\n * @example\n * ```typescript\n * const kv = client.kv();\n *\n * // Async put (fire-and-forget)\n * kv.put({ key: \"my-key\", value: encode(\"my-value\"), scope: KVScope.Global });\n *\n * // Sync get (returns a Promise)\n * const response = await kv.getSync({ key: \"my-key\", scope: KVScope.Global });\n * if (response.success) {\n * console.log(\"Value:\", response.value);\n * }\n * ```\n */\nexport class KVClient {\n private _client: AetherClient;\n\n /** @internal */\n constructor(client: AetherClient) {\n this._client = client;\n }\n\n // ===========================================================================\n // Async Operations (fire-and-forget, responses via onKVResponse callback)\n // ===========================================================================\n\n /**\n * Retrieves a value from the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link getSync}.\n *\n * @param opts - Get operation options\n */\n get(opts: KVGetOptions): void {\n this._client.sendKVOperation({\n op: \"GET\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Stores a value in the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link putSync}.\n *\n * @param opts - Put operation options\n */\n put(opts: KVPutOptions): void {\n this._client.sendKVOperation({\n op: \"PUT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n value: opts.value,\n userId: opts.userId,\n workspace: opts.workspace,\n ttl: opts.ttl,\n });\n }\n\n /**\n * Removes a key from the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link deleteSync}.\n *\n * @param opts - Delete operation options\n */\n delete(opts: KVDeleteOptions): void {\n this._client.sendKVOperation({\n op: \"DELETE\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Lists keys from the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link listSync}.\n *\n * @param opts - List operation options\n */\n list(opts?: KVListOptions): void {\n this._client.sendKVOperation({\n op: \"LIST\",\n scope: opts?.scope ?? KVScope.Global,\n key: opts?.keyPrefix,\n userId: opts?.userId,\n workspace: opts?.workspace,\n });\n }\n\n // ===========================================================================\n // Synchronous Operations (Promise-based with timeout)\n // ===========================================================================\n\n /**\n * Retrieves a value from the KV store and waits for the response.\n *\n * @param opts - Get operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async getSync(opts: KVGetOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"GET\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Stores a value in the KV store and waits for the response.\n *\n * @param opts - Put operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async putSync(opts: KVPutOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"PUT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n value: opts.value,\n userId: opts.userId,\n workspace: opts.workspace,\n ttl: opts.ttl,\n requestId,\n });\n });\n }\n\n /**\n * Removes a key from the KV store and waits for the response.\n *\n * @param opts - Delete operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async deleteSync(opts: KVDeleteOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"DELETE\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Lists keys from the KV store and waits for the response.\n *\n * @param opts - List operation options (includes optional timeout)\n * @returns Promise resolving to the KV response\n * @throws {@link TimeoutError} if the operation times out\n */\n async listSync(opts?: KVListOptions): Promise<KVResponse> {\n const timeout = opts?.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"LIST\",\n scope: opts?.scope ?? KVScope.Global,\n key: opts?.keyPrefix,\n userId: opts?.userId,\n workspace: opts?.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Increments a counter in the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link incrementSync}.\n *\n * @param opts - Increment operation options\n */\n increment(opts: KVIncrementOptions): void {\n this._client.sendKVOperation({\n op: \"INCREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Decrements a counter in the KV store (async).\n *\n * The response is delivered via the onKVResponse handler callback.\n * For synchronous operation, use {@link decrementSync}.\n *\n * @param opts - Decrement operation options\n */\n decrement(opts: KVDecrementOptions): void {\n this._client.sendKVOperation({\n op: \"DECREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n });\n }\n\n /**\n * Increments a counter in the KV store and waits for the response.\n *\n * @param opts - Increment operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with counterValue set\n * @throws {@link TimeoutError} if the operation times out\n */\n async incrementSync(opts: KVIncrementOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"INCREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Decrements a counter in the KV store and waits for the response.\n *\n * @param opts - Decrement operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with counterValue set\n * @throws {@link TimeoutError} if the operation times out\n */\n async decrementSync(opts: KVDecrementOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"DECREMENT\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n requestId,\n });\n });\n }\n\n /**\n * Increments a counter only if it is strictly below `ceiling` (async).\n *\n * The response (with `applied` and `counterValue`) is delivered via the onKVResponse callback.\n * For synchronous operation, use {@link incrementIfSync}.\n *\n * @param opts - IncrementIf operation options\n */\n incrementIf(opts: KVIncrementIfOptions): void {\n this._client.sendKVOperation({\n op: \"INCREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.ceiling),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n });\n }\n\n /**\n * Decrements a counter only if it is strictly above `floor` (async).\n *\n * The response (with `applied` and `counterValue`) is delivered via the onKVResponse callback.\n * For synchronous operation, use {@link decrementIfSync}.\n *\n * @param opts - DecrementIf operation options\n */\n decrementIf(opts: KVDecrementIfOptions): void {\n this._client.sendKVOperation({\n op: \"DECREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.floor),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n });\n }\n\n /**\n * Increments a counter only if it is strictly below `ceiling`, and waits for the response.\n *\n * @param opts - IncrementIf operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with `counterValue` and `applied` set\n * @throws {@link TimeoutError} if the operation times out\n */\n async incrementIfSync(opts: KVIncrementIfOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"INCREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.ceiling),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n requestId,\n });\n });\n }\n\n /**\n * Decrements a counter only if it is strictly above `floor`, and waits for the response.\n *\n * @param opts - DecrementIf operation options (includes optional timeout)\n * @returns Promise resolving to the KV response with `counterValue` and `applied` set\n * @throws {@link TimeoutError} if the operation times out\n */\n async decrementIfSync(opts: KVDecrementIfOptions): Promise<KVResponse> {\n const timeout = opts.timeout ?? DEFAULT_KV_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendKVOperation({\n op: \"DECREMENT_IF\",\n scope: opts.scope ?? KVScope.Global,\n key: opts.key,\n userId: opts.userId,\n workspace: opts.workspace,\n guardValue: BigInt(opts.floor),\n deltaValue: opts.delta != null ? BigInt(opts.delta) : undefined,\n requestId,\n });\n });\n }\n\n // ===========================================================================\n // Convenience Methods\n // ===========================================================================\n\n /**\n * Retrieves a value from the global scope (async).\n *\n * @param key - The key to retrieve\n */\n getGlobal(key: string): void {\n this.get({ key, scope: KVScope.Global });\n }\n\n /**\n * Stores a value in the global scope (async).\n *\n * @param key - The key to store\n * @param value - The value to store\n */\n putGlobal(key: string, value: Uint8Array): void {\n this.put({ key, value, scope: KVScope.Global });\n }\n\n /**\n * Removes a key from the global scope (async).\n *\n * @param key - The key to delete\n */\n deleteGlobal(key: string): void {\n this.delete({ key, scope: KVScope.Global });\n }\n\n /**\n * Lists keys from the global scope (async).\n *\n * @param keyPrefix - Prefix to filter keys (empty for all)\n */\n listGlobal(keyPrefix = \"\"): void {\n this.list({ keyPrefix, scope: KVScope.Global });\n }\n\n // ===========================================================================\n // Private Helpers\n // ===========================================================================\n\n /**\n * Waits for a correlated KV response with timeout.\n * @internal\n */\n private _waitForResponse(\n requestId: string,\n timeout: number,\n sendFn: () => void,\n ): Promise<KVResponse> {\n return new Promise<KVResponse>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._client.removePendingRequest(requestId);\n reject(new TimeoutError(\"KV operation timed out\", timeout / 1000));\n }, timeout);\n\n this._client.registerPendingKVRequest(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n sendFn();\n });\n }\n}\n","/**\n * Checkpoint operations for the Aether TypeScript SDK.\n *\n * Checkpoints allow agents/tasks to persist arbitrary state that survives\n * restarts. This is separate from message offset tracking (handled\n * automatically by RabbitMQ Streams).\n *\n * @module checkpoint\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport type { CheckpointResponse } from \"./types.js\";\nimport { TimeoutError } from \"./errors.js\";\n\n/** Default timeout for synchronous checkpoint operations (5 seconds). */\nconst DEFAULT_CHECKPOINT_TIMEOUT = 5000;\n\n/**\n * Options for a checkpoint save operation.\n */\nexport interface CheckpointSaveOptions {\n /** The checkpoint data to save. */\n data: Uint8Array;\n /** Checkpoint key. Allows multiple named checkpoints per identity. Default: \"default\". */\n key?: string;\n /** TTL in seconds (-1 = server default, 0 = no expiration). */\n ttl?: number;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Options for a checkpoint load operation.\n */\nexport interface CheckpointLoadOptions {\n /** Checkpoint key to load. Default: \"default\". */\n key?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Options for a checkpoint delete operation.\n */\nexport interface CheckpointDeleteOptions {\n /** Checkpoint key to delete. Default: \"default\". */\n key?: string;\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * Options for a checkpoint list operation.\n */\nexport interface CheckpointListOptions {\n /** Timeout in milliseconds for sync operations. */\n timeout?: number;\n}\n\n/**\n * CheckpointClient provides checkpoint operations over an Aether connection.\n *\n * Access this through `client.checkpoint()` rather than constructing directly.\n *\n * Supports both async (fire-and-forget with callback) and sync (Promise-based)\n * operation modes.\n *\n * @example\n * ```typescript\n * const cp = client.checkpoint();\n *\n * // Save state\n * const encoder = new TextEncoder();\n * await cp.saveSync({ data: encoder.encode(JSON.stringify(myState)) });\n *\n * // Load state\n * const response = await cp.loadSync({});\n * if (response.success && response.data.length > 0) {\n * const state = JSON.parse(new TextDecoder().decode(response.data));\n * }\n *\n * // List checkpoints\n * const listResponse = await cp.listSync({});\n * console.log(\"Checkpoint keys:\", listResponse.keys);\n * ```\n */\nexport class CheckpointClient {\n private _client: AetherClient;\n\n /** @internal */\n constructor(client: AetherClient) {\n this._client = client;\n }\n\n // ===========================================================================\n // Async Operations (fire-and-forget, responses via onCheckpointResponse)\n // ===========================================================================\n\n /**\n * Saves checkpoint data (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n save(opts: CheckpointSaveOptions): void {\n this._client.sendCheckpointOperation({\n op: \"SAVE\",\n key: opts.key ?? \"\",\n data: opts.data,\n ttl: opts.ttl ?? -1,\n });\n }\n\n /**\n * Loads checkpoint data (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n load(opts?: CheckpointLoadOptions): void {\n this._client.sendCheckpointOperation({\n op: \"LOAD\",\n key: opts?.key ?? \"\",\n });\n }\n\n /**\n * Deletes a checkpoint (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n delete(opts?: CheckpointDeleteOptions): void {\n this._client.sendCheckpointOperation({\n op: \"DELETE\",\n key: opts?.key ?? \"\",\n });\n }\n\n /**\n * Lists checkpoint keys (async).\n * The response is delivered via the onCheckpointResponse handler.\n */\n list(): void {\n this._client.sendCheckpointOperation({\n op: \"LIST\",\n });\n }\n\n // ===========================================================================\n // Synchronous Operations (Promise-based with timeout)\n // ===========================================================================\n\n /**\n * Saves checkpoint data and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async saveSync(opts: CheckpointSaveOptions): Promise<CheckpointResponse> {\n const timeout = opts.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"SAVE\",\n key: opts.key ?? \"\",\n data: opts.data,\n ttl: opts.ttl ?? -1,\n requestId,\n });\n });\n }\n\n /**\n * Loads checkpoint data and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async loadSync(opts?: CheckpointLoadOptions): Promise<CheckpointResponse> {\n const timeout = opts?.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"LOAD\",\n key: opts?.key ?? \"\",\n requestId,\n });\n });\n }\n\n /**\n * Deletes a checkpoint and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async deleteSync(opts?: CheckpointDeleteOptions): Promise<CheckpointResponse> {\n const timeout = opts?.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"DELETE\",\n key: opts?.key ?? \"\",\n requestId,\n });\n });\n }\n\n /**\n * Lists checkpoint keys and waits for the response.\n *\n * @throws {@link TimeoutError} if the operation times out\n */\n async listSync(opts?: CheckpointListOptions): Promise<CheckpointResponse> {\n const timeout = opts?.timeout ?? DEFAULT_CHECKPOINT_TIMEOUT;\n const requestId = this._client.nextRequestId();\n\n return this._waitForResponse(requestId, timeout, () => {\n this._client.sendCheckpointOperation({\n op: \"LIST\",\n requestId,\n });\n });\n }\n\n // ===========================================================================\n // Private Helpers\n // ===========================================================================\n\n private _waitForResponse(\n requestId: string,\n timeout: number,\n sendFn: () => void,\n ): Promise<CheckpointResponse> {\n return new Promise<CheckpointResponse>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._client.removePendingRequest(requestId);\n reject(new TimeoutError(\"Checkpoint operation timed out\", timeout / 1000));\n }, timeout);\n\n this._client.registerPendingCheckpointRequest(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n sendFn();\n });\n }\n}\n","/**\n * Tunnel (tunnelDial) support for the Aether TypeScript SDK.\n *\n * Provides `tunnelDial()` on AetherClient for opening a bidirectional byte-stream\n * tunnel through the Aether gRPC connection to a remote service.\n *\n * Uses the Web Streams API (ReadableStream / WritableStream) so callers work\n * in both Node ≥18 and browser environments.\n *\n * @module tunnel\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport { ConnectionError } from \"./errors.js\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst TUNNEL_CHUNK_SIZE = 256 * 1024; // 256 KiB per TunnelData frame\nconst INBOUND_ACK_THRESHOLD = 256 * 1024; // send TunnelAck after consuming this many bytes\nconst DEFAULT_INITIAL_CREDITS = 16;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Wire protocol for the tunnel. */\nexport type TunnelProtocol = \"tcp\" | \"udp\" | \"ws\" | \"websocket\";\n\n/** Options for tunnelDial(). */\nexport interface TunnelDialOptions {\n /** Hint passed to the remote sidecar (e.g. \"host:port\"). */\n remoteHint?: string;\n /** Idle timeout in ms (server-side enforcement). */\n idleTimeoutMs?: number;\n /** Byte quota (server-side enforcement). */\n maxBytes?: number;\n /** Arbitrary metadata forwarded in TunnelOpen (e.g. WS sub-protocols). */\n metadata?: Record<string, string>;\n /** Reserved for v2 reconnect/resume; ignored in v1. */\n sessionToken?: string;\n /** Initial outbound credit window (default: 16). */\n initialCredits?: number;\n /**\n * Pin the tunnel to a named terminator backend. The backend's allow-list\n * still applies — explicit naming selects which backend's ACL is consulted,\n * not whether the tunnel is allowed.\n */\n backend?: string;\n}\n\n/** Reason string from a remote TunnelClose frame. */\nexport type TunnelCloseReason = \"NORMAL\" | \"PEER_RESET\" | \"IDLE_TIMEOUT\" | \"QUOTA\" | \"ERROR\" | string;\n\n/** Error thrown when the remote side sends a TunnelClose frame. */\nexport class TunnelClosedError extends Error {\n readonly reason: TunnelCloseReason;\n readonly detail: string;\n constructor(reason: TunnelCloseReason, detail: string) {\n super(`Aether tunnel closed: ${reason}: ${detail}`);\n this.name = \"TunnelClosedError\";\n this.reason = reason;\n this.detail = detail;\n }\n}\n\n/**\n * Duplex tunnel object returned by tunnelDial().\n *\n * - `readable`: incoming bytes from the remote end.\n * - `writable`: outgoing bytes to the remote end.\n * - `close()`: send a NORMAL TunnelClose and clean up.\n */\nexport interface TunnelStream {\n /** Readable stream of inbound Uint8Array chunks from the remote end. */\n readonly readable: ReadableStream<Uint8Array>;\n /** Writable stream; write Uint8Array chunks to send to the remote end. */\n readonly writable: WritableStream<Uint8Array>;\n /** Sends TunnelClose{NORMAL} and tears down both streams. */\n close(): void;\n /** Resolves when the tunnel is fully closed (either side). */\n readonly closed: Promise<void>;\n}\n\n// =============================================================================\n// Internal per-tunnel state (registered in _pendingTunnels on the client)\n// =============================================================================\n\n/** @internal */\nexport interface TunnelInflight {\n /** Push inbound data (from downstream TunnelData) into the readable side. */\n pushData(data: Uint8Array, fin: boolean): void;\n /** Replenish outbound credits (from downstream TunnelAck). */\n addCredits(n: number): void;\n /** Signal that the remote closed the tunnel. */\n closeWithError(err: TunnelClosedError): void;\n}\n\n// =============================================================================\n// tunnelDial — main entry point\n// =============================================================================\n\n/**\n * Opens a byte-stream tunnel through the Aether connection.\n *\n * @param client - Connected AetherClient instance.\n * @param target - Target topic (e.g. \"sv::proxy::default\").\n * @param protocol - Wire protocol: \"tcp\", \"udp\", \"ws\", or \"websocket\".\n * @param options - Optional dial parameters.\n * @returns A TunnelStream with readable/writable Web Streams and a close() method.\n * @throws {@link ConnectionError} if not connected.\n */\nexport function tunnelDial(\n client: AetherClient,\n target: string,\n protocol: TunnelProtocol,\n options: TunnelDialOptions = {},\n): TunnelStream {\n if (!(client as unknown as { _connected: boolean })._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n if (!target) {\n throw new ConnectionError(\"tunnelDial: target topic is required\");\n }\n\n const tunnelId = (client as unknown as { nextRequestId(): string }).nextRequestId();\n const initialCredits = options.initialCredits ?? DEFAULT_INITIAL_CREDITS;\n\n // ---- outbound credit tracking ----\n let outCredits = initialCredits;\n // Waiters blocked on credits: each entry is a resolve fn for one credit slot.\n const creditWaiters: Array<() => void> = [];\n\n function consumeCredit(): Promise<void> {\n if (outCredits > 0) {\n outCredits--;\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => { creditWaiters.push(resolve); });\n }\n\n function addCredits(n: number): void {\n outCredits += n;\n // Wake blocked writers one credit at a time.\n while (outCredits > 0 && creditWaiters.length > 0) {\n outCredits--;\n const waiter = creditWaiters.shift()!;\n waiter();\n }\n }\n\n // ---- inbound flow control ----\n let inboundBytesConsumed = 0;\n\n // ---- closed state ----\n let closed = false;\n let closedError: TunnelClosedError | undefined;\n let closedResolve!: () => void;\n const closedPromise = new Promise<void>((resolve) => { closedResolve = resolve; });\n\n // ---- ReadableStream for inbound bytes ----\n let readableController!: ReadableStreamDefaultController<Uint8Array>;\n const readable = new ReadableStream<Uint8Array>({\n start(controller) {\n readableController = controller;\n },\n cancel() {\n doClose(\"NORMAL\");\n },\n });\n\n // ---- WritableStream for outbound bytes ----\n const writable = new WritableStream<Uint8Array>({\n async write(chunk) {\n if (closed) {\n throw closedError ?? new TunnelClosedError(\"NORMAL\", \"tunnel closed\");\n }\n let offset = 0;\n while (offset < chunk.length) {\n await consumeCredit();\n if (closed) {\n throw closedError ?? new TunnelClosedError(\"NORMAL\", \"tunnel closed\");\n }\n const end = Math.min(offset + TUNNEL_CHUNK_SIZE, chunk.length);\n const slice = chunk.slice(offset, end);\n offset = end;\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelData: {\n tunnelId,\n data: slice,\n fin: false,\n },\n });\n }\n },\n close() {\n // WritableStream closed by caller — send FIN frame then tear down.\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelData: {\n tunnelId,\n data: new Uint8Array(0),\n fin: true,\n },\n });\n doClose(\"NORMAL\");\n },\n abort(_reason) {\n doClose(\"NORMAL\");\n },\n });\n\n // ---- inflight registration ----\n const inflight: TunnelInflight = {\n pushData(data: Uint8Array, fin: boolean) {\n if (closed) return;\n if (data.length > 0) {\n readableController.enqueue(data);\n // Track consumed bytes and send TunnelAck when threshold crossed.\n inboundBytesConsumed += data.length;\n if (inboundBytesConsumed >= INBOUND_ACK_THRESHOLD) {\n const credits = Math.floor(inboundBytesConsumed / INBOUND_ACK_THRESHOLD) * 16;\n inboundBytesConsumed = inboundBytesConsumed % INBOUND_ACK_THRESHOLD;\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelAck: {\n tunnelId,\n credits,\n },\n });\n }\n }\n if (fin) {\n readableController.close();\n doClose(\"NORMAL\");\n }\n },\n addCredits,\n closeWithError(err: TunnelClosedError) {\n if (closed) return;\n closedError = err;\n try { readableController.error(err); } catch { /* already closed */ }\n // Wake all pending writers with an error.\n closed = true;\n while (creditWaiters.length > 0) {\n const waiter = creditWaiters.shift()!;\n waiter(); // they will see `closed === true` and throw\n }\n const pendingMap = (client as unknown as { _pendingTunnels: Map<string, TunnelInflight> })._pendingTunnels;\n pendingMap.delete(tunnelId);\n closedResolve();\n },\n };\n\n const pendingMap = (client as unknown as { _pendingTunnels: Map<string, TunnelInflight> })._pendingTunnels;\n pendingMap.set(tunnelId, inflight);\n\n // ---- send TunnelOpen ----\n const openMsg: Record<string, unknown> = {\n tunnelId,\n targetTopic: target,\n protocol: (protocol === \"ws\" || protocol === \"websocket\") ? \"WEBSOCKET\" : protocol.toUpperCase(),\n remoteHint: options.remoteHint ?? \"\",\n metadata: options.metadata ?? {},\n sessionToken: options.sessionToken ?? \"\",\n backendName: options.backend ?? \"\",\n };\n if (options.idleTimeoutMs != null) {\n openMsg[\"idleTimeoutMs\"] = options.idleTimeoutMs;\n }\n if (options.maxBytes != null) {\n openMsg[\"maxBytes\"] = options.maxBytes;\n }\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelOpen: openMsg,\n });\n\n // ---- close helper ----\n function doClose(_reason: TunnelCloseReason): void {\n if (closed) return;\n closed = true;\n // Wake any blocked writers.\n while (creditWaiters.length > 0) {\n const waiter = creditWaiters.shift()!;\n waiter();\n }\n pendingMap.delete(tunnelId);\n closedResolve();\n }\n\n return {\n readable,\n writable,\n closed: closedPromise,\n close() {\n if (closed) return;\n (client as unknown as { _sendUpstream(msg: Record<string, unknown>): void })._sendUpstream({\n tunnelClose: {\n tunnelId,\n reason: \"NORMAL\",\n detail: \"\",\n },\n });\n doClose(\"NORMAL\");\n },\n };\n}\n","/**\n * Authority grant cache for the Aether TypeScript client.\n *\n * Mirrors the Python `AuthorityGrantCache` (see\n * `sdk/python-client/scitrera_aether_client/authority_cache.py`):\n *\n * - Caches grants per `(sourceSessionId, audienceType, audienceId)`.\n * - Soft-renews at `expiresAt - softRenewSkewMs` (configurable).\n * - Honors server `cacheHintTtlSeconds` from `AuthorityGrantResponse` as\n * an upper bound on the cached lifetime.\n * - Listens for `AuthorityGrantRevocation` push events and invalidates\n * matching entries by `grantId` OR `rootGrantId` (cascade).\n * - `deriveForTask(...)` uses the idempotent `DERIVE_FOR_TARGET` op so\n * repeated calls return the same grant rather than minting new ones.\n *\n * Concurrency: per-key in-flight Promise dedupe collapses concurrent\n * `getOrExchange` / `deriveForTask` calls so only one network round-trip\n * happens per cache key at a time.\n *\n * @module authority-cache\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport type { AuthorityGrantInfo, AuthorityGrantResponse, AuthorityGrantRevocation } from \"./types.js\";\n\n/**\n * Configuration for {@link AuthorityGrantCache}.\n */\nexport interface AuthorityGrantCacheOptions {\n /**\n * Soft-renew skew, in milliseconds. Re-exchange a grant this long\n * before its server-side `expiresAt`. Default: 30000 (30 s) to match\n * the connection-lock heartbeat cadence.\n */\n softRenewSkewMs?: number;\n\n /**\n * Default per-op timeout (ms) passed through to the underlying client\n * when the cache issues exchange / derive / revoke calls. Default:\n * 10000.\n */\n opTimeoutMs?: number;\n\n /**\n * Wall-clock provider, returning unix-ms. Pluggable for tests.\n * Default: `Date.now`.\n */\n clock?: () => number;\n\n /**\n * When true the cache treats `AuthorityGrantInfo.expiresAt` as\n * unix-MILLISECONDS rather than unix-seconds. The proto comment on\n * `AuthorityGrantInfo` says \"Unix seconds\" but the runtime\n * `ACLAuthorityGrantInfo` uses milliseconds in practice — pick the\n * unit your gateway emits. Default: `false` (seconds).\n */\n expiresAtInMillis?: boolean;\n}\n\n/** Subset of {@link AetherClient} the cache depends on. */\nexport interface AuthorityCacheClient {\n exchangeAuthorityGrant(opts: Record<string, unknown>): Promise<AuthorityGrantResponse>;\n deriveAuthorityGrantForTarget(opts: Record<string, unknown>): Promise<AuthorityGrantResponse>;\n revokeAuthorityGrant(grantId: string, timeout?: number): Promise<AuthorityGrantResponse>;\n _removeAuthorityCache?(cache: AuthorityGrantCache): void;\n}\n\n/** Composite cache key. */\ntype CacheKey = string;\n\ninterface CacheEntry {\n grant: AuthorityGrantInfo;\n /** Absolute deadline (unix-ms) at which this entry is considered stale. */\n effectiveDeadlineMs: number;\n /** Absolute server-side expires_at, in proto units (see {@link AuthorityGrantCacheOptions.expiresAtInMillis}). */\n rawExpiresAt: number;\n cacheHintTtlS: number;\n fetchedAtMs: number;\n}\n\n/**\n * Per-actor cache of runtime authority grants. See module docstring for\n * the behavioural contract.\n */\nexport class AuthorityGrantCache {\n private readonly _client: AuthorityCacheClient;\n private readonly _softRenewSkewMs: number;\n private readonly _opTimeoutMs: number;\n private readonly _clock: () => number;\n private readonly _expiresAtInMillis: boolean;\n\n private readonly _entries = new Map<CacheKey, CacheEntry>();\n /** grantId -> set of cache keys, for fast revocation lookup. */\n private readonly _grantIdIndex = new Map<string, Set<CacheKey>>();\n /** rootGrantId -> set of cache keys, for cascade invalidation. */\n private readonly _rootGrantIdIndex = new Map<string, Set<CacheKey>>();\n /** In-flight per-key fetch promises, for single-flight de-dupe. */\n private readonly _inflight = new Map<CacheKey, Promise<AuthorityGrantInfo | null>>();\n\n private _closed = false;\n\n constructor(client: AuthorityCacheClient, opts: AuthorityGrantCacheOptions = {}) {\n if (opts.softRenewSkewMs !== undefined && opts.softRenewSkewMs < 0) {\n throw new Error(\"softRenewSkewMs must be non-negative\");\n }\n this._client = client;\n this._softRenewSkewMs = opts.softRenewSkewMs ?? 30_000;\n this._opTimeoutMs = opts.opTimeoutMs ?? 10_000;\n this._clock = opts.clock ?? (() => Date.now());\n this._expiresAtInMillis = opts.expiresAtInMillis ?? false;\n }\n\n // ===========================================================================\n // Public API\n // ===========================================================================\n\n /**\n * Return a cached grant for the (sourceSessionId, audienceType,\n * audienceId) triplet, or exchange a fresh one. Callers MUST keep the\n * rest of the request shape stable for a given key.\n *\n * Returns `null` when the gateway response is missing, has\n * `success === false`, or carries no grant — callers should fall back\n * to direct invocation or surface the error.\n */\n async getOrExchange(opts: {\n sourceSessionId: string;\n audienceType?: string;\n audienceId?: string;\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n }): Promise<AuthorityGrantInfo | null> {\n const audienceType = opts.audienceType ?? \"\";\n const audienceId = opts.audienceId ?? \"\";\n const key = makeKey(opts.sourceSessionId, audienceType, audienceId);\n\n const cached = this._getUnexpired(key);\n if (cached !== null) {\n return cached;\n }\n\n return this._withInflight(key, async () => {\n const cachedAfterLock = this._getUnexpired(key);\n if (cachedAfterLock !== null) {\n return cachedAfterLock;\n }\n const response = await this._client.exchangeAuthorityGrant({\n sourceSessionId: opts.sourceSessionId,\n audienceType,\n audienceId,\n workspaceScope: opts.workspaceScope,\n resourceScope: opts.resourceScope,\n operationScope: opts.operationScope,\n maxAccessLevel: opts.maxAccessLevel,\n validWhileAudienceActive: opts.validWhileAudienceActive,\n expiresAt: opts.expiresAt,\n renewableUntil: opts.renewableUntil,\n mayDelegate: opts.mayDelegate,\n remainingHops: opts.remainingHops,\n reason: opts.reason,\n metadata: opts.metadata,\n timeout: opts.timeout ?? this._opTimeoutMs,\n });\n const grant = extractGrant(response);\n if (!grant) {\n return null;\n }\n this._store(key, grant, response);\n return grant;\n });\n }\n\n /**\n * Idempotent derive for a target task: returns an existing visible\n * grant matching (parentGrantId, taskId, audience) when one is in\n * place, otherwise mints a new one via `DERIVE_FOR_TARGET`. Safe to\n * call repeatedly without leaking grants.\n */\n async deriveForTask(opts: {\n parentGrantId: string;\n taskId: string;\n audienceType?: string;\n audienceId?: string;\n operationScope?: string[];\n maxAccessLevel?: number;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n timeout?: number;\n }): Promise<AuthorityGrantInfo | null> {\n return this.deriveForTarget({\n parentGrantId: opts.parentGrantId,\n targetType: \"task\",\n targetId: opts.taskId,\n audienceType: opts.audienceType,\n audienceId: opts.audienceId,\n operationScope: opts.operationScope,\n maxAccessLevel: opts.maxAccessLevel,\n expiresAt: opts.expiresAt,\n renewableUntil: opts.renewableUntil,\n mayDelegate: opts.mayDelegate,\n remainingHops: opts.remainingHops,\n reason: opts.reason,\n timeout: opts.timeout,\n });\n }\n\n /** General form of {@link deriveForTask} for arbitrary target principals. */\n async deriveForTarget(opts: {\n parentGrantId: string;\n targetType: string;\n targetId: string;\n audienceType?: string;\n audienceId?: string;\n operationScope?: string[];\n maxAccessLevel?: number;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n timeout?: number;\n }): Promise<AuthorityGrantInfo | null> {\n const audienceType = opts.audienceType ?? \"\";\n const audienceId = opts.audienceId ?? \"\";\n const key = makeKey(\n `derive::${opts.parentGrantId}::${opts.targetType}::${opts.targetId}`,\n audienceType,\n audienceId,\n );\n\n const cached = this._getUnexpired(key);\n if (cached !== null) {\n return cached;\n }\n\n return this._withInflight(key, async () => {\n const cachedAfterLock = this._getUnexpired(key);\n if (cachedAfterLock !== null) {\n return cachedAfterLock;\n }\n const response = await this._client.deriveAuthorityGrantForTarget({\n parentGrantId: opts.parentGrantId,\n targetType: opts.targetType,\n targetId: opts.targetId,\n audienceType,\n audienceId,\n operationScope: opts.operationScope,\n maxAccessLevel: opts.maxAccessLevel,\n expiresAt: opts.expiresAt,\n renewableUntil: opts.renewableUntil,\n mayDelegate: opts.mayDelegate,\n remainingHops: opts.remainingHops,\n reason: opts.reason,\n timeout: opts.timeout ?? this._opTimeoutMs,\n });\n const grant = extractGrant(response);\n if (!grant) {\n return null;\n }\n this._store(key, grant, response);\n return grant;\n });\n }\n\n /**\n * Drop every cache entry whose grant ID OR root grant ID matches.\n * Returns the number of entries dropped. Safe to call from any\n * context.\n */\n invalidate(grantIdOrRoot: string): number {\n let dropped = 0;\n for (const idx of [this._grantIdIndex, this._rootGrantIdIndex]) {\n const keys = idx.get(grantIdOrRoot);\n if (!keys) {\n continue;\n }\n // Snapshot the keys because _drop mutates the index.\n for (const key of [...keys]) {\n if (this._drop(key)) {\n dropped++;\n }\n }\n idx.delete(grantIdOrRoot);\n }\n return dropped;\n }\n\n /**\n * Best-effort revoke every cached grant on the gateway, then clear.\n * Per-grant errors are caught and logged via `console.warn`.\n */\n async revokeAll(): Promise<void> {\n const entries = [...this._entries.values()];\n this._entries.clear();\n this._grantIdIndex.clear();\n this._rootGrantIdIndex.clear();\n\n await Promise.all(\n entries.map(async (entry) => {\n const grantId = entry.grant.grantId;\n if (!grantId) {\n return;\n }\n try {\n await this._client.revokeAuthorityGrant(grantId, this._opTimeoutMs);\n } catch (err) {\n console.warn(`AuthorityGrantCache.revokeAll: revoke ${grantId} failed`, err);\n }\n }),\n );\n }\n\n /**\n * Invalidate cache entries matching a server-pushed revocation event.\n * Returns the number of entries dropped. Wired into the client\n * dispatch loop by {@link AetherClient.makeAuthorityCache}; tests may\n * also call this directly.\n */\n handleRevocationEvent(evt: AuthorityGrantRevocation): number {\n let dropped = 0;\n if (evt.grantId) {\n dropped += this.invalidate(evt.grantId);\n }\n if (evt.rootGrantId && evt.rootGrantId !== evt.grantId) {\n dropped += this.invalidate(evt.rootGrantId);\n }\n return dropped;\n }\n\n /** Cache stats for observability tests. */\n stats(): { size: number; grantIdsIndexed: number; rootGrantIdsIndexed: number } {\n return {\n size: this._entries.size,\n grantIdsIndexed: this._grantIdIndex.size,\n rootGrantIdsIndexed: this._rootGrantIdIndex.size,\n };\n }\n\n // ===========================================================================\n // High-level convenience helpers (Phase 4)\n // ===========================================================================\n\n /**\n * Report whether `grantId` is currently cached and fresh (not revoked,\n * not past its soft-renew deadline). Cache-only — never round-trips to\n * the gateway. Stale/revoked entries observed here are evicted as a\n * side-effect.\n */\n isValid(grantId: string): boolean {\n if (!grantId) {\n return false;\n }\n const keys = this._grantIdIndex.get(grantId);\n if (!keys || keys.size === 0) {\n return false;\n }\n // Snapshot — `_getUnexpired` mutates the index when it evicts.\n for (const key of [...keys]) {\n if (this._getUnexpired(key) !== null) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Return a snapshot of every cached grant that is currently fresh,\n * de-duplicated by `grantId`. Stale/revoked entries observed during\n * the snapshot are evicted as a side-effect.\n */\n listActive(): AuthorityGrantInfo[] {\n const out: AuthorityGrantInfo[] = [];\n const seen = new Set<string>();\n // Snapshot keys first so eviction during iteration is safe.\n for (const key of [...this._entries.keys()]) {\n const grant = this._getUnexpired(key);\n if (!grant || !grant.grantId || seen.has(grant.grantId)) {\n continue;\n }\n seen.add(grant.grantId);\n out.push(grant);\n }\n return out;\n }\n\n /**\n * Drop `grantId` from the cache without calling the gateway. Alias of\n * {@link invalidate} with a name that telegraphs the local-only\n * semantics; the matching server-side revoke is\n * {@link AetherClient.revokeAuthorityGrant}. Returns the number of\n * entries dropped.\n */\n revokeLocal(grantId: string): number {\n return this.invalidate(grantId);\n }\n\n /**\n * Force-drop a cached grant and re-exchange it.\n *\n * Returns `null` when the cache does not know `grantId`, the matching\n * entry was originally derived (those cannot be refreshed via\n * exchange — re-derive explicitly), or the underlying exchange fails.\n */\n async refresh(\n grantId: string,\n opts: {\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n } = {},\n ): Promise<AuthorityGrantInfo | null> {\n if (!grantId) {\n return null;\n }\n const keys = this._grantIdIndex.get(grantId);\n if (!keys || keys.size === 0) {\n return null;\n }\n // Pick the first key — all keys for a given grantId share the same\n // grant payload.\n const [firstKey] = keys;\n const [sourceSessionId, audienceType, audienceId] = firstKey.split(\"|||\");\n this.invalidate(grantId);\n if (sourceSessionId.startsWith(\"derive::\")) {\n return null;\n }\n return this.getOrExchange({\n sourceSessionId,\n audienceType,\n audienceId,\n ...opts,\n });\n }\n\n /**\n * Deregister this cache from its parent client so it stops receiving\n * AuthorityGrantRevocation events. Idempotent.\n */\n close(): void {\n if (this._closed) {\n return;\n }\n this._closed = true;\n this._entries.clear();\n this._grantIdIndex.clear();\n this._rootGrantIdIndex.clear();\n this._client._removeAuthorityCache?.(this);\n }\n\n // ===========================================================================\n // Internals\n // ===========================================================================\n\n private _getUnexpired(key: CacheKey): AuthorityGrantInfo | null {\n const entry = this._entries.get(key);\n if (!entry) {\n return null;\n }\n if (entry.grant.revoked) {\n this._drop(key);\n return null;\n }\n const now = this._clock();\n if (entry.effectiveDeadlineMs > 0 && now >= entry.effectiveDeadlineMs) {\n this._drop(key);\n return null;\n }\n return entry.grant;\n }\n\n private _store(\n key: CacheKey,\n grant: AuthorityGrantInfo,\n response: AuthorityGrantResponse,\n ): void {\n // Drop any prior entry under this key first.\n const prior = this._entries.get(key);\n if (prior) {\n this._unindex(key, prior.grant);\n }\n\n const fetchedAt = this._clock();\n const cacheHintTtlS = response.cacheHintTtlSeconds ?? 0;\n const rawExpiresAt = grant.expiresAt ?? 0;\n const deadlines: number[] = [];\n if (rawExpiresAt > 0) {\n const expiresAtMs = this._expiresAtInMillis ? rawExpiresAt : rawExpiresAt * 1000;\n deadlines.push(expiresAtMs - this._softRenewSkewMs);\n }\n if (cacheHintTtlS > 0) {\n deadlines.push(fetchedAt + cacheHintTtlS * 1000);\n }\n const effectiveDeadlineMs = deadlines.length === 0 ? 0 : Math.min(...deadlines);\n\n this._entries.set(key, {\n grant,\n effectiveDeadlineMs,\n rawExpiresAt,\n cacheHintTtlS,\n fetchedAtMs: fetchedAt,\n });\n this._index(key, grant);\n }\n\n private _drop(key: CacheKey): boolean {\n const entry = this._entries.get(key);\n if (!entry) {\n return false;\n }\n this._entries.delete(key);\n this._unindex(key, entry.grant);\n return true;\n }\n\n private _index(key: CacheKey, grant: AuthorityGrantInfo): void {\n if (grant.grantId) {\n let set = this._grantIdIndex.get(grant.grantId);\n if (!set) {\n set = new Set<CacheKey>();\n this._grantIdIndex.set(grant.grantId, set);\n }\n set.add(key);\n }\n if (grant.rootGrantId && grant.rootGrantId !== grant.grantId) {\n let set = this._rootGrantIdIndex.get(grant.rootGrantId);\n if (!set) {\n set = new Set<CacheKey>();\n this._rootGrantIdIndex.set(grant.rootGrantId, set);\n }\n set.add(key);\n }\n }\n\n private _unindex(key: CacheKey, grant: AuthorityGrantInfo): void {\n if (grant.grantId) {\n const set = this._grantIdIndex.get(grant.grantId);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n this._grantIdIndex.delete(grant.grantId);\n }\n }\n }\n if (grant.rootGrantId) {\n const set = this._rootGrantIdIndex.get(grant.rootGrantId);\n if (set) {\n set.delete(key);\n if (set.size === 0) {\n this._rootGrantIdIndex.delete(grant.rootGrantId);\n }\n }\n }\n }\n\n private _withInflight(\n key: CacheKey,\n fetcher: () => Promise<AuthorityGrantInfo | null>,\n ): Promise<AuthorityGrantInfo | null> {\n const existing = this._inflight.get(key);\n if (existing) {\n return existing;\n }\n const promise = fetcher().finally(() => {\n this._inflight.delete(key);\n });\n this._inflight.set(key, promise);\n return promise;\n }\n}\n\nfunction makeKey(sourceSessionId: string, audienceType: string, audienceId: string): CacheKey {\n // Triple-pipe is a delimiter that is illegal in any valid principal id /\n // audience identifier today. Mirror the Python tuple-key encoding.\n return `${sourceSessionId}|||${audienceType}|||${audienceId}`;\n}\n\nfunction extractGrant(response: AuthorityGrantResponse | undefined | null): AuthorityGrantInfo | null {\n if (!response || !response.success) {\n return null;\n }\n const grant = response.grant;\n if (!grant || !grant.grantId) {\n return null;\n }\n return grant;\n}\n","{\n \"name\": \"@scitrera/aether-client\",\n \"version\": \"0.2.1\",\n \"description\": \"TypeScript/JavaScript SDK for the Aether distributed control plane\",\n \"license\": \"Apache-2.0\",\n \"author\": \"scitrera.ai\",\n \"homepage\": \"https://memorylayer.ai\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/scitrera/aether\",\n \"directory\": \"sdk/typescript\"\n },\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n },\n \"require\": {\n \"types\": \"./dist/index.d.cts\",\n \"default\": \"./dist/index.cjs\"\n }\n }\n },\n \"files\": [\n \"dist\",\n \"README.md\"\n ],\n \"scripts\": {\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\"\n },\n \"dependencies\": {\n \"@grpc/grpc-js\": \"1.14.3\",\n \"@grpc/proto-loader\": \"0.8.1\"\n },\n \"devDependencies\": {\n \"typescript\": \"^5.4.0\",\n \"tsup\": \"^8.0.0\",\n \"vitest\": \"^1.4.0\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n },\n \"keywords\": [\n \"aether\",\n \"scitrera\",\n \"grpc\",\n \"distributed\",\n \"control-plane\",\n \"messaging\"\n ]\n}\n","// Client-version metadata for the InitConnection versioning spec.\n// Merged into the InitConnection payload by BaseClient on every\n// (re)connect so the gateway audit log can attribute connections to a\n// specific SDK build without consumers having to wire anything.\n\nimport packageJson from \"../package.json\" with { type: \"json\" };\n\nconst CLIENT_SDK_NAME = \"ts\";\n\n/**\n * Cached version metadata. Computed lazily so module load does not pay\n * a runtime detection cost when the SDK is never connected, but\n * memoised after the first call.\n */\nlet cachedMeta:\n | {\n clientVersion: string;\n clientSdk: string;\n clientBuildInfo: { runtime: string; os: string };\n }\n | undefined;\n\n/**\n * Returns this SDK's version + build-info, shaped to merge directly\n * onto an InitConnection message. Browser builds default runtime/os to\n * \"browser\"/the user-agent string because process.* is not available;\n * Node.js builds use process.versions.node and process.platform/arch.\n */\nexport function clientVersionMeta(): {\n clientVersion: string;\n clientSdk: string;\n clientBuildInfo: { runtime: string; os: string };\n} {\n if (cachedMeta !== undefined) {\n return cachedMeta;\n }\n\n const version = (packageJson as { version?: string }).version ?? \"unknown\";\n\n let runtime = \"unknown\";\n let os = \"unknown\";\n if (typeof process !== \"undefined\" && process.versions && process.versions.node) {\n runtime = `node${process.versions.node}`;\n os = `${process.platform}/${process.arch}`;\n } else if (typeof navigator !== \"undefined\") {\n runtime = \"browser\";\n os = navigator.userAgent ?? \"browser\";\n }\n\n cachedMeta = {\n clientVersion: version,\n clientSdk: CLIENT_SDK_NAME,\n clientBuildInfo: { runtime, os },\n };\n return cachedMeta;\n}\n","/**\n * Base client implementation for the Aether TypeScript SDK.\n *\n * This module provides the AetherClient class that handles gRPC connection\n * management, TLS configuration, message queue infrastructure, and automatic\n * reconnection with exponential backoff. Specific client types (AgentClient,\n * UserClient, etc.) extend this base client.\n *\n * Key architectural principle: The connection itself IS the distributed lock\n * AND the heartbeat. When the gRPC stream closes, the identity lock is\n * immediately released. No separate heartbeat API exists.\n *\n * @module client\n */\n\nimport type {\n ConnectionOptions,\n TLSOptions,\n Credentials,\n MessageHandler,\n ConfigHandler,\n SignalHandler,\n ErrorHandler,\n KVResponseHandler,\n TaskAssignmentHandler,\n CheckpointResponseHandler,\n ProgressHandler,\n ConnectHandler,\n DisconnectHandler,\n ReconnectingHandler,\n WorkspaceResponseHandler,\n AgentResponseHandler,\n ACLResponseHandler,\n AuthorityGrantResponseHandler,\n AuthorityGrantRevocation,\n AuthorityGrantRevocationHandler,\n WorkflowResponseHandler,\n TokenResponseHandler,\n OutgoingMessage,\n IncomingMessage,\n ConfigSnapshot,\n Signal,\n ErrorResponse,\n ConnectionAck,\n TaskAssignment,\n KVResponse,\n CheckpointResponse,\n ProgressUpdate,\n ReportProgressOptions,\n TaskQueryResponse,\n TaskOperationResponse,\n TaskInfo,\n TaskQueryOptions,\n TaskQueryResponseHandler,\n TaskOperationResponseHandler,\n CreateTaskResponse,\n CreateTaskResponseHandler,\n WorkspaceResponse,\n AgentResponse,\n ACLResponse,\n AuthorityGrantResponse,\n AuthorityGrantInfo,\n WorkflowResponse,\n TokenResponse,\n TokenInfo,\n AuditSubmitResponse,\n AuditSubmitResponseHandler,\n} from \"./types.js\";\nimport { MessageType, KVScope, SignalType } from \"./types.js\";\nimport {\n ConnectionError,\n DuplicateIdentityError,\n ReconnectionError,\n InvalidArgumentError,\n isRecoverable,\n} from \"./errors.js\";\nimport { KVClient } from \"./kv.js\";\nimport { CheckpointClient } from \"./checkpoint.js\";\nimport type { TunnelInflight } from \"./tunnel.js\";\nimport { TunnelClosedError } from \"./tunnel.js\";\nimport type { AuthorityGrantCacheOptions } from \"./authority-cache.js\";\nimport { AuthorityGrantCache } from \"./authority-cache.js\";\nimport type { ProxyHttpResponse } from \"./proxy.js\";\nimport { clientVersionMeta } from \"./version-meta.js\";\n\n// =============================================================================\n// Client Options\n// =============================================================================\n\n/**\n * Configuration options for the base Aether client.\n */\nexport interface AetherClientOptions {\n /** Gateway address in host:port format. Required. */\n address: string;\n /** Optional TLS configuration for secure connections. */\n tls?: TLSOptions;\n /** Connection behavior configuration. */\n connection?: ConnectionOptions;\n /** Authentication credentials. */\n credentials?: Credentials;\n /** Whether to automatically reconnect on connection loss. Default: true. */\n reconnect?: boolean;\n /** Initial delay in ms between reconnect attempts. Default: 1000. */\n reconnectDelay?: number;\n /** Maximum delay in ms between reconnect attempts. Default: 30000. */\n maxReconnectDelay?: number;\n /**\n * When true, if the gateway returns a DuplicateIdentityError (ALREADY_EXISTS)\n * during connection, the client will wait and retry automatically.\n * Shorthand for connection.retryOnDuplicate. Default: false.\n */\n retryOnDuplicate?: boolean;\n /**\n * How long to wait (ms) before retrying after a DuplicateIdentityError.\n * Shorthand for connection.retryOnDuplicateDelay. Default: 5000.\n */\n retryOnDuplicateDelay?: number;\n}\n\n// =============================================================================\n// Internal KV Operation Type\n// =============================================================================\n\n/** @internal */\nexport interface KVOperationParams {\n op: \"GET\" | \"PUT\" | \"LIST\" | \"DELETE\" | \"INCREMENT\" | \"DECREMENT\" | \"INCREMENT_IF\" | \"DECREMENT_IF\";\n scope: KVScope;\n key?: string;\n value?: Uint8Array;\n userId?: string;\n workspace?: string;\n ttl?: number;\n requestId?: string;\n /** Guard value for INCREMENT_IF (ceiling) and DECREMENT_IF (floor) operations. */\n guardValue?: bigint;\n /** Step size for INCREMENT_IF / DECREMENT_IF. When omitted the server defaults to 1. */\n deltaValue?: bigint;\n}\n\n// =============================================================================\n// Internal Checkpoint Operation Type\n// =============================================================================\n\n/** @internal */\nexport interface CheckpointOperationParams {\n op: \"SAVE\" | \"LOAD\" | \"DELETE\" | \"LIST\";\n key?: string;\n data?: Uint8Array;\n ttl?: number;\n requestId?: string;\n}\n\n// =============================================================================\n// Default Connection Options\n// =============================================================================\n\nconst DEFAULT_CONNECTION: Required<ConnectionOptions> = {\n maxRetries: 5,\n initialBackoff: 1000,\n maxBackoff: 30000,\n backoffMultiplier: 2.0,\n autoReconnect: true,\n connectTimeout: 30000,\n retryOnDuplicate: false,\n retryOnDuplicateDelay: 5000,\n retryOnDuplicateMaxAttempts: 5,\n};\n\n// =============================================================================\n// AetherClient\n// =============================================================================\n\n/**\n * Base client for connecting to the Aether distributed control plane.\n *\n * AetherClient manages the gRPC bidirectional streaming connection,\n * handles automatic reconnection with exponential backoff, and provides\n * the message send/receive infrastructure.\n *\n * This class is not typically used directly. Instead, use one of the\n * specialized client types:\n * - {@link AgentClient} for agent connections\n * - {@link UserClient} for user/browser connections\n *\n * @example\n * ```typescript\n * import { AetherClient } from \"@scitrera/aether-client\";\n *\n * const client = new AetherClient({ address: \"localhost:50051\" });\n *\n * client.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await client.connect();\n * ```\n */\nexport class AetherClient {\n // Configuration\n protected readonly _address: string;\n protected readonly _tls: TLSOptions | undefined;\n protected readonly _connectionOpts: Required<ConnectionOptions>;\n protected readonly _credentials: Credentials;\n\n // Connection state\n protected _connected = false;\n protected _connecting = false;\n protected _sessionId = \"\";\n protected _resumeSessionId = \"\";\n private _requestCounter = 0;\n\n // Handler registry\n private _onMessage: MessageHandler = () => {};\n private _onConfig: ConfigHandler = () => {};\n private _onSignal: SignalHandler = () => {};\n private _onError: ErrorHandler = () => {};\n private _onKVResponse: KVResponseHandler = () => {};\n private _onTaskAssignment: TaskAssignmentHandler = () => {};\n private _onCheckpointResponse: CheckpointResponseHandler = () => {};\n private _onProgress: ProgressHandler = () => {};\n private _onConnect: ConnectHandler = () => {};\n private _onDisconnect: DisconnectHandler = () => {};\n private _onReconnecting: ReconnectingHandler = () => {};\n\n // Task management handlers\n private _onTaskQueryResponse: TaskQueryResponseHandler = () => {};\n private _onTaskOperationResponse: TaskOperationResponseHandler = () => {};\n private _onCreateTaskResponse: CreateTaskResponseHandler = () => {};\n\n // Workspace/Agent/ACL/Workflow handlers\n private _onWorkspaceResponse: WorkspaceResponseHandler = () => {};\n private _onAgentResponse: AgentResponseHandler = () => {};\n private _onACLResponse: ACLResponseHandler = () => {};\n private _onAuthorityGrantResponse: AuthorityGrantResponseHandler = () => {};\n private _onAuthorityGrantRevocation: AuthorityGrantRevocationHandler = () => {};\n private _onAuditSubmitResponse: AuditSubmitResponseHandler = () => {};\n\n // Registered authority-grant caches receive AuthorityGrantRevocation\n // push events before the user-supplied handler. @internal\n private _authorityGrantCaches: AuthorityGrantCache[] = [];\n private _onWorkflowResponse: WorkflowResponseHandler = () => {};\n private _onTokenResponse: TokenResponseHandler = () => {};\n\n // Typed message handlers\n private _onChatMessage: MessageHandler | null = null;\n private _onControlMessage: MessageHandler | null = null;\n private _onToolCallMessage: MessageHandler | null = null;\n private _onEventMessage: MessageHandler | null = null;\n private _onMetricMessage: MessageHandler | null = null;\n\n // Pending request correlation maps\n private _pendingKVRequests = new Map<string, (response: KVResponse) => void>();\n private _pendingCheckpointRequests = new Map<string, (response: CheckpointResponse) => void>();\n private _pendingTaskQueryRequests = new Map<string, (response: TaskQueryResponse) => void>();\n private _pendingTaskOpRequests = new Map<string, (response: TaskOperationResponse) => void>();\n private _pendingCreateTaskRequests = new Map<string, (response: CreateTaskResponse) => void>();\n private _pendingWorkspaceRequests = new Map<string, (response: WorkspaceResponse) => void>();\n private _pendingAgentRequests = new Map<string, (response: AgentResponse) => void>();\n private _pendingACLRequests = new Map<string, (response: ACLResponse) => void>();\n private _pendingAuthorityGrantRequests = new Map<string, (response: AuthorityGrantResponse) => void>();\n private _pendingWorkflowRequests = new Map<string, (response: WorkflowResponse) => void>();\n private _pendingAuditSubmitRequests = new Map<string, (response: AuditSubmitResponse) => void>();\n private _pendingTokenRequests = new Map<string, (response: TokenResponse) => void>();\n\n // Proxy HTTP pending requests: request_id → resolver\n // @internal\n _pendingProxyHttpRequests = new Map<string, (response: ProxyHttpResponse) => void>();\n // Accumulated body chunks keyed by request_id, for chunked responses\n // @internal\n _pendingProxyHttpChunks = new Map<string, Uint8Array[]>();\n // Active streaming proxy responses: request_id → controller. Set by\n // proxyHttp() when streamResponse=true; populated as ProxyHttpBodyChunk\n // frames arrive so the caller's ReadableStream<Uint8Array> can yield them\n // incrementally.\n // @internal\n _pendingProxyHttpStreams = new Map<\n string,\n {\n controller: ReadableStreamDefaultController<Uint8Array>;\n headerResolved: boolean;\n }\n >();\n\n // Tunnel inflight map: tunnel_id → TunnelInflight handler\n // @internal\n _pendingTunnels = new Map<string, TunnelInflight>();\n\n // KV client instance (lazy)\n private _kvClient: KVClient | undefined;\n\n // Checkpoint client instance (lazy)\n private _checkpointClient: CheckpointClient | undefined;\n\n // RetryOnDuplicate configuration\n private readonly _retryOnDuplicate: boolean;\n private readonly _retryOnDuplicateDelay: number;\n private readonly _retryOnDuplicateMaxAttempts: number;\n\n // gRPC connection objects (populated when @grpc/grpc-js is available)\n private _grpcClient: unknown = null;\n private _stream: unknown = null;\n private _disconnectRequested = false;\n private _reconnecting = false;\n\n // Loaded proto package definition — stored for sub-message encoding (e.g. Metric)\n private _packageDefinition: Record<string, unknown> | null = null;\n\n /**\n * Creates a new AetherClient.\n *\n * The client is created but not connected. Call {@link connect} to establish\n * the connection to the gateway.\n *\n * @param options - Client configuration options\n * @throws {@link InvalidArgumentError} if the address is not provided\n */\n constructor(options: AetherClientOptions) {\n if (!options.address) {\n throw new InvalidArgumentError(\"Gateway address is required\", \"address\");\n }\n\n this._address = options.address;\n this._tls = options.tls;\n this._credentials = options.credentials ?? {};\n\n // Merge connection options with defaults\n const connOpts = options.connection ?? {};\n\n // RetryOnDuplicate: top-level shorthand takes precedence over connection sub-object\n this._retryOnDuplicate =\n options.retryOnDuplicate ?? connOpts.retryOnDuplicate ?? false;\n this._retryOnDuplicateDelay =\n options.retryOnDuplicateDelay ?? connOpts.retryOnDuplicateDelay ?? 5000;\n this._retryOnDuplicateMaxAttempts =\n connOpts.retryOnDuplicateMaxAttempts ?? 5;\n\n this._connectionOpts = {\n maxRetries: connOpts.maxRetries ?? DEFAULT_CONNECTION.maxRetries,\n initialBackoff: options.reconnectDelay ?? connOpts.initialBackoff ?? DEFAULT_CONNECTION.initialBackoff,\n maxBackoff: options.maxReconnectDelay ?? connOpts.maxBackoff ?? DEFAULT_CONNECTION.maxBackoff,\n backoffMultiplier: connOpts.backoffMultiplier ?? DEFAULT_CONNECTION.backoffMultiplier,\n autoReconnect: options.reconnect ?? connOpts.autoReconnect ?? DEFAULT_CONNECTION.autoReconnect,\n connectTimeout: connOpts.connectTimeout ?? DEFAULT_CONNECTION.connectTimeout,\n retryOnDuplicate: this._retryOnDuplicate,\n retryOnDuplicateDelay: this._retryOnDuplicateDelay,\n retryOnDuplicateMaxAttempts: this._retryOnDuplicateMaxAttempts,\n };\n }\n\n // ===========================================================================\n // Connection Lifecycle\n // ===========================================================================\n\n /**\n * Establishes a connection to the Aether gateway.\n *\n * Opens a gRPC bidirectional stream and sends the InitConnection message.\n * If auto-reconnect is enabled, the client will automatically attempt to\n * reconnect on connection loss.\n *\n * If `retryOnDuplicate` is enabled and the gateway responds with a\n * DuplicateIdentityError (ALREADY_EXISTS), the client will wait briefly\n * and retry up to `retryOnDuplicateMaxAttempts` times. This handles the\n * race condition where a previous instance's lock has not yet expired.\n *\n * @throws {@link ConnectionError} if the connection cannot be established\n * @throws {@link DuplicateIdentityError} if identity is already connected\n * and retryOnDuplicate is disabled or exhausted\n */\n async connect(): Promise<void> {\n if (this._connected) {\n return;\n }\n if (this._connecting) {\n return;\n }\n\n this._connecting = true;\n this._disconnectRequested = false;\n\n try {\n if (this._retryOnDuplicate) {\n await this._connectWithDuplicateRetry();\n } else {\n await this._establishConnection();\n }\n this._connected = true;\n } finally {\n this._connecting = false;\n }\n }\n\n /**\n * Attempts connection, retrying on DuplicateIdentityError.\n * @internal\n */\n private async _connectWithDuplicateRetry(): Promise<void> {\n const maxAttempts = this._retryOnDuplicateMaxAttempts;\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n // Reset any partial connection state before each attempt\n await this._closeConnection();\n\n // Track whether a duplicate error was received during this attempt.\n // We listen for it via a one-shot error handler shim.\n let duplicateReceived = false;\n const prevOnError = this._onError;\n this._onError = (errResp) => {\n if (errResp.code === \"ALREADY_EXISTS\" || errResp.code === \"DUPLICATE_IDENTITY\") {\n duplicateReceived = true;\n }\n prevOnError(errResp);\n };\n\n try {\n await this._establishConnection();\n // Connection succeeded — restore handler and return\n this._onError = prevOnError;\n return;\n } catch (err) {\n this._onError = prevOnError;\n lastError = err instanceof Error ? err : new Error(String(err));\n\n // Check if the error is a DuplicateIdentityError or the flag was set\n const isDuplicate =\n duplicateReceived ||\n err instanceof DuplicateIdentityError ||\n (err instanceof Error && err.message.toLowerCase().includes(\"already_exists\"));\n\n if (!isDuplicate || attempt >= maxAttempts) {\n throw err;\n }\n\n // Wait before retrying\n await new Promise<void>((resolve) => setTimeout(resolve, this._retryOnDuplicateDelay));\n }\n }\n\n throw lastError ?? new DuplicateIdentityError(\"\", \"exhausted retryOnDuplicate attempts\");\n }\n\n /**\n * Gracefully disconnects from the Aether gateway.\n *\n * Closes the gRPC stream and releases the identity lock on the server.\n * Automatic reconnection is suppressed for this disconnection.\n */\n async disconnect(): Promise<void> {\n this._disconnectRequested = true;\n this._connected = false;\n await this._closeConnection();\n }\n\n /**\n * Returns whether the client is currently connected to the gateway.\n */\n get connected(): boolean {\n return this._connected;\n }\n\n /**\n * Returns the current session ID assigned by the gateway.\n * Empty string if not connected.\n */\n get sessionId(): string {\n return this._sessionId;\n }\n\n // ===========================================================================\n // Message Sending\n // ===========================================================================\n\n /**\n * Sends a message through the Aether gateway.\n *\n * @param message - The outgoing message to send\n * @throws {@link ConnectionError} if not connected\n */\n async send(message: OutgoingMessage): Promise<void> {\n if (!this._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n this._sendUpstream({\n send: {\n targetTopic: message.targetTopic,\n payload: message.payload,\n messageType: message.messageType ?? MessageType.Opaque,\n },\n });\n }\n\n /**\n * Sends a KV operation through the gateway.\n * @internal Used by KVClient.\n */\n sendKVOperation(params: KVOperationParams): void {\n this._sendUpstream({\n kvOp: {\n op: params.op,\n scope: params.scope,\n key: params.key ?? \"\",\n value: params.value,\n userId: params.userId ?? \"\",\n workspace: params.workspace ?? \"\",\n ttl: params.ttl ?? 0,\n requestId: params.requestId ?? \"\",\n guardValue: params.guardValue,\n deltaValue: params.deltaValue,\n },\n });\n }\n\n /**\n * Sends a checkpoint operation through the gateway.\n * @internal Used by CheckpointClient.\n */\n sendCheckpointOperation(params: CheckpointOperationParams): void {\n this._sendUpstream({\n checkpointOp: {\n op: params.op,\n key: params.key ?? \"\",\n data: params.data,\n ttl: params.ttl ?? -1,\n requestId: params.requestId ?? \"\",\n },\n });\n }\n\n // ===========================================================================\n // Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for incoming messages.\n *\n * @param handler - Function called when a message is received\n *\n * @example\n * ```typescript\n * client.onMessage((msg) => {\n * console.log(`From ${msg.sourceTopic}: ${new TextDecoder().decode(msg.payload)}`);\n * });\n * ```\n */\n onMessage(handler: MessageHandler): void {\n this._onMessage = handler;\n }\n\n /**\n * Registers a handler for configuration snapshots.\n *\n * Called once when the connection is established, providing the initial\n * KV store state for the workspace.\n *\n * @param handler - Function called when a config snapshot is received\n */\n onConfig(handler: ConfigHandler): void {\n this._onConfig = handler;\n }\n\n /**\n * Registers a handler for signals from the gateway.\n *\n * @param handler - Function called when a signal is received\n */\n onSignal(handler: SignalHandler): void {\n this._onSignal = handler;\n }\n\n /**\n * Registers a handler for error responses from the gateway.\n *\n * @param handler - Function called when an error response is received\n */\n onError(handler: ErrorHandler): void {\n this._onError = handler;\n }\n\n /**\n * Registers a handler for KV operation responses.\n *\n * @param handler - Function called when a KV response is received\n */\n onKVResponse(handler: KVResponseHandler): void {\n this._onKVResponse = handler;\n }\n\n /**\n * Registers a handler for task assignments.\n *\n * Used by orchestrators to receive task assignments that require\n * starting new agent or task instances.\n *\n * @param handler - Function called when a task assignment is received\n */\n onTaskAssignment(handler: TaskAssignmentHandler): void {\n this._onTaskAssignment = handler;\n }\n\n /**\n * Registers a handler for checkpoint operation responses.\n *\n * @param handler - Function called when a checkpoint response is received\n */\n onCheckpointResponse(handler: CheckpointResponseHandler): void {\n this._onCheckpointResponse = handler;\n }\n\n /**\n * Registers a handler for progress updates from agents/tasks.\n *\n * Progress updates are delivered via the pg::{workspace} stream with\n * server-side recipient filtering.\n *\n * @param handler - Function called when a progress update is received\n */\n onProgress(handler: ProgressHandler): void {\n this._onProgress = handler;\n }\n\n /**\n * Registers a handler for successful connections.\n *\n * Called both for initial connection and reconnections.\n *\n * @param handler - Function called with the connection acknowledgment\n */\n onConnect(handler: ConnectHandler): void {\n this._onConnect = handler;\n }\n\n /**\n * Registers a handler for disconnection events.\n *\n * Called before any automatic reconnection attempt.\n *\n * @param handler - Function called with the disconnection reason\n */\n onDisconnect(handler: DisconnectHandler): void {\n this._onDisconnect = handler;\n }\n\n /**\n * Registers a handler for reconnection attempts.\n *\n * @param handler - Function called with the attempt number\n */\n onReconnecting(handler: ReconnectingHandler): void {\n this._onReconnecting = handler;\n }\n\n /**\n * Registers a handler for task query responses.\n *\n * @param handler - Function called when a task query response is received\n */\n onTaskQueryResponse(handler: TaskQueryResponseHandler): void {\n this._onTaskQueryResponse = handler;\n }\n\n /**\n * Registers a handler for task operation responses.\n *\n * @param handler - Function called when a task operation response is received\n */\n onTaskOperationResponse(handler: TaskOperationResponseHandler): void {\n this._onTaskOperationResponse = handler;\n }\n\n /**\n * Registers a handler for create-task responses (fire-and-forget path,\n * i.e. when no request_id is supplied or a response arrives without a\n * matching pending entry).\n *\n * @param handler - Function called when a create-task response is received\n */\n onCreateTaskResponse(handler: CreateTaskResponseHandler): void {\n this._onCreateTaskResponse = handler;\n }\n\n /**\n * Registers a handler for Chat messages.\n *\n * @param handler - Function called when a Chat message is received\n */\n onChatMessage(handler: MessageHandler): void {\n this._onChatMessage = handler;\n }\n\n /**\n * Registers a handler for Control messages.\n *\n * @param handler - Function called when a Control message is received\n */\n onControlMessage(handler: MessageHandler): void {\n this._onControlMessage = handler;\n }\n\n /**\n * Registers a handler for ToolCall messages.\n *\n * @param handler - Function called when a ToolCall message is received\n */\n onToolCallMessage(handler: MessageHandler): void {\n this._onToolCallMessage = handler;\n }\n\n /**\n * Registers a handler for Event messages.\n *\n * @param handler - Function called when an Event message is received\n */\n onEventMessage(handler: MessageHandler): void {\n this._onEventMessage = handler;\n }\n\n /**\n * Registers a handler for Metric messages.\n *\n * @param handler - Function called when a Metric message is received\n */\n onMetricMessage(handler: MessageHandler): void {\n this._onMetricMessage = handler;\n }\n\n // ===========================================================================\n // KV Client Access\n // ===========================================================================\n\n /**\n * Returns the KV operations client.\n *\n * @returns The KVClient instance for performing KV store operations\n *\n * @example\n * ```typescript\n * const kv = client.kv();\n * const response = await kv.getSync({ key: \"my-key\", scope: KVScope.Global });\n * ```\n */\n kv(): KVClient {\n if (!this._kvClient) {\n this._kvClient = new KVClient(this);\n }\n return this._kvClient;\n }\n\n /**\n * Returns the checkpoint operations client.\n *\n * @returns The CheckpointClient instance for checkpoint save/load/delete/list\n *\n * @example\n * ```typescript\n * const cp = client.checkpoint();\n * const response = await cp.loadSync({ key: \"my-state\" });\n * ```\n */\n checkpoint(): CheckpointClient {\n if (!this._checkpointClient) {\n this._checkpointClient = new CheckpointClient(this);\n }\n return this._checkpointClient;\n }\n\n // ===========================================================================\n // Request Correlation (internal)\n // ===========================================================================\n\n /**\n * Generates a unique request ID for correlating responses.\n * @internal\n */\n nextRequestId(): string {\n this._requestCounter++;\n return `req-${Date.now()}-${this._requestCounter}`;\n }\n\n /**\n * Registers a pending KV request for response correlation.\n * @internal\n */\n registerPendingKVRequest(requestId: string, callback: (response: KVResponse) => void): void {\n this._pendingKVRequests.set(requestId, callback);\n }\n\n /**\n * Registers a pending checkpoint request for response correlation.\n * @internal\n */\n registerPendingCheckpointRequest(requestId: string, callback: (response: CheckpointResponse) => void): void {\n this._pendingCheckpointRequests.set(requestId, callback);\n }\n\n /**\n * Removes a pending request (used on timeout cleanup).\n * @internal\n */\n removePendingRequest(requestId: string): void {\n this._pendingKVRequests.delete(requestId);\n this._pendingCheckpointRequests.delete(requestId);\n }\n\n // ===========================================================================\n // Init Message (overridden by subclasses)\n // ===========================================================================\n\n /**\n * Builds the InitConnection message for the connection handshake.\n * Subclasses override this to provide their specific identity.\n * @internal\n */\n protected _buildInitMessage(): Record<string, unknown> {\n return {\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // gRPC Connection Management\n // ===========================================================================\n\n /**\n * Establishes the gRPC connection and starts the message loop.\n * @internal\n */\n private async _establishConnection(): Promise<void> {\n try {\n // Dynamic import of @grpc/grpc-js (Node.js only)\n const grpc = await import(\"@grpc/grpc-js\");\n const protoLoader = await import(\"@grpc/proto-loader\");\n\n // Resolve proto file path\n const path = await import(\"path\");\n const url = await import(\"url\");\n const dirname = path.dirname(url.fileURLToPath(import.meta.url));\n const protoPath = path.resolve(dirname, \"../../api/proto/aether.proto\");\n\n // Load proto definition\n const packageDefinition = await protoLoader.load(protoPath, {\n keepCase: false,\n longs: Number,\n enums: Number,\n defaults: true,\n oneofs: true,\n });\n\n // Store package definition for sub-message encoding (e.g. Metric)\n this._packageDefinition = packageDefinition as Record<string, unknown>;\n\n const protoDescriptor = grpc.loadPackageDefinition(packageDefinition) as Record<string, unknown>;\n const aetherV1 = (protoDescriptor[\"aether\"] as Record<string, unknown>)?.[\"v1\"] as Record<string, unknown>;\n\n if (!aetherV1) {\n throw new ConnectionError(\"Failed to load aether.v1 proto package\");\n }\n\n // Create gRPC channel credentials\n let channelCredentials: ReturnType<typeof grpc.credentials.createInsecure>;\n if (this._tls) {\n channelCredentials = grpc.credentials.createSsl(\n this._tls.rootCerts ?? null,\n this._tls.privateKey ?? null,\n this._tls.certChain ?? null,\n );\n } else {\n channelCredentials = grpc.credentials.createInsecure();\n }\n\n // Create client\n const ServiceClient = aetherV1[\"AetherGateway\"] as new (\n address: string,\n credentials: ReturnType<typeof grpc.credentials.createInsecure>,\n ) => Record<string, unknown>;\n this._grpcClient = new ServiceClient(this._address, channelCredentials);\n\n // Open bidirectional stream\n const client = this._grpcClient as Record<string, (...args: unknown[]) => unknown>;\n this._stream = client[\"connect\"]() as Record<string, unknown>;\n\n const stream = this._stream as {\n write: (msg: unknown) => void;\n on: (event: string, handler: (...args: unknown[]) => void) => void;\n end: () => void;\n };\n\n // Set up message handler\n stream.on(\"data\", (...args: unknown[]) => {\n this._handleDownstreamMessage(args[0] as Record<string, unknown>);\n });\n\n // Set up error handler\n stream.on(\"error\", (...args: unknown[]) => {\n this._handleStreamError(args[0] as Error);\n });\n\n // Set up end handler\n stream.on(\"end\", () => {\n this._handleStreamEnd();\n });\n\n // Send init message. Merge in SDK version metadata so the gateway\n // can attribute the connection to a specific TS build in audit\n // rows — additive, ignored by older gateways. Subclass-supplied\n // fields win on collision.\n const initMsg = { ...clientVersionMeta(), ...this._buildInitMessage() };\n stream.write({ init: initMsg });\n\n } catch (err) {\n if (err instanceof ConnectionError) {\n throw err;\n }\n throw new ConnectionError(\n `Failed to connect to gateway at ${this._address}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n /**\n * Closes the gRPC connection.\n * @internal\n */\n private async _closeConnection(): Promise<void> {\n if (this._stream) {\n const stream = this._stream as { end: () => void; removeAllListeners?: () => void };\n try {\n // Remove event listeners before ending to prevent stale handlers\n // from firing during reconnection and triggering duplicate attempts\n stream.removeAllListeners?.();\n stream.end();\n } catch {\n // Ignore errors during close\n }\n this._stream = null;\n }\n\n if (this._grpcClient) {\n const client = this._grpcClient as { close?: () => void };\n try {\n client.close?.();\n } catch {\n // Ignore errors during close\n }\n this._grpcClient = null;\n }\n }\n\n /**\n * Sends an upstream message on the gRPC stream.\n * @internal\n */\n protected _sendUpstream(message: Record<string, unknown>): void {\n if (!this._stream) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n const stream = this._stream as { write: (msg: unknown) => void };\n stream.write(message);\n }\n\n // ===========================================================================\n // Downstream Message Handling\n // ===========================================================================\n\n /**\n * Routes a downstream message to the appropriate handler.\n * @internal\n */\n private _handleDownstreamMessage(data: Record<string, unknown>): void {\n // Detect which payload field is set (oneof)\n if (data[\"connectionAck\"] || data[\"connection_ack\"]) {\n const ack = (data[\"connectionAck\"] ?? data[\"connection_ack\"]) as Record<string, unknown>;\n this._sessionId = String(ack[\"sessionId\"] ?? ack[\"session_id\"] ?? \"\");\n this._resumeSessionId = this._sessionId;\n const connAck: ConnectionAck = {\n sessionId: this._sessionId,\n resumed: Boolean(ack[\"resumed\"]),\n assignedId: String(ack[\"assignedId\"] ?? ack[\"assigned_id\"] ?? \"\"),\n };\n this._onConnect(connAck);\n return;\n }\n\n if (data[\"msg\"]) {\n const msg = data[\"msg\"] as Record<string, unknown>;\n const incoming: IncomingMessage = {\n sourceTopic: String(msg[\"sourceTopic\"] ?? msg[\"source_topic\"] ?? \"\"),\n payload: msg[\"payload\"] instanceof Uint8Array ? msg[\"payload\"] : new Uint8Array(),\n messageType: Number(msg[\"messageType\"] ?? msg[\"message_type\"] ?? 0),\n receivedAt: new Date(),\n };\n this._onMessage(incoming);\n\n // Dispatch to typed message handler\n switch (incoming.messageType) {\n case MessageType.Chat:\n this._onChatMessage?.(incoming);\n break;\n case MessageType.Control:\n this._onControlMessage?.(incoming);\n break;\n case MessageType.ToolCall:\n this._onToolCallMessage?.(incoming);\n break;\n case MessageType.Event:\n this._onEventMessage?.(incoming);\n break;\n case MessageType.Metric:\n this._onMetricMessage?.(incoming);\n break;\n case MessageType.Opaque:\n // No typed handler — falls through to onMessage catch-all above\n break;\n }\n return;\n }\n\n if (data[\"config\"]) {\n const cfg = data[\"config\"] as Record<string, unknown>;\n const rawKv = (cfg[\"kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const rawGlobalKv = (cfg[\"globalKv\"] ?? cfg[\"global_kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const rawWsExclKv = (cfg[\"workspaceExclusiveKv\"] ?? cfg[\"workspace_exclusive_kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const rawGlobalExclKv = (cfg[\"globalExclusiveKv\"] ?? cfg[\"global_exclusive_kv\"] ?? {}) as Record<string, Buffer | Uint8Array>;\n const config: ConfigSnapshot = {\n kv: Object.fromEntries(Object.entries(rawKv).map(([k, v]) => [k, new Uint8Array(v)])),\n globalKv: Object.fromEntries(Object.entries(rawGlobalKv).map(([k, v]) => [k, new Uint8Array(v)])),\n workspaceExclusiveKv: Object.fromEntries(Object.entries(rawWsExclKv).map(([k, v]) => [k, new Uint8Array(v)])),\n globalExclusiveKv: Object.fromEntries(Object.entries(rawGlobalExclKv).map(([k, v]) => [k, new Uint8Array(v)])),\n };\n this._onConfig(config);\n return;\n }\n\n if (data[\"signal\"]) {\n const sig = data[\"signal\"] as Record<string, unknown>;\n const signal: Signal = {\n type: Number(sig[\"type\"]) as SignalType,\n reason: String(sig[\"reason\"] ?? \"\"),\n };\n this._onSignal(signal);\n\n if (signal.type === SignalType.ForceDisconnect) {\n this._connected = false;\n this._disconnectRequested = true; // Terminal — do not auto-reconnect\n this._onDisconnect(signal.reason || \"Force disconnect signal received\");\n } else if (signal.type === SignalType.GracefulDisconnect) {\n this._connected = false;\n // Do NOT set _disconnectRequested — allow auto-reconnect\n this._onDisconnect(signal.reason || \"Graceful disconnect signal received\");\n }\n return;\n }\n\n if (data[\"error\"]) {\n const err = data[\"error\"] as Record<string, unknown>;\n const errorResponse: ErrorResponse = {\n code: String(err[\"code\"] ?? \"\"),\n message: String(err[\"message\"] ?? \"\"),\n retryable: Boolean(err[\"retryable\"]),\n retryAfterMs: Number(err[\"retryAfterMs\"] ?? err[\"retry_after_ms\"] ?? 0),\n };\n this._onError(errorResponse);\n return;\n }\n\n if (data[\"kv\"]) {\n const kv = data[\"kv\"] as Record<string, unknown>;\n const rawCounter = kv[\"counterValue\"] ?? kv[\"counter_value\"];\n const rawApplied = kv[\"applied\"];\n const response: KVResponse = {\n success: Boolean(kv[\"success\"]),\n value: kv[\"value\"] instanceof Uint8Array ? kv[\"value\"] : new Uint8Array(),\n keys: (kv[\"keys\"] ?? []) as string[],\n kvMap: (kv[\"kvMap\"] ?? kv[\"kv_map\"] ?? {}) as Record<string, string>,\n requestId: String(kv[\"requestId\"] ?? kv[\"request_id\"] ?? \"\"),\n counterValue: rawCounter !== undefined ? Number(rawCounter) : undefined,\n applied: rawApplied !== undefined ? Boolean(rawApplied) : undefined,\n };\n\n // Route to correlated request if available\n const pending = this._pendingKVRequests.get(response.requestId);\n if (pending) {\n this._pendingKVRequests.delete(response.requestId);\n pending(response);\n } else {\n this._onKVResponse(response);\n }\n return;\n }\n\n if (data[\"taskAssignment\"] || data[\"task_assignment\"]) {\n const ta = (data[\"taskAssignment\"] ?? data[\"task_assignment\"]) as Record<string, unknown>;\n const assignment: TaskAssignment = {\n taskId: String(ta[\"taskId\"] ?? ta[\"task_id\"] ?? \"\"),\n taskType: String(ta[\"taskType\"] ?? ta[\"task_type\"] ?? \"\"),\n assignedTo: String(ta[\"assignedTo\"] ?? ta[\"assigned_to\"] ?? \"\"),\n metadata: (ta[\"metadata\"] ?? {}) as Record<string, string>,\n assignedAt: Number(ta[\"assignedAt\"] ?? ta[\"assigned_at\"] ?? 0),\n profile: String(ta[\"profile\"] ?? \"\"),\n launchParams: (ta[\"launchParams\"] ?? ta[\"launch_params\"] ?? {}) as Record<string, string>,\n targetImplementation: String(ta[\"targetImplementation\"] ?? ta[\"target_implementation\"] ?? \"\"),\n workspace: String(ta[\"workspace\"] ?? \"\"),\n specifier: String(ta[\"specifier\"] ?? \"\"),\n };\n this._onTaskAssignment(assignment);\n return;\n }\n\n if (data[\"progressUpdate\"] || data[\"progress_update\"]) {\n const pu = (data[\"progressUpdate\"] ?? data[\"progress_update\"]) as Record<string, unknown>;\n const step = pu[\"step\"] as Record<string, unknown> | undefined;\n const update: ProgressUpdate = {\n source: String(pu[\"source\"] ?? \"\"),\n taskId: String(pu[\"taskId\"] ?? pu[\"task_id\"] ?? \"\"),\n state: String(pu[\"state\"] ?? \"\"),\n completion: Number(pu[\"completion\"] ?? -1),\n summary: String(pu[\"summary\"] ?? \"\"),\n step: step ? {\n name: String(step[\"name\"] ?? \"\"),\n detail: String(step[\"detail\"] ?? \"\"),\n sequence: Number(step[\"sequence\"] ?? 0),\n totalSteps: Number(step[\"totalSteps\"] ?? step[\"total_steps\"] ?? 0),\n stepType: String(step[\"stepType\"] ?? step[\"step_type\"] ?? \"\"),\n } : undefined,\n timestampMs: Number(pu[\"timestampMs\"] ?? pu[\"timestamp_ms\"] ?? 0),\n workspace: String(pu[\"workspace\"] ?? \"\"),\n requestId: String(pu[\"requestId\"] ?? pu[\"request_id\"] ?? \"\"),\n metadata: (pu[\"metadata\"] ?? {}) as Record<string, string>,\n recipient: String(pu[\"recipient\"] ?? \"\"),\n };\n this._onProgress(update);\n return;\n }\n\n if (data[\"checkpoint\"]) {\n const cp = data[\"checkpoint\"] as Record<string, unknown>;\n const response: CheckpointResponse = {\n success: Boolean(cp[\"success\"]),\n data: cp[\"data\"] instanceof Uint8Array ? cp[\"data\"] : new Uint8Array(),\n keys: (cp[\"keys\"] ?? []) as string[],\n error: String(cp[\"error\"] ?? \"\"),\n savedAt: Number(cp[\"savedAt\"] ?? cp[\"saved_at\"] ?? 0),\n requestId: String(cp[\"requestId\"] ?? cp[\"request_id\"] ?? \"\"),\n };\n\n // Route to correlated request if available\n const pending = this._pendingCheckpointRequests.get(response.requestId);\n if (pending) {\n this._pendingCheckpointRequests.delete(response.requestId);\n pending(response);\n } else {\n this._onCheckpointResponse(response);\n }\n return;\n }\n\n if (data[\"taskQuery\"] || data[\"task_query\"]) {\n const tq = (data[\"taskQuery\"] ?? data[\"task_query\"]) as Record<string, unknown>;\n const requestId = String(tq[\"requestId\"] ?? tq[\"request_id\"] ?? \"\");\n const response: TaskQueryResponse = {\n success: Boolean(tq[\"success\"]),\n error: String(tq[\"error\"] ?? \"\"),\n task: tq[\"task\"] ? this._parseTaskInfo(tq[\"task\"] as Record<string, unknown>) : undefined,\n tasks: ((tq[\"tasks\"] ?? []) as Record<string, unknown>[]).map(t => this._parseTaskInfo(t)),\n totalCount: Number(tq[\"totalCount\"] ?? tq[\"total_count\"] ?? 0),\n requestId,\n };\n\n const pending = this._pendingTaskQueryRequests.get(requestId);\n if (pending) {\n this._pendingTaskQueryRequests.delete(requestId);\n pending(response);\n } else {\n this._onTaskQueryResponse(response);\n }\n return;\n }\n\n if (data[\"taskOp\"] || data[\"task_op\"]) {\n const to = (data[\"taskOp\"] ?? data[\"task_op\"]) as Record<string, unknown>;\n const requestId = String(to[\"requestId\"] ?? to[\"request_id\"] ?? \"\");\n const response: TaskOperationResponse = {\n success: Boolean(to[\"success\"]),\n message: String(to[\"message\"] ?? \"\"),\n error: String(to[\"error\"] ?? \"\"),\n task: to[\"task\"] ? this._parseTaskInfo(to[\"task\"] as Record<string, unknown>) : undefined,\n requestId,\n };\n\n const pending = this._pendingTaskOpRequests.get(requestId);\n if (pending) {\n this._pendingTaskOpRequests.delete(requestId);\n pending(response);\n } else {\n this._onTaskOperationResponse(response);\n }\n return;\n }\n\n if (data[\"workspace\"]) {\n const ws = data[\"workspace\"] as Record<string, unknown>;\n const requestId = String(ws[\"requestId\"] ?? ws[\"request_id\"] ?? \"\");\n const response: WorkspaceResponse = {\n success: Boolean(ws[\"success\"]),\n error: String(ws[\"error\"] ?? \"\"),\n message: String(ws[\"message\"] ?? \"\"),\n totalCount: Number(ws[\"totalCount\"] ?? ws[\"total_count\"] ?? 0),\n requestId,\n ...ws,\n };\n\n const pending = this._pendingWorkspaceRequests.get(requestId);\n if (pending) {\n this._pendingWorkspaceRequests.delete(requestId);\n pending(response);\n } else {\n this._onWorkspaceResponse(response);\n }\n return;\n }\n\n if (data[\"agent\"]) {\n const ag = data[\"agent\"] as Record<string, unknown>;\n const requestId = String(ag[\"requestId\"] ?? ag[\"request_id\"] ?? \"\");\n const response: AgentResponse = {\n success: Boolean(ag[\"success\"]),\n error: String(ag[\"error\"] ?? \"\"),\n message: String(ag[\"message\"] ?? \"\"),\n totalCount: Number(ag[\"totalCount\"] ?? ag[\"total_count\"] ?? 0),\n requestId,\n ...ag,\n };\n\n const pending = this._pendingAgentRequests.get(requestId);\n if (pending) {\n this._pendingAgentRequests.delete(requestId);\n pending(response);\n } else {\n this._onAgentResponse(response);\n }\n return;\n }\n\n if (data[\"acl\"]) {\n const acl = data[\"acl\"] as Record<string, unknown>;\n const requestId = String(acl[\"requestId\"] ?? acl[\"request_id\"] ?? \"\");\n const response: ACLResponse = {\n success: Boolean(acl[\"success\"]),\n error: String(acl[\"error\"] ?? \"\"),\n message: String(acl[\"message\"] ?? \"\"),\n requestId,\n ...acl,\n };\n\n const pending = this._pendingACLRequests.get(requestId);\n if (pending) {\n this._pendingACLRequests.delete(requestId);\n pending(response);\n } else {\n this._onACLResponse(response);\n }\n return;\n }\n\n if (data[\"authorityGrant\"] || data[\"authority_grant\"]) {\n const ag = (data[\"authorityGrant\"] ?? data[\"authority_grant\"]) as Record<string, unknown>;\n const requestId = String(ag[\"requestId\"] ?? ag[\"request_id\"] ?? \"\");\n const rawGrant = ag[\"grant\"] as Record<string, unknown> | null | undefined;\n const rawGrants = ag[\"grants\"];\n\n const response: AuthorityGrantResponse = {\n success: Boolean(ag[\"success\"]),\n error: String(ag[\"error\"] ?? \"\"),\n message: String(ag[\"message\"] ?? \"\"),\n grant: rawGrant ? this._parseAuthorityGrantInfo(rawGrant) : undefined,\n requestId,\n grants: Array.isArray(rawGrants)\n ? (rawGrants as Record<string, unknown>[]).map((g) => this._parseAuthorityGrantInfo(g))\n : undefined,\n total: Number(ag[\"total\"] ?? 0),\n cacheHintTtlSeconds: Number(ag[\"cacheHintTtlSeconds\"] ?? ag[\"cache_hint_ttl_seconds\"] ?? 0),\n };\n\n const pending = this._pendingAuthorityGrantRequests.get(requestId);\n if (pending) {\n this._pendingAuthorityGrantRequests.delete(requestId);\n pending(response);\n } else {\n this._onAuthorityGrantResponse(response);\n }\n return;\n }\n\n if (data[\"authorityGrantRevocation\"] || data[\"authority_grant_revocation\"]) {\n const raw = (data[\"authorityGrantRevocation\"] ?? data[\"authority_grant_revocation\"]) as Record<string, unknown>;\n const evt: AuthorityGrantRevocation = {\n grantId: String(raw[\"grantId\"] ?? raw[\"grant_id\"] ?? \"\"),\n rootGrantId: String(raw[\"rootGrantId\"] ?? raw[\"root_grant_id\"] ?? \"\"),\n reason: String(raw[\"reason\"] ?? \"\"),\n revokedAt: Number(raw[\"revokedAt\"] ?? raw[\"revoked_at\"] ?? 0),\n cascade: Boolean(raw[\"cascade\"]),\n };\n\n // Dispatch to every registered cache before firing the user handler.\n for (const cache of this._authorityGrantCaches) {\n try {\n cache.handleRevocationEvent(evt);\n } catch {\n // Best-effort: cache errors are isolated from each other and\n // from the user handler.\n }\n }\n this._onAuthorityGrantRevocation(evt);\n return;\n }\n\n if (data[\"createTask\"] || data[\"create_task\"]) {\n const ct = (data[\"createTask\"] ?? data[\"create_task\"]) as Record<string, unknown>;\n const requestId = String(ct[\"requestId\"] ?? ct[\"request_id\"] ?? \"\");\n const response: CreateTaskResponse = {\n success: Boolean(ct[\"success\"]),\n taskId: String(ct[\"taskId\"] ?? ct[\"task_id\"] ?? \"\"),\n status: String(ct[\"status\"] ?? \"\"),\n errorCode: String(ct[\"errorCode\"] ?? ct[\"error_code\"] ?? \"\"),\n errorMessage: String(ct[\"errorMessage\"] ?? ct[\"error_message\"] ?? \"\"),\n requestId,\n assignedTo: String(ct[\"assignedTo\"] ?? ct[\"assigned_to\"] ?? \"\"),\n };\n\n const pending = this._pendingCreateTaskRequests.get(requestId);\n if (pending) {\n this._pendingCreateTaskRequests.delete(requestId);\n pending(response);\n } else {\n this._onCreateTaskResponse(response);\n }\n return;\n }\n\n if (data[\"workflowResponse\"] || data[\"workflow_response\"]) {\n const wf = (data[\"workflowResponse\"] ?? data[\"workflow_response\"]) as Record<string, unknown>;\n const requestId = String(wf[\"requestId\"] ?? wf[\"request_id\"] ?? \"\");\n const response: WorkflowResponse = {\n success: Boolean(wf[\"success\"]),\n error: String(wf[\"error\"] ?? \"\"),\n message: String(wf[\"message\"] ?? \"\"),\n data: wf[\"data\"] instanceof Uint8Array ? wf[\"data\"] : undefined,\n totalCount: Number(wf[\"totalCount\"] ?? wf[\"total_count\"] ?? 0),\n requestId,\n };\n\n const pending = this._pendingWorkflowRequests.get(requestId);\n if (pending) {\n this._pendingWorkflowRequests.delete(requestId);\n pending(response);\n } else {\n this._onWorkflowResponse(response);\n }\n return;\n }\n\n if (data[\"submitAuditEventResponse\"] || data[\"submit_audit_event_response\"]) {\n const ar = (data[\"submitAuditEventResponse\"] ?? data[\"submit_audit_event_response\"]) as Record<string, unknown>;\n const clientRequestId = String(ar[\"clientRequestId\"] ?? ar[\"client_request_id\"] ?? \"\");\n const response: AuditSubmitResponse = {\n clientRequestId,\n success: Boolean(ar[\"success\"]),\n errorCode: String(ar[\"errorCode\"] ?? ar[\"error_code\"] ?? \"\"),\n errorMessage: String(ar[\"errorMessage\"] ?? ar[\"error_message\"] ?? \"\"),\n };\n const pending = this._pendingAuditSubmitRequests.get(clientRequestId);\n if (pending) {\n this._pendingAuditSubmitRequests.delete(clientRequestId);\n pending(response);\n } else {\n this._onAuditSubmitResponse(response);\n }\n return;\n }\n\n if (data[\"token\"] || data[\"tokenResponse\"] || data[\"token_response\"]) {\n const tr = (data[\"token\"] ?? data[\"tokenResponse\"] ?? data[\"token_response\"]) as Record<string, unknown>;\n const requestId = String(tr[\"requestId\"] ?? tr[\"request_id\"] ?? \"\");\n\n const parseTokenInfo = (t: Record<string, unknown>): TokenInfo => ({\n id: String(t[\"id\"] ?? \"\"),\n name: String(t[\"name\"] ?? \"\"),\n principalType: String(t[\"principalType\"] ?? t[\"principal_type\"] ?? \"\"),\n workspacePatterns: Array.isArray(t[\"workspacePatterns\"] ?? t[\"workspace_patterns\"])\n ? ((t[\"workspacePatterns\"] ?? t[\"workspace_patterns\"]) as unknown[]).map(String)\n : [],\n scopes: Array.isArray(t[\"scopes\"]) ? (t[\"scopes\"] as unknown[]).map(String) : [],\n createdBy: String(t[\"createdBy\"] ?? t[\"created_by\"] ?? \"\"),\n expiresAt: Number(t[\"expiresAt\"] ?? t[\"expires_at\"] ?? 0),\n lastUsedAt: Number(t[\"lastUsedAt\"] ?? t[\"last_used_at\"] ?? 0),\n revoked: Boolean(t[\"revoked\"]),\n revokedAt: Number(t[\"revokedAt\"] ?? t[\"revoked_at\"] ?? 0),\n createdAt: Number(t[\"createdAt\"] ?? t[\"created_at\"] ?? 0),\n updatedAt: Number(t[\"updatedAt\"] ?? t[\"updated_at\"] ?? 0),\n });\n\n const rawToken = tr[\"token\"] as Record<string, unknown> | null | undefined;\n const rawCreated = tr[\"createdToken\"] ?? tr[\"created_token\"] as Record<string, unknown> | null | undefined;\n const rawTokens = tr[\"tokens\"];\n\n const response: TokenResponse = {\n success: Boolean(tr[\"success\"]),\n error: String(tr[\"error\"] ?? \"\"),\n message: String(tr[\"message\"] ?? \"\"),\n token: rawToken ? parseTokenInfo(rawToken) : undefined,\n tokens: Array.isArray(rawTokens) ? (rawTokens as Record<string, unknown>[]).map(parseTokenInfo) : [],\n totalCount: Number(tr[\"totalCount\"] ?? tr[\"total_count\"] ?? 0),\n plaintextToken: String(tr[\"plaintextToken\"] ?? tr[\"plaintext_token\"] ?? \"\"),\n createdToken: rawCreated ? parseTokenInfo(rawCreated as Record<string, unknown>) : undefined,\n requestId,\n };\n\n const pending = this._pendingTokenRequests.get(requestId);\n if (pending) {\n this._pendingTokenRequests.delete(requestId);\n pending(response);\n } else {\n this._onTokenResponse(response);\n }\n return;\n }\n\n if (data[\"proxyHttpResponse\"] || data[\"proxy_http_response\"]) {\n const raw = (data[\"proxyHttpResponse\"] ?? data[\"proxy_http_response\"]) as Record<string, unknown>;\n const requestId = String(raw[\"requestId\"] ?? raw[\"request_id\"] ?? \"\");\n const rawErr = raw[\"error\"] as Record<string, unknown> | null | undefined;\n const response = {\n requestId,\n statusCode: Number(raw[\"statusCode\"] ?? raw[\"status_code\"] ?? 0),\n headers: (raw[\"headers\"] ?? {}) as Record<string, string>,\n body: raw[\"body\"] instanceof Uint8Array ? raw[\"body\"] : new Uint8Array(),\n bodyChunked: Boolean(raw[\"bodyChunked\"] ?? raw[\"body_chunked\"]),\n error: rawErr ? { kind: Number(rawErr[\"kind\"] ?? 0), message: String(rawErr[\"message\"] ?? \"\") } : undefined,\n };\n\n // Streaming path: a header lands first (resolves the request), then a\n // post-header header frame is treated as a terminal mid-stream error.\n const streamSlot = this._pendingProxyHttpStreams.get(requestId);\n if (streamSlot) {\n if (streamSlot.headerResolved) {\n // Mid-stream error — close the stream with an error.\n if (response.error) {\n streamSlot.controller.error(new Error(`${response.error.message}`));\n } else {\n streamSlot.controller.close();\n }\n this._pendingProxyHttpStreams.delete(requestId);\n return;\n }\n streamSlot.headerResolved = true;\n const pending = this._pendingProxyHttpRequests.get(requestId);\n if (pending) {\n this._pendingProxyHttpRequests.delete(requestId);\n pending(response);\n }\n // If header already carries a terminal error (TTFB failure), close.\n if (response.error) {\n streamSlot.controller.error(new Error(`${response.error.message}`));\n this._pendingProxyHttpStreams.delete(requestId);\n }\n return;\n }\n\n if (response.bodyChunked) {\n // Store partial response — body will be assembled from chunks\n this._pendingProxyHttpChunks.set(requestId, []);\n // Stash the response shell to reuse when fin arrives\n // We reuse the pending map entry itself once fin arrives; store the shell alongside chunks\n (this._pendingProxyHttpChunks as Map<string, unknown>).set(requestId + \":shell\", response);\n } else {\n const pending = this._pendingProxyHttpRequests.get(requestId);\n if (pending) {\n this._pendingProxyHttpRequests.delete(requestId);\n pending(response);\n }\n }\n return;\n }\n\n if (data[\"proxyHttpBodyChunk\"] || data[\"proxy_http_body_chunk\"]) {\n const raw = (data[\"proxyHttpBodyChunk\"] ?? data[\"proxy_http_body_chunk\"]) as Record<string, unknown>;\n const requestId = String(raw[\"requestId\"] ?? raw[\"request_id\"] ?? \"\");\n const isRequest = Boolean(raw[\"isRequest\"] ?? raw[\"is_request\"]);\n if (isRequest) return; // sent by us; ignore echoes\n\n const data_ = raw[\"data\"] instanceof Uint8Array ? raw[\"data\"] : new Uint8Array();\n const fin = Boolean(raw[\"fin\"]);\n\n // Streaming-body path: enqueue directly into the caller's\n // ReadableStream<Uint8Array> controller.\n const streamSlot = this._pendingProxyHttpStreams.get(requestId);\n if (streamSlot) {\n if (data_.length > 0) {\n streamSlot.controller.enqueue(data_);\n }\n if (fin) {\n streamSlot.controller.close();\n this._pendingProxyHttpStreams.delete(requestId);\n }\n return;\n }\n\n const chunks = this._pendingProxyHttpChunks.get(requestId);\n if (chunks && Array.isArray(chunks)) {\n chunks.push(data_);\n if (fin) {\n // Assemble body\n const totalLen = chunks.reduce((s, c) => s + c.length, 0);\n const body = new Uint8Array(totalLen);\n let offset = 0;\n for (const c of chunks) { body.set(c, offset); offset += c.length; }\n\n this._pendingProxyHttpChunks.delete(requestId);\n const shell = (this._pendingProxyHttpChunks as Map<string, unknown>).get(requestId + \":shell\") as Record<string, unknown> | undefined;\n (this._pendingProxyHttpChunks as Map<string, unknown>).delete(requestId + \":shell\");\n\n const pending = this._pendingProxyHttpRequests.get(requestId);\n if (pending) {\n this._pendingProxyHttpRequests.delete(requestId);\n pending({ ...(shell ?? {}), body } as Parameters<typeof pending>[0]);\n }\n }\n }\n return;\n }\n\n if (data[\"tunnelData\"] || data[\"tunnel_data\"]) {\n const raw = (data[\"tunnelData\"] ?? data[\"tunnel_data\"]) as Record<string, unknown>;\n const tunnelId = String(raw[\"tunnelId\"] ?? raw[\"tunnel_id\"] ?? \"\");\n const rawData = raw[\"data\"];\n const bytes = rawData instanceof Uint8Array ? rawData : (Buffer.isBuffer(rawData) ? new Uint8Array(rawData) : new Uint8Array());\n const fin = Boolean(raw[\"fin\"]);\n const inflight = this._pendingTunnels.get(tunnelId);\n if (inflight) {\n inflight.pushData(bytes, fin);\n }\n return;\n }\n\n if (data[\"tunnelAck\"] || data[\"tunnel_ack\"]) {\n const raw = (data[\"tunnelAck\"] ?? data[\"tunnel_ack\"]) as Record<string, unknown>;\n const tunnelId = String(raw[\"tunnelId\"] ?? raw[\"tunnel_id\"] ?? \"\");\n const credits = Number(raw[\"credits\"] ?? 0);\n const inflight = this._pendingTunnels.get(tunnelId);\n if (inflight) {\n inflight.addCredits(credits);\n }\n return;\n }\n\n if (data[\"tunnelClose\"] || data[\"tunnel_close\"]) {\n const raw = (data[\"tunnelClose\"] ?? data[\"tunnel_close\"]) as Record<string, unknown>;\n const tunnelId = String(raw[\"tunnelId\"] ?? raw[\"tunnel_id\"] ?? \"\");\n const reason = String(raw[\"reason\"] ?? \"NORMAL\");\n const detail = String(raw[\"detail\"] ?? \"\");\n const inflight = this._pendingTunnels.get(tunnelId);\n if (inflight) {\n inflight.closeWithError(new TunnelClosedError(reason, detail));\n }\n return;\n }\n }\n\n // ===========================================================================\n // Error and Stream End Handling\n // ===========================================================================\n\n /**\n * Handles gRPC stream errors.\n * @internal\n */\n private _handleStreamError(err: Error): void {\n const wasConnected = this._connected;\n this._connected = false;\n\n if (this._disconnectRequested) {\n return;\n }\n\n if (wasConnected) {\n this._onDisconnect(err.message);\n }\n\n // Attempt reconnection if the error is recoverable\n if (this._connectionOpts.autoReconnect && isRecoverable(err)) {\n this._attemptReconnection();\n }\n }\n\n /**\n * Handles gRPC stream end.\n * @internal\n */\n private _handleStreamEnd(): void {\n const wasConnected = this._connected;\n this._connected = false;\n\n if (this._disconnectRequested) {\n return;\n }\n\n if (wasConnected) {\n this._onDisconnect(\"Stream ended\");\n }\n\n if (this._connectionOpts.autoReconnect) {\n this._attemptReconnection();\n }\n }\n\n /**\n * Attempts automatic reconnection with exponential backoff.\n * @internal\n */\n private async _attemptReconnection(): Promise<void> {\n // Prevent concurrent reconnection loops (e.g. both error and end handlers fire)\n if (this._reconnecting) {\n return;\n }\n this._reconnecting = true;\n\n try {\n let delay = this._connectionOpts.initialBackoff;\n const maxRetries = this._connectionOpts.maxRetries;\n\n for (let attempt = 1; maxRetries === 0 || attempt <= maxRetries; attempt++) {\n if (this._disconnectRequested) {\n return;\n }\n\n this._onReconnecting(attempt);\n\n // Wait with backoff\n await new Promise<void>((resolve) => setTimeout(resolve, delay));\n\n if (this._disconnectRequested) {\n return;\n }\n\n try {\n // Clean up old connection before establishing new one\n await this._closeConnection();\n await this._establishConnection();\n this._connected = true;\n\n // Re-send init message is handled inside _establishConnection\n return;\n } catch {\n // Calculate next backoff delay\n delay = Math.min(\n delay * this._connectionOpts.backoffMultiplier,\n this._connectionOpts.maxBackoff,\n );\n // Add jitter (10% random variation)\n delay = delay * (0.9 + Math.random() * 0.2);\n }\n }\n\n // Exhausted all retries\n const err = new ReconnectionError(maxRetries);\n this._onDisconnect(err.message);\n } finally {\n this._reconnecting = false;\n }\n }\n\n // ===========================================================================\n // Progress Reporting\n // ===========================================================================\n\n /**\n * Reports progress for a task through the Aether gateway.\n *\n * Progress updates are routed through RabbitMQ Streams via the pg::{workspace}\n * topic with server-side recipient filtering.\n *\n * @param opts - Progress report options\n * @throws {@link ConnectionError} if not connected\n */\n reportProgress(opts: ReportProgressOptions): void {\n if (!this._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n\n const report: Record<string, unknown> = {\n taskId: opts.taskId,\n state: opts.state ?? \"\",\n completion: opts.completion ?? -1,\n summary: opts.summary ?? \"\",\n recipient: opts.recipient ?? \"\",\n requestId: opts.requestId ?? \"\",\n metadata: opts.metadata ?? {},\n };\n\n if (opts.stepName) {\n report[\"step\"] = {\n name: opts.stepName,\n detail: opts.stepDetail ?? \"\",\n sequence: opts.stepSequence ?? 0,\n totalSteps: opts.stepTotal ?? 0,\n stepType: opts.stepType ?? \"\",\n };\n }\n\n this._sendUpstream({ progressReport: report });\n }\n\n // ===========================================================================\n // Internal Send Helper\n // ===========================================================================\n\n /**\n * Encodes a Metric object to protobuf bytes using the loaded proto descriptor.\n *\n * Uses the `aether.v1.Metric` type from the package definition stored at\n * connection time. Throws if the descriptor is not yet available — sending\n * JSON-encoded bytes here would silently fail on the gateway with\n * ERR_METRIC_INVALID, so we eagerly surface the misuse.\n *\n * @param metric - The metric object to encode\n * @returns Encoded bytes\n * @internal\n */\n protected _encodeMetric(metric: Record<string, unknown>): Uint8Array {\n const pkgDef = this._packageDefinition;\n if (!pkgDef) {\n throw new Error(\"Cannot encode metric: proto descriptor not loaded — call connect() first\");\n }\n const metricType = pkgDef[\"aether.v1.Metric\"] as { encode: (obj: unknown) => { finish: () => Uint8Array } } | undefined;\n if (!metricType?.encode) {\n throw new Error(\"Cannot encode metric: aether.v1.Metric not present in loaded proto descriptor\");\n }\n return metricType.encode(metric).finish();\n }\n\n /**\n * Low-level message send helper used by subclasses.\n * @internal\n */\n protected _sendMessage(targetTopic: string, payload: Uint8Array, messageType: MessageType): void {\n this._sendUpstream({\n send: {\n targetTopic,\n payload,\n messageType,\n },\n });\n }\n\n // ===========================================================================\n // Task Management\n // ===========================================================================\n\n /**\n * Parses a raw task info object from the server into a TaskInfo.\n * @internal\n */\n private _parseTaskInfo(t: Record<string, unknown>): TaskInfo {\n return {\n taskId: String(t[\"taskId\"] ?? t[\"task_id\"] ?? \"\"),\n taskType: String(t[\"taskType\"] ?? t[\"task_type\"] ?? \"\"),\n status: String(t[\"status\"] ?? \"\"),\n workspace: String(t[\"workspace\"] ?? \"\"),\n targetTopic: String(t[\"targetTopic\"] ?? t[\"target_topic\"] ?? \"\"),\n assignedTo: String(t[\"assignedTo\"] ?? t[\"assigned_to\"] ?? \"\"),\n createdAt: Number(t[\"createdAt\"] ?? t[\"created_at\"] ?? 0),\n startedAt: Number(t[\"startedAt\"] ?? t[\"started_at\"] ?? 0),\n completedAt: Number(t[\"completedAt\"] ?? t[\"completed_at\"] ?? 0),\n attempt: Number(t[\"attempt\"] ?? 0),\n maxAttempts: Number(t[\"maxAttempts\"] ?? t[\"max_attempts\"] ?? 0),\n error: String(t[\"error\"] ?? \"\"),\n metadata: (t[\"metadata\"] ?? {}) as Record<string, string>,\n };\n }\n\n /**\n * Parses a raw authority grant object from the server into an AuthorityGrantInfo.\n * @internal\n */\n private _parseAuthorityGrantInfo(g: Record<string, unknown>): AuthorityGrantInfo {\n const parsePrincipalRef = (ref: unknown) => {\n if (!ref || typeof ref !== \"object\") {\n return undefined;\n }\n const value = ref as Record<string, unknown>;\n return {\n principalType: String(value[\"principalType\"] ?? value[\"principal_type\"] ?? \"\"),\n principalId: String(value[\"principalId\"] ?? value[\"principal_id\"] ?? \"\"),\n };\n };\n\n const parseResourceScope = (entry: unknown) => {\n const value = (entry ?? {}) as Record<string, unknown>;\n return {\n resourceType: String(value[\"resourceType\"] ?? value[\"resource_type\"] ?? \"\"),\n patterns: Array.isArray(value[\"patterns\"]) ? (value[\"patterns\"] as unknown[]).map(String) : [],\n };\n };\n\n return {\n grantId: String(g[\"grantId\"] ?? g[\"grant_id\"] ?? \"\"),\n rootGrantId: String(g[\"rootGrantId\"] ?? g[\"root_grant_id\"] ?? \"\"),\n subject: parsePrincipalRef(g[\"subject\"]),\n delegate: parsePrincipalRef(g[\"delegate\"]),\n issuedBy: parsePrincipalRef(g[\"issuedBy\"] ?? g[\"issued_by\"]),\n rootSubject: parsePrincipalRef(g[\"rootSubject\"] ?? g[\"root_subject\"]),\n parentGrantId: String(g[\"parentGrantId\"] ?? g[\"parent_grant_id\"] ?? \"\"),\n mayDelegate: Boolean(g[\"mayDelegate\"] ?? g[\"may_delegate\"]),\n remainingHops: Number(g[\"remainingHops\"] ?? g[\"remaining_hops\"] ?? 0),\n workspaceScope: Array.isArray(g[\"workspaceScope\"] ?? g[\"workspace_scope\"])\n ? ((g[\"workspaceScope\"] ?? g[\"workspace_scope\"]) as unknown[]).map(String)\n : [],\n resourceScope: Array.isArray(g[\"resourceScope\"] ?? g[\"resource_scope\"])\n ? ((g[\"resourceScope\"] ?? g[\"resource_scope\"]) as unknown[]).map(parseResourceScope)\n : [],\n operationScope: Array.isArray(g[\"operationScope\"] ?? g[\"operation_scope\"])\n ? ((g[\"operationScope\"] ?? g[\"operation_scope\"]) as unknown[]).map(String)\n : [],\n maxAccessLevel: Number(g[\"maxAccessLevel\"] ?? g[\"max_access_level\"] ?? 0),\n accessLevelName: String(g[\"accessLevelName\"] ?? g[\"access_level_name\"] ?? \"\"),\n audienceType: String(g[\"audienceType\"] ?? g[\"audience_type\"] ?? \"\"),\n audienceId: String(g[\"audienceId\"] ?? g[\"audience_id\"] ?? \"\"),\n validWhileAudienceActive: Boolean(g[\"validWhileAudienceActive\"] ?? g[\"valid_while_audience_active\"]),\n expiresAt: Number(g[\"expiresAt\"] ?? g[\"expires_at\"] ?? 0),\n renewableUntil: Number(g[\"renewableUntil\"] ?? g[\"renewable_until\"] ?? 0),\n renewedAt: Number(g[\"renewedAt\"] ?? g[\"renewed_at\"] ?? 0),\n revoked: Boolean(g[\"revoked\"]),\n revokedAt: Number(g[\"revokedAt\"] ?? g[\"revoked_at\"] ?? 0),\n reason: String(g[\"reason\"] ?? \"\"),\n metadata: (g[\"metadata\"] ?? {}) as Record<string, string>,\n createdAt: Number(g[\"createdAt\"] ?? g[\"created_at\"] ?? 0),\n };\n }\n\n /**\n * Lists tasks with optional filters.\n */\n queryTasks(opts: TaskQueryOptions = {}): Promise<TaskQueryResponse> {\n const timeout = opts.timeout ?? 10000;\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskQueryRequests.delete(requestId);\n reject(new Error(\"queryTasks timed out\"));\n }, timeout);\n\n this._pendingTaskQueryRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskQuery: {\n op: 0, // LIST\n requestId,\n filter: {\n status: opts.status ?? \"\",\n workspace: opts.workspace ?? \"\",\n taskType: opts.taskType ?? \"\",\n limit: opts.limit ?? 0,\n offset: opts.offset ?? 0,\n },\n },\n });\n });\n }\n\n /**\n * Gets a specific task by ID.\n */\n getTask(taskId: string, timeout = 10000): Promise<TaskQueryResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskQueryRequests.delete(requestId);\n reject(new Error(\"getTask timed out\"));\n }, timeout);\n\n this._pendingTaskQueryRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskQuery: {\n op: 1, // GET\n taskId,\n requestId,\n },\n });\n });\n }\n\n /**\n * Cancels a running or queued task.\n */\n cancelTask(taskId: string, reason = \"\", timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"cancelTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 1, // CANCEL\n taskId,\n reason,\n requestId,\n },\n });\n });\n }\n\n /**\n * Retries a failed task.\n */\n retryTask(taskId: string, timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"retryTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 0, // RETRY\n taskId,\n requestId,\n },\n });\n });\n }\n\n /**\n * Completes a task (for POOL workers).\n */\n completeTask(taskId: string, timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"completeTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 2, // COMPLETE\n taskId,\n requestId,\n },\n });\n });\n }\n\n /**\n * Marks a task as failed (for POOL workers).\n */\n failTask(taskId: string, reason = \"\", timeout = 10000): Promise<TaskOperationResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTaskOpRequests.delete(requestId);\n reject(new Error(\"failTask timed out\"));\n }, timeout);\n\n this._pendingTaskOpRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n taskOp: {\n op: 3, // FAIL\n taskId,\n reason,\n requestId,\n },\n });\n });\n }\n\n // ===========================================================================\n // Create Task (blocking)\n // ===========================================================================\n\n /**\n * Sends a CreateTaskRequest and waits for the server's CreateTaskResponse.\n *\n * A unique request_id is injected automatically so the response can be\n * correlated. Unlike the fire-and-forget `createTask` override in subclasses,\n * this method blocks until the gateway echoes back the assigned task_id.\n *\n * @param op - CreateTaskRequest fields (task_type, workspace, assignment_mode, etc.)\n * @param timeout - Timeout in ms (default 10 000)\n * @returns Promise resolving to the CreateTaskResponse\n */\n createTaskBlocking(op: Record<string, unknown>, timeout = 10000): Promise<CreateTaskResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingCreateTaskRequests.delete(requestId);\n reject(new Error(\"createTaskBlocking timed out\"));\n }, timeout);\n\n this._pendingCreateTaskRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n createTask: { ...op, requestId },\n });\n });\n }\n\n // ===========================================================================\n // Workspace / Agent / ACL / Workflow Operations\n // ===========================================================================\n\n /**\n * Sends a workspace operation upstream.\n *\n * @param op - The workspace operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the workspace response\n */\n sendWorkspaceOperation(op: Record<string, unknown>, timeout = 10000): Promise<WorkspaceResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingWorkspaceRequests.delete(requestId);\n reject(new Error(\"workspace operation timed out\"));\n }, timeout);\n\n this._pendingWorkspaceRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n workspaceOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Sends an agent operation upstream.\n *\n * @param op - The agent operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the agent response\n */\n sendAgentOperation(op: Record<string, unknown>, timeout = 10000): Promise<AgentResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingAgentRequests.delete(requestId);\n reject(new Error(\"agent operation timed out\"));\n }, timeout);\n\n this._pendingAgentRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n agentOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Sends an ACL operation upstream.\n *\n * @param op - The ACL operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the ACL response\n */\n sendACLOperation(op: Record<string, unknown>, timeout = 10000): Promise<ACLResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingACLRequests.delete(requestId);\n reject(new Error(\"ACL operation timed out\"));\n }, timeout);\n\n this._pendingACLRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n aclOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Sends a runtime authority-grant operation upstream.\n *\n * @param op - The authority grant operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the authority-grant response\n */\n sendAuthorityGrantOperation(op: Record<string, unknown>, timeout = 10000): Promise<AuthorityGrantResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingAuthorityGrantRequests.delete(requestId);\n reject(new Error(\"authority grant operation timed out\"));\n }, timeout);\n\n this._pendingAuthorityGrantRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n authorityGrantOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Submits a foreign audit event to the gateway's audit pipeline.\n *\n * @param opts - Audit event fields\n * @param timeout - Timeout in ms (default 10 000)\n * @returns Promise resolving to the audit-submit response\n */\n submitAuditEvent(\n opts: {\n eventType: string;\n operation?: string;\n resourceType?: string;\n resourceId?: string;\n workspace?: string;\n success?: boolean;\n errorMessage?: string;\n metadata?: Record<string, string>;\n },\n timeout = 10000,\n ): Promise<AuditSubmitResponse> {\n const clientRequestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingAuditSubmitRequests.delete(clientRequestId);\n reject(new Error(\"submit audit event timed out\"));\n }, timeout);\n this._pendingAuditSubmitRequests.set(clientRequestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n this._sendUpstream({\n submitAuditEvent: {\n clientRequestId,\n eventType: opts.eventType,\n operation: opts.operation ?? \"\",\n resourceType: opts.resourceType ?? \"\",\n resourceId: opts.resourceId ?? \"\",\n workspace: opts.workspace ?? \"\",\n success: opts.success ?? true,\n errorMessage: opts.errorMessage ?? \"\",\n metadata: opts.metadata ?? {},\n },\n });\n });\n }\n\n /**\n * Sends a workflow operation upstream.\n *\n * @param op - The workflow operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the workflow response\n */\n sendWorkflowOperation(op: Record<string, unknown>, timeout = 10000): Promise<WorkflowResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingWorkflowRequests.delete(requestId);\n reject(new Error(\"workflow operation timed out\"));\n }, timeout);\n\n this._pendingWorkflowRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n workflowOp: { ...op, requestId },\n });\n });\n }\n\n // ===========================================================================\n // Workspace / Agent / ACL / Workflow Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for workspace operation responses.\n *\n * @param handler - Function called when a workspace response is received\n */\n onWorkspaceResponse(handler: WorkspaceResponseHandler): void {\n this._onWorkspaceResponse = handler;\n }\n\n /**\n * Registers a handler for agent operation responses.\n *\n * @param handler - Function called when an agent response is received\n */\n onAgentResponse(handler: AgentResponseHandler): void {\n this._onAgentResponse = handler;\n }\n\n /**\n * Registers a handler for ACL operation responses.\n *\n * @param handler - Function called when an ACL response is received\n */\n onACLResponse(handler: ACLResponseHandler): void {\n this._onACLResponse = handler;\n }\n\n /**\n * Registers a handler for runtime authority-grant responses.\n *\n * @param handler - Function called when an authority-grant response is received\n */\n onAuthorityGrantResponse(handler: AuthorityGrantResponseHandler): void {\n this._onAuthorityGrantResponse = handler;\n }\n\n /**\n * Registers a handler for unsolicited audit-submit responses (i.e. responses\n * not correlated to a pending {@link submitAuditEvent} call).\n *\n * @param handler - Function called when an audit-submit response is received\n */\n onAuditSubmitResponse(handler: AuditSubmitResponseHandler): void {\n this._onAuditSubmitResponse = handler;\n }\n\n /**\n * Registers a handler for server-pushed AuthorityGrantRevocation events.\n * Caches registered via {@link makeAuthorityCache} are invoked first; the\n * user handler runs after every cache has been notified.\n */\n onAuthorityGrantRevocation(handler: AuthorityGrantRevocationHandler): void {\n this._onAuthorityGrantRevocation = handler;\n }\n\n // =========================================================================\n // Authority Grant High-Level Wrappers\n //\n // Low-level: one method per AuthorityGrantOperation op. For ergonomic\n // caching, soft-renew, and revocation invalidation use\n // {@link makeAuthorityCache} and its high-level helpers\n // (getOrExchange / deriveForTask / isValid / listActive /\n // revokeLocal / refresh).\n // =========================================================================\n\n /**\n * Bootstrap a runtime authority grant for the current actor.\n *\n * If `sourceSessionId` is empty, only a user may self-exchange. When it\n * is set, the caller must hold the `_perm:exchange_authority_grants`\n * permission and the referenced session must belong to an active user.\n */\n exchangeAuthorityGrant(\n opts: {\n sourceSessionId?: string;\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n audienceType?: string;\n audienceId?: string;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n } = {},\n ): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"EXCHANGE\",\n exchangeRequest: {\n sourceSessionId: opts.sourceSessionId ?? \"\",\n workspaceScope: opts.workspaceScope ?? [],\n resourceScope: opts.resourceScope ?? [],\n operationScope: opts.operationScope ?? [],\n maxAccessLevel: opts.maxAccessLevel ?? 0,\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n validWhileAudienceActive: opts.validWhileAudienceActive ?? false,\n expiresAt: opts.expiresAt ?? 0,\n renewableUntil: opts.renewableUntil ?? 0,\n mayDelegate: opts.mayDelegate ?? false,\n remainingHops: opts.remainingHops ?? 0,\n reason: opts.reason ?? \"\",\n metadata: opts.metadata ?? {},\n },\n },\n opts.timeout,\n );\n }\n\n /**\n * Derive a child runtime authority grant for a downstream delegate.\n */\n deriveAuthorityGrant(opts: {\n parentGrantId: string;\n delegateType: string;\n delegateId: string;\n workspaceScope?: string[];\n resourceScope?: { resourceType: string; patterns: string[] }[];\n operationScope?: string[];\n maxAccessLevel?: number;\n audienceType?: string;\n audienceId?: string;\n validWhileAudienceActive?: boolean;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n metadata?: Record<string, string>;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"DERIVE\",\n deriveRequest: {\n parentGrantId: opts.parentGrantId,\n delegate: { principalType: opts.delegateType, principalId: opts.delegateId },\n workspaceScope: opts.workspaceScope ?? [],\n resourceScope: opts.resourceScope ?? [],\n operationScope: opts.operationScope ?? [],\n maxAccessLevel: opts.maxAccessLevel ?? 0,\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n validWhileAudienceActive: opts.validWhileAudienceActive ?? false,\n expiresAt: opts.expiresAt ?? 0,\n renewableUntil: opts.renewableUntil ?? 0,\n mayDelegate: opts.mayDelegate ?? false,\n remainingHops: opts.remainingHops ?? 0,\n reason: opts.reason ?? \"\",\n metadata: opts.metadata ?? {},\n },\n },\n opts.timeout,\n );\n }\n\n /** Get a runtime authority grant by ID. */\n getAuthorityGrant(grantId: string, timeout?: number): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation({ op: \"GET\", grantId }, timeout);\n }\n\n /**\n * Renew a runtime authority grant lease. `expiresAt` (proto units) takes\n * precedence; `extendSeconds` extends the current expiry by N seconds\n * server-side and is ignored when `expiresAt` is non-zero.\n */\n renewAuthorityGrant(opts: {\n grantId: string;\n expiresAt?: number;\n extendSeconds?: number;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"RENEW\",\n grantId: opts.grantId,\n renewRequest: {\n grantId: opts.grantId,\n expiresAt: opts.expiresAt ?? 0,\n extendSeconds: opts.extendSeconds ?? 0,\n },\n },\n opts.timeout,\n );\n }\n\n /** Revoke a runtime authority grant by ID. */\n revokeAuthorityGrant(grantId: string, timeout?: number): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation({ op: \"REVOKE\", grantId }, timeout);\n }\n\n /** List grants where the actor is delegate or subject. */\n listMyAuthorityGrants(opts: {\n audienceType?: string;\n audienceId?: string;\n includeRevoked?: boolean;\n limit?: number;\n offset?: number;\n timeout?: number;\n } = {}): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"LIST_MY_GRANTS\",\n listRequest: {\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n includeRevoked: opts.includeRevoked ?? false,\n limit: opts.limit ?? 0,\n offset: opts.offset ?? 0,\n },\n },\n opts.timeout,\n );\n }\n\n /** List grants where the actor is the subject (i.e., grants OTHERS hold on me). */\n listAuthorityGrantsOnMe(opts: {\n audienceType?: string;\n audienceId?: string;\n includeRevoked?: boolean;\n limit?: number;\n offset?: number;\n timeout?: number;\n } = {}): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"LIST_GRANTS_ON_ME\",\n listRequest: {\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n includeRevoked: opts.includeRevoked ?? false,\n limit: opts.limit ?? 0,\n offset: opts.offset ?? 0,\n },\n },\n opts.timeout,\n );\n }\n\n /** Exchange multiple authority grants in a single round-trip. */\n batchExchangeAuthorityGrants(opts: {\n requests: Record<string, unknown>[];\n stopOnFirstError?: boolean;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"BATCH_EXCHANGE\",\n batchExchangeRequest: {\n requests: opts.requests,\n stopOnFirstError: opts.stopOnFirstError ?? false,\n },\n },\n opts.timeout,\n );\n }\n\n /**\n * Idempotent derive: returns existing visible grant matching\n * (parentGrantId, target, audience) or mints a new one.\n *\n * Safe to call repeatedly without leaking grants.\n */\n deriveAuthorityGrantForTarget(opts: {\n parentGrantId: string;\n targetType: string;\n targetId: string;\n audienceType?: string;\n audienceId?: string;\n operationScope?: string[];\n maxAccessLevel?: number;\n expiresAt?: number;\n renewableUntil?: number;\n mayDelegate?: boolean;\n remainingHops?: number;\n reason?: string;\n timeout?: number;\n }): Promise<AuthorityGrantResponse> {\n return this.sendAuthorityGrantOperation(\n {\n op: \"DERIVE_FOR_TARGET\",\n deriveForTargetRequest: {\n parentGrantId: opts.parentGrantId,\n target: { principalType: opts.targetType, principalId: opts.targetId },\n audienceType: opts.audienceType ?? \"\",\n audienceId: opts.audienceId ?? \"\",\n operationScope: opts.operationScope ?? [],\n maxAccessLevel: opts.maxAccessLevel ?? 0,\n expiresAt: opts.expiresAt ?? 0,\n renewableUntil: opts.renewableUntil ?? 0,\n mayDelegate: opts.mayDelegate ?? false,\n remainingHops: opts.remainingHops ?? 0,\n reason: opts.reason ?? \"\",\n },\n },\n opts.timeout,\n );\n }\n\n /**\n * Construct a new {@link AuthorityGrantCache} wired into this client.\n * AuthorityGrantRevocation push events on the downstream stream are\n * dispatched to the cache automatically. Call {@link AuthorityGrantCache.close}\n * to deregister it.\n */\n makeAuthorityCache(opts: AuthorityGrantCacheOptions = {}): AuthorityGrantCache {\n const cache = new AuthorityGrantCache(this, opts);\n this._authorityGrantCaches.push(cache);\n return cache;\n }\n\n /** @internal */\n _removeAuthorityCache(cache: AuthorityGrantCache): void {\n this._authorityGrantCaches = this._authorityGrantCaches.filter((c) => c !== cache);\n }\n\n /**\n * Registers a handler for workflow operation responses.\n *\n * @param handler - Function called when a workflow response is received\n */\n onWorkflowResponse(handler: WorkflowResponseHandler): void {\n this._onWorkflowResponse = handler;\n }\n\n /**\n * Sends a token management operation to the gateway.\n *\n * @param op - The token operation payload\n * @param timeout - Timeout in ms\n * @returns Promise resolving to the token response\n */\n sendTokenOperation(op: Record<string, unknown>, timeout = 10000): Promise<TokenResponse> {\n const requestId = this.nextRequestId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingTokenRequests.delete(requestId);\n reject(new Error(\"token operation timed out\"));\n }, timeout);\n\n this._pendingTokenRequests.set(requestId, (response) => {\n clearTimeout(timer);\n resolve(response);\n });\n\n this._sendUpstream({\n tokenOp: { ...op, requestId },\n });\n });\n }\n\n /**\n * Registers a handler for token operation responses.\n *\n * @param handler - Function called when a token response is received\n */\n onTokenResponse(handler: TokenResponseHandler): void {\n this._onTokenResponse = handler;\n }\n}\n","/**\n * Admin client for the Aether TypeScript SDK.\n *\n * AdminClient wraps a connected AetherClient and provides named helper methods\n * for all administrative operations exposed through the gRPC streaming protocol:\n * token management, ACL rules, workspace CRUD, agent registry, and gateway\n * health / connection queries.\n *\n * The underlying AetherClient must already be connected before calling any\n * AdminClient method. All methods return Promises that resolve when the\n * gateway sends the correlated response, or reject on timeout.\n *\n * @module admin\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type {\n TokenResponse,\n ACLResponse,\n WorkspaceResponse,\n AgentResponse,\n} from \"./types.js\";\n\n// =============================================================================\n// Shared option types\n// =============================================================================\n\n/** Timeout option shared by all admin methods. */\nexport interface AdminTimeoutOptions {\n /** Operation timeout in milliseconds. Default: 10000. */\n timeout?: number;\n}\n\n// =============================================================================\n// Token operation types\n// =============================================================================\n\n/** Options for creating an API token. */\nexport interface CreateTokenOptions extends AdminTimeoutOptions {\n /** Human-readable name for the token. Required. */\n name: string;\n /** Principal type this token authenticates (e.g., \"agent\", \"user\"). */\n principalType?: string;\n /** Glob patterns for workspaces this token may access. */\n workspacePatterns?: string[];\n /** Permission scopes granted by this token. */\n scopes?: string[];\n /** Expiry duration in seconds from now (0 = no expiry). */\n expiresInSeconds?: number;\n}\n\n/** Options for revoking an API token. */\nexport interface RevokeTokenOptions extends AdminTimeoutOptions {\n /** Token ID to revoke. Required. */\n tokenId: string;\n}\n\n/** Options for listing API tokens. */\nexport interface ListTokensOptions extends AdminTimeoutOptions {\n /** Filter by principal type. */\n principalType?: string;\n /** If true, include revoked tokens in results. */\n includeRevoked?: boolean;\n /** Maximum number of results to return. */\n limit?: number;\n}\n\n// =============================================================================\n// ACL operation types\n// =============================================================================\n\n/** Options for creating an ACL rule (granting access). */\nexport interface CreateACLRuleOptions extends AdminTimeoutOptions {\n /** Principal type being granted access (e.g., \"agent\", \"user\"). Required. */\n principalType: string;\n /** Principal ID being granted access. Required. */\n principalId: string;\n /** Resource type the access applies to (e.g., \"workspace\"). Required. */\n resourceType: string;\n /** Resource ID the access applies to. Required. */\n resourceId: string;\n /** Permission level (e.g., \"read\", \"write\", \"admin\"). Required. */\n permission: string;\n /** Optional expiry as Unix timestamp (seconds). 0 = no expiry. */\n expiresAt?: number;\n /** Arbitrary metadata to attach to the rule. */\n metadata?: Record<string, string>;\n}\n\n/** Options for deleting an ACL rule. */\nexport interface DeleteACLRuleOptions extends AdminTimeoutOptions {\n /** Rule ID to delete. Required. */\n ruleId: string;\n}\n\n/** Options for listing ACL rules. */\nexport interface ListACLRulesOptions extends AdminTimeoutOptions {\n /** Filter by principal type. */\n principalType?: string;\n /** Filter by principal ID. */\n principalId?: string;\n /** Filter by resource type. */\n resourceType?: string;\n /** Filter by resource ID. */\n resourceId?: string;\n}\n\n/** Options for reading a fallback policy by category. */\nexport interface GetFallbackPolicyOptions extends AdminTimeoutOptions {\n /**\n * Rule category, formatted as \"{principal_type}_{resource_type}\" (e.g.,\n * \"user_workspace\", \"agent_kv_scope\", \"service_kv_scope\").\n */\n ruleCategory: string;\n}\n\n/** Options for upserting a fallback policy. */\nexport interface SetFallbackPolicyOptions extends AdminTimeoutOptions {\n /** Rule category to upsert. */\n ruleCategory: string;\n /**\n * Default access level when no explicit acl_rules row matches. Use the\n * numeric tiers from internal/acl/types.go: 0=NONE, 10=READ, 20=READWRITE,\n * 30=MANAGE, 40=ADMIN, 50=SUPERADMIN.\n */\n fallbackAccessLevel: number;\n}\n\n/** Principal reference used by authority-grant admin operations. */\nexport interface AuthorityGrantPrincipalRef {\n principalType: string;\n principalId: string;\n}\n\n/** Resource-specific scope entry for authority grants. */\nexport interface AuthorityGrantResourceScope {\n resourceType: string;\n patterns: string[];\n}\n\n// NOTE: ListAuthorityGrantsOptions / GetAuthorityGrantOptions /\n// CreateAuthorityGrantOptions / RenewAuthorityGrantOptions /\n// RevokeAuthorityGrantOptions were removed alongside the corresponding\n// streaming-admin methods. The streaming ACLOperation no longer carries\n// authority-grant ops; use the runtime AuthorityGrantOperation surface\n// (Phase 4 SDK cache helpers) or the REST admin endpoints for management.\n\n// =============================================================================\n// Workspace operation types\n// =============================================================================\n\n/** Options for listing workspaces. */\nexport interface ListWorkspacesOptions extends AdminTimeoutOptions {\n /** Maximum number of results to return. */\n limit?: number;\n /** Offset for pagination. */\n offset?: number;\n}\n\n/** Data for creating a workspace. */\nexport interface CreateWorkspaceOptions extends AdminTimeoutOptions {\n /** Workspace ID (the string identifier). Required. */\n workspaceId: string;\n /** Human-readable display name. */\n displayName?: string;\n /** Arbitrary metadata. */\n metadata?: Record<string, string>;\n}\n\n/** Data for updating a workspace. */\nexport interface UpdateWorkspaceOptions extends AdminTimeoutOptions {\n /** Workspace ID to update. Required. */\n workspaceId: string;\n /** New display name. */\n displayName?: string;\n /** Updated metadata. */\n metadata?: Record<string, string>;\n}\n\n/** Options for deleting a workspace. */\nexport interface DeleteWorkspaceOptions extends AdminTimeoutOptions {\n /** Workspace ID to delete. Required. */\n workspaceId: string;\n}\n\n// =============================================================================\n// Agent operation types\n// =============================================================================\n\n/** Options for listing registered agent types. */\nexport interface ListAgentsOptions extends AdminTimeoutOptions {\n /** Filter by workspace. */\n workspace?: string;\n /** Maximum number of results to return. */\n limit?: number;\n}\n\n/** Options for getting a specific agent registration. */\nexport interface GetAgentOptions extends AdminTimeoutOptions {\n /** The agent implementation name. Required. */\n implementation: string;\n}\n\n// =============================================================================\n// Admin query types\n// =============================================================================\n\n/** Response from admin queries. Loosely typed to accommodate the AdminResponse oneof. */\nexport interface AdminQueryResponse {\n readonly success: boolean;\n readonly error: string;\n readonly health?: Record<string, unknown>;\n readonly info?: Record<string, unknown>;\n readonly stats?: Record<string, unknown>;\n readonly connection?: Record<string, unknown>;\n readonly connections?: Record<string, unknown>[];\n readonly totalCount: number;\n}\n\n/** Handler type for admin query responses. */\nexport type AdminQueryResponseHandler = (response: AdminQueryResponse) => void | Promise<void>;\n\n/** Options for listing connections. */\nexport interface ListConnectionsOptions extends AdminTimeoutOptions {\n /** Filter by workspace. */\n workspace?: string;\n /** Filter by principal type. */\n principalType?: string;\n}\n\n/** Options for disconnecting a session. */\nexport interface DisconnectSessionOptions extends AdminTimeoutOptions {\n /** Session ID to disconnect. Required. */\n sessionId: string;\n /** Optional reason message sent to the disconnected client. */\n reason?: string;\n}\n\n// =============================================================================\n// AdminClient\n// =============================================================================\n\n/**\n * Administrative client for managing an Aether gateway.\n *\n * AdminClient wraps any connected {@link AetherClient} (typically an\n * AgentClient or UserClient) and exposes named helper methods for the full\n * set of administrative operations that are available through the gRPC\n * streaming protocol.\n *\n * @example\n * ```typescript\n * import { AgentClient, AdminClient } from \"@scitrera/aether-client\";\n *\n * const agent = new AgentClient({\n * address: \"localhost:50051\",\n * workspace: \"default\",\n * implementation: \"admin-agent\",\n * specifier: \"ops-1\",\n * credentials: { \"x-api-key\": \"my-admin-key\" },\n * });\n * await agent.connect();\n *\n * const admin = new AdminClient(agent);\n *\n * // List workspaces\n * const wsr = await admin.listWorkspaces();\n * console.log(wsr);\n *\n * // Create a token\n * const tr = await admin.createToken({ name: \"ci-token\", principalType: \"agent\" });\n * console.log(tr.plaintextToken);\n * ```\n */\nexport class AdminClient {\n private readonly _client: AetherClient;\n\n /**\n * Creates an AdminClient backed by the given AetherClient.\n *\n * The AetherClient must be connected before calling any method.\n *\n * @param client - A connected AetherClient instance\n */\n constructor(client: AetherClient) {\n this._client = client;\n }\n\n // ===========================================================================\n // Token Operations\n // ===========================================================================\n\n /**\n * Creates a new API token.\n *\n * @param opts - Token creation parameters\n * @returns Promise resolving to the token response (includes plaintextToken)\n */\n createToken(opts: CreateTokenOptions): Promise<TokenResponse> {\n const { timeout, name, principalType, workspacePatterns, scopes, expiresInSeconds } = opts;\n return this._client.sendTokenOperation(\n {\n op: \"CREATE\",\n createRequest: {\n name,\n principalType: principalType ?? \"\",\n workspacePatterns: workspacePatterns ?? [],\n scopes: scopes ?? [],\n expiresInSeconds: expiresInSeconds ?? 0,\n },\n },\n timeout,\n );\n }\n\n /**\n * Revokes an API token by ID.\n *\n * @param opts - Revoke options containing the token ID\n * @returns Promise resolving to the token response\n */\n revokeToken(opts: RevokeTokenOptions): Promise<TokenResponse> {\n const { timeout, tokenId } = opts;\n return this._client.sendTokenOperation({ op: \"REVOKE\", tokenId }, timeout);\n }\n\n /**\n * Lists API tokens with optional filters.\n *\n * @param opts - List options\n * @returns Promise resolving to the token response (tokens array)\n */\n listTokens(opts: ListTokensOptions = {}): Promise<TokenResponse> {\n const { timeout, principalType, includeRevoked, limit } = opts;\n return this._client.sendTokenOperation(\n {\n op: \"LIST\",\n filter: {\n principalType: principalType ?? \"\",\n includeRevoked: includeRevoked ?? false,\n limit: limit ?? 0,\n },\n },\n timeout,\n );\n }\n\n // ===========================================================================\n // ACL Operations\n // ===========================================================================\n\n /**\n * Creates an ACL rule granting access.\n *\n * @param opts - ACL rule creation parameters\n * @returns Promise resolving to the ACL response\n */\n createACLRule(opts: CreateACLRuleOptions): Promise<ACLResponse> {\n const { timeout, principalType, principalId, resourceType, resourceId, permission, expiresAt, metadata } = opts;\n return this._client.sendACLOperation(\n {\n op: \"GRANT\",\n grantRequest: {\n principalType,\n principalId,\n resourceType,\n resourceId,\n permission,\n expiresAt: expiresAt ?? 0,\n metadata: metadata ?? {},\n },\n },\n timeout,\n );\n }\n\n /**\n * Deletes an ACL rule by ID.\n *\n * @param opts - Delete options containing the rule ID\n * @returns Promise resolving to the ACL response\n */\n deleteACLRule(opts: DeleteACLRuleOptions): Promise<ACLResponse> {\n const { timeout, ruleId } = opts;\n return this._client.sendACLOperation({ op: \"REVOKE\", ruleId }, timeout);\n }\n\n /**\n * Lists ACL rules with optional filters.\n *\n * @param opts - List options\n * @returns Promise resolving to the ACL response (rules array in response)\n */\n listACLRules(opts: ListACLRulesOptions = {}): Promise<ACLResponse> {\n const { timeout, principalType, principalId, resourceType, resourceId } = opts;\n return this._client.sendACLOperation(\n {\n op: \"LIST_RULES\",\n ruleFilter: {\n principalType: principalType ?? \"\",\n principalId: principalId ?? \"\",\n resourceType: resourceType ?? \"\",\n resourceId: resourceId ?? \"\",\n },\n },\n timeout,\n );\n }\n\n /**\n * Reads the fallback policy for a rule category.\n *\n * Fallback policies decide the default ACL outcome when no explicit\n * `acl_rules` row matches the (principal_type, resource_type) pair.\n * The `ruleCategory` is the catonical\n * `{principal_type}_{resource_type}` slug — e.g., \"agent_kv_scope\".\n */\n getFallbackPolicy(opts: GetFallbackPolicyOptions): Promise<ACLResponse> {\n const { timeout, ruleCategory } = opts;\n return this._client.sendACLOperation(\n { op: \"GET_FALLBACK_POLICY\", ruleCategory },\n timeout,\n );\n }\n\n /**\n * Upserts a fallback policy for a rule category.\n *\n * Use ``fallbackAccessLevel: 0`` to flip a category to default-deny.\n */\n setFallbackPolicy(opts: SetFallbackPolicyOptions): Promise<ACLResponse> {\n const { timeout, ruleCategory, fallbackAccessLevel } = opts;\n return this._client.sendACLOperation(\n {\n op: \"SET_FALLBACK_POLICY\",\n ruleCategory,\n fallbackRequest: {\n ruleCategory,\n fallbackAccessLevel,\n },\n },\n timeout,\n );\n }\n\n // NOTE: listAuthorityGrants / getAuthorityGrant / createAuthorityGrant /\n // renewAuthorityGrant / revokeAuthorityGrant were removed alongside the\n // corresponding streaming ACLOperation cases. Use the runtime\n // AuthorityGrantOperation surface (Phase 4 SDK cache helpers) or the\n // REST admin endpoints for management.\n\n // ===========================================================================\n // Workspace Operations\n // ===========================================================================\n\n /**\n * Lists workspaces.\n *\n * @param opts - List options\n * @returns Promise resolving to the workspace response\n */\n listWorkspaces(opts: ListWorkspacesOptions = {}): Promise<WorkspaceResponse> {\n const { timeout, limit, offset } = opts;\n return this._client.sendWorkspaceOperation(\n {\n op: \"LIST\",\n filter: { limit: limit ?? 0, offset: offset ?? 0 },\n },\n timeout,\n );\n }\n\n /**\n * Creates a new workspace.\n *\n * @param opts - Workspace creation parameters\n * @returns Promise resolving to the workspace response\n */\n createWorkspace(opts: CreateWorkspaceOptions): Promise<WorkspaceResponse> {\n const { timeout, workspaceId, displayName, metadata } = opts;\n return this._client.sendWorkspaceOperation(\n {\n op: \"CREATE\",\n workspace: {\n workspaceId,\n displayName: displayName ?? \"\",\n metadata: metadata ?? {},\n },\n },\n timeout,\n );\n }\n\n /**\n * Updates an existing workspace.\n *\n * @param opts - Workspace update parameters\n * @returns Promise resolving to the workspace response\n */\n updateWorkspace(opts: UpdateWorkspaceOptions): Promise<WorkspaceResponse> {\n const { timeout, workspaceId, displayName, metadata } = opts;\n return this._client.sendWorkspaceOperation(\n {\n op: \"UPDATE\",\n workspaceId,\n workspace: {\n workspaceId,\n displayName: displayName ?? \"\",\n metadata: metadata ?? {},\n },\n },\n timeout,\n );\n }\n\n /**\n * Deletes a workspace by ID.\n *\n * @param opts - Delete options containing the workspace ID\n * @returns Promise resolving to the workspace response\n */\n deleteWorkspace(opts: DeleteWorkspaceOptions): Promise<WorkspaceResponse> {\n const { timeout, workspaceId } = opts;\n return this._client.sendWorkspaceOperation({ op: \"DELETE\", workspaceId }, timeout);\n }\n\n // ===========================================================================\n // Agent Operations\n // ===========================================================================\n\n /**\n * Lists registered agent types.\n *\n * @param opts - List options\n * @returns Promise resolving to the agent response\n */\n listAgents(opts: ListAgentsOptions = {}): Promise<AgentResponse> {\n const { timeout, workspace, limit } = opts;\n return this._client.sendAgentOperation(\n {\n op: \"LIST\",\n filter: {\n workspace: workspace ?? \"\",\n limit: limit ?? 0,\n },\n },\n timeout,\n );\n }\n\n /**\n * Gets the registration details for a specific agent implementation.\n *\n * @param opts - Options including the implementation name\n * @returns Promise resolving to the agent response\n */\n getAgent(opts: GetAgentOptions): Promise<AgentResponse> {\n const { timeout, implementation } = opts;\n return this._client.sendAgentOperation({ op: \"GET\", implementation }, timeout);\n }\n\n // ===========================================================================\n // Admin Queries (health, connections)\n // ===========================================================================\n\n /**\n * Queries gateway health, including component status for Redis, RabbitMQ,\n * and PostgreSQL.\n *\n * Note: This sends a GET_HEALTH admin query through the gRPC stream.\n * The gateway must have admin-over-stream enabled.\n *\n * @param timeout - Timeout in milliseconds (default: 10000)\n * @returns Promise resolving to the admin query response\n */\n getHealth(timeout?: number): Promise<AdminQueryResponse> {\n return this._client\n .sendWorkspaceOperation({ _adminQuery: \"GET_HEALTH\" }, timeout)\n .then((r) => ({\n success: r.success,\n error: r.error,\n health: r[\"health\"] as Record<string, unknown> | undefined,\n info: undefined,\n stats: undefined,\n connection: undefined,\n connections: undefined,\n totalCount: 0,\n }));\n }\n\n /**\n * Lists active connections on the gateway.\n *\n * @param opts - Optional filter and timeout options\n * @returns Promise resolving to the admin query response (connections array)\n */\n getConnections(opts: ListConnectionsOptions = {}): Promise<AdminQueryResponse> {\n const { timeout, workspace, principalType } = opts;\n return this._client\n .sendWorkspaceOperation(\n {\n _adminQuery: \"LIST_CONNECTIONS\",\n filter: {\n workspace: workspace ?? \"\",\n principalType: principalType ?? \"\",\n },\n },\n timeout,\n )\n .then((r) => ({\n success: r.success,\n error: r.error,\n health: undefined,\n info: undefined,\n stats: undefined,\n connection: undefined,\n connections: r[\"connections\"] as Record<string, unknown>[] | undefined,\n totalCount: r.totalCount,\n }));\n }\n\n /**\n * Forcibly disconnects a session by session ID.\n *\n * @param opts - Options containing the session ID and optional reason\n * @returns Promise resolving to the workspace response\n */\n disconnectSession(opts: DisconnectSessionOptions): Promise<WorkspaceResponse> {\n const { timeout, sessionId, reason } = opts;\n return this._client.sendWorkspaceOperation(\n {\n _sessionOp: \"DISCONNECT\",\n sessionId,\n reason: reason ?? \"\",\n },\n timeout,\n );\n }\n}\n","/**\n * Topic construction helpers for the Aether TypeScript SDK.\n *\n * This module provides helper functions for constructing topic strings used\n * for message routing in the Aether system. Topics follow a structured\n * format that identifies the principal type and location.\n *\n * Segment separator is \"::\" (not \".\") so field values can legitimately\n * contain \".\" — e.g. Python FQN implementations\n * (\"scitrera_ai_runtime.cowork.aether_bridge.CoworkAgent\") or email-style\n * user_ids (\"alice@example.com\") — without the parser ambiguity that a\n * dotted separator would create.\n *\n * Topic Schema:\n * - ag::{workspace}::{impl}::{spec} - Specific agent instance\n * - tu::{workspace}::{impl}::{spec} - Unique task (named)\n * - ta::{workspace}::{impl}::{id} - Non-unique task instance (server-assigned ID)\n * - tb::{workspace}::{impl} - Task broadcast (load-balancing)\n * - us::{user_id}::{window_id} - User window-specific messages\n * - uw::{user_id}::{workspace} - User workspace-scoped messages\n * - ga::{workspace} - Global agent broadcast in workspace\n * - gu::{workspace} - Global user broadcast in workspace\n * - event::* - Workflow Engine only (broadcast events)\n * - metric::* - Metrics Bridge only (telemetry ingestion)\n *\n * @module topics\n */\n\n// =============================================================================\n// Identity Separator\n// =============================================================================\n\n/**\n * Segment separator for all identity / topic strings. Must match\n * server/pkg/models/topics.go::IdentitySep and the Python SDK's IDENTITY_SEP.\n */\nexport const IDENTITY_SEP = \"::\";\n\n// =============================================================================\n// Topic Prefixes\n// =============================================================================\n\n/** Prefix for agent topics. */\nexport const TOPIC_PREFIX_AGENT = \"ag\";\n\n/** Prefix for unique task topics. */\nexport const TOPIC_PREFIX_UNIQUE_TASK = \"tu\";\n\n/** Prefix for non-unique task topics. */\nexport const TOPIC_PREFIX_TASK = \"ta\";\n\n/** Prefix for task broadcast topics. */\nexport const TOPIC_PREFIX_TASK_BROADCAST = \"tb\";\n\n/** Prefix for user session topics. */\nexport const TOPIC_PREFIX_USER = \"us\";\n\n/** Prefix for user workspace topics. */\nexport const TOPIC_PREFIX_USER_WORKSPACE = \"uw\";\n\n/** Prefix for global agent broadcast topics. */\nexport const TOPIC_PREFIX_GLOBAL_AGENTS = \"ga\";\n\n/** Prefix for global user broadcast topics. */\nexport const TOPIC_PREFIX_GLOBAL_USERS = \"gu\";\n\n/** Prefix for event topics (workflow engine). */\nexport const TOPIC_PREFIX_EVENT = \"event\";\n\n/** Prefix for metric topics (metrics bridge). */\nexport const TOPIC_PREFIX_METRIC = \"metric\";\n\n/** Prefix for progress stream topics. */\nexport const TOPIC_PREFIX_PROGRESS = \"pg\";\n\n/** Prefix for bridge topics. */\nexport const TOPIC_PREFIX_BRIDGE = \"br\";\n\n// =============================================================================\n// Topic Construction Helpers - Agents\n// =============================================================================\n\n/**\n * Creates a topic string for a specific agent.\n *\n * @param workspace - The agent's workspace\n * @param implementation - The agent's implementation type\n * @param specifier - The agent's unique specifier\n * @returns Topic string in format: ag::{workspace}::{implementation}::{specifier}\n *\n * @example\n * ```typescript\n * const topic = agentTopic(\"prod\", \"data-processor\", \"instance-1\");\n * // Returns: \"ag::prod::data-processor::instance-1\"\n * ```\n */\nexport function agentTopic(workspace: string, implementation: string, specifier: string): string {\n return `${TOPIC_PREFIX_AGENT}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${specifier}`;\n}\n\n/**\n * Creates a broadcast topic for all agents in a workspace.\n *\n * @param workspace - The workspace to broadcast to\n * @returns Topic string in format: ga::{workspace}\n */\nexport function globalAgentsTopic(workspace: string): string {\n return `${TOPIC_PREFIX_GLOBAL_AGENTS}${IDENTITY_SEP}${workspace}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - Tasks\n// =============================================================================\n\n/**\n * Creates a topic string for a unique (named) task.\n *\n * @param workspace - The task's workspace\n * @param implementation - The task's implementation type\n * @param specifier - The task's unique specifier\n * @returns Topic string in format: tu::{workspace}::{implementation}::{specifier}\n */\nexport function uniqueTaskTopic(workspace: string, implementation: string, specifier: string): string {\n return `${TOPIC_PREFIX_UNIQUE_TASK}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${specifier}`;\n}\n\n/**\n * Creates a topic string for a non-unique task instance.\n *\n * @param workspace - The task's workspace\n * @param implementation - The task's implementation type\n * @param id - The server-assigned task instance ID\n * @returns Topic string in format: ta::{workspace}::{implementation}::{id}\n */\nexport function taskTopic(workspace: string, implementation: string, id: string): string {\n return `${TOPIC_PREFIX_TASK}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${id}`;\n}\n\n/**\n * Creates a broadcast topic for task load balancing.\n *\n * Non-unique tasks subscribe to this topic to receive work items that can\n * be claimed by any available worker of that implementation type.\n *\n * @param workspace - The task's workspace\n * @param implementation - The task's implementation type\n * @returns Topic string in format: tb::{workspace}::{implementation}\n */\nexport function taskBroadcastTopic(workspace: string, implementation: string): string {\n return `${TOPIC_PREFIX_TASK_BROADCAST}${IDENTITY_SEP}${workspace}${IDENTITY_SEP}${implementation}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - Users\n// =============================================================================\n\n/**\n * Creates a topic string for a user session.\n *\n * @param userId - The user's unique identifier\n * @param windowId - The window/session identifier\n * @returns Topic string in format: us::{userId}::{windowId}\n */\nexport function userTopic(userId: string, windowId: string): string {\n return `${TOPIC_PREFIX_USER}${IDENTITY_SEP}${userId}${IDENTITY_SEP}${windowId}`;\n}\n\n/**\n * Creates a topic string for user workspace messages.\n *\n * Messages sent to this topic reach a specific user regardless of which\n * window/tab they are using.\n *\n * @param userId - The user's unique identifier\n * @param workspace - The workspace\n * @returns Topic string in format: uw::{userId}::{workspace}\n */\nexport function userWorkspaceTopic(userId: string, workspace: string): string {\n return `${TOPIC_PREFIX_USER_WORKSPACE}${IDENTITY_SEP}${userId}${IDENTITY_SEP}${workspace}`;\n}\n\n/**\n * Creates a broadcast topic for all users in a workspace.\n *\n * @param workspace - The workspace to broadcast to\n * @returns Topic string in format: gu::{workspace}\n */\nexport function globalUsersTopic(workspace: string): string {\n return `${TOPIC_PREFIX_GLOBAL_USERS}${IDENTITY_SEP}${workspace}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - System Topics\n// =============================================================================\n\n/**\n * Creates a topic string for broadcast events.\n *\n * @param eventType - The event type identifier\n * @returns Topic string in format: event::{eventType}\n */\nexport function eventTopic(eventType: string): string {\n return `${TOPIC_PREFIX_EVENT}${IDENTITY_SEP}${eventType}`;\n}\n\n/**\n * Returns the wildcard pattern for all events.\n *\n * This is the topic that Workflow Engines subscribe to.\n *\n * @returns \"event::*\"\n */\nexport function eventWildcardTopic(): string {\n return `${TOPIC_PREFIX_EVENT}${IDENTITY_SEP}*`;\n}\n\n/**\n * Creates a topic string for telemetry/metrics.\n *\n * @param metricType - The metric type identifier\n * @returns Topic string in format: metric::{metricType}\n */\nexport function metricTopic(metricType: string): string {\n return `${TOPIC_PREFIX_METRIC}${IDENTITY_SEP}${metricType}`;\n}\n\n/**\n * Returns the wildcard pattern for all metrics.\n *\n * This is the topic that Metrics Bridges subscribe to.\n *\n * @returns \"metric::*\"\n */\nexport function metricWildcardTopic(): string {\n return `${TOPIC_PREFIX_METRIC}${IDENTITY_SEP}*`;\n}\n\n/**\n * Creates a topic string for workspace progress updates.\n *\n * Progress updates from agents and tasks in a workspace are published to this\n * topic. Users and agents subscribe to it with server-side recipient filtering.\n *\n * @param workspace - The workspace\n * @returns Topic string in format: pg::{workspace}\n */\nexport function progressTopic(workspace: string): string {\n return `${TOPIC_PREFIX_PROGRESS}${IDENTITY_SEP}${workspace}`;\n}\n\n// =============================================================================\n// Topic Construction Helpers - Bridges\n// =============================================================================\n\n/**\n * Creates a topic string for a specific bridge instance.\n *\n * Bridges are cross-workspace principals identified only by implementation\n * and specifier (no workspace component).\n *\n * @param implementation - The bridge implementation type (e.g., \"aether-msgbridge\")\n * @param specifier - The bridge's unique specifier (e.g., \"discord-1\")\n * @returns Topic string in format: br::{implementation}::{specifier}\n *\n * @example\n * ```typescript\n * const topic = bridgeTopic(\"aether-msgbridge\", \"discord-1\");\n * // Returns: \"br::aether-msgbridge::discord-1\"\n * ```\n */\nexport function bridgeTopic(implementation: string, specifier: string): string {\n return `${TOPIC_PREFIX_BRIDGE}${IDENTITY_SEP}${implementation}${IDENTITY_SEP}${specifier}`;\n}","/**\n * Agent client implementation for the Aether TypeScript SDK.\n *\n * This module provides the AgentClient class for connecting to the Aether\n * gateway as an agent. Agents are persistent entities with\n * workspace/implementation/specifier identity that can send and receive\n * messages, manage state, and participate in task orchestration.\n *\n * @module agents\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType, TaskAssignmentMode } from \"./types.js\";\nimport type { MessageHandler } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n globalAgentsTopic,\n globalUsersTopic,\n eventWildcardTopic,\n metricWildcardTopic,\n} from \"./topics.js\";\nimport type { Metric } from \"./metrics-builder.js\";\n\n// =============================================================================\n// Agent Client Options\n// =============================================================================\n\n/**\n * Configuration options for the AgentClient.\n */\nexport interface AgentClientOptions extends AetherClientOptions {\n /** The workspace to connect to. Required. */\n workspace: string;\n /** The agent implementation type. Required. */\n implementation: string;\n /** The unique specifier for this agent instance. Required. */\n specifier: string;\n}\n\n// =============================================================================\n// Task Creation Options\n// =============================================================================\n\n/**\n * Options for creating a task.\n */\nexport interface CreateTaskOptions {\n /** The type of task to create. Required. */\n taskType: string;\n /** The workspace for the task. If empty, uses the agent's workspace. */\n workspace?: string;\n /** For TARGETED mode: the agent to assign to. */\n targetAgentId?: string;\n /** For POOL mode: the agent implementation type to match. */\n targetImplementation?: string;\n /** Optional parameter overrides for orchestration. */\n launchParamOverrides?: Record<string, string>;\n /** Optional task metadata. */\n metadata?: Record<string, string>;\n /** Assignment mode. Default: SelfAssign. */\n assignmentMode?: TaskAssignmentMode;\n}\n\n// =============================================================================\n// AgentClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as an agent.\n *\n * Agents are persistent entities identified by workspace, implementation,\n * and specifier. Each agent identity can only have one active connection\n * at a time (Connection = Lock paradigm).\n *\n * AgentClient extends AetherClient and adds agent-specific functionality:\n * - Identity management (workspace, implementation, specifier)\n * - Messaging helpers (sendToAgent, sendToUser, sendToTask, broadcast)\n * - Event and metric publishing\n * - Workspace switching\n * - Task creation\n *\n * @example\n * ```typescript\n * import { AgentClient } from \"@scitrera/aether-client\";\n *\n * const agent = new AgentClient({\n * address: \"localhost:50051\",\n * workspace: \"prod\",\n * implementation: \"data-processor\",\n * specifier: \"instance-1\",\n * });\n *\n * agent.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await agent.connect();\n * ```\n */\nexport class AgentClient extends AetherClient {\n private _workspace: string;\n private readonly _implementation: string;\n private readonly _specifier: string;\n\n /**\n * Creates a new AgentClient.\n *\n * @param options - Agent client configuration\n * @throws {@link InvalidArgumentError} if required fields are missing\n */\n constructor(options: AgentClientOptions) {\n super(options);\n\n if (!options.workspace) {\n throw new InvalidArgumentError(\"Workspace is required\", \"workspace\");\n }\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n if (!options.specifier) {\n throw new InvalidArgumentError(\"Specifier is required\", \"specifier\");\n }\n\n this._workspace = options.workspace;\n this._implementation = options.implementation;\n this._specifier = options.specifier;\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n /** Returns the agent's current workspace. */\n get workspace(): string {\n return this._workspace;\n }\n\n /** Returns the agent's implementation type. */\n get implementation(): string {\n return this._implementation;\n }\n\n /** Returns the agent's specifier (instance identifier). */\n get specifier(): string {\n return this._specifier;\n }\n\n /**\n * Returns this agent's topic address.\n *\n * Format: ag::{workspace}::{implementation}::{specifier}\n */\n get topic(): string {\n return agentTopic(this._workspace, this._implementation, this._specifier);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n agent: {\n workspace: this._workspace,\n implementation: this._implementation,\n specifier: this._specifier,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Workspace Management\n // ===========================================================================\n\n /**\n * Switches the agent's workspace.\n *\n * Sends a SwitchWorkspace message to the gateway, which will update\n * the agent's topic subscription and optionally send a new ConfigSnapshot.\n *\n * @param newWorkspace - The new workspace to switch to\n * @throws {@link InvalidArgumentError} if the workspace is empty\n */\n switchWorkspace(newWorkspace: string): void {\n if (!newWorkspace) {\n throw new InvalidArgumentError(\"Workspace cannot be empty\", \"newWorkspace\");\n }\n\n this._sendUpstream({\n switchWorkspace: {\n newWorkspaceId: newWorkspace,\n },\n });\n\n this._workspace = newWorkspace;\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = agentTopic(workspace, implementation, specifier);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific task.\n *\n * For unique tasks (with specifier), uses tu::{workspace}::{impl}::{spec} topic.\n * For non-unique tasks (empty specifier), uses tb::{workspace}::{impl} broadcast topic.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n *\n * @param userId - Target user's ID\n * @param windowId - Target user's window/session ID\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userTopic(userId, windowId);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a user's workspace scope.\n *\n * This reaches the user regardless of which window/tab they are using.\n *\n * @param userId - Target user's ID\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUserWorkspace(\n userId: string,\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userWorkspaceTopic(userId, workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n // ===========================================================================\n // Broadcast Helpers\n // ===========================================================================\n\n /**\n * Sends a message to all agents in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToAgents(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = globalAgentsTopic(workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to all users in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToUsers(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = globalUsersTopic(workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n // ===========================================================================\n // Event and Metric Publishing\n // ===========================================================================\n\n /**\n * Publishes an event to the workflow engine.\n *\n * @param payload - Event payload (bytes)\n */\n sendEvent(payload: Uint8Array): void {\n this._sendMessage(eventWildcardTopic(), payload, MessageType.Event);\n }\n\n /**\n * Publishes a metric to the metrics bridge.\n *\n * @param metric - Structured metric to publish. Use {@link newMetric} to construct one.\n */\n sendMetric(metric: Metric): void {\n const payload = this._encodeMetric(metric as Record<string, unknown>);\n this._sendMessage(metricWildcardTopic(), payload, MessageType.Metric);\n }\n\n // ===========================================================================\n // Task Creation\n // ===========================================================================\n\n /**\n * Creates a new task with the specified parameters.\n *\n * @param opts - Task creation options\n * @throws {@link InvalidArgumentError} if task type is missing\n */\n createTask(opts: CreateTaskOptions): void {\n if (!opts.taskType) {\n throw new InvalidArgumentError(\"Task type is required\", \"taskType\");\n }\n\n const workspace = opts.workspace || this._workspace;\n let assignmentMode = opts.assignmentMode ?? TaskAssignmentMode.SelfAssign;\n\n // Auto-set TARGETED mode if target is specified\n if (opts.targetAgentId && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Targeted;\n }\n\n // Auto-set POOL mode if target implementation is specified\n if (opts.targetImplementation && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Pool;\n }\n\n this._sendUpstream({\n createTask: {\n taskType: opts.taskType,\n workspace,\n assignmentMode,\n targetAgentId: opts.targetAgentId ?? \"\",\n targetImplementation: opts.targetImplementation ?? \"\",\n launchParamOverrides: opts.launchParamOverrides ?? {},\n metadata: opts.metadata ?? {},\n },\n });\n }\n\n // ===========================================================================\n // Convenience Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler specifically for task-related messages.\n *\n * Filters incoming messages to only those from task topics (tu.* or ta.*).\n *\n * @param handler - Function called when a task message is received\n */\n onTaskMessage(handler: MessageHandler): void {\n const existingHandler = this[\"_onMessage\" as keyof this] as MessageHandler;\n this.onMessage((msg) => {\n if (msg.sourceTopic.startsWith(\"tu.\") || msg.sourceTopic.startsWith(\"ta.\") || msg.sourceTopic.startsWith(\"tb.\")) {\n handler(msg);\n } else if (existingHandler) {\n existingHandler(msg);\n }\n });\n }\n\n /**\n * Registers a handler specifically for control messages.\n *\n * Note: Since the base protocol delivers all messages through a single\n * stream, this filters based on source topic prefixes. For more granular\n * filtering, use onMessage directly and inspect the payload.\n *\n * @param handler - Function called when a control message is received\n */\n onControlMessage(handler: MessageHandler): void {\n const existingHandler = this[\"_onMessage\" as keyof this] as MessageHandler;\n this.onMessage((msg) => {\n // Control messages can come from any source; delegate to user handler\n // for inspection. This provides a simple hook point.\n handler(msg);\n if (existingHandler) {\n existingHandler(msg);\n }\n });\n }\n}\n","/**\n * Task client implementation for the Aether TypeScript SDK.\n *\n * This module provides the TaskClient class for connecting to the Aether\n * gateway as a task. Tasks can be unique (named, with a specifier) or\n * non-unique (server-assigned ID, load-balanced via broadcast topic).\n *\n * @module tasks\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType, TaskAssignmentMode } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n eventWildcardTopic,\n metricWildcardTopic,\n} from \"./topics.js\";\nimport type { CreateTaskOptions } from \"./agents.js\";\nimport type { Metric } from \"./metrics-builder.js\";\n\n// =============================================================================\n// Task Client Options\n// =============================================================================\n\n/**\n * Configuration options for the TaskClient.\n */\nexport interface TaskClientOptions extends AetherClientOptions {\n /** The workspace to connect to. Required. */\n workspace: string;\n /** The task implementation type. Required. */\n implementation: string;\n /** Unique specifier for this task. Empty for non-unique tasks. */\n uniqueSpecifier?: string;\n}\n\n// =============================================================================\n// TaskClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a task.\n *\n * Tasks come in two flavors:\n * - **Unique tasks** (with specifier): Persistent identity like agents,\n * only one connection at a time. Topic: tu::{workspace}::{impl}::{spec}\n * - **Non-unique tasks** (empty specifier): Server-assigned ID, multiple\n * instances allowed. Subscribe to both ta::{workspace}::{impl}::{id} and\n * the shared tb::{workspace}::{impl} broadcast for work claiming.\n *\n * @example\n * ```typescript\n * // Unique task\n * const task = new TaskClient({\n * address: \"localhost:50051\",\n * workspace: \"prod\",\n * implementation: \"report-gen\",\n * uniqueSpecifier: \"daily-report\",\n * });\n *\n * // Non-unique task (worker pool)\n * const worker = new TaskClient({\n * address: \"localhost:50051\",\n * workspace: \"prod\",\n * implementation: \"data-processor\",\n * });\n * ```\n */\nexport class TaskClient extends AetherClient {\n private _workspace: string;\n private readonly _implementation: string;\n private readonly _uniqueSpecifier: string;\n\n constructor(options: TaskClientOptions) {\n super(options);\n\n if (!options.workspace) {\n throw new InvalidArgumentError(\"Workspace is required\", \"workspace\");\n }\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n\n this._workspace = options.workspace;\n this._implementation = options.implementation;\n this._uniqueSpecifier = options.uniqueSpecifier ?? \"\";\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n get workspace(): string {\n return this._workspace;\n }\n\n get implementation(): string {\n return this._implementation;\n }\n\n get uniqueSpecifier(): string {\n return this._uniqueSpecifier;\n }\n\n /** Whether this is a unique (named) task. */\n get isUnique(): boolean {\n return this._uniqueSpecifier !== \"\";\n }\n\n /**\n * Returns this task's topic address.\n * For unique tasks: tu::{workspace}::{impl}::{spec}\n * For non-unique tasks: returns the broadcast topic tb::{workspace}::{impl}\n * (the actual instance topic is assigned by the server).\n */\n get topic(): string {\n if (this._uniqueSpecifier) {\n return uniqueTaskTopic(this._workspace, this._implementation, this._uniqueSpecifier);\n }\n return taskBroadcastTopic(this._workspace, this._implementation);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n task: {\n workspace: this._workspace,\n implementation: this._implementation,\n uniqueSpecifier: this._uniqueSpecifier,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Workspace Management\n // ===========================================================================\n\n /**\n * Switches the task's workspace.\n *\n * @param newWorkspace - The new workspace to switch to\n * @throws {@link InvalidArgumentError} if the workspace is empty\n */\n switchWorkspace(newWorkspace: string): void {\n if (!newWorkspace) {\n throw new InvalidArgumentError(\"Workspace cannot be empty\", \"newWorkspace\");\n }\n this._sendUpstream({\n switchWorkspace: {\n newWorkspaceId: newWorkspace,\n },\n });\n this._workspace = newWorkspace;\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent.\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a message to a specific task.\n * For unique tasks (with specifier), uses tu.* topic.\n * For non-unique tasks (empty specifier), uses tb.* broadcast topic.\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userTopic(userId, windowId), payload, messageType);\n }\n\n // ===========================================================================\n // Event and Metric Publishing\n // ===========================================================================\n\n /**\n * Publishes an event to the workflow engine.\n */\n sendEvent(payload: Uint8Array): void {\n this._sendMessage(eventWildcardTopic(), payload, MessageType.Event);\n }\n\n /**\n * Publishes a metric to the metrics bridge.\n *\n * @param metric - Structured metric to publish. Use {@link newMetric} to construct one.\n */\n sendMetric(metric: Metric): void {\n const payload = this._encodeMetric(metric as Record<string, unknown>);\n this._sendMessage(metricWildcardTopic(), payload, MessageType.Metric);\n }\n\n // ===========================================================================\n // Task Creation\n // ===========================================================================\n\n /**\n * Creates a new task with the specified parameters.\n *\n * @param opts - Task creation options\n * @throws {@link InvalidArgumentError} if task type is missing\n */\n createTask(opts: CreateTaskOptions): void {\n if (!opts.taskType) {\n throw new InvalidArgumentError(\"Task type is required\", \"taskType\");\n }\n\n const workspace = opts.workspace || this._workspace;\n let assignmentMode = opts.assignmentMode ?? TaskAssignmentMode.SelfAssign;\n\n // Auto-set TARGETED mode if target is specified\n if (opts.targetAgentId && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Targeted;\n }\n\n // Auto-set POOL mode if target implementation is specified\n if (opts.targetImplementation && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Pool;\n }\n\n this._sendUpstream({\n createTask: {\n taskType: opts.taskType,\n workspace,\n assignmentMode,\n targetAgentId: opts.targetAgentId ?? \"\",\n targetImplementation: opts.targetImplementation ?? \"\",\n launchParamOverrides: opts.launchParamOverrides ?? {},\n metadata: opts.metadata ?? {},\n },\n });\n }\n}\n","/**\n * User client implementation for the Aether TypeScript SDK.\n *\n * This module provides the UserClient class for connecting to the Aether\n * gateway as a user. Users are identified by userId and windowId, allowing\n * multiple browser tabs or sessions per user.\n *\n * Per the Aether specification, users can only send direct messages.\n * They cannot publish events or metrics like agents and tasks can.\n *\n * @module users\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType, TaskAssignmentMode } from \"./types.js\";\nimport type { MessageHandler } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n} from \"./topics.js\";\nimport type { CreateTaskOptions } from \"./agents.js\";\n\n// =============================================================================\n// User Client Options\n// =============================================================================\n\n/**\n * Configuration options for the UserClient.\n */\nexport interface UserClientOptions extends AetherClientOptions {\n /** The user's unique identifier. Required. */\n userId: string;\n /** The window/session identifier. Required. */\n windowId: string;\n /** Optional initial workspace association. */\n workspace?: string;\n}\n\n// =============================================================================\n// UserClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a user.\n *\n * Users are identified by userId and windowId, allowing multiple browser\n * tabs or sessions per user. Each user session (userId + windowId combination)\n * is unique and can only have one active connection at a time.\n *\n * UserClient extends AetherClient and adds user-specific functionality:\n * - Identity management (userId, windowId)\n * - Messaging helpers (sendToAgent, sendToUser, sendToTask)\n * - Optional workspace association\n *\n * Note: Per the Aether specification, users can only send direct messages.\n * They cannot publish events or metrics.\n *\n * @example\n * ```typescript\n * import { UserClient } from \"@scitrera/aether-client\";\n *\n * const user = new UserClient({\n * address: \"localhost:50051\",\n * userId: \"alice\",\n * windowId: \"tab-1\",\n * });\n *\n * user.onIncomingMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await user.connect();\n *\n * // Send a message to an agent\n * const encoder = new TextEncoder();\n * user.sendToAgent(\"prod\", \"data-processor\", \"instance-1\",\n * encoder.encode(JSON.stringify({ action: \"process\" }))\n * );\n * ```\n */\nexport class UserClient extends AetherClient {\n private readonly _userId: string;\n private readonly _windowId: string;\n private _workspace: string;\n\n /**\n * Creates a new UserClient.\n *\n * @param options - User client configuration\n * @throws {@link InvalidArgumentError} if required fields are missing\n */\n constructor(options: UserClientOptions) {\n super(options);\n\n if (!options.userId) {\n throw new InvalidArgumentError(\"User ID is required\", \"userId\");\n }\n if (!options.windowId) {\n throw new InvalidArgumentError(\"Window ID is required\", \"windowId\");\n }\n\n this._userId = options.userId;\n this._windowId = options.windowId;\n this._workspace = options.workspace ?? \"\";\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n /** Returns the user's unique identifier. */\n get userId(): string {\n return this._userId;\n }\n\n /** Returns the user's window/session identifier. */\n get windowId(): string {\n return this._windowId;\n }\n\n /** Returns the user's current workspace (if set). */\n get workspace(): string {\n return this._workspace;\n }\n\n /**\n * Returns this user's topic address.\n *\n * Format: us::{userId}::{windowId}\n */\n get topic(): string {\n return userTopic(this._userId, this._windowId);\n }\n\n /**\n * Returns this user's workspace-scoped topic address.\n *\n * Format: uw::{userId}::{workspace}\n *\n * Returns empty string if no workspace is set.\n */\n get workspaceTopic(): string {\n if (!this._workspace) return \"\";\n return userWorkspaceTopic(this._userId, this._workspace);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n user: {\n userId: this._userId,\n windowId: this._windowId,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Workspace Management\n // ===========================================================================\n\n /**\n * Sets the user's current workspace for workspace-scoped operations.\n *\n * This is a local operation that does not notify the gateway.\n *\n * @param workspace - The workspace to associate with\n */\n setWorkspace(workspace: string): void {\n this._workspace = workspace;\n }\n\n /**\n * Switches the user's workspace on the gateway.\n *\n * Sends a SwitchWorkspace message to the gateway, which will update\n * topic subscriptions (including progress) and send a new ConfigSnapshot.\n *\n * @param newWorkspace - The new workspace to switch to\n * @throws {@link InvalidArgumentError} if the workspace is empty\n */\n switchWorkspace(newWorkspace: string): void {\n if (!newWorkspace) {\n throw new InvalidArgumentError(\"Workspace cannot be empty\", \"newWorkspace\");\n }\n this._sendUpstream({\n switchWorkspace: {\n newWorkspaceId: newWorkspace,\n },\n });\n this._workspace = newWorkspace;\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = agentTopic(workspace, implementation, specifier);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific task.\n *\n * For unique tasks (with specifier), uses tu::{workspace}::{impl}::{spec} topic.\n * For non-unique tasks (empty specifier), uses tb::{workspace}::{impl} broadcast topic.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n *\n * @param userId - Target user's ID\n * @param windowId - Target user's window/session ID\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userTopic(userId, windowId);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a user's workspace scope.\n *\n * @param userId - Target user's ID\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUserWorkspace(\n userId: string,\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = userWorkspaceTopic(userId, workspace);\n this._sendMessage(topic, payload, messageType);\n }\n\n // ===========================================================================\n // Task Creation\n // ===========================================================================\n\n /**\n * Creates a new task with the specified parameters.\n *\n * Users can create tasks targeting agents or task pools.\n *\n * @param opts - Task creation options\n * @throws {@link InvalidArgumentError} if task type is missing\n */\n createTask(opts: CreateTaskOptions): void {\n if (!opts.taskType) {\n throw new InvalidArgumentError(\"Task type is required\", \"taskType\");\n }\n\n const workspace = opts.workspace || this._workspace;\n let assignmentMode = opts.assignmentMode ?? TaskAssignmentMode.SelfAssign;\n\n // Auto-set TARGETED mode if target is specified\n if (opts.targetAgentId && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Targeted;\n }\n\n // Auto-set POOL mode if target implementation is specified\n if (opts.targetImplementation && assignmentMode === TaskAssignmentMode.SelfAssign) {\n assignmentMode = TaskAssignmentMode.Pool;\n }\n\n this._sendUpstream({\n createTask: {\n taskType: opts.taskType,\n workspace,\n assignmentMode,\n targetAgentId: opts.targetAgentId ?? \"\",\n targetImplementation: opts.targetImplementation ?? \"\",\n launchParamOverrides: opts.launchParamOverrides ?? {},\n metadata: opts.metadata ?? {},\n },\n });\n }\n\n // ===========================================================================\n // Convenience Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for all incoming messages.\n *\n * This is an alias for onMessage, provided for API clarity in the\n * user context.\n *\n * @param handler - Function called when a message is received\n */\n onIncomingMessage(handler: MessageHandler): void {\n this.onMessage(handler);\n }\n}\n","/**\n * Orchestrator client implementation for the Aether TypeScript SDK.\n *\n * Orchestrators manage agent/task lifecycle: receiving startup requests\n * when targeted agents are offline, launching compute resources, and\n * managing agent pools and scaling.\n *\n * @module orchestrator\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\nimport type { TaskAssignment, ConnectionAck } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n} from \"./topics.js\";\n\n// =============================================================================\n// Orchestrator Client Options\n// =============================================================================\n\n/**\n * Configuration options for the OrchestratorClient.\n */\nexport interface OrchestratorClientOptions extends AetherClientOptions {\n /** The orchestrator implementation type (e.g., \"kubernetes-orchestrator\"). Required. */\n implementation: string;\n /** Profiles this orchestrator supports (e.g., [\"kubernetes\", \"docker\"]). Required, at least one. */\n supportedProfiles: string[];\n /** Unique specifier for this instance. Auto-generated if not provided. */\n specifier?: string;\n}\n\n// =============================================================================\n// OrchestratorClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as an orchestrator.\n *\n * Orchestrators receive task assignments via the onTaskAssignment handler\n * and are responsible for launching the appropriate compute resources.\n *\n * @example\n * ```typescript\n * const orchestrator = new OrchestratorClient({\n * address: \"localhost:50051\",\n * implementation: \"k8s-orchestrator\",\n * supportedProfiles: [\"kubernetes\"],\n * });\n *\n * orchestrator.onTaskAssignment((assignment) => {\n * console.log(`Starting ${assignment.targetImplementation} for task ${assignment.taskId}`);\n * // Launch container based on assignment.launchParams\n * });\n *\n * await orchestrator.connect();\n * ```\n */\nexport class OrchestratorClient extends AetherClient {\n private readonly _implementation: string;\n private readonly _specifier: string;\n private readonly _supportedProfiles: string[];\n\n constructor(options: OrchestratorClientOptions) {\n super(options);\n\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n if (!options.supportedProfiles || options.supportedProfiles.length === 0) {\n throw new InvalidArgumentError(\"At least one supported profile is required\", \"supportedProfiles\");\n }\n\n this._implementation = options.implementation;\n this._specifier = options.specifier ?? crypto.randomUUID().slice(0, 8);\n this._supportedProfiles = options.supportedProfiles;\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n get implementation(): string {\n return this._implementation;\n }\n\n get specifier(): string {\n return this._specifier;\n }\n\n get supportedProfiles(): string[] {\n return [...this._supportedProfiles];\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n orchestrator: {\n implementation: this._implementation,\n specifier: this._specifier,\n supportedProfiles: this._supportedProfiles,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a status/control message to an agent.\n */\n sendStatusToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a status/control message to a task.\n * For unique tasks (with specifier), uses tu.* topic.\n * For non-unique tasks (empty specifier), uses tb.* broadcast topic.\n */\n sendStatusToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n}\n\n// =============================================================================\n// BaseOrchestrator Options\n// =============================================================================\n\n/**\n * Configuration options for BaseOrchestrator subclasses.\n */\nexport interface BaseOrchestratorOptions extends OrchestratorClientOptions {\n /**\n * Whether to log task assignment details to the console.\n * Default: false.\n */\n logAssignments?: boolean;\n}\n\n// =============================================================================\n// BaseOrchestrator\n// =============================================================================\n\n/**\n * Abstract base class for building orchestrators.\n *\n * BaseOrchestrator wraps {@link OrchestratorClient} and provides a structured\n * framework for managing agent/task lifecycle. Subclasses implement the\n * abstract {@link launchTask} method to handle task assignments with their\n * specific compute backend (Docker, Kubernetes, subprocess, etc.).\n *\n * The class manages the full orchestrator lifecycle:\n * - Connecting to the Aether gateway as an Orchestrator principal\n * - Receiving {@link TaskAssignment} messages and dispatching to launchTask\n * - Error handling and logging hooks\n *\n * @example\n * ```typescript\n * import { BaseOrchestrator, TaskAssignment } from \"@scitrera/aether-client\";\n *\n * class MyOrchestrator extends BaseOrchestrator {\n * async launchTask(assignment: TaskAssignment): Promise<void> {\n * console.log(`Launching task ${assignment.taskId} (profile: ${assignment.profile})`);\n * // Start a subprocess, container, etc. using assignment.launchParams\n * }\n * }\n *\n * const orch = new MyOrchestrator({\n * address: \"localhost:50051\",\n * implementation: \"my-orchestrator\",\n * supportedProfiles: [\"my-profile\"],\n * });\n *\n * orch.onConnect((ack) => {\n * console.log(`Connected with session ${ack.sessionId}`);\n * });\n *\n * await orch.connect();\n * ```\n */\nexport abstract class BaseOrchestrator {\n /** The underlying OrchestratorClient for direct gateway access. */\n readonly client: OrchestratorClient;\n\n private readonly _logAssignments: boolean;\n\n /**\n * Creates a new BaseOrchestrator.\n *\n * @param options - Orchestrator configuration options\n */\n constructor(options: BaseOrchestratorOptions) {\n this._logAssignments = options.logAssignments ?? false;\n this.client = new OrchestratorClient(options);\n\n // Wire task assignment handler to launchTask\n this.client.onTaskAssignment((assignment) => {\n return this._handleAssignment(assignment);\n });\n }\n\n // ===========================================================================\n // Abstract Interface\n // ===========================================================================\n\n /**\n * Called when the gateway assigns a task to this orchestrator.\n *\n * Subclasses must implement this method to launch the appropriate compute\n * resource (container, process, VM, etc.) based on the assignment details.\n *\n * The assignment includes:\n * - `taskId`: Unique task identifier\n * - `profile`: The profile that matched (from supportedProfiles)\n * - `targetImplementation`: The agent/task implementation to launch\n * - `workspace`: The workspace this task belongs to\n * - `specifier`: Optional unique specifier for the agent/task\n * - `launchParams`: Key-value launch parameters (image, command, env vars, etc.)\n * - `metadata`: Arbitrary task metadata\n *\n * @param assignment - The task assignment received from the gateway\n */\n abstract launchTask(assignment: TaskAssignment): void | Promise<void>;\n\n // ===========================================================================\n // Lifecycle\n // ===========================================================================\n\n /**\n * Connects to the Aether gateway.\n *\n * Must be called before the orchestrator can receive task assignments.\n */\n async connect(): Promise<void> {\n await this.client.connect();\n }\n\n /**\n * Disconnects from the Aether gateway.\n */\n async disconnect(): Promise<void> {\n await this.client.disconnect();\n }\n\n /**\n * Returns whether the orchestrator is currently connected.\n */\n get connected(): boolean {\n return this.client.connected;\n }\n\n /**\n * Returns the current session ID assigned by the gateway.\n * Empty string if not connected.\n */\n get sessionId(): string {\n return this.client.sessionId;\n }\n\n /**\n * Returns the orchestrator's implementation type.\n */\n get implementation(): string {\n return this.client.implementation;\n }\n\n /**\n * Returns the orchestrator's specifier.\n */\n get specifier(): string {\n return this.client.specifier;\n }\n\n /**\n * Returns the list of profiles this orchestrator supports.\n */\n get supportedProfiles(): string[] {\n return this.client.supportedProfiles;\n }\n\n // ===========================================================================\n // Handler Registration\n // ===========================================================================\n\n /**\n * Registers a handler for successful connection events.\n *\n * @param handler - Called with the ConnectionAck when connected\n */\n onConnect(handler: (ack: ConnectionAck) => void | Promise<void>): void {\n this.client.onConnect(handler);\n }\n\n /**\n * Registers a handler for disconnection events.\n *\n * @param handler - Called with the reason string when disconnected\n */\n onDisconnect(handler: (reason: string) => void | Promise<void>): void {\n this.client.onDisconnect(handler);\n }\n\n /**\n * Registers a handler for reconnection attempts.\n *\n * @param handler - Called with the attempt number on each reconnect try\n */\n onReconnecting(handler: (attempt: number) => void | Promise<void>): void {\n this.client.onReconnecting(handler);\n }\n\n // ===========================================================================\n // Message Sending\n // ===========================================================================\n\n /**\n * Sends a status/control message to an agent.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload\n * @param messageType - Message type. Default: Control\n */\n sendStatusToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this.client.sendStatusToAgent(workspace, implementation, specifier, payload, messageType);\n }\n\n /**\n * Sends a status/control message to a task.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload\n * @param messageType - Message type. Default: Control\n */\n sendStatusToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this.client.sendStatusToTask(workspace, implementation, specifier, payload, messageType);\n }\n\n // ===========================================================================\n // Internal\n // ===========================================================================\n\n /**\n * Internal handler that logs and dispatches to launchTask.\n * @internal\n */\n private async _handleAssignment(assignment: TaskAssignment): Promise<void> {\n if (this._logAssignments) {\n console.log(\n `[BaseOrchestrator] Task assignment received: taskId=${assignment.taskId}` +\n ` profile=${assignment.profile} impl=${assignment.targetImplementation}` +\n ` workspace=${assignment.workspace}`,\n );\n }\n await this.launchTask(assignment);\n }\n}\n","/**\n * Workflow engine client implementation for the Aether TypeScript SDK.\n *\n * The workflow engine is the sole subscriber to event.* topics and processes\n * broadcast events to trigger downstream actions by sending commands to\n * agents/tasks. It is a singleton per gateway deployment.\n *\n * @module workflow\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\nimport {\n agentTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n globalAgentsTopic,\n globalUsersTopic,\n userTopic,\n metricWildcardTopic,\n} from \"./topics.js\";\nimport type { Metric } from \"./metrics-builder.js\";\n\n// =============================================================================\n// Workflow Engine Client Options\n// =============================================================================\n\n/**\n * Configuration options for the WorkflowEngineClient.\n *\n * No additional identity fields are needed — the workflow engine is\n * identified by its principal type alone (singleton per gateway).\n */\nexport type WorkflowEngineClientOptions = AetherClientOptions;\n\n// =============================================================================\n// WorkflowEngineClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a workflow engine.\n *\n * The workflow engine receives all events (event.*) and can send commands\n * to any principal type. It is the central event processor for the system.\n *\n * @example\n * ```typescript\n * const engine = new WorkflowEngineClient({\n * address: \"localhost:50051\",\n * });\n *\n * engine.onMessage((msg) => {\n * // Process incoming events\n * const event = JSON.parse(new TextDecoder().decode(msg.payload));\n * console.log(`Event from ${msg.sourceTopic}:`, event);\n * });\n *\n * await engine.connect();\n * ```\n */\nexport class WorkflowEngineClient extends AetherClient {\n constructor(options: WorkflowEngineClientOptions) {\n super(options);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n workflowEngine: {},\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a command to a specific agent.\n */\n sendCommandToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a command to a specific task.\n * For unique tasks (with specifier), uses tu.* topic.\n * For non-unique tasks (empty specifier), uses tb.* broadcast topic.\n */\n sendCommandToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a broadcast to all agents in a workspace.\n */\n broadcastToAgents(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Control,\n ): void {\n this._sendMessage(globalAgentsTopic(workspace), payload, messageType);\n }\n\n /**\n * Sends a broadcast to all users in a workspace.\n */\n broadcastToUsers(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(globalUsersTopic(workspace), payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userTopic(userId, windowId), payload, messageType);\n }\n\n /**\n * Publishes a metric to the metrics bridge.\n *\n * @param metric - Structured metric to publish. Use {@link newMetric} to construct one.\n */\n sendMetric(metric: Metric): void {\n const payload = this._encodeMetric(metric as Record<string, unknown>);\n this._sendMessage(metricWildcardTopic(), payload, MessageType.Metric);\n }\n}\n","/**\n * Metrics bridge client implementation for the Aether TypeScript SDK.\n *\n * The metrics bridge is a receive-only client that subscribes to metric.*\n * topics to collect telemetry data from agents and tasks. It is a singleton\n * per gateway deployment.\n *\n * @module metrics\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\n\n// =============================================================================\n// Metrics Bridge Client Options\n// =============================================================================\n\n/**\n * Configuration options for the MetricsBridgeClient.\n *\n * No additional identity fields are needed — the metrics bridge is\n * identified by its principal type alone (singleton per gateway).\n */\nexport type MetricsBridgeClientOptions = AetherClientOptions;\n\n// =============================================================================\n// MetricsBridgeClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a metrics bridge.\n *\n * The metrics bridge is receive-only: it subscribes to metric.* topics\n * to collect telemetry data published by agents and tasks. It does not\n * send messages to other principals.\n *\n * @example\n * ```typescript\n * const bridge = new MetricsBridgeClient({\n * address: \"localhost:50051\",\n * });\n *\n * bridge.onMessage((msg) => {\n * // Process incoming metrics\n * const metric = JSON.parse(new TextDecoder().decode(msg.payload));\n * console.log(`Metric from ${msg.sourceTopic}:`, metric);\n * });\n *\n * await bridge.connect();\n * ```\n */\nexport class MetricsBridgeClient extends AetherClient {\n constructor(options: MetricsBridgeClientOptions) {\n super(options);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n metricsBridge: {},\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Messaging\n // ===========================================================================\n\n /**\n * Sends an acknowledgment to a source topic.\n *\n * @param targetTopic - The topic to send the acknowledgment to\n * @param payload - The acknowledgment payload\n */\n sendAcknowledgment(targetTopic: string, payload: Uint8Array): void {\n this._sendMessage(targetTopic, payload, MessageType.Control);\n }\n}\n","/**\n * Fluent builder for constructing Metric payloads.\n *\n * Metric is the canonical payload for SendMessage when message_type == METRIC.\n * All entries are interpreted as additive deltas; negative qty values require\n * the `capability/metric_credit` ACL permission on the sender.\n *\n * @module metrics-builder\n *\n * @example\n * ```typescript\n * import { newMetric } from \"@scitrera/aether-client\";\n *\n * const metric = newMetric()\n * .trace(\"req-abc-123\")\n * .add(\"tokens_in\", \"modelA\", 512)\n * .add(\"tokens_out\", \"modelA\", 128)\n * .tag(\"source.version\", \"1.0.0\")\n * .clientTimestampMs(Date.now())\n * .build();\n *\n * agent.sendMetric(metric);\n * ```\n */\n\nimport type { Metric } from './proto/aether/v1/Metric.js';\nimport type { MetricEntry } from './proto/aether/v1/MetricEntry.js';\n\nexport type { Metric, MetricEntry };\n\n/**\n * Fluent builder for constructing a {@link Metric}.\n */\nexport class MetricBuilder {\n private m: Metric;\n\n constructor() {\n this.m = {\n traceId: '',\n entries: [],\n metadata: {},\n clientTimestampMs: 0,\n };\n }\n\n /**\n * Sets the optional correlation/trace ID tying these entries to upstream work.\n */\n trace(id: string): this {\n this.m.traceId = id;\n return this;\n }\n\n /**\n * Adds a metric entry (additive delta).\n *\n * @param name - Counter name, e.g. \"tokens_in\", \"time_seconds\"\n * @param kind - Sub-classifier, e.g. \"modelA\" (may be empty)\n * @param qty - Additive delta; negative requires `capability/metric_credit`\n */\n add(name: string, kind: string, qty: number): this {\n if (!this.m.entries) {\n this.m.entries = [];\n }\n this.m.entries.push({ name, kind, qty });\n return this;\n }\n\n /**\n * Adds a free-form metadata tag.\n *\n * Well-known keys: lifecycle (\"startup\" | \"shutdown\"),\n * source.version, source.region, source.host, ...\n */\n tag(key: string, value: string): this {\n if (!this.m.metadata) {\n this.m.metadata = {};\n }\n this.m.metadata[key] = value;\n return this;\n }\n\n /**\n * Sets the optional client-side timestamp (ms since epoch).\n *\n * The server always stamps its own authoritative timestamp on the\n * MessageEnvelope; this field is an advisory ordering hint only.\n *\n * Accepts `number` or `string` to support int64 values that exceed\n * `Number.MAX_SAFE_INTEGER` (the generated proto type allows both,\n * driven by `--longs=String` in compile_protos.sh).\n */\n clientTimestampMs(ts: number | string): this {\n this.m.clientTimestampMs = ts;\n return this;\n }\n\n /**\n * Returns the constructed Metric object.\n */\n build(): Metric {\n return this.m;\n }\n}\n\n/**\n * Creates a new {@link MetricBuilder}.\n *\n * @example\n * ```typescript\n * const metric = newMetric()\n * .add(\"tokens_in\", \"gpt4\", 512)\n * .build();\n * ```\n */\nexport function newMetric(): MetricBuilder {\n return new MetricBuilder();\n}\n","/**\n * Bridge client implementation for the Aether TypeScript SDK.\n *\n * This module provides the BridgeClient class for connecting to the Aether\n * gateway as a cross-workspace message bridge. Bridges relay messages across\n * workspace boundaries and can send to any principal type in any workspace.\n *\n * Unlike workspace-scoped principals (agents, tasks, users), bridges have no\n * workspace field in their identity — allowing them to send to targets in any\n * workspace. Each bridge identity can only have one active connection at a time\n * (Connection = Lock paradigm).\n *\n * @module bridge\n */\n\nimport { AetherClient } from \"./client.js\";\nimport type { AetherClientOptions } from \"./client.js\";\nimport { MessageType } from \"./types.js\";\nimport { InvalidArgumentError } from \"./errors.js\";\nimport {\n agentTopic,\n bridgeTopic,\n uniqueTaskTopic,\n taskBroadcastTopic,\n userTopic,\n userWorkspaceTopic,\n globalAgentsTopic,\n globalUsersTopic,\n} from \"./topics.js\";\n\n// =============================================================================\n// Bridge Client Options\n// =============================================================================\n\n/**\n * Configuration options for the BridgeClient.\n */\nexport interface BridgeClientOptions extends AetherClientOptions {\n /** The bridge implementation type (e.g., \"aether-msgbridge\", \"webhook-bridge\"). Required. */\n implementation: string;\n /** The unique specifier for this bridge instance (e.g., \"default\", \"discord-1\"). Required. */\n specifier: string;\n}\n\n// =============================================================================\n// BridgeClient\n// =============================================================================\n\n/**\n * Client for connecting to the Aether gateway as a cross-workspace message bridge.\n *\n * Bridges are identified by implementation and specifier with no workspace field,\n * allowing them to operate across workspace boundaries. Each bridge identity can\n * only have one active connection at a time (Connection = Lock paradigm).\n *\n * BridgeClient extends AetherClient and adds bridge-specific functionality:\n * - Identity management (implementation, specifier)\n * - Messaging helpers to any workspace (sendToAgent, sendToUser, sendToTask, broadcast)\n *\n * Topic format: br::{implementation}::{specifier}\n *\n * @example\n * ```typescript\n * import { BridgeClient } from \"@scitrera/aether-client\";\n *\n * const bridge = new BridgeClient({\n * address: \"localhost:50051\",\n * implementation: \"aether-msgbridge\",\n * specifier: \"discord-1\",\n * });\n *\n * bridge.onMessage((msg) => {\n * console.log(`Received from ${msg.sourceTopic}:`, msg.payload);\n * });\n *\n * await bridge.connect();\n *\n * // Send to any workspace — bridges are cross-workspace\n * const encoder = new TextEncoder();\n * bridge.sendToAgent(\"prod\", \"my-agent\", \"instance-1\", encoder.encode(\"Hello!\"));\n * bridge.sendToUser(\"alice\", \"tab-1\", encoder.encode(\"Notification from Discord\"));\n * ```\n */\nexport class BridgeClient extends AetherClient {\n private readonly _implementation: string;\n private readonly _specifier: string;\n\n /**\n * Creates a new BridgeClient.\n *\n * @param options - Bridge client configuration\n * @throws {@link InvalidArgumentError} if required fields are missing\n */\n constructor(options: BridgeClientOptions) {\n super(options);\n\n if (!options.implementation) {\n throw new InvalidArgumentError(\"Implementation is required\", \"implementation\");\n }\n if (!options.specifier) {\n throw new InvalidArgumentError(\"Specifier is required\", \"specifier\");\n }\n\n this._implementation = options.implementation;\n this._specifier = options.specifier;\n }\n\n // ===========================================================================\n // Identity Accessors\n // ===========================================================================\n\n /** Returns the bridge's implementation type. */\n get implementation(): string {\n return this._implementation;\n }\n\n /** Returns the bridge's specifier (instance identifier). */\n get specifier(): string {\n return this._specifier;\n }\n\n /**\n * Returns this bridge's topic address.\n *\n * Format: br::{implementation}::{specifier}\n */\n get topic(): string {\n return bridgeTopic(this._implementation, this._specifier);\n }\n\n // ===========================================================================\n // Init Message\n // ===========================================================================\n\n /** @internal */\n protected override _buildInitMessage(): Record<string, unknown> {\n return {\n bridge: {\n implementation: this._implementation,\n specifier: this._specifier,\n },\n credentials: this._credentials,\n resumeSessionId: this._resumeSessionId,\n };\n }\n\n // ===========================================================================\n // Message Sending Helpers\n // ===========================================================================\n\n /**\n * Sends a message to a specific agent in any workspace.\n *\n * @param workspace - Target agent's workspace\n * @param implementation - Target agent's implementation type\n * @param specifier - Target agent's specifier\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToAgent(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(agentTopic(workspace, implementation, specifier), payload, messageType);\n }\n\n /**\n * Sends a message to a specific task in any workspace.\n *\n * For unique tasks (with specifier), uses tu::{workspace}::{impl}::{spec} topic.\n * For non-unique tasks (empty specifier), uses tb::{workspace}::{impl} broadcast topic.\n *\n * @param workspace - Target task's workspace\n * @param implementation - Target task's implementation type\n * @param specifier - Target task's specifier (empty for broadcast)\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToTask(\n workspace: string,\n implementation: string,\n specifier: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n const topic = specifier\n ? uniqueTaskTopic(workspace, implementation, specifier)\n : taskBroadcastTopic(workspace, implementation);\n this._sendMessage(topic, payload, messageType);\n }\n\n /**\n * Sends a message to a specific user session.\n *\n * @param userId - Target user's ID\n * @param windowId - Target user's window/session ID\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUser(\n userId: string,\n windowId: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userTopic(userId, windowId), payload, messageType);\n }\n\n /**\n * Sends a message to a user's workspace scope.\n *\n * This reaches the user regardless of which window/tab they are using.\n *\n * @param userId - Target user's ID\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n sendToUserWorkspace(\n userId: string,\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(userWorkspaceTopic(userId, workspace), payload, messageType);\n }\n\n // ===========================================================================\n // Broadcast Helpers\n // ===========================================================================\n\n /**\n * Sends a message to all agents in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToAgents(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(globalAgentsTopic(workspace), payload, messageType);\n }\n\n /**\n * Sends a message to all users in a workspace.\n *\n * @param workspace - Target workspace\n * @param payload - Message payload (bytes)\n * @param messageType - Message type. Default: Chat\n */\n broadcastToUsers(\n workspace: string,\n payload: Uint8Array,\n messageType: MessageType = MessageType.Opaque,\n ): void {\n this._sendMessage(globalUsersTopic(workspace), payload, messageType);\n }\n}\n","/**\n * Proxy HTTP support for the Aether TypeScript SDK.\n *\n * Provides `proxyHttp()` on AetherClient for tunneling HTTP requests through\n * the Aether gRPC stream, and `AetherFetchTransport` as a drop-in replacement\n * for the Web Fetch API transport layer.\n *\n * Bodies larger than CHUNK_THRESHOLD (256 KB) are split into\n * ProxyHttpBodyChunk frames and reassembled on the response side.\n *\n * @module proxy\n */\n\nimport type { AetherClient } from \"./client.js\";\nimport { ConnectionError, TimeoutError } from \"./errors.js\";\n\n// =============================================================================\n// Constants\n// =============================================================================\n\nconst CHUNK_THRESHOLD = 256 * 1024; // 256 KB\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/** Transport-layer error kinds from the gateway. */\nexport enum ProxyErrorKind {\n Unknown = 0,\n DialFailed = 1,\n Timeout = 2,\n UpstreamReset = 3,\n AclDenied = 4,\n SidecarUnavailable = 5,\n PayloadTooLarge = 6,\n DecodeFailed = 7,\n}\n\n/** Transport-layer error from the gateway (not an HTTP error). */\nexport interface ProxyError {\n readonly kind: ProxyErrorKind;\n readonly message: string;\n}\n\n/** Structured response from a proxied HTTP request. */\nexport interface ProxyHttpResponse {\n readonly requestId: string;\n readonly statusCode: number;\n readonly headers: Record<string, string>;\n readonly body: Uint8Array;\n readonly bodyChunked: boolean;\n readonly error?: ProxyError;\n}\n\n/** Options for proxyHttp(). */\nexport interface ProxyHttpOptions {\n /** Request headers to send. */\n headers?: Record<string, string>;\n /** Request body (raw bytes). */\n body?: Uint8Array;\n /** Timeout in milliseconds (default: 30 000). */\n timeoutMs?: number;\n /** Whether to follow HTTP redirects (default: true). */\n followRedirects?: boolean;\n /**\n * Pin the request to a named terminator backend. The backend's allow-list\n * still applies — explicit naming selects which backend's ACL is consulted,\n * not whether the request is allowed.\n */\n backend?: string;\n /**\n * Opt into unbounded response streaming (SSE / log tails / model token\n * streams). When true, ``timeoutMs`` becomes the time-to-first-byte\n * deadline only; subsequent body bytes are governed by\n * ``streamIdleTimeoutMs``. The response body is delivered as a real\n * ``ReadableStream<Uint8Array>`` so consumers can iterate chunks as they\n * arrive without buffering the whole response.\n */\n streamResponse?: boolean;\n /**\n * Idle deadline (ms) between body bytes when ``streamResponse=true``.\n * Default 30 000 (30s) when unset. Exceeding closes the stream with\n * ``ProxyError{TIMEOUT}``.\n */\n streamIdleTimeoutMs?: number;\n /**\n * Maximum total response body bytes when ``streamResponse=true``. 0 (the\n * default) means \"use the per-backend cap\". Exceeding closes the stream\n * with ``ProxyError{PAYLOAD_TOO_LARGE}``.\n */\n maxResponseBodyBytes?: number;\n}\n\n/** Error thrown when the proxy transport layer fails. */\nexport class ProxyHttpError extends Error {\n readonly proxyError: ProxyError;\n constructor(err: ProxyError) {\n super(`Proxy transport error [${ProxyErrorKind[err.kind]}]: ${err.message}`);\n this.name = \"ProxyHttpError\";\n this.proxyError = err;\n }\n}\n\n// =============================================================================\n// proxyHttp — callable as client.proxyHttp(...)\n// =============================================================================\n\n/**\n * Sends an HTTP request through the Aether gRPC stream to a service principal\n * and returns a fetch-compatible `Response` object.\n *\n * @param client - Connected AetherClient instance\n * @param target - Target topic, e.g. `\"sv::memorylayer::default\"` or wildcard `\"sv::memorylayer\"`\n * @param method - HTTP method, e.g. `\"GET\"`, `\"POST\"`\n * @param path - Path including query string, e.g. `\"/v1/memories/abc\"`\n * @param opts - Optional headers, body, timeout, followRedirects\n * @returns A `Response`-compatible object (standard Web API Response)\n * @throws {@link ProxyHttpError} on transport-layer failure\n * @throws {@link TimeoutError} if the request times out\n * @throws {@link ConnectionError} if not connected\n */\nexport async function proxyHttp(\n client: AetherClient,\n target: string,\n method: string,\n path: string,\n opts: ProxyHttpOptions = {},\n): Promise<Response> {\n if (!(client as unknown as { _connected: boolean })._connected) {\n throw new ConnectionError(\"Not connected to gateway\");\n }\n\n const requestId = (client as { nextRequestId(): string }).nextRequestId();\n const timeoutMs = opts.timeoutMs ?? 30_000;\n const body = opts.body ?? new Uint8Array(0);\n const headers = opts.headers ?? {};\n const followRedirects = opts.followRedirects ?? true;\n const backendName = opts.backend ?? \"\";\n const streamResponse = opts.streamResponse ?? false;\n const streamIdleTimeoutMs = opts.streamIdleTimeoutMs ?? 0;\n const maxResponseBodyBytes = opts.maxResponseBodyBytes ?? 0;\n const bodyChunked = body.length > CHUNK_THRESHOLD;\n\n // For streaming responses, we wire a ReadableStream<Uint8Array> whose\n // controller is fed by the client's chunk dispatcher. The promise resolves\n // as soon as the header (TTFB) lands so the caller gets a real Response\n // back without waiting for fin.\n let streamingController: ReadableStreamDefaultController<Uint8Array> | null = null;\n const streamSlotMap = (client as {\n _pendingProxyHttpStreams: Map<\n string,\n { controller: ReadableStreamDefaultController<Uint8Array>; headerResolved: boolean }\n >;\n })._pendingProxyHttpStreams;\n const readable = streamResponse\n ? new ReadableStream<Uint8Array>({\n start(controller) {\n streamingController = controller;\n streamSlotMap.set(requestId, { controller, headerResolved: false });\n },\n cancel() {\n streamSlotMap.delete(requestId);\n },\n })\n : null;\n\n return new Promise<Response>((resolve, reject) => {\n const timer = setTimeout(() => {\n (client as { _pendingProxyHttpRequests: Map<string, unknown> })._pendingProxyHttpRequests.delete(requestId);\n (client as { _pendingProxyHttpChunks: Map<string, unknown> })._pendingProxyHttpChunks.delete(requestId);\n (client as { _pendingProxyHttpChunks: Map<string, unknown> })._pendingProxyHttpChunks.delete(requestId + \":shell\");\n if (streamResponse) {\n streamSlotMap.delete(requestId);\n if (streamingController) {\n try { streamingController.error(new TimeoutError(`proxyHttp timed out after ${timeoutMs}ms`)); } catch { /* already closed */ }\n }\n }\n reject(new TimeoutError(`proxyHttp timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n const pendingMap = (client as { _pendingProxyHttpRequests: Map<string, (r: ProxyHttpResponse) => void> })._pendingProxyHttpRequests;\n pendingMap.set(requestId, (resp: ProxyHttpResponse) => {\n clearTimeout(timer);\n if (resp.error && resp.error.kind !== ProxyErrorKind.Unknown) {\n if (streamResponse && streamingController) {\n try { streamingController.error(new ProxyHttpError(resp.error)); } catch { /* */ }\n }\n reject(new ProxyHttpError(resp.error));\n return;\n }\n // Streaming responses surface the ReadableStream<Uint8Array> body so\n // chunks arrive incrementally; bounded responses keep the legacy\n // buffered shape.\n if (streamResponse && readable) {\n const responseHeaders = new Headers(resp.headers);\n resolve(new Response(readable, {\n status: resp.statusCode,\n headers: responseHeaders,\n }));\n return;\n }\n const responseHeaders = new Headers(resp.headers);\n resolve(new Response(resp.body.length > 0 ? resp.body : null, {\n status: resp.statusCode,\n headers: responseHeaders,\n }));\n });\n\n // Send the request envelope\n const upstream = client as unknown as { _sendUpstream(msg: Record<string, unknown>): void };\n\n if (!bodyChunked) {\n upstream._sendUpstream({\n proxyHttpRequest: {\n requestId,\n targetTopic: target,\n method,\n path,\n headers,\n body,\n bodyChunked: false,\n timeoutMs,\n followRedirects,\n backendName,\n streamResponseIndefinitely: streamResponse,\n streamIdleTimeoutMs,\n maxResponseBodyBytes,\n },\n });\n } else {\n // Send header envelope first with bodyChunked=true, empty body\n upstream._sendUpstream({\n proxyHttpRequest: {\n requestId,\n targetTopic: target,\n method,\n path,\n headers,\n body: new Uint8Array(0),\n bodyChunked: true,\n timeoutMs,\n followRedirects,\n backendName,\n streamResponseIndefinitely: streamResponse,\n streamIdleTimeoutMs,\n maxResponseBodyBytes,\n },\n });\n // Send body as chunks\n let seq = 0;\n let offset = 0;\n while (offset < body.length) {\n const end = Math.min(offset + CHUNK_THRESHOLD, body.length);\n const chunk = body.slice(offset, end);\n const fin = end >= body.length;\n upstream._sendUpstream({\n proxyHttpBodyChunk: {\n requestId,\n isRequest: true,\n seq,\n data: chunk,\n fin,\n },\n });\n seq++;\n offset = end;\n }\n }\n });\n}\n\n// =============================================================================\n// AetherFetchTransport — drop-in for the Web Fetch API\n// =============================================================================\n\n/**\n * A drop-in transport for the Web Fetch API that routes requests through\n * an Aether gRPC connection to a service principal.\n *\n * @example\n * ```typescript\n * const transport = new AetherFetchTransport(agentClient, \"sv::memorylayer::default\");\n * const response = await transport.fetch(\"/v1/memories/abc\");\n * ```\n */\nexport class AetherFetchTransport {\n private readonly _client: AetherClient;\n private readonly _target: string;\n private readonly _defaultTimeoutMs: number;\n private readonly _defaultBackend: string;\n\n /**\n * @param client - Connected AetherClient\n * @param target - Default target topic (e.g. `\"sv::memorylayer::default\"`)\n * @param timeoutMs - Default request timeout in ms (default: 30 000)\n * @param backend - Optional default terminator backend name applied to\n * every request. The backend's allow-list still applies — explicit\n * naming selects which backend's ACL is consulted.\n */\n constructor(client: AetherClient, target: string, timeoutMs = 30_000, backend = \"\") {\n this._client = client;\n this._target = target;\n this._defaultTimeoutMs = timeoutMs;\n this._defaultBackend = backend;\n }\n\n /**\n * Fetch-compatible method. Accepts a URL string or Request object plus\n * optional RequestInit overrides.\n *\n * The URL hostname/protocol is ignored — requests are routed to the\n * configured target topic. Only the pathname + search are used as the path.\n *\n * @returns Web API `Response`\n */\n async fetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {\n let method = \"GET\";\n let path = \"/\";\n let reqHeaders: Record<string, string> = {};\n let reqBody: Uint8Array | undefined;\n\n if (typeof input === \"string\" || input instanceof URL) {\n const url = typeof input === \"string\" ? new URL(input, \"http://placeholder\") : input;\n path = url.pathname + url.search;\n method = (init?.method ?? \"GET\").toUpperCase();\n } else {\n // Request object\n const url = new URL(input.url, \"http://placeholder\");\n path = url.pathname + url.search;\n method = input.method.toUpperCase();\n // Copy headers from Request object\n input.headers.forEach((value, key) => { reqHeaders[key] = value; });\n }\n\n // Merge init headers\n if (init?.headers) {\n if (init.headers instanceof Headers) {\n init.headers.forEach((v, k) => { reqHeaders[k] = v; });\n } else if (Array.isArray(init.headers)) {\n for (const [k, v] of init.headers) { reqHeaders[k] = v; }\n } else {\n Object.assign(reqHeaders, init.headers);\n }\n }\n\n // Resolve body\n const rawBody = init?.body ?? (input instanceof Request ? input.body : null);\n if (rawBody != null) {\n if (rawBody instanceof Uint8Array) {\n reqBody = rawBody;\n } else if (rawBody instanceof ArrayBuffer) {\n reqBody = new Uint8Array(rawBody);\n } else if (typeof rawBody === \"string\") {\n reqBody = new TextEncoder().encode(rawBody);\n } else if (rawBody instanceof ReadableStream) {\n // Drain the stream\n const reader = rawBody.getReader();\n const parts: Uint8Array[] = [];\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (value) parts.push(value instanceof Uint8Array ? value : new Uint8Array(value as ArrayBuffer));\n }\n const total = parts.reduce((s, p) => s + p.length, 0);\n reqBody = new Uint8Array(total);\n let off = 0;\n for (const p of parts) { reqBody.set(p, off); off += p.length; }\n }\n }\n\n return proxyHttp(this._client, this._target, method, path, {\n headers: reqHeaders,\n body: reqBody,\n timeoutMs: this._defaultTimeoutMs,\n backend: this._defaultBackend || undefined,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC2BO,IAAK,gBAAL,kBAAKA,mBAAL;AACL,EAAAA,eAAA,WAAQ;AACR,EAAAA,eAAA,gBAAa;AACb,EAAAA,eAAA,mBAAgB;AACjB,EAAAA,eAAA,UAAO;AACP,EAAAA,eAAA,oBAAiB;AACjB,EAAAA,eAAA,mBAAgB;AAChB,EAAAA,eAAA,kBAAe;AACf,EAAAA,eAAA,aAAU;AARC,SAAAA;AAAA,GAAA;AAwBL,IAAK,cAAL,kBAAKC,iBAAL;AACL,EAAAA,0BAAA,iBAAc,KAAd;AACA,EAAAA,0BAAA,UAAO,KAAP;AACA,EAAAA,0BAAA,aAAU,KAAV;AACA,EAAAA,0BAAA,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