@easbot/acp 0.3.36 → 0.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -4,7 +4,7 @@ import z$1, { z } from 'zod';
4
4
  import { NameErrors as NameErrors$1, ACPConnectionRegistryConfig, ACPConnectionResult, ACPConnectionState, ACPRoutingContext, ACPRoutingResult, EasServer } from '@easbot/utils';
5
5
  export { ACPComposedContext, ACPConnectionRegistryConfig, ACPConnectionResult, ACPConnectionState, ACPDegradationInfo, ACPHistoryContext, ACPInteractionConfig, ACPInteractionContext, ACPInteractionMessage, ACPRoutingContext, ACPRoutingResult, ServiceError, ServiceError as ServiceErrorInstance } from '@easbot/utils';
6
6
  import { EasbotClient, ContextMode } from '@easbot/sdk';
7
- import { AvailableCommand, SessionConfigOption, SessionNotification, McpServer, Agent, AgentSideConnection, InitializeRequest, InitializeResponse, AuthenticateRequest, AuthenticateResponse, NewSessionRequest, NewSessionResponse, LoadSessionRequest, LoadSessionResponse, PromptRequest, PromptResponse, CancelNotification, ForkSessionRequest, ForkSessionResponse, ResumeSessionRequest, ResumeSessionResponse, ListSessionsRequest, ListSessionsResponse, SetSessionModeRequest, SetSessionModeResponse, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, CloseSessionRequest, CloseSessionResponse } from '@agentclientprotocol/sdk';
7
+ import { AvailableCommand, SessionConfigOption, SessionNotification, RequestPermissionRequest, RequestPermissionResponse, AgentContext, McpServer, InitializeRequest, InitializeResponse, AuthenticateRequest, AuthenticateResponse, NewSessionRequest, NewSessionResponse, LoadSessionRequest, LoadSessionResponse, PromptRequest, PromptResponse, CancelNotification, ForkSessionRequest, ForkSessionResponse, ResumeSessionRequest, ResumeSessionResponse, ListSessionsRequest, ListSessionsResponse, SetSessionModeRequest, SetSessionModeResponse, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, CloseSessionRequest, CloseSessionResponse } from '@agentclientprotocol/sdk/unstable';
8
8
 
9
9
  type TranslationResources = {
10
10
  translation: Record<string, string>;
@@ -1675,39 +1675,24 @@ declare class RegistrySessionRouter extends SessionRouter {
1675
1675
  protected getConnectionsByService(baseUrl: string): ACPConnectionState[];
1676
1676
  }
1677
1677
 
1678
- interface ACPConnection {
1678
+ interface AcpPeer {
1679
1679
  sessionUpdate(params: SessionNotification): Promise<void>;
1680
- requestPermission(params: ACPRequestPermissionParams): Promise<ACPRequestPermissionResponse>;
1681
- extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1682
- extNotification(method: string, params: Record<string, unknown>): Promise<void>;
1680
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
1681
+ request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1682
+ notify(method: string, params: Record<string, unknown>): Promise<void>;
1683
1683
  }
1684
- interface ACPRequestPermissionParams {
1685
- sessionId: string;
1686
- toolCall: {
1687
- callId: string;
1688
- status?: string;
1689
- title?: string;
1690
- rawInput?: unknown;
1691
- kind?: string;
1692
- locations?: string[];
1693
- };
1694
- options: Array<{
1695
- optionId: string;
1696
- name: string;
1697
- kind?: string;
1698
- }>;
1699
- }
1700
- interface ACPRequestPermissionResponse {
1701
- outcome: {
1702
- outcome: 'selected';
1703
- optionId: string;
1704
- } | {
1705
- outcome: 'cancelled';
1706
- };
1684
+ declare class SdkPeer implements AcpPeer {
1685
+ private readonly context;
1686
+ constructor(context: AgentContext);
1687
+ sessionUpdate(params: SessionNotification): Promise<void>;
1688
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
1689
+ request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1690
+ notify(method: string, params: Record<string, unknown>): Promise<void>;
1707
1691
  }
1692
+
1708
1693
  declare class AcpEventBridge {
1709
1694
  private sdk;
1710
- private connection;
1695
+ private peer;
1711
1696
  private abortController;
1712
1697
  private started;
1713
1698
  private permissionQueues;
@@ -1715,7 +1700,7 @@ declare class AcpEventBridge {
1715
1700
  private permissionOptions;
1716
1701
  private acpService?;
1717
1702
  private _cachedPrimaryAgents;
1718
- constructor(sdk: EasbotClient, connection: ACPConnection);
1703
+ constructor(sdk: EasbotClient, peer: AcpPeer);
1719
1704
  setService(service: {
1720
1705
  abortConnection?: () => void;
1721
1706
  closeConnection?: () => void;
@@ -1799,17 +1784,17 @@ interface ACPServiceConfig {
1799
1784
  connectionRegistry?: ServerConnectionRegistry.Registry;
1800
1785
  sessionRouter?: SessionRouter;
1801
1786
  }
1802
- declare abstract class ACPService implements Agent {
1787
+ declare abstract class ACPService {
1803
1788
  protected config: ACPServiceConfig;
1804
1789
  protected readonly serviceMode: ServiceMode$1;
1805
- protected connection: AgentSideConnection | undefined;
1790
+ protected peer: AcpPeer | undefined;
1806
1791
  protected sdk: EasbotClient;
1807
1792
  protected connectionRegistry: ServerConnectionRegistry.Registry | null;
1808
1793
  protected sessionRouter: SessionRouter | null;
1809
1794
  protected sessionManager: AdapterSessionManager;
1810
1795
  private executorInitialized;
1811
1796
  protected status: AgentStatus;
1812
- constructor(connection: AgentSideConnection | undefined, config: ACPServiceConfig);
1797
+ constructor(peer: AcpPeer | undefined, config: ACPServiceConfig);
1813
1798
  protected initializeExecutor(): Promise<void>;
1814
1799
  protected setStatus(newStatus: AgentStatus, agentId?: string): void;
1815
1800
  protected getStatus(): AgentStatus;
@@ -1833,9 +1818,8 @@ declare abstract class ACPService implements Agent {
1833
1818
  closeSession(params: CloseSessionRequest): Promise<CloseSessionResponse>;
1834
1819
  private buildSessionStateResponse;
1835
1820
  private parseModelSelection;
1836
- setConnection(connection: AgentSideConnection): void;
1837
- getConnection(): AgentSideConnection | undefined;
1838
- setServerConnection(connection: any): void;
1821
+ setPeer(peer: AcpPeer): void;
1822
+ getPeer(): AcpPeer | undefined;
1839
1823
  abortConnection(): void;
1840
1824
  closeConnection(): void;
1841
1825
  getServerConnectionRegistry(): ServerConnectionRegistry.Registry | null;
@@ -1937,7 +1921,7 @@ declare function startWebSocketServer(agent: EasBotAgent, config: ACPServerConfi
1937
1921
  interface EventBroadcaster {
1938
1922
  broadcast: (sessionId: string, event: SessionNotification) => void;
1939
1923
  }
1940
- declare class ServerAgentSideConnection implements ACPConnection {
1924
+ declare class ServerAgentSideConnection implements AcpPeer {
1941
1925
  private broadcaster;
1942
1926
  private sessionIds;
1943
1927
  private sessionRefCounts;
@@ -1947,26 +1931,9 @@ declare class ServerAgentSideConnection implements ACPConnection {
1947
1931
  clearSessions(): void;
1948
1932
  getSessions(): string[];
1949
1933
  sessionUpdate(params: SessionNotification): Promise<void>;
1950
- requestPermission(params: {
1951
- sessionId: string;
1952
- toolCall: {
1953
- callId: string;
1954
- };
1955
- options: Array<{
1956
- optionId: string;
1957
- name: string;
1958
- kind?: string;
1959
- }>;
1960
- }): Promise<{
1961
- outcome: {
1962
- outcome: 'selected';
1963
- optionId: string;
1964
- } | {
1965
- outcome: 'cancelled';
1966
- };
1967
- }>;
1968
- extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1969
- extNotification(method: string, params: Record<string, unknown>): Promise<void>;
1934
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
1935
+ request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1936
+ notify(method: string, params: Record<string, unknown>): Promise<void>;
1970
1937
  }
1971
1938
 
1972
1939
  interface EasBotAgentConfig extends ACPServiceConfig {
@@ -1980,8 +1947,10 @@ declare class EasBotAgent extends ACPService {
1980
1947
  private acpEventBridge;
1981
1948
  private server;
1982
1949
  private isAgentInitialized;
1950
+ private connection;
1983
1951
  static create(config: EasBotAgentConfig): Promise<EasBotAgent>;
1984
- constructor(connection: AgentSideConnection | undefined, config: EasBotAgentConfig);
1952
+ constructor(peer: AcpPeer | undefined, config: EasBotAgentConfig);
1953
+ private createAgentApp;
1985
1954
  initialize(params: InitializeRequest): Promise<InitializeResponse>;
1986
1955
  private initializeAgent;
1987
1956
  start(): Promise<void>;
@@ -2010,7 +1979,7 @@ declare namespace EasbotAdapter {
2010
1979
  function getAgent<T = unknown>(): Promise<T | null>;
2011
1980
  function getServer<T = ACPServerInstance>(): Promise<T | null>;
2012
1981
  function getSDK(): Promise<EasbotClient | null>;
2013
- function getACPConnection(): Promise<AgentSideConnection | null>;
1982
+ function getACPConnection(): Promise<AcpPeer | null>;
2014
1983
  function getState(): Promise<{
2015
1984
  initialized: boolean;
2016
1985
  directory: string;
@@ -2039,4 +2008,4 @@ declare function registerToGateway(config: ACPServerConfig$1): Promise<boolean>;
2039
2008
  declare function deregisterFromGateway(): Promise<void>;
2040
2009
  declare function hasRegistrationSession(): boolean;
2041
2010
 
2042
- export { ACPClientConfigSchema, ACPClientsConfigSchema, ACPInfoACPConfigSchema, ACPParsePartialConfig, ACPServerConfigSchema, type ACPServerInstance, ACPValidateConfig, ACP_BUSINESS_CODES, ACP_BUSINESS_HINTS, ACP_JSON_REL_PATH, ACP_STDIO_COMMAND, AcpCache, type AcpCliDeps, type AcpCliResult, type AcpConfigStateResult, type AcpEndpointChannel, type AcpEndpointInput, AcpError, AcpEventBridge, AdapterBootstrap, type AdapterBootstrapConfig, type AdapterEnvInitStage, AdapterEnvironmentInitializationError, AdapterError, AgentStatus, COMMANDS_HELP, type CommandHelp, EasBotAgent, type EasBotAgentConfig, EasbotAdapter, ErrorType, type FormatLogOptions, type GatewayUrlAdapter, I18n, LanguagesSupported, type Locale, NameErrors, RegistrySessionRouter, RoutingError, RoutingErrorCode, ServerAgentSideConnection, ServerConnectionRegistry, ServiceMode, ServiceModeConflictError, type ServiceModeValue, SessionRouter, type TranslateOptions, type TranslationResources, type TypeWithI18N, applyEnvironmentOverrides, changeI18nLanguage, clearConfigCache, createACPServerInstance, createAdapterEnvironmentInitializationError, createAdapterError, createChannelError, createConfigError, createNetworkError, createRoutingError, createServiceModeConflictError, createTimeoutError, deregisterFromGateway, formatLog, getAcpEndpointUrl, getAgentAddress, getClientById, getClientsConfig, getConfig, getConfigDirectory, getDefaultClient, getGatewayClientUrl, getGatewayUrlAdapter, getGlobal, getHomeDir, getInstance, getProjectDirectory, getRegisteredResources, getSdk, getServerConfig, getWorktree, getXdgData, handleAcpCli, hasRegistrationSession, initI18n, isAdapterEnvironmentInitializationError, isAdapterError, isAdapterErrorFatal, isAdapterErrorRetryable, isConfigLoaded, isRoutingError, isServiceModeConflictError, languages, loadACPServerConfig, loadConfig, loadConfigFromEnv, registerBusinessErrors, registerI18nResources, registerToGateway, reloadConfig, renderBanner, renderHelp, resetEasbotClientAdapter, resetGatewayUrlAdapter, resetGlobalAdapter, resetInstanceAdapter, setEasbotClientAdapter, setGatewayUrlAdapter, setGlobalAdapter, setInstanceAdapter, startACPServer, startHttpServer, startWebSocketServer, t, translate };
2011
+ export { ACPClientConfigSchema, ACPClientsConfigSchema, ACPInfoACPConfigSchema, ACPParsePartialConfig, ACPServerConfigSchema, type ACPServerInstance, ACPValidateConfig, ACP_BUSINESS_CODES, ACP_BUSINESS_HINTS, ACP_JSON_REL_PATH, ACP_STDIO_COMMAND, AcpCache, type AcpCliDeps, type AcpCliResult, type AcpConfigStateResult, type AcpEndpointChannel, type AcpEndpointInput, AcpError, AcpEventBridge, type AcpPeer, AdapterBootstrap, type AdapterBootstrapConfig, type AdapterEnvInitStage, AdapterEnvironmentInitializationError, AdapterError, AgentStatus, COMMANDS_HELP, type CommandHelp, EasBotAgent, type EasBotAgentConfig, EasbotAdapter, ErrorType, type FormatLogOptions, type GatewayUrlAdapter, I18n, LanguagesSupported, type Locale, NameErrors, RegistrySessionRouter, RoutingError, RoutingErrorCode, SdkPeer, ServerAgentSideConnection, ServerConnectionRegistry, ServiceMode, ServiceModeConflictError, type ServiceModeValue, SessionRouter, type TranslateOptions, type TranslationResources, type TypeWithI18N, applyEnvironmentOverrides, changeI18nLanguage, clearConfigCache, createACPServerInstance, createAdapterEnvironmentInitializationError, createAdapterError, createChannelError, createConfigError, createNetworkError, createRoutingError, createServiceModeConflictError, createTimeoutError, deregisterFromGateway, formatLog, getAcpEndpointUrl, getAgentAddress, getClientById, getClientsConfig, getConfig, getConfigDirectory, getDefaultClient, getGatewayClientUrl, getGatewayUrlAdapter, getGlobal, getHomeDir, getInstance, getProjectDirectory, getRegisteredResources, getSdk, getServerConfig, getWorktree, getXdgData, handleAcpCli, hasRegistrationSession, initI18n, isAdapterEnvironmentInitializationError, isAdapterError, isAdapterErrorFatal, isAdapterErrorRetryable, isConfigLoaded, isRoutingError, isServiceModeConflictError, languages, loadACPServerConfig, loadConfig, loadConfigFromEnv, registerBusinessErrors, registerI18nResources, registerToGateway, reloadConfig, renderBanner, renderHelp, resetEasbotClientAdapter, resetGatewayUrlAdapter, resetGlobalAdapter, resetInstanceAdapter, setEasbotClientAdapter, setGatewayUrlAdapter, setGlobalAdapter, setInstanceAdapter, startACPServer, startHttpServer, startWebSocketServer, t, translate };
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import z$1, { z } from 'zod';
4
4
  import { NameErrors as NameErrors$1, ACPConnectionRegistryConfig, ACPConnectionResult, ACPConnectionState, ACPRoutingContext, ACPRoutingResult, EasServer } from '@easbot/utils';
5
5
  export { ACPComposedContext, ACPConnectionRegistryConfig, ACPConnectionResult, ACPConnectionState, ACPDegradationInfo, ACPHistoryContext, ACPInteractionConfig, ACPInteractionContext, ACPInteractionMessage, ACPRoutingContext, ACPRoutingResult, ServiceError, ServiceError as ServiceErrorInstance } from '@easbot/utils';
6
6
  import { EasbotClient, ContextMode } from '@easbot/sdk';
7
- import { AvailableCommand, SessionConfigOption, SessionNotification, McpServer, Agent, AgentSideConnection, InitializeRequest, InitializeResponse, AuthenticateRequest, AuthenticateResponse, NewSessionRequest, NewSessionResponse, LoadSessionRequest, LoadSessionResponse, PromptRequest, PromptResponse, CancelNotification, ForkSessionRequest, ForkSessionResponse, ResumeSessionRequest, ResumeSessionResponse, ListSessionsRequest, ListSessionsResponse, SetSessionModeRequest, SetSessionModeResponse, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, CloseSessionRequest, CloseSessionResponse } from '@agentclientprotocol/sdk';
7
+ import { AvailableCommand, SessionConfigOption, SessionNotification, RequestPermissionRequest, RequestPermissionResponse, AgentContext, McpServer, InitializeRequest, InitializeResponse, AuthenticateRequest, AuthenticateResponse, NewSessionRequest, NewSessionResponse, LoadSessionRequest, LoadSessionResponse, PromptRequest, PromptResponse, CancelNotification, ForkSessionRequest, ForkSessionResponse, ResumeSessionRequest, ResumeSessionResponse, ListSessionsRequest, ListSessionsResponse, SetSessionModeRequest, SetSessionModeResponse, SetSessionConfigOptionRequest, SetSessionConfigOptionResponse, CloseSessionRequest, CloseSessionResponse } from '@agentclientprotocol/sdk/unstable';
8
8
 
9
9
  type TranslationResources = {
10
10
  translation: Record<string, string>;
@@ -1675,39 +1675,24 @@ declare class RegistrySessionRouter extends SessionRouter {
1675
1675
  protected getConnectionsByService(baseUrl: string): ACPConnectionState[];
1676
1676
  }
1677
1677
 
1678
- interface ACPConnection {
1678
+ interface AcpPeer {
1679
1679
  sessionUpdate(params: SessionNotification): Promise<void>;
1680
- requestPermission(params: ACPRequestPermissionParams): Promise<ACPRequestPermissionResponse>;
1681
- extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1682
- extNotification(method: string, params: Record<string, unknown>): Promise<void>;
1680
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
1681
+ request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1682
+ notify(method: string, params: Record<string, unknown>): Promise<void>;
1683
1683
  }
1684
- interface ACPRequestPermissionParams {
1685
- sessionId: string;
1686
- toolCall: {
1687
- callId: string;
1688
- status?: string;
1689
- title?: string;
1690
- rawInput?: unknown;
1691
- kind?: string;
1692
- locations?: string[];
1693
- };
1694
- options: Array<{
1695
- optionId: string;
1696
- name: string;
1697
- kind?: string;
1698
- }>;
1699
- }
1700
- interface ACPRequestPermissionResponse {
1701
- outcome: {
1702
- outcome: 'selected';
1703
- optionId: string;
1704
- } | {
1705
- outcome: 'cancelled';
1706
- };
1684
+ declare class SdkPeer implements AcpPeer {
1685
+ private readonly context;
1686
+ constructor(context: AgentContext);
1687
+ sessionUpdate(params: SessionNotification): Promise<void>;
1688
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
1689
+ request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1690
+ notify(method: string, params: Record<string, unknown>): Promise<void>;
1707
1691
  }
1692
+
1708
1693
  declare class AcpEventBridge {
1709
1694
  private sdk;
1710
- private connection;
1695
+ private peer;
1711
1696
  private abortController;
1712
1697
  private started;
1713
1698
  private permissionQueues;
@@ -1715,7 +1700,7 @@ declare class AcpEventBridge {
1715
1700
  private permissionOptions;
1716
1701
  private acpService?;
1717
1702
  private _cachedPrimaryAgents;
1718
- constructor(sdk: EasbotClient, connection: ACPConnection);
1703
+ constructor(sdk: EasbotClient, peer: AcpPeer);
1719
1704
  setService(service: {
1720
1705
  abortConnection?: () => void;
1721
1706
  closeConnection?: () => void;
@@ -1799,17 +1784,17 @@ interface ACPServiceConfig {
1799
1784
  connectionRegistry?: ServerConnectionRegistry.Registry;
1800
1785
  sessionRouter?: SessionRouter;
1801
1786
  }
1802
- declare abstract class ACPService implements Agent {
1787
+ declare abstract class ACPService {
1803
1788
  protected config: ACPServiceConfig;
1804
1789
  protected readonly serviceMode: ServiceMode$1;
1805
- protected connection: AgentSideConnection | undefined;
1790
+ protected peer: AcpPeer | undefined;
1806
1791
  protected sdk: EasbotClient;
1807
1792
  protected connectionRegistry: ServerConnectionRegistry.Registry | null;
1808
1793
  protected sessionRouter: SessionRouter | null;
1809
1794
  protected sessionManager: AdapterSessionManager;
1810
1795
  private executorInitialized;
1811
1796
  protected status: AgentStatus;
1812
- constructor(connection: AgentSideConnection | undefined, config: ACPServiceConfig);
1797
+ constructor(peer: AcpPeer | undefined, config: ACPServiceConfig);
1813
1798
  protected initializeExecutor(): Promise<void>;
1814
1799
  protected setStatus(newStatus: AgentStatus, agentId?: string): void;
1815
1800
  protected getStatus(): AgentStatus;
@@ -1833,9 +1818,8 @@ declare abstract class ACPService implements Agent {
1833
1818
  closeSession(params: CloseSessionRequest): Promise<CloseSessionResponse>;
1834
1819
  private buildSessionStateResponse;
1835
1820
  private parseModelSelection;
1836
- setConnection(connection: AgentSideConnection): void;
1837
- getConnection(): AgentSideConnection | undefined;
1838
- setServerConnection(connection: any): void;
1821
+ setPeer(peer: AcpPeer): void;
1822
+ getPeer(): AcpPeer | undefined;
1839
1823
  abortConnection(): void;
1840
1824
  closeConnection(): void;
1841
1825
  getServerConnectionRegistry(): ServerConnectionRegistry.Registry | null;
@@ -1937,7 +1921,7 @@ declare function startWebSocketServer(agent: EasBotAgent, config: ACPServerConfi
1937
1921
  interface EventBroadcaster {
1938
1922
  broadcast: (sessionId: string, event: SessionNotification) => void;
1939
1923
  }
1940
- declare class ServerAgentSideConnection implements ACPConnection {
1924
+ declare class ServerAgentSideConnection implements AcpPeer {
1941
1925
  private broadcaster;
1942
1926
  private sessionIds;
1943
1927
  private sessionRefCounts;
@@ -1947,26 +1931,9 @@ declare class ServerAgentSideConnection implements ACPConnection {
1947
1931
  clearSessions(): void;
1948
1932
  getSessions(): string[];
1949
1933
  sessionUpdate(params: SessionNotification): Promise<void>;
1950
- requestPermission(params: {
1951
- sessionId: string;
1952
- toolCall: {
1953
- callId: string;
1954
- };
1955
- options: Array<{
1956
- optionId: string;
1957
- name: string;
1958
- kind?: string;
1959
- }>;
1960
- }): Promise<{
1961
- outcome: {
1962
- outcome: 'selected';
1963
- optionId: string;
1964
- } | {
1965
- outcome: 'cancelled';
1966
- };
1967
- }>;
1968
- extMethod(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1969
- extNotification(method: string, params: Record<string, unknown>): Promise<void>;
1934
+ requestPermission(params: RequestPermissionRequest): Promise<RequestPermissionResponse>;
1935
+ request(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
1936
+ notify(method: string, params: Record<string, unknown>): Promise<void>;
1970
1937
  }
1971
1938
 
1972
1939
  interface EasBotAgentConfig extends ACPServiceConfig {
@@ -1980,8 +1947,10 @@ declare class EasBotAgent extends ACPService {
1980
1947
  private acpEventBridge;
1981
1948
  private server;
1982
1949
  private isAgentInitialized;
1950
+ private connection;
1983
1951
  static create(config: EasBotAgentConfig): Promise<EasBotAgent>;
1984
- constructor(connection: AgentSideConnection | undefined, config: EasBotAgentConfig);
1952
+ constructor(peer: AcpPeer | undefined, config: EasBotAgentConfig);
1953
+ private createAgentApp;
1985
1954
  initialize(params: InitializeRequest): Promise<InitializeResponse>;
1986
1955
  private initializeAgent;
1987
1956
  start(): Promise<void>;
@@ -2010,7 +1979,7 @@ declare namespace EasbotAdapter {
2010
1979
  function getAgent<T = unknown>(): Promise<T | null>;
2011
1980
  function getServer<T = ACPServerInstance>(): Promise<T | null>;
2012
1981
  function getSDK(): Promise<EasbotClient | null>;
2013
- function getACPConnection(): Promise<AgentSideConnection | null>;
1982
+ function getACPConnection(): Promise<AcpPeer | null>;
2014
1983
  function getState(): Promise<{
2015
1984
  initialized: boolean;
2016
1985
  directory: string;
@@ -2039,4 +2008,4 @@ declare function registerToGateway(config: ACPServerConfig$1): Promise<boolean>;
2039
2008
  declare function deregisterFromGateway(): Promise<void>;
2040
2009
  declare function hasRegistrationSession(): boolean;
2041
2010
 
2042
- export { ACPClientConfigSchema, ACPClientsConfigSchema, ACPInfoACPConfigSchema, ACPParsePartialConfig, ACPServerConfigSchema, type ACPServerInstance, ACPValidateConfig, ACP_BUSINESS_CODES, ACP_BUSINESS_HINTS, ACP_JSON_REL_PATH, ACP_STDIO_COMMAND, AcpCache, type AcpCliDeps, type AcpCliResult, type AcpConfigStateResult, type AcpEndpointChannel, type AcpEndpointInput, AcpError, AcpEventBridge, AdapterBootstrap, type AdapterBootstrapConfig, type AdapterEnvInitStage, AdapterEnvironmentInitializationError, AdapterError, AgentStatus, COMMANDS_HELP, type CommandHelp, EasBotAgent, type EasBotAgentConfig, EasbotAdapter, ErrorType, type FormatLogOptions, type GatewayUrlAdapter, I18n, LanguagesSupported, type Locale, NameErrors, RegistrySessionRouter, RoutingError, RoutingErrorCode, ServerAgentSideConnection, ServerConnectionRegistry, ServiceMode, ServiceModeConflictError, type ServiceModeValue, SessionRouter, type TranslateOptions, type TranslationResources, type TypeWithI18N, applyEnvironmentOverrides, changeI18nLanguage, clearConfigCache, createACPServerInstance, createAdapterEnvironmentInitializationError, createAdapterError, createChannelError, createConfigError, createNetworkError, createRoutingError, createServiceModeConflictError, createTimeoutError, deregisterFromGateway, formatLog, getAcpEndpointUrl, getAgentAddress, getClientById, getClientsConfig, getConfig, getConfigDirectory, getDefaultClient, getGatewayClientUrl, getGatewayUrlAdapter, getGlobal, getHomeDir, getInstance, getProjectDirectory, getRegisteredResources, getSdk, getServerConfig, getWorktree, getXdgData, handleAcpCli, hasRegistrationSession, initI18n, isAdapterEnvironmentInitializationError, isAdapterError, isAdapterErrorFatal, isAdapterErrorRetryable, isConfigLoaded, isRoutingError, isServiceModeConflictError, languages, loadACPServerConfig, loadConfig, loadConfigFromEnv, registerBusinessErrors, registerI18nResources, registerToGateway, reloadConfig, renderBanner, renderHelp, resetEasbotClientAdapter, resetGatewayUrlAdapter, resetGlobalAdapter, resetInstanceAdapter, setEasbotClientAdapter, setGatewayUrlAdapter, setGlobalAdapter, setInstanceAdapter, startACPServer, startHttpServer, startWebSocketServer, t, translate };
2011
+ export { ACPClientConfigSchema, ACPClientsConfigSchema, ACPInfoACPConfigSchema, ACPParsePartialConfig, ACPServerConfigSchema, type ACPServerInstance, ACPValidateConfig, ACP_BUSINESS_CODES, ACP_BUSINESS_HINTS, ACP_JSON_REL_PATH, ACP_STDIO_COMMAND, AcpCache, type AcpCliDeps, type AcpCliResult, type AcpConfigStateResult, type AcpEndpointChannel, type AcpEndpointInput, AcpError, AcpEventBridge, type AcpPeer, AdapterBootstrap, type AdapterBootstrapConfig, type AdapterEnvInitStage, AdapterEnvironmentInitializationError, AdapterError, AgentStatus, COMMANDS_HELP, type CommandHelp, EasBotAgent, type EasBotAgentConfig, EasbotAdapter, ErrorType, type FormatLogOptions, type GatewayUrlAdapter, I18n, LanguagesSupported, type Locale, NameErrors, RegistrySessionRouter, RoutingError, RoutingErrorCode, SdkPeer, ServerAgentSideConnection, ServerConnectionRegistry, ServiceMode, ServiceModeConflictError, type ServiceModeValue, SessionRouter, type TranslateOptions, type TranslationResources, type TypeWithI18N, applyEnvironmentOverrides, changeI18nLanguage, clearConfigCache, createACPServerInstance, createAdapterEnvironmentInitializationError, createAdapterError, createChannelError, createConfigError, createNetworkError, createRoutingError, createServiceModeConflictError, createTimeoutError, deregisterFromGateway, formatLog, getAcpEndpointUrl, getAgentAddress, getClientById, getClientsConfig, getConfig, getConfigDirectory, getDefaultClient, getGatewayClientUrl, getGatewayUrlAdapter, getGlobal, getHomeDir, getInstance, getProjectDirectory, getRegisteredResources, getSdk, getServerConfig, getWorktree, getXdgData, handleAcpCli, hasRegistrationSession, initI18n, isAdapterEnvironmentInitializationError, isAdapterError, isAdapterErrorFatal, isAdapterErrorRetryable, isConfigLoaded, isRoutingError, isServiceModeConflictError, languages, loadACPServerConfig, loadConfig, loadConfigFromEnv, registerBusinessErrors, registerI18nResources, registerToGateway, reloadConfig, renderBanner, renderHelp, resetEasbotClientAdapter, resetGatewayUrlAdapter, resetGlobalAdapter, resetInstanceAdapter, setEasbotClientAdapter, setGatewayUrlAdapter, setGlobalAdapter, setInstanceAdapter, startACPServer, startHttpServer, startWebSocketServer, t, translate };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export{k as COMMANDS_HELP,c as I18n,b as LanguagesSupported,f as changeI18nLanguage,j as formatLog,g as getRegisteredResources,o as handleAcpCli,e as initI18n,a as languages,d as registerI18nResources,l as renderBanner,m as renderHelp,i as t,h as translate}from'./chunks/chunk-SWK2ITXO.mjs';import'./chunks/chunk-D4TSQ2TT.mjs';export{e as clearConfigCache,j as getClientById,i as getClientsConfig,c as getConfig,g as getConfigDirectory,k as getDefaultClient,l as getGatewayClientUrl,h as getServerConfig,d as isConfigLoaded,b as loadConfig,f as reloadConfig}from'./chunks/chunk-JEYD2VIG.mjs';export{a as AcpEventBridge,x as AdapterBootstrap,q as EasBotAgent,w as EasbotAdapter,f as RegistrySessionRouter,c as RoutingErrorCode,l as ServerAgentSideConnection,b as ServerConnectionRegistry,g as ServiceMode,e as SessionRouter,k as applyEnvironmentOverrides,p as createACPServerInstance,v as createAdapterEnvironmentInitializationError,d as createRoutingError,h as createServiceModeConflictError,t as deregisterFromGateway,r as getAgentAddress,u as hasRegistrationSession,i as loadACPServerConfig,j as loadConfigFromEnv,s as registerToGateway,o as startACPServer,m as startHttpServer,n as startWebSocketServer}from'./chunks/chunk-FDMRPUSH.mjs';export{p as ACP_BUSINESS_CODES,q as ACP_BUSINESS_HINTS,s as ACP_STDIO_COMMAND,c as AcpError,d as ErrorType,b as NameErrors,a as ServiceError,k as createAdapterError,l as createChannelError,n as createConfigError,m as createNetworkError,o as createTimeoutError,t as getAcpEndpointUrl,h as isAdapterEnvironmentInitializationError,e as isAdapterError,j as isAdapterErrorFatal,i as isAdapterErrorRetryable,g as isRoutingError,f as isServiceModeConflictError,r as registerBusinessErrors}from'./chunks/chunk-B3ANZALB.mjs';import'./chunks/chunk-ZGY6CLVQ.mjs';export{l as ACPAgentRuntimeConfigSchema,b as ACPClientConfigSchema,c as ACPClientsConfigSchema,j as ACPConnectionConfigSchema,h as ACPHttpConnectionConfigSchema,n as ACPInfoACPClientsConfigSchema,d as ACPInfoACPConfigSchema,m as ACPInfoACPServerConfigSchema,k as ACPModelConfigSchema,f as ACPParsePartialConfig,a as ACPServerConfigSchema,g as ACPStdioConnectionConfigSchema,e as ACPValidateConfig,i as ACPWebSocketConnectionConfigSchema,p as ACP_DEFAULT_CLIENT_CONFIG,o as ACP_DEFAULT_SERVER_CONFIG,q as ACP_JSON_REL_PATH,r as AcpCache}from'./chunks/chunk-FAYVTNTB.mjs';export{l as getGatewayUrlAdapter,c as getGlobal,m as getHomeDir,f as getInstance,p as getProjectDirectory,i as getSdk,o as getWorktree,n as getXdgData,h as resetEasbotClientAdapter,k as resetGatewayUrlAdapter,b as resetGlobalAdapter,e as resetInstanceAdapter,g as setEasbotClientAdapter,j as setGatewayUrlAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-ZZK2JEUF.mjs';export{a as AgentStatus,b as ChannelType}from'./chunks/chunk-33M2R2US.mjs';import'./chunks/chunk-HQBRVVXS.mjs';
1
+ export{k as COMMANDS_HELP,c as I18n,b as LanguagesSupported,f as changeI18nLanguage,j as formatLog,g as getRegisteredResources,o as handleAcpCli,e as initI18n,a as languages,d as registerI18nResources,l as renderBanner,m as renderHelp,i as t,h as translate}from'./chunks/chunk-233AKRGW.mjs';import'./chunks/chunk-D4TSQ2TT.mjs';export{e as clearConfigCache,j as getClientById,i as getClientsConfig,c as getConfig,g as getConfigDirectory,k as getDefaultClient,l as getGatewayClientUrl,h as getServerConfig,d as isConfigLoaded,b as loadConfig,f as reloadConfig}from'./chunks/chunk-JEYD2VIG.mjs';export{a as AcpEventBridge,y as AdapterBootstrap,r as EasBotAgent,x as EasbotAdapter,f as RegistrySessionRouter,c as RoutingErrorCode,g as SdkPeer,m as ServerAgentSideConnection,b as ServerConnectionRegistry,h as ServiceMode,e as SessionRouter,l as applyEnvironmentOverrides,q as createACPServerInstance,w as createAdapterEnvironmentInitializationError,d as createRoutingError,i as createServiceModeConflictError,u as deregisterFromGateway,s as getAgentAddress,v as hasRegistrationSession,j as loadACPServerConfig,k as loadConfigFromEnv,t as registerToGateway,p as startACPServer,n as startHttpServer,o as startWebSocketServer}from'./chunks/chunk-KAXUGIGH.mjs';export{p as ACP_BUSINESS_CODES,q as ACP_BUSINESS_HINTS,s as ACP_STDIO_COMMAND,c as AcpError,d as ErrorType,b as NameErrors,a as ServiceError,k as createAdapterError,l as createChannelError,n as createConfigError,m as createNetworkError,o as createTimeoutError,t as getAcpEndpointUrl,h as isAdapterEnvironmentInitializationError,e as isAdapterError,j as isAdapterErrorFatal,i as isAdapterErrorRetryable,g as isRoutingError,f as isServiceModeConflictError,r as registerBusinessErrors}from'./chunks/chunk-B3ANZALB.mjs';import'./chunks/chunk-ZGY6CLVQ.mjs';export{l as ACPAgentRuntimeConfigSchema,b as ACPClientConfigSchema,c as ACPClientsConfigSchema,j as ACPConnectionConfigSchema,h as ACPHttpConnectionConfigSchema,n as ACPInfoACPClientsConfigSchema,d as ACPInfoACPConfigSchema,m as ACPInfoACPServerConfigSchema,k as ACPModelConfigSchema,f as ACPParsePartialConfig,a as ACPServerConfigSchema,g as ACPStdioConnectionConfigSchema,e as ACPValidateConfig,i as ACPWebSocketConnectionConfigSchema,p as ACP_DEFAULT_CLIENT_CONFIG,o as ACP_DEFAULT_SERVER_CONFIG,q as ACP_JSON_REL_PATH,r as AcpCache}from'./chunks/chunk-FAYVTNTB.mjs';export{l as getGatewayUrlAdapter,c as getGlobal,m as getHomeDir,f as getInstance,p as getProjectDirectory,i as getSdk,o as getWorktree,n as getXdgData,h as resetEasbotClientAdapter,k as resetGatewayUrlAdapter,b as resetGlobalAdapter,e as resetInstanceAdapter,g as setEasbotClientAdapter,j as setGatewayUrlAdapter,a as setGlobalAdapter,d as setInstanceAdapter}from'./chunks/chunk-ZZK2JEUF.mjs';export{a as AgentStatus,b as ChannelType}from'./chunks/chunk-WFIRDYOS.mjs';import'./chunks/chunk-HQBRVVXS.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/acp",
3
- "version": "0.3.36",
3
+ "version": "0.3.37",
4
4
  "description": "EASBot ACP (Agent Communication Protocol) adapter — multi-channel server / client / connection layer for the Agent Client Protocol (stdio / http / websocket), with config loader, L2 cache and standalone CLI.",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -48,14 +48,14 @@
48
48
  "LICENSE"
49
49
  ],
50
50
  "dependencies": {
51
- "@agentclientprotocol/sdk": "^1.3.0",
51
+ "@agentclientprotocol/sdk": "^2.7.0",
52
52
  "diff": "^9.0.0",
53
53
  "ws": "^8.20.0",
54
54
  "zod": "^4.6.7",
55
- "@easbot/types": "0.3.36",
56
- "@easbot/sdk": "0.3.36",
57
- "@easbot/utils": "0.3.36",
58
- "@easbot/terminal": "0.3.36"
55
+ "@easbot/types": "0.3.37",
56
+ "@easbot/sdk": "0.3.37",
57
+ "@easbot/terminal": "0.3.37",
58
+ "@easbot/utils": "0.3.37"
59
59
  },
60
60
  "devDependencies": {
61
61
  "@types/node": "^25.9.5",
@@ -1 +0,0 @@
1
- export{x as AdapterBootstrap,w as EasbotAdapter,v as createAdapterEnvironmentInitializationError}from'./chunk-FDMRPUSH.mjs';import'./chunk-B3ANZALB.mjs';import'./chunk-ZGY6CLVQ.mjs';import'./chunk-FAYVTNTB.mjs';import'./chunk-ZZK2JEUF.mjs';import'./chunk-33M2R2US.mjs';import'./chunk-HQBRVVXS.mjs';
@@ -1,8 +0,0 @@
1
- import {c,t,f as f$1}from'./chunk-B3ANZALB.mjs';import {a as a$1}from'./chunk-ZGY6CLVQ.mjs';import {r}from'./chunk-FAYVTNTB.mjs';import {f,d,e,l}from'./chunk-ZZK2JEUF.mjs';import {b}from'./chunk-33M2R2US.mjs';import {a}from'./chunk-HQBRVVXS.mjs';import {Log,State,Filesystem,NameErrors,errorMeta,ConfigFileWatcher,Identifier,GatewayClient,parseModelId,ParseCommand,formatModelId,PKG,createServer}from'@easbot/utils';import {readFileSync}from'fs';import pt,{dirname,join}from'path';import {fileURLToPath,pathToFileURL}from'url';import {applyPatch}from'diff';import {TodoListSchema}from'@easbot/types';import {createHash}from'crypto';import {ndJsonStream,AgentSideConnection,RequestError}from'@agentclientprotocol/sdk';import {WebSocketServer}from'ws';import'@easbot/sdk';var E=Log.create({service:"acp.event.bridge"}),G=class{constructor(e,t){a(this,"sdk");a(this,"connection");a(this,"abortController",null);a(this,"started",false);a(this,"permissionQueues",new Map);a(this,"_messageMetaCache",new Map);a(this,"permissionOptions",[{optionId:"once",kind:"allow_once",name:"Allow once"},{optionId:"always",kind:"allow_always",name:"Always allow"},{optionId:"reject",kind:"reject_once",name:"Reject"}]);a(this,"acpService");a(this,"_cachedPrimaryAgents",null);this.sdk=e,this.connection=t;}setService(e){this.acpService=e;}async start(){if(this.started){E.warn("AcpEventBridge already started");return}this.started=true,this.abortController=new AbortController,E.info("starting ACP event bridge"),this.runEventSubscription().catch(e=>{this.abortController?.signal.aborted||E.error("event subscription failed",{error:errorMeta(e)});});}async stop(){this.started&&(E.info("stopping ACP event bridge"),this.started=false,this.abortController?.abort(),this.permissionQueues.clear(),this._messageMetaCache.clear(),this._cachedPrimaryAgents=null,E.info("ACP event bridge stopped"));}async runEventSubscription(){let e=this.abortController;if(e)for(;;){if(e.signal.aborted)return;let t=await this.sdk.global.event({signal:e.signal});for await(let n of t.stream){if(e.signal.aborted)return;let r=n?.payload;r&&await this.handleEvent(r).catch(o=>{E.error("failed to handle event",{error:errorMeta(o),type:r.type});});}if(e.signal.aborted)return}}async handleEvent(e){switch(e.type){case "permission.asked":await this.handlePermissionAsked(e.properties);break;case "question.asked":await this.handleQuestionAsked(e.properties);break;case "message.part.updated":await this.handleMessagePartUpdated(e.properties);break;case "session.status":await this.handleSessionStatus(e.properties);break;case "session.deleted":{let n=e.properties.info?.id??"";await this.handleSessionDeleted({sessionId:n});break}}}async handleSessionStatus(e){let{sessionId:t,status:n}=e;if(!this.connection){E.warn("No connection available to publish session status");return}try{await this.connection.extNotification("session_status_update",{sessionId:t,status:n});}catch(r){E.error("Failed to publish session status via extNotification",{sessionId:t,status:n,error:errorMeta(r)});}n.type==="idle"&&(this.permissionQueues.delete(t),this.clearMessageMetaCache(t));}async handleSessionDeleted(e){let{sessionId:t}=e;if(!this.connection){E.warn("No connection available to notify session deletion");return}if(typeof t!="string"||t.length===0){E.debug("handleSessionDeleted: skipping, sessionId is missing or invalid",{sessionId:t});return}this.permissionQueues.delete(t),this.clearMessageMetaCache(t);try{await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:"[System] Session has been deleted by the backend. This session is no longer available."}}});}catch(n){E.error("Failed to notify session deletion to client",{sessionId:t,error:errorMeta(n)});}}async handlePermissionAsked(e){let{id:t,sessionId:n,permission:r,tool:o,metadata:d}=e,l=(this.permissionQueues.get(n)??Promise.resolve()).then(async()=>{let h=r==="external_directory"&&d?.tool?Ce(d.tool):Ce(r),b=r==="external_directory"&&d?.tool?ye(d.tool,d):ye(r,d),I=await this.connection.requestPermission({sessionId:n,toolCall:{callId:o?.callId??t,status:"pending",title:r,rawInput:d,kind:h,locations:(b??[]).map(C=>C.path)},options:this.permissionOptions}).catch(async C=>{E.error("failed to request permission from ACP",{error:errorMeta(C),permissionId:t,sessionId:n}),await this.sdk.permission.reply({requestId:t,reply:"reject"});});if(I){if(I.outcome.outcome!=="selected"){await this.sdk.permission.reply({requestId:t,reply:"reject"});return}if(I.outcome.optionId!=="reject"&&r==="edit"){let C=d?.filepath??d?.filePath??"",x=d?.diff??"";if(C&&x){let y=PKG.file(C),c=await y.exists()?await y.text():"",i=mt(c,x);i&&await this.connection.extMethod("client.writeTextFile",{sessionId:n,path:C,content:i});}}await this.sdk.permission.reply({requestId:t,reply:I.outcome.optionId});}}).catch(h=>{E.error("failed to handle permission",{error:errorMeta(h),permissionId:t});}).finally(()=>{this.permissionQueues.get(n)===l&&this.permissionQueues.delete(n);});this.permissionQueues.set(n,l);}async handleQuestionAsked(e){let{id:t,sessionId:n,questions:r}=e;E.debug("Handling question asked in ACP bridge",{requestId:t,sessionId:n,questionCount:r.length});try{let o=await this.connection.extMethod("client.requestQuestion",{sessionId:n,requestId:t,questions:r});if(!o){E.warn("Question request returned no result"),await this.sdk.question.reject({requestId:t});return}o.outcome==="selected"&&o.answers&&o.answers.length>0?await this.sdk.question.reply({requestId:t,answers:o.answers.map(d=>[d.answer])}):await this.sdk.question.reject({requestId:t});}catch(o){E.error("Failed to handle question via extMethod",{error:errorMeta(o),requestId:t,sessionId:n}),await this.sdk.question.reject({requestId:t});}}async handleMessagePartUpdated(e){let{part:t}=e,n=await this.getMessageMeta(t.sessionId,t.messageId);n?.role==="assistant"&&(n.agent&&await this.shouldFilterAgent(n.agent)||(t.type==="tool"?await this.handleToolPart(t):t.type==="text"?await this.handleTextPart(t,e.delta):t.type==="reasoning"?await this.handleReasoningPart(t,e.delta):t.type==="step-finish"&&await this.handleStepFinishPart(t)));}async handleToolPart(e){let{sessionId:t,callId:n,tool:r,state:o,messageId:d}=e;if(!t){E.debug("AcpEventBridge: skipping tool part without sessionId",{callId:n,tool:r,messageId:d});return}let p=Ce(r);switch(o.status){case "pending":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call",toolCallId:n,title:r,kind:p,status:"pending",locations:[],rawInput:{},_meta:{messageId:d}}}).catch(l=>{E.error("failed to send tool pending to ACP",{error:errorMeta(l)});});return;case "in_progress":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"in_progress",kind:p,title:r,locations:ye(r,o.input),rawInput:o.input,_meta:{messageId:d}}}).catch(l=>{E.error("failed to send tool in_progress to ACP",{error:errorMeta(l)});});return;case "completed":{let l=[{type:"content",content:{type:"text",text:o.output}}];if(p==="edit"){let h=o.input,b=h.filePath??h.filepath??"",I=h.oldString??"",C=h.newString??h.content??"";l.push({type:"diff",path:b,oldText:I,newText:C});}if(r==="todo"){let h=TodoListSchema.safeParse(JSON.parse(o.output));h.success&&o.input.operation==="write"&&await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"plan",entries:h.data.map(b=>{let I=b.status==="cancelled"?"completed":b.status;return {priority:b.priority,status:I,content:b.content}})}}).catch(b=>{E.error("failed to send session update for todo",{error:errorMeta(b)});});}await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"completed",kind:p,content:l,title:o.title??r,rawInput:o.input,rawOutput:{output:o.output,metadata:o.metadata},_meta:{messageId:d}}}).catch(h=>{E.error("failed to send tool completed to ACP",{error:errorMeta(h)});});return}case "failed":await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"tool_call_update",toolCallId:n,status:"failed",kind:p,title:r,rawInput:o.input,content:[{type:"content",content:{type:"text",text:o.error}}],rawOutput:{error:o.error},_meta:{messageId:d}}}).catch(l=>{E.error("failed to send tool error to ACP",{error:errorMeta(l)});});return}}async handleTextPart(e,t){if(e.ignored===true)return;if(!e.sessionId){E.debug("AcpEventBridge: skipping text part without sessionId",{messageId:e.messageId});return}if(!("time"in e&&e.time&&typeof e.time=="object"&&"end"in e.time&&!!e.time.end))return;let r=e.text;r&&await this.connection.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_message_chunk",messageId:e.messageId,content:{type:"text",text:r}}}).catch(o=>{E.error("failed to send text to ACP",{error:errorMeta(o)});});}async handleReasoningPart(e,t){if(!e.sessionId){E.debug("AcpEventBridge: skipping reasoning part without sessionId",{messageId:e.messageId});return}if(!("time"in e&&e.time&&typeof e.time=="object"&&"end"in e.time&&!!e.time.end))return;let r=e.text;r&&await this.connection.sessionUpdate({sessionId:e.sessionId,update:{sessionUpdate:"agent_thought_chunk",messageId:e.messageId,content:{type:"text",text:r}}}).catch(o=>{E.error("failed to send reasoning to ACP",{error:errorMeta(o)});});}async handleStepFinishPart(e){let{sessionId:t,messageId:n,tokens:r}=e;if(!this.connection)return;if(!t){E.debug("AcpEventBridge: skipping step-finish part without sessionId",{messageId:n});return}let o=(r?.input??0)+(r?.reasoning??0),d=await this.getContextLimit(t,n);await this.connection.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:o,size:d,_meta:{messageId:n}}}).catch(p=>{E.error("failed to send usage_update for step-finish",{error:errorMeta(p)});});}async getContextLimit(e,t){try{let r=(await this.sdk.session.messages({sessionId:e}).then(o=>o.data).catch(()=>{}))?.find(o=>o.info.id===t);if(r){let o=r.info;if(o.providerId&&o.modelId)return (await this.sdk.config.providers({}).then(h=>h.data?.providers??[]).catch(()=>[])).find(h=>h.id===o.providerId)?.models[o.modelId]?.limit?.context??2e5}}catch(n){E.errorDegradable("failed to get context limit",{error:errorMeta(n)});}return 2e5}async getMessageMeta(e,t){let n=`${e}:${t}`,r=this._messageMetaCache.get(n);if(r)return r;let o=await this.sdk.session.message({sessionId:e,messageId:t},{throwOnError:true}).then(p=>p.data).catch(p=>{p instanceof Error&&p.name!=="NotFoundError"&&E.error("unexpected error when fetching message",{error:errorMeta(p),sessionId:e,messageId:t});});if(!o)return;let d={role:o.info.role,agent:o.info.agent};return this._messageMetaCache.set(n,d),d}clearMessageMetaCache(e){let t=`${e}:`;for(let n of this._messageMetaCache.keys())n.startsWith(t)&&this._messageMetaCache.delete(n);}async shouldFilterAgent(e){if(!this._cachedPrimaryAgents)try{let n=(await this.sdk.agent.list({})).data||[];this._cachedPrimaryAgents=new Set(n.filter(r=>r.mode==="primary"&&r.hidden!==!0).map(r=>r.name));}catch{this._cachedPrimaryAgents=new Set;}return !this._cachedPrimaryAgents.has(e)}};function Ce(s){switch(s.toLowerCase()){case "bash":return "execute";case "webfetch":return "fetch";case "edit":case "patch":case "write":return "edit";case "grep":case "glob":case "lsp":case "context7_resolve_library_id":case "context7_get_library_docs":return "search";case "list":case "read":return "read";default:return "other"}}function ye(s,e){if(!e)return [];switch(s.toLowerCase()){case "read":case "edit":case "write":case "patch":case "lsp":{let n=e.filePath??e.filepath??"";return n?[{path:n}]:[]}case "glob":case "grep":return e.path?[{path:e.path}]:[];case "list":return e.path?[{path:e.path}]:[];case "bash":case "shell":{let n=e.cwd??"";return n?[{path:n}]:[]}case "external_directory":{let n=e.tool?.toLowerCase(),r=e.filepath??"",o=e.realPath??"",d=e.parentDir??"";if(n==="read"||n==="edit"||n==="write"||n==="patch"||n==="lsp")return o?[{path:o}]:r?[{path:r}]:[];if(n==="list"||n==="glob"||n==="grep"){let l=o??r,h=l?pt.posix.dirname(l):d;return h?[{path:h}]:[]}let p=o??r;return p?[{path:p}]:d?[{path:d}]:[]}default:return []}}function mt(s,e){try{let t=applyPatch(s,e);return t===!1?null:t}catch{return null}}var Z=Log.create({service:"acp.connection.registry"}),le;(i=>{let s=null;async function e(){return s||(s=await c.create()),s}async function t(g){return s||(s=await c.create(g),Z.info("ServerConnectionRegistry initialized")),s}i.init=t;async function n(g){return (await e()).connect(g.baseUrl,g.localAgentId,g.remoteAgentId,g.remoteSessionId,g.localSessionId)}i.connect=n;async function r(g){return (await e()).resolve(g)}i.resolve=r;function o(g){if(s)return s.resolve(g)}i.resolveSync=o;async function d(g){(await e()).closeConnection(g);}i.close=d;async function p(g,a){(await e()).markDegraded(g,a);}i.markDegraded=p;async function l(g){return (await e()).getConnectionsByAgent(g)}i.getConnectionsByLocalAgent=l;async function h(g){return (await e()).getConnectionsByService(g)}i.getConnectionsByService=h;async function b(){return (await e()).getAllActiveConnections()}i.getAllActiveConnections=b;async function I(g,a){(await e()).updateLastSeenMessageId(g,a);}i.updateLastSeenMessageId=I;async function C(g,a){(await e()).updateSessionUpdates(g,a);}i.updateSessionUpdates=C;async function x(g,a){let u=await e(),m=u.resolve(g);m&&u.updateSessionUpdates(m.connectionId,a);}i.updateSessionUpdatesBySessionId=x;function y(g){if(s)return s.findConnectionIdBySubscriber(g)}i.findConnectionIdBySubscriber=y;class c{constructor(a$1){a(this,"defaultHistoryScope");a(this,"defaultHistoryWindowSize");a(this,"defaultDegradePolicy");a(this,"agentIndex",new Map);a(this,"serviceIndex",new Map);a(this,"connections",new Map);this.defaultHistoryScope=a$1?.defaultHistoryScope??"session",this.defaultHistoryWindowSize=a$1?.defaultHistoryWindowSize??10,this.defaultDegradePolicy=a$1?.defaultDegradePolicy??"streaming_first",Z.debug("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(a){return new c(a)}connect(a,u,m,P,f){let v=this.agentIndex.get(u);if(v)for(let M of v){let R=this.connections.get(M);if(R&&R.baseUrl===a&&R.status!=="closed")return P&&R.sessionId!==P&&(R.sessionId=P,R.sessionSequence=R.sessionSequence??[],R.sessionSequence.includes(P)||R.sessionSequence.push(P),R.remoteSessionStatus="idle"),f&&(R.localSessionId=f),R.updatedAt=Date.now(),{connectionId:R.connectionId,sessionId:R.sessionId,localAgentId:R.localAgentId,remoteAgentId:R.remoteAgentId,baseUrl:R.baseUrl}}let S=this.generateConnectionId(),_=P??`session-${this.generateShortId()}`,k={localAgentId:u,remoteAgentId:m,connectionId:S,sessionId:_,...f?{localSessionId:f}:{},baseUrl:a,historyScope:this.defaultHistoryScope,historyWindowSize:this.defaultHistoryWindowSize,degradePolicy:this.defaultDegradePolicy,updatedAt:Date.now(),status:"active",remoteSessionStatus:"idle"};return this.connections.set(S,k),this.agentIndex.has(u)||this.agentIndex.set(u,new Set),this.agentIndex.get(u).add(S),this.serviceIndex.has(a)||this.serviceIndex.set(a,new Set),this.serviceIndex.get(a).add(S),{connectionId:S,sessionId:_,localAgentId:u,remoteAgentId:m,baseUrl:a}}resolve(a,u=false){let m=this.connections.get(a);if(m)return m;let P=this.agentIndex.get(a);if(P&&P.size>0)for(let f of P){let v=this.connections.get(f);if(v&&v.status!=="closed")return v}for(let f of this.connections.values())if(f.status!=="closed"&&(f.sessionId===a||f.localSessionId===a))return f;if(u){let S=this.connect("http://localhost","system-local","system-remote",a);return this.connections.get(S.connectionId)}}closeConnection(a){let u=this.connections.get(a);if(!u)return;this.connections.delete(a);let m=this.agentIndex.get(u.localAgentId);m&&(m.delete(a),m.size===0&&this.agentIndex.delete(u.localAgentId));let P=this.serviceIndex.get(u.baseUrl);P&&(P.delete(a),P.size===0&&this.serviceIndex.delete(u.baseUrl)),Z.debug("connection closed and removed",{connectionId:a,localAgentId:u.localAgentId,remoteAgentId:u.remoteAgentId});}markDegraded(a,u){let m=this.connections.get(a);m&&(m.status="degraded",m.updatedAt=Date.now(),Z.debug("connection marked degraded",{connectionId:a,reason:u}));}getConnectionsByAgent(a){let u=this.agentIndex.get(a);return u?Array.from(u).map(m=>this.connections.get(m)).filter(m=>m!==void 0&&m.status!=="closed"):[]}getConnectionsByService(a){let u=this.serviceIndex.get(a);return u?Array.from(u).map(m=>this.connections.get(m)).filter(m=>m!==void 0&&m.status!=="closed"):[]}getAllActiveConnections(){return Array.from(this.connections.values()).filter(a=>a.status!=="closed")}updateLastSeenMessageId(a,u){let m=this.connections.get(a);m&&(m.lastSeenMessageId=u,m.updatedAt=Date.now());}updateSessionUpdates(a,u){let m=this.connections.get(a);m&&(u.availableCommands!==void 0&&(m.availableCommands=u.availableCommands),u.configOptions!==void 0&&(m.configOptions=u.configOptions),u.currentModeId!==void 0&&(m.currentModeId=u.currentModeId),u.remoteSessionStatus!==void 0&&(m.remoteSessionStatus=u.remoteSessionStatus),m.updatedAt=Date.now(),Z.debug("connection session updates",{connectionId:a,hasCommands:!!u.availableCommands,hasConfig:!!u.configOptions,hasMode:!!u.currentModeId}));}findConnectionIdBySubscriber(a){for(let[u,m]of this.connections)if(m.subscriber===a)return u}generateConnectionId(){return `conn-${this.generateShortId()}`}generateShortId(){return createHash("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").substring(0,8)}async close(){this.connections.clear(),this.agentIndex.clear(),this.serviceIndex.clear(),s=null,Z.info("connection registry closed");}}i.ConnectionRegistry=c;})(le||(le={}));var j=Log.create({service:"acp.connection.router"}),vt=(o=>(o.EMPTY_CONTEXT="EMPTY_CONTEXT",o.AMBIGUOUS_ROUTE="AMBIGUOUS_ROUTE",o.NOT_FOUND="NOT_FOUND",o.CONNECTION_CLOSED="CONNECTION_CLOSED",o.MISSING_REQUIRED_PARAMS="MISSING_REQUIRED_PARAMS",o))(vt||{});function ue(s,e,t){return new c.RoutingError({message:e,code:s,context:t})}var Ae=class s{static create(){return new s}constructor(){j.info("session router created");}route(e){if(!this.isValidContext(e))return {success:false,error:"routing context is empty or invalid"};try{return e.connectionId?this.routeByConnectionId(e.connectionId):e.localAgentId&&e.baseUrl?this.routeByPeerAndBaseUrl(e.localAgentId,e.baseUrl):e.baseUrl&&e.sessionId?this.routeByBaseUrlAndSessionId(e.baseUrl,e.sessionId):{success:!1,error:"insufficient routing parameters: need connectionId, or localAgentId+baseUrl, or baseUrl+sessionId"}}catch(t){let n=errorMeta(t).message;return j.error("routing failed",{context:e,error:errorMeta(t)}),{success:false,error:n}}}routeOrThrow(e){let t=this.route(e);if(!t.success)throw ue(this.getErrorCode(t.error),t.error??"routing failed",e);if(!t.connectionId)throw ue("NOT_FOUND","connection not found",e);let n=this.getConnectionState(t.connectionId);if(!n)throw ue("NOT_FOUND","connection state not found",e);if(n.status==="closed")throw ue("CONNECTION_CLOSED","connection is closed",e);return n}registerConnection(e){return !e.connectionId||!e.localAgentId||!e.remoteAgentId||!e.baseUrl||!e.sessionId?{success:false,error:"invalid connection state: missing required fields"}:(j.debug("connection registered",{connectionId:e.connectionId,localAgentId:e.localAgentId,remoteAgentId:e.remoteAgentId,baseUrl:e.baseUrl}),{success:true,connectionId:e.connectionId,sessionId:e.sessionId,localAgentId:e.localAgentId,remoteAgentId:e.remoteAgentId,baseUrl:e.baseUrl})}unregisterConnection(e){let t=this.getConnectionState(e);return t?(j.debug("connection unregistered",{connectionId:e,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}),true):(j.debug("connection not found for unregister",{connectionId:e}),false)}isValidContext(e){return !!(e.connectionId||e.remoteAgentId||e.baseUrl||e.sessionId)}routeByConnectionId(e){let t=this.getConnectionState(e);return t?t.status==="closed"?{success:false,error:`connection is closed: ${e}`}:{success:true,connectionId:t.connectionId,sessionId:t.sessionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}:{success:false,error:`connection not found: ${e}`}}routeByPeerAndBaseUrl(e,t){let r=this.getConnectionsByPeer(e).filter(d=>d.baseUrl===t&&d.status!=="closed");if(r.length===0)return {success:false,error:`no connection found for localAgentId=${e}, baseUrl=${t}`};if(r.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${e}, baseUrl=${t}`};let o=r[0];return {success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}}routeByBaseUrlAndSessionId(e,t){let r=this.getConnectionsByService(e).filter(d=>d.sessionId===t&&d.status!=="closed");if(r.length===0)return {success:false,error:`no connection found for baseUrl=${e}, sessionId=${t}`};if(r.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${e}, sessionId=${t}`};let o=r[0];return {success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}}getConnectionState(e){j.warn("getConnectionState not implemented, returning undefined",{connectionId:e});}getConnectionsByPeer(e){return j.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:e}),[]}getConnectionsByService(e){return j.warn("getConnectionsByService not implemented, returning empty array",{baseUrl:e}),[]}getErrorCode(e){return e?e.includes("empty")||e.includes("invalid")?"EMPTY_CONTEXT":e.includes("ambiguous")?"AMBIGUOUS_ROUTE":e.includes("not found")?"NOT_FOUND":e.includes("closed")?"CONNECTION_CLOSED":e.includes("insufficient")||e.includes("missing")?"MISSING_REQUIRED_PARAMS":"NOT_FOUND":"NOT_FOUND"}},pe=class s extends Ae{constructor(t){super();a(this,"registry");this.registry=t,j.info("registry session router created");}static fromRegistry(t){return new s(t)}getConnectionState(t){return this.registry.resolve(t)}getConnectionsByPeer(t){return this.registry.getConnectionsByPeer(t)}getConnectionsByService(t){return this.registry.getConnectionsByService(t)}};var Ie=["general","coder"],Ne="general";var ge=Log.create({service:"acp.session"}),ne=class{constructor(e){a(this,"sessions",new Map);a(this,"sdk");this.sdk=e;}tryGet(e){return this.sessions.get(e)}async create(e,t,n,r){let d={id:e,cwd:t,mcpServers:n,createdAt:new Date,model:r};return ge.info("creating_session",{state:d}),this.sessions.set(e,d),d}async load(e,t,n,r){let o=await this.sdk.session.get({sessionId:e},{throwOnError:true}).then(l=>l.data),d=r,p={id:e,cwd:t,mcpServers:n,createdAt:new Date(o.time.created),model:d};return ge.debug("loading_session",{state:p}),this.sessions.set(e,p),p}get(e){let t=this.sessions.get(e);if(!t)throw ge.error("session not found",{sessionId:e}),RequestError.invalidParams(JSON.stringify({error:`Session not found: ${e}`}));return t}getModel(e){return this.get(e).model}setModel(e,t){let n=this.get(e);return n.model=t,this.sessions.set(e,n),n}getVariant(e){return this.get(e).variant}setVariant(e,t){let n=this.get(e);return n.variant=t,this.sessions.set(e,n),n}setMode(e,t){let n=this.get(e);return n.modeId=t,this.sessions.set(e,n),n}setContextMode(e,t){let n=this.get(e);return n.contextMode=t,this.sessions.set(e,n),n}setAgent(e,t){let n=this.get(e);return n.agent=t,this.sessions.set(e,n),n}close(e){return this.sessions.delete(e)}dispose(){this.sessions.clear(),ge.debug("all sessions cleared");}resolveConnectionState(e){}};var A=Log.create({service:"acp.acp.service"}),se=class{constructor(e,t){a(this,"config");a(this,"serviceMode");a(this,"connection");a(this,"sdk");a(this,"connectionRegistry",null);a(this,"sessionRouter",null);a(this,"sessionManager");a(this,"executorInitialized",false);a(this,"status","initializing");this.connection=e,this.config=t,this.sdk=t.acp.sdk,this.serviceMode=t.serviceMode,this.sessionManager=new ne(this.sdk),t.connectionRegistry&&(this.connectionRegistry=t.connectionRegistry),t.sessionRouter&&(this.sessionRouter=t.sessionRouter),A.info("ACPService instance created",{channel:t.channel.type,hasConnection:!!e,hasProvidedRegistry:!!t.connectionRegistry,hasProvidedRouter:!!t.sessionRouter});}async initializeExecutor(){if(this.executorInitialized){A.warn("Executor components already initialized");return}this.connectionRegistry||(this.connectionRegistry=await le.init(),A.debug("ServerConnectionRegistry initialized")),this.sessionRouter||(this.sessionRouter=pe.fromRegistry({resolve:e=>this.connectionRegistry.resolve(e),getConnectionsByPeer:e=>this.connectionRegistry.getConnectionsByAgent(e),getConnectionsByService:e=>this.connectionRegistry.getConnectionsByService(e)}),A.debug("SessionRouter created")),this.executorInitialized=true,A.info("Executor components initialized");}setStatus(e,t="agent"){let n=this.status;if(n===e)return;this.status=e,A.debug("Agent status changed",{oldStatus:n,newStatus:e,agentId:t});}getStatus(){return this.status}authenticate(e){return Promise.resolve(void 0)}async newSession(e){A.debug("ACP newSession requested",{cwd:e.cwd});let t=e.cwd,r=(await this.sdk.model.default())?.data,d=(await this.sdk.session.create({directory:t})).data?.id;if(!d)throw new NameErrors.OperationFailedError({message:"Failed to create session: no session ID returned",operation:"acp-session-create"});let p=await this.sessionManager.create(d,t,e.mcpServers,r),l=await this.buildSessionStateResponse(p.id,t);return {sessionId:p.id,...l,_meta:{}}}async loadSession(e){A.debug("ACP loadSession requested",{sessionId:e.sessionId});let t=e.cwd,r=(await this.sdk.model.default())?.data;return await this.sessionManager.load(e.sessionId,t,e.mcpServers,r),{...await this.buildSessionStateResponse(e.sessionId,t),_meta:{}}}async prompt(e){let t=e.sessionId,n=this.sessionManager.get(t),r=n.cwd,o=e._meta??{},d=typeof o.agent=="string"&&o.agent?o.agent:void 0,p=typeof o.model=="string"&&o.model?parseModelId(o.model):void 0,l=n.model,h=p?.providerId?{providerId:p.providerId,modelId:p.modelId}:p?.modelId?{providerId:l?.providerId??"",modelId:p.modelId}:l??(await this.sdk.model.default())?.data,b=d??n.agent??(await this.sdk.agent.default())?.data?.name??"build";this.sendAvailableCommandsUpdate(t).catch(y=>{A.warn("Failed to send initial available commands update",{sessionId:t,directory:r,error:errorMeta(y)});});let I=[];for(let y of e.prompt)switch(y.type){case "text":{let c=y.annotations?.audience,i=c?.length===1&&c[0]==="assistant",g=c?.length===1&&c[0]==="user";I.push({type:"text",text:y.text,...i&&{synthetic:true},...g&&{ignored:true}});break}case "image":{let c=this.parseUri(y.uri??""),i=c.type==="file"?c.filename:"image";y.data?I.push({type:"file",url:`data:${y.mimeType};base64,${y.data}`,filename:i,mime:y.mimeType}):y.uri?.startsWith("http:")&&I.push({type:"file",url:y.uri,filename:i,mime:y.mimeType});break}case "resource_link":{let c=this.parseUri(y.uri);y.name&&c.type==="file"&&(c.filename=y.name),I.push(c);break}case "resource":{let c=y.resource;if("text"in c&&c.text)I.push({type:"text",text:c.text});else if("blob"in c&&c.blob&&c.mimeType){let i=this.parseUri(c.uri??""),g=i.type==="file"?i.filename:"file";I.push({type:"file",url:`data:${c.mimeType};base64,${c.blob}`,filename:g,mime:c.mimeType});}break}}A.debug("prompt parts",{sessionId:t,parts:I});let C=(()=>{let y=I.filter(u=>u.type==="text").map(u=>u.text).join("").trim();if(!y.startsWith("/"))return;let c=ParseCommand.tokenize(y.slice(1));if(c.length===0)return;let[i,...g]=c,a=g.join(" ").trim();return A.debug("command",{name:i,args:a}),{name:i,args:a}})();if(!C)return this.sdk.session.prompt({sessionId:t,model:{providerId:h.providerId,modelId:h.modelId},parts:I,agent:b,variant:n.variant,contextMode:n.contextMode}).catch(y=>{A.error("prompt execution failed",{sessionId:t,error:errorMeta(y)});}),{stopReason:"end_turn",_meta:{}};let x=await this.sdk.command.get({name:C.name},{throwOnError:true}).then(y=>y.data);if(x)return x.commandType==="local"&&this.connection?(this.sdk.session.command({sessionId:t,command:x.name,arguments:C.args??"",agent:b,model:formatModelId(h),variant:n.variant,contextMode:n.contextMode,parts:I}).then(async y=>{let c=y.data?.success?y.data.output:`[Error] ${y.data?.error??"Command execution failed"}`;this.connection?.sessionUpdate({sessionId:t,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}});let i=await this.getContextLimit(h.providerId,h.modelId,r);i&&this.connection?.sessionUpdate({sessionId:t,update:{sessionUpdate:"usage_update",used:0,size:i}});}).catch(y=>{A.error("local command execution failed",{command:x.name,error:errorMeta(y)});}),{stopReason:"end_turn",_meta:{}}):(this.sdk.session.command({sessionId:t,command:x.name,arguments:C.args??"",agent:b,model:formatModelId(h),variant:n.variant,contextMode:n.contextMode,parts:I}).catch(y=>{A.error("prompt command execution failed",{command:x.name,error:errorMeta(y)});}),{stopReason:"end_turn",_meta:{}});switch(C.name){case "compact":if(!h.providerId||!h.modelId)throw new NameErrors.MissingFieldError({message:"Model providerId and modelId are required for compact command",field:"model"});await this.sdk.session.summarize({sessionId:t,providerId:h.providerId,modelId:h.modelId},{throwOnError:true});break}return await this.sendUsageUpdate(t,r),{stopReason:"end_turn",_meta:{}}}async cancel(e){this.sessionManager.tryGet(e.sessionId)?.cwd??"";try{this.sdk&&await this.sdk.session.abort({sessionId:e.sessionId}).catch(r=>{A.warn("SDK abort failed",{sessionId:e.sessionId,error:errorMeta(r)});}),A.debug("Session cancelled",{sessionId:e.sessionId});}catch(r){throw A.error("Failed to cancel session",{sessionId:e.sessionId,error:errorMeta(r)}),r}}parseUri(e){try{if(e.startsWith("file://")){let t=e.slice(7),n=t.split("/").pop()||t;return {type:"file",url:e,filename:n,mime:"text/plain"}}if(e.startsWith("zed://")){let n=new URL(e).searchParams.get("path");if(n){let r=n.split("/").pop()||n;return {type:"file",url:pathToFileURL(n).href,filename:r,mime:"text/plain"}}}return {type:"text",text:e}}catch{return {type:"text",text:e}}}async sendUsageUpdate(e,t){if(!this.sdk||!this.connection)return;if(!e){A.debug("sendUsageUpdate: skipping, sessionId is empty");return}let n=await this.sdk.session.messages({sessionId:e},{throwOnError:true}).then(h=>h.data).catch(h=>{A.error("failed to fetch messages for usage update",{error:errorMeta(h)});});if(!n)return;let r=n.filter(h=>h.info.role==="assistant"),o=r[r.length-1];if(!o)return;let d=o.info,p=await this.getContextLimit(d.providerId,d.modelId,t);if(!p)return;let l=d.tokens.input+(d.tokens.cache?.read??0);await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"usage_update",used:l,size:p}});}async sendAvailableCommandsUpdate(e,t){if(this.sdk&&this.connection){if(!e){A.debug("sendAvailableCommandsUpdate: skipping, sessionId is empty");return}try{let r=this.sessionManager.get(e)?.contextMode,d=(await this.sdk.command.list({contextMode:r},{throwOnError:!0})).data?.filter(p=>!p.hidden).map(p=>({name:p.name,description:p.description??""}))??[];await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:d}});}catch(n){A.error("failed to send available commands update",{error:errorMeta(n)});}}}async sendConfigOptionUpdate(e,t,n){if(this.connection){if(!e){A.debug("sendConfigOptionUpdate: skipping, sessionId is empty");return}try{let o=(n??await this.buildSessionStateResponse(e,t)).configOptions;if(!o||o.length===0)return;await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"config_option_update",configOptions:o}});}catch(r){A.error("failed to send config_option_update to ACP client",{sessionId:e,error:errorMeta(r)});}}}async sendCurrentModeUpdate(e,t){if(this.connection){if(!e){A.debug("sendCurrentModeUpdate: skipping, sessionId is empty");return}try{await this.connection.sessionUpdate({sessionId:e,update:{sessionUpdate:"current_mode_update",currentModeId:t}});}catch(n){A.error("failed to send current_mode_update to ACP client",{sessionId:e,modeId:t,error:errorMeta(n)});}}}async getContextLimit(e,t,n){return this.sdk?(await this.sdk.config.providers({}).then(p=>p.data?.providers??[]).catch(p=>(A.error("failed to get providers for context limit",{error:errorMeta(p)}),[]))).find(p=>p.id===e)?.models[t]?.limit.context??2e5:null}async unstable_forkSession(e){A.debug("ACP forkSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.mcpServers??[],o=(await this.sdk.model.default())?.data,d=await this.sdk.session.fork({sessionId:e.sessionId,directory:t},{throwOnError:true}).then(b=>b.data);if(!d)throw new NameErrors.OperationFailedError({message:"Fork session returned no data",operation:"acp-session-fork"});let p=d.id;await this.sessionManager.load(p,t,n,o);let h=await this.buildSessionStateResponse(p,t);return A.debug("fork_session",{sessionId:p,mcpServers:n.length}),{sessionId:p,...h,_meta:{}}}async resumeSession(e){A.debug("ACP resumeSession requested",{sessionId:e.sessionId});let t=e.cwd,n=e.sessionId,r=e.mcpServers??[],d=(await this.sdk.model.default())?.data;await this.sessionManager.load(n,t,r,d);let l=await this.buildSessionStateResponse(n,t);return A.debug("resume_session",{sessionId:n,mcpServers:r.length}),{...l,_meta:{}}}async listSessions(e){let t=e.cursor?Number(e.cursor):void 0,n=100,o=(await this.sdk.session.list({directory:e.cwd??void 0,roots:true},{throwOnError:true}).then(I=>I.data??[])).toSorted((I,C)=>C.time.updated-I.time.updated),p=(t?o.filter(I=>I.time.updated<t):o).slice(0,n),l=p.map(I=>({sessionId:I.id,cwd:I.directory,title:I.title??`Session ${I.id}`,updatedAt:new Date(I.time.updated).toISOString()})),h=p[p.length-1],b=p.length===n&&h?String(h.time.updated):void 0;return {sessions:l,nextCursor:b}}async setSessionMode(e){A.debug("ACP setSessionMode requested",{sessionId:e.sessionId,modeId:e.modeId}),this.sessionManager.setMode(e.sessionId,e.modeId);let t=this.sessionManager.get(e.sessionId);return await this.sendCurrentModeUpdate(e.sessionId,e.modeId),await this.sendConfigOptionUpdate(e.sessionId,t.cwd),{_meta:{}}}async setSessionConfigOption(e){if(A.debug("ACP setSessionConfigOption requested",{sessionId:e.sessionId,configId:e.configId,value:e.value}),e.configId==="model"){let r=typeof e.value=="string"?e.value:void 0;if(r){let o=this.parseModelSelection(r);this.sessionManager.setModel(e.sessionId,o.model);}}else if(e.configId==="agent"){let r=typeof e.value=="string"?e.value:void 0;this.sessionManager.setAgent(e.sessionId,r);}else if(e.configId==="thought_level"){let r=typeof e.value=="string"?e.value:void 0;this.sessionManager.setVariant(e.sessionId,r);}else if(e.configId==="context_mode"){let r=typeof e.value=="string"&&Ie.includes(e.value)?e.value:void 0;this.sessionManager.setContextMode(e.sessionId,r);}let t=this.sessionManager.get(e.sessionId),n=await this.buildSessionStateResponse(e.sessionId,t.cwd);return await this.sendConfigOptionUpdate(e.sessionId,t.cwd,n),{_meta:{},configOptions:n.configOptions??[]}}async closeSession(e){return A.debug("ACP closeSession requested",{sessionId:e.sessionId}),await this.cancel({sessionId:e.sessionId}),this.sessionManager.close(e.sessionId),{_meta:{}}}async buildSessionStateResponse(e,t){let n=this.sessionManager.tryGet(e),r=n?.model??(await this.sdk.model.default())?.data,o=r?.providerId&&r?.modelId?formatModelId(r):void 0,d=[];try{d=(await this.sdk.config.providers({}).then(x=>x.data?.providers??[])).flatMap(x=>{let y=x.models??{};return Object.keys(y).map(c=>({modelId:`${x.id}/${c}`,name:`${x.id}/${c}`}))});}catch(C){A.warn("failed to build available models for session state",{sessionId:e,error:errorMeta(C)});}o&&!d.some(C=>C.modelId===o)&&(d=[{modelId:o,name:o},...d]);let p=[];try{p=((await this.sdk.agent.list({})).data??[]).filter(y=>y.hidden!==!0&&y.mode!=="subagent").map(y=>({id:y.name,name:y.name,description:y.description}));}catch(C){A.warn("failed to build available agents for session state",{sessionId:e,error:errorMeta(C)});}let l=n?.modeId,h=n?.variant??"low",b=n?.contextMode??Ne,I=n?.agent??"build";return await this.sendAvailableCommandsUpdate(e,t),{models:o?{currentModelId:o,availableModels:d}:void 0,modes:l?{currentModeId:l,availableModes:[{id:l,name:l}]}:void 0,configOptions:[{id:"model",name:"Model",category:"model",type:"select",currentValue:o??"",options:d.map(C=>({value:C.modelId,name:C.name,description:C.description??null}))},{id:"agent",name:"Agent",category:"agent",type:"select",currentValue:I,options:p.map(C=>({value:C.id,name:C.name,description:C.description??null}))},{id:"thought_level",name:"Thought Level",category:"thought_level",type:"select",currentValue:h,options:[{value:"off",name:"Off"},{value:"low",name:"Low"},{value:"medium",name:"Medium"},{value:"high",name:"High"}]},{id:"context_mode",name:"Context Mode",category:"context_mode",type:"select",currentValue:b,options:Ie.map(C=>({value:C,name:C.charAt(0).toUpperCase()+C.slice(1)}))}]}}parseModelSelection(e){let t=parseModelId(e);if(t.providerId&&t.modelId)return {model:{providerId:t.providerId,modelId:t.modelId}};throw new NameErrors.InvalidArgumentError({message:`Invalid model id: "${e}" (expected format: <providerId>/<modelId>)`,param:"modelId"})}setConnection(e){this.connection=e,A.debug("ACPService connection updated");}getConnection(){return this.connection}setServerConnection(e){this.connection=e,A.debug("ACPService serverConnection updated");}abortConnection(){this.connection&&A.debug("Connection aborted");}closeConnection(){this.connection&&A.debug("Connection closed");}getServerConnectionRegistry(){return this.connectionRegistry}getSessionRouter(){return this.sessionRouter}createConnection(e,t,n,r){if(!this.connectionRegistry)throw new NameErrors.OperationFailedError({message:"ServerConnectionRegistry not initialized. Call initializeExecutor() first.",operation:"acp-connect"});if(!t||!n)throw new NameErrors.MissingFieldError({message:"localAgentId and remoteAgentId are required",field:"agentIds"});return this.connectionRegistry.connect(e,t,n,r)}async routeToConnection(e){if(!this.sessionRouter)throw new NameErrors.OperationFailedError({message:"SessionRouter not initialized. Call initializeExecutor() first.",operation:"acp-route"});return this.sessionRouter.route(e)}async dispose(){A.info("Disposing ACPService"),this.sessionManager&&(this.sessionManager.dispose?.(),A.debug("SessionManager disposed")),this.connectionRegistry&&(await this.connectionRegistry.close(),this.connectionRegistry=null,A.debug("ServerConnectionRegistry closed")),this.sessionRouter=null,this.executorInitialized=false,A.info("ACPService disposed");}};var F={HTTP:b.HTTP,STDIO:b.STDIO,WEBSOCKET:b.WS};function Be(s,e=[]){return new c.ServiceModeConflictError({message:s,conflictingModes:e})}function Rt(s){let e=[];return s.channel&&e.push(s.channel),e}function De(s){let e=Rt(s);if(e.length===0)throw Be("No service mode specified. Please specify exactly one of: http, stdio, websocket",[]);if(e.length>1)throw Be(`Multiple service modes specified: ${e.join(", ")}. Please specify exactly one mode.`,e)}var Pe={channel:F.WEBSOCKET,port:3e3,hostname:"localhost",timeout:3e4,historyScope:"session",historyWindowSize:10,degradePolicy:"streaming_first",sessionExpireMs:300*1e3};var D=Log.create({service:"acp.server.config"}),Q="EAS_";function He(s){return !(!s||s.trim()===""||s.startsWith("-")||s.endsWith("-")||!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(s))}function ze(s){return Number.isInteger(s)&&s>=1&&s<=65535}function Le(s){return Number.isFinite(s)&&s>0}function kt(s){let e={...Pe,...s};try{De(e);}catch(t){throw f$1(t)&&D.error("Invalid service mode configuration",{message:errorMeta(t).message,conflictingModes:t.data.conflictingModes}),t}if(e.port!==void 0&&!ze(e.port))throw D.error("Invalid port configuration",{port:e.port}),new NameErrors.InvalidArgumentError({message:`Invalid port number: ${e.port}. Must be between 1 and 65535`,param:"port"});if(e.hostname!==void 0&&!He(e.hostname))throw D.error("Invalid hostname configuration",{hostname:e.hostname}),new NameErrors.InvalidArgumentError({message:`Invalid hostname: ${e.hostname}`,param:"hostname"});if(e.timeout!==void 0&&!Le(e.timeout))throw D.error("Invalid timeout configuration",{timeout:e.timeout}),new NameErrors.InvalidArgumentError({message:`Invalid timeout: ${e.timeout}. Must be a positive number`,param:"timeout"});if(e.channel===F.STDIO&&e.stdio&&(!e.stdio.command||e.stdio.command.trim()===""))throw D.error("Invalid stdio configuration",{command:e.stdio.command}),new NameErrors.MissingFieldError({message:"STDIO command is required",field:"command"});return D.debug("ACPServer config loaded",{channel:e.channel,port:e.port,hostname:e.hostname}),e}function Fe(){let s={},e=process.env[`${Q}ACP_CHANNEL`];if(e){let l=e.toLowerCase();Object.values(F).includes(l)?s.channel=l:D.warn("Invalid EAS_ACP_CHANNEL environment variable",{value:e});}let t=process.env[`${Q}ACP_PORT`];if(t){let l=parseInt(t,10);ze(l)?s.port=l:D.warn("Invalid EAS_ACP_PORT environment variable",{value:t});}let n=process.env[`${Q}ACP_HOSTNAME`];n&&(He(n)?s.hostname=n:D.warn("Invalid EAS_ACP_HOSTNAME environment variable",{value:n}));let r=process.env[`${Q}ACP_TIMEOUT`];if(r){let l=parseInt(r,10);Le(l)?s.timeout=l:D.warn("Invalid EAS_ACP_TIMEOUT environment variable",{value:r});}let o=process.env[`${Q}ACP_HISTORY_SCOPE`];o&&(["session","peer","global"].includes(o)?s.historyScope=o:D.warn("Invalid EAS_ACP_HISTORY_SCOPE environment variable",{value:o}));let d=process.env[`${Q}ACP_HISTORY_WINDOW_SIZE`];if(d){let l=parseInt(d,10);Number.isInteger(l)&&l>0?s.historyWindowSize=l:D.warn("Invalid EAS_ACP_HISTORY_WINDOW_SIZE environment variable",{value:d});}let p=process.env[`${Q}ACP_DEGRADE_POLICY`];return p&&(["polling_only","streaming_first"].includes(p)?s.degradePolicy=p:D.warn("Invalid EAS_ACP_DEGRADE_POLICY environment variable",{value:p})),D.debug("Config loaded from environment",{config:s}),s}function cs(s){let e=Fe(),t={...e,...s};return D.info("ACPServer config with environment overrides",{original:{channel:e.channel,port:e.port,hostname:e.hostname},overrides:s,final:{channel:t.channel,port:t.port,hostname:t.hostname}}),t}function $e(s){let e=Fe(),t={...Pe,...e,...s},n=kt(t);return D.info("ACPServer config resolved (default < env < explicit)",{env:{channel:e.channel,port:e.port,hostname:e.hostname},explicit:{channel:s.channel,port:s.port,hostname:s.hostname},final:{channel:n.channel,port:n.port,hostname:n.hostname}}),n}var be=Log.create({service:"acp.server.rpc-handler"}),K={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,INTERNAL_ERROR:-32603},X=class{constructor(e){a(this,"agent");this.agent=e;}async handle(e){let{method:t,params:n,id:r}=e;be.debug("AcpRpcHandler.handle",{method:t,hasParams:!!n,id:r});try{let o;switch(t){case "initialize":o=await this.handleInitialize(n);break;case "authenticate":o=await this.handleAuthenticate(n);break;case "session.new":case "newSession":o=await this.handleNewSession(n);break;case "session.load":case "loadSession":o=await this.handleLoadSession(n);break;case "session.close":case "closeSession":o=await this.handleCloseSession(n);break;case "session.prompt":case "prompt":o=await this.handlePrompt(n);break;case "session.cancel":case "cancel":await this.handleCancel(n),o={success:!0};break;case "session.list":case "listSessions":o=await this.handleListSessions(n);break;case "session.fork":case "forkSession":o=await this.handleForkSession(n);break;case "session.resume":case "resumeSession":o=await this.handleResumeSession(n);break;case "session.setMode":case "setSessionMode":o=await this.handleSetSessionMode(n);break;case "session.setConfigOption":case "setSessionConfigOption":o=await this.handleSetSessionConfigOption(n);break;case "status":o=this.handleStatus();break;case "subscriptions":o=this.handleSubscriptions();break;default:throw be.warn("Unknown method",{method:t}),new NameErrors.NotFoundError({message:`Method not found: ${t}`,location:"rpc-method"})}return {jsonrpc:"2.0",id:r,result:o}}catch(o){return be.error("AcpRpcHandler error",{method:t,error:errorMeta(o)}),{jsonrpc:"2.0",id:r,error:{code:K.INTERNAL_ERROR,message:errorMeta(o).message}}}}async handleInitialize(e){return this.agent.initialize(e)}async handleAuthenticate(e){return this.agent.authenticate(e)}async handleNewSession(e){return this.agent.newSession(e)}async handleLoadSession(e){return this.agent.loadSession(e)}async handleCloseSession(e){return this.agent.closeSession(e)}async handlePrompt(e){return this.agent.prompt(e)}async handleCancel(e){return this.agent.cancel(e)}async handleListSessions(e){return this.agent.listSessions(e)}async handleForkSession(e){return this.agent.unstable_forkSession(e)}async handleResumeSession(e){return this.agent.resumeSession(e)}async handleSetSessionMode(e){return this.agent.setSessionMode(e)}async handleSetSessionConfigOption(e){return this.agent.setSessionConfigOption(e)}handleStatus(){return {status:"running",channel:"http",timestamp:Date.now(),uptime:process.uptime()}}handleSubscriptions(){return {sessions:[]}}};var fe=Log.create({service:"acp.server.agent-side-connection"}),ee=class{constructor(){a(this,"broadcaster",null);a(this,"sessionIds",new Set);a(this,"sessionRefCounts",new Map);}setBroadcaster(e){this.broadcaster=e;}addSession(e){this.sessionIds.add(e),this.sessionRefCounts.set(e,(this.sessionRefCounts.get(e)??0)+1);}removeSession(e){let t=this.sessionRefCounts.get(e)??0;if(t<=1){this.sessionRefCounts.delete(e),this.sessionIds.delete(e);return}this.sessionRefCounts.set(e,t-1);}clearSessions(){this.sessionIds.clear(),this.sessionRefCounts.clear();}getSessions(){return Array.from(this.sessionIds)}async sessionUpdate(e){let{sessionId:t,update:n}=e;fe.debug("ServerAgentSideConnection.sessionUpdate",{sessionId:t,updateType:n.sessionUpdate}),this.broadcaster&&this.broadcaster.broadcast(t,e);}async requestPermission(e){return fe.debug("ServerAgentSideConnection.requestPermission",{sessionId:e.sessionId}),{outcome:{outcome:"cancelled"}}}async extMethod(e,t){return fe.debug("ServerAgentSideConnection.extMethod",{method:e}),{}}async extNotification(e,t){if(fe.debug("ServerAgentSideConnection.extNotification",{method:e,params:t}),this.broadcaster&&t){let n=t.sessionId||t.sessionId;if(n&&this.sessionIds.has(n)){let r={sessionId:n,update:{sessionUpdate:e,...t}};this.broadcaster.broadcast(n,r);}}}};var L=Log.create({service:"acp.server.http"});async function Ge(s,e){if(L.info("Starting HTTP server",{port:e.port,hostname:e.hostname}),e.channel!==F.HTTP)throw new NameErrors.InvalidArgumentError({message:`Invalid channel type for HTTP server: ${e.channel}`,param:"channel"});let t=new Map,n=new Map,r=new ee,o={broadcast:(i,g)=>{b(i,g);}};r.setBroadcaster(o);let d=new X(s),p=s.getSDK();if(!p)throw new NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let l=new G(p,r);l.setService(s);let h=(i,g)=>{let a=t.get(i);if(!a)return false;try{return a.controller.enqueue(new TextEncoder().encode(g)),a.lastHeartbeat=Date.now(),!0}catch(u){return L.warn("Failed to push to SSE connection",{connectionId:i,error:errorMeta(u)}),false}},b=(i,g)=>{let a=n.get(i);if(!a||a.size===0)return;let m={jsonrpc:"2.0",method:g.update.sessionUpdate,params:{sessionId:i,...g.update,timestamp:Date.now()}},P=`data: ${JSON.stringify(m)}
2
-
3
- `;for(let f of a)h(f,P)||(t.delete(f),a.delete(f),r.removeSession(i));},I=(i,g)=>(r.addSession(i),new ReadableStream({start:async a=>{let u={id:g,controller:a,sessionId:i,createdAt:Date.now(),lastHeartbeat:Date.now()};t.set(g,u),n.has(i)||n.set(i,new Set),n.get(i).add(g),L.debug("SSE client connected",{connectionId:g,sessionId:i});let m=`data: ${JSON.stringify({type:"connected",connectionId:g,sessionId:i})}
4
-
5
- `;a.enqueue(new TextEncoder().encode(m)),s.sendAvailableCommandsUpdate(i).catch(P=>{L.warn("Failed to send initial available commands update",{sessionId:i,connectionId:g,error:errorMeta(P)});});},cancel:()=>{let a=t.get(g);if(a){t.delete(g);let u=n.get(a.sessionId);u&&(u.delete(g),u.size===0&&n.delete(a.sessionId)),r.removeSession(a.sessionId),L.debug("SSE client disconnected",{connectionId:g,sessionId:a.sessionId});}}})),C=null,x=()=>{C||(C=setInterval(()=>{let i=Date.now(),g=3e5;for(let[a,u]of t.entries())if(i-u.lastHeartbeat>g){L.warn("SSE connection timeout, closing",{connectionId:a});try{u.controller.close();}catch{}t.delete(a);let m=n.get(u.sessionId);m&&(m.delete(a),m.size===0&&n.delete(u.sessionId)),r.removeSession(u.sessionId);}else try{u.controller.enqueue(new TextEncoder().encode(`: heartbeat
6
-
7
- `)),u.lastHeartbeat=i;}catch{}},1e4));},y=[{method:"post",path:"/acp",handler:async i=>{let g=await i.req.json().catch(()=>null);if(!g||typeof g!="object")return i.json({jsonrpc:"2.0",error:{code:K.PARSE_ERROR,message:"Parse error"}},400);let a=g;if(!a.method||a.jsonrpc!=="2.0")return i.json({jsonrpc:"2.0",error:{code:K.INVALID_REQUEST,message:"Invalid Request"}},400);if(a.method==="session.prompt")return d.handle(a).catch(m=>{L.error("HTTP server: session.prompt error",{error:errorMeta(m)});}),i.json({jsonrpc:"2.0",id:a.id,result:{accepted:true}},202);let u=await d.handle(a);if(a.method==="initialize"){let m=`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;return i.json(u,200,{"Acp-Connection-Id":m})}return i.json(u)}},{method:"get",path:"/acp",handler:i=>{let g=i.req.header("Acp-Connection-Id"),a=i.req.header("Acp-Session-Id");if(!i.req.header("Accept")?.includes("text/event-stream"))return i.json({error:"Not Acceptable"},406);let m=g||`conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;if(a){let v=`sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,S=I(a,v);return new Response(S,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":m,"Acp-Session-Id":a}})}let P=`conn_sse_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,f=I("__connection__",P);return new Response(f,{headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","X-Accel-Buffering":"no","Acp-Connection-Id":m}})}},{method:"delete",path:"/acp",handler:async i=>{let g=i.req.header("Acp-Connection-Id");return L.debug("HTTP server: connection terminated",{connectionId:g}),i.json({success:true})}}],c=createServer({port:e.port,hostname:e.hostname,routes:y,timeout:e.timeout,cors:true});try{await l.start(),s.setServerConnection(r),x();}catch(i){throw L.error("HTTP server: failed to start background resources, cleaning up",{error:errorMeta(i)}),await l.stop().catch(()=>{}),C&&(clearInterval(C),C=null),await c.stop().catch(()=>{}),i}return L.info("HTTP server started",{url:`http://${e.hostname}:${e.port}`}),{server:c,stop:async()=>{L.info("Stopping HTTP server"),C&&(clearInterval(C),C=null),await l.stop();for(let i of t.values())try{i.controller.close();}catch{}t.clear(),n.clear(),r.clearSessions(),await c.stop(),L.info("HTTP server stopped");}}}var z=Log.create({service:"acp.server.websocket"});function Dt(s){try{let e=new URL(s),t=e.hostname,n=parseInt(e.port,10);if(t&&!Number.isNaN(n)&&n>0&&n<=65535)return {port:n,hostname:t}}catch{}}async function Qe(s,e){let t=e.ws?Dt(e.ws.url):void 0,n=t?.port??e.port??3e3,r=t?.hostname??e.hostname??"localhost",o="/acp";if(z.info("Starting WebSocket server",{port:n,hostname:r,wsUrl:e.ws?.url}),e.channel!==F.WEBSOCKET)throw new NameErrors.InvalidArgumentError({message:`Invalid channel type for WebSocket server: ${e.channel}`,param:"channel"});let d=new Map,p=new Map,l=new ee,h={broadcast:(f,v)=>{x(f,v);}};l.setBroadcaster(h);let b=new X(s),I=s.getSDK();if(!I)throw new NameErrors.MissingFieldError({message:"SDK not configured on agent",field:"sdk"});let C=new G(I,l);C.setService(s);let x=(f,v)=>{let _={jsonrpc:"2.0",method:v.update.sessionUpdate,params:{sessionId:f,...v.update,timestamp:Date.now()}},k=JSON.stringify(_);for(let[M,R]of p.entries())if(R.subscribedSessions.has(f)){let O=d.get(M);O&&O.ws.readyState===O.ws.OPEN&&O.ws.send(k);}},y=f=>{for(let[v,S]of d.entries())if(S.ws===f)return v},c=(f,v)=>{let S=p.get(f);S&&(S.subscribedSessions.has(v)||(S.subscribedSessions.add(v),l.addSession(v)));},i=(f,v)=>{let S=p.get(f);S&&S.subscribedSessions.has(v)&&(S.subscribedSessions.delete(v),l.removeSession(v));},g={onOpen:(f,v)=>{let S=`ws_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;d.set(S,{id:S,ws:v,createdAt:Date.now()}),p.set(S,{clientId:S,subscribedSessions:new Set}),z.debug("WebSocket client connected",{clientId:S}),v.send(JSON.stringify({type:"connected",clientId:S}));},onMessage:async(f,v)=>{try{let S=JSON.parse(f.data.toString());if(S.type==="ping"){v.send(JSON.stringify({type:"pong"}));return}let _=y(v);if(!_)return;let k,M;if(S.type==="message"||S.type==="request")k={jsonrpc:"2.0",id:S.id,method:S.method,params:S.params},M=S.sessionId;else if(S.jsonrpc==="2.0"&&S.method)k={jsonrpc:"2.0",id:S.id,method:S.method,params:S.params},M=S.params?.sessionId;else {z.warn("WebSocket server: unknown message format",{data:S});return}if(k.method==="session.subscribe"){M&&(c(_,M),s.sendAvailableCommandsUpdate(M).catch(O=>{z.warn("Failed to send initial available commands update",{sessionId:M,error:errorMeta(O)});})),v.send(JSON.stringify({type:"response",id:k.id,result:{subscribed:!0,sessionId:M}}));return}if(k.method==="session.unsubscribe"){M&&i(_,M),v.send(JSON.stringify({type:"response",id:k.id,result:{unsubscribed:!0,sessionId:M}}));return}if(k.method==="session.interrupt"){let O={jsonrpc:"2.0",method:"session.cancel",params:{sessionId:M}},de=await b.handle(O);v.send(JSON.stringify({type:"response",id:k.id,result:de.result,error:de.error}));return}if(k.method==="session.prompt"){if(v.send(JSON.stringify({jsonrpc:"2.0",id:k.id,result:{accepted:!0}})),M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}b.handle(k).catch(O=>{z.error("WebSocket server: session.prompt error",{error:errorMeta(O)});});return}if(M){let O=d.get(_);O&&(O.sessionId=M),c(_,M);}let R=await b.handle(k);v.send(JSON.stringify({type:"response",id:R.id,result:R.result,error:R.error}));}catch(S){z.error("WebSocket server: error handling message",{error:errorMeta(S)});}},onClose:(f,v)=>{let S=y(v);if(S){d.delete(S);let _=p.get(S);if(_){for(let k of _.subscribedSessions)l.removeSession(k);p.delete(S);}z.debug("WebSocket client disconnected",{clientId:S});}},onError:(f,v)=>{z.error("WebSocket error",{error:f.type});}},a=createServer({port:n,hostname:r,routes:[{method:"post",path:"/acp",handler:async f=>{let v=await f.req.json().catch(()=>null);if(!v||typeof v!="object")return f.json({jsonrpc:"2.0",error:{code:K.PARSE_ERROR,message:"Parse error"}},400);let S=v;if(!S.method||S.jsonrpc!=="2.0")return f.json({jsonrpc:"2.0",error:{code:K.INVALID_REQUEST,message:"Invalid Request"}},400);let _=await b.handle(S);return f.json(_)}},{method:"delete",path:"/acp",handler:async f=>{let v=f.req.header("Acp-Connection-Id");return z.debug("WebSocket server: connection terminated",{connectionId:v}),f.json({success:true})}}],timeout:e.timeout,cors:true}),u=a.raw,m=null,P=null;u&&(m=new WebSocketServer({noServer:true}),P=(f,v,S)=>{try{let k=new URL(f.url||"/",`http://${f.headers.host}`).pathname,M=f.headers.upgrade?.toLowerCase();k===o&&M==="websocket"&&m.handleUpgrade(f,v,S,R=>{g.onOpen?.({type:"open"},R),R.on("message",O=>{g.onMessage?.({data:O},R);}),R.on("close",(O,de)=>{g.onClose?.({code:O,reason:de},R);}),R.on("error",O=>{g.onError?.({type:"error",message:errorMeta(O).message},R);});});}catch{}},u.on("upgrade",P));try{await C.start(),s.setServerConnection(l);}catch(f){if(z.error("WebSocket server: failed to start background resources, cleaning up",{error:errorMeta(f)}),await C.stop().catch(()=>{}),u&&P&&(u.off("upgrade",P),P=null),m){try{await new Promise(v=>m.close(()=>v()));}catch{}m=null;}throw await a.stop().catch(()=>{}),f}return z.info("WebSocket server started",{url:e.ws?.url||`ws://${r}:${n}`,path:o}),{server:a,stop:async()=>{z.info("Stopping WebSocket server"),await C.stop(),u&&P&&(u.off("upgrade",P),P=null);for(let f of d.values())try{f.ws.close();}catch{}if(d.clear(),p.clear(),l.clearSessions(),m){try{await new Promise(f=>m.close(()=>f()));}catch{}m=null;}await a.stop(),z.info("WebSocket server stopped");}}}var re=Log.create({service:"acp.server.core"});async function Ke(s,e){let t=$e(e||{});re.info("Starting ACPServer",{channel:t.channel,port:t.port,hostname:t.hostname});let n,r;switch(t.channel){case F.HTTP:({server:n,stop:r}=await Ge(s,t));break;case F.WEBSOCKET:({server:n,stop:r}=await Qe(s,t));break;default:throw new NameErrors.InvalidArgumentError({message:`Unsupported service mode: ${t.channel}`,param:"channel"})}let o={type:t.channel,server:n,agent:s,stop:async()=>{re.info("Stopping ACPServer",{type:t.channel}),await r();},healthCheck:async()=>{if(typeof n=="object"&&n!==null&&"healthCheck"in n){let d=n.healthCheck;if(typeof d=="function")return d()}return true}};return re.info("ACPServer started successfully",{type:o.type,url:Ft(t)}),o}function Ft(s){return t({channel:s.channel,hostname:s.hostname,port:s.port})??"unknown://"}async function $t(s){await Promise.all(s.map(async e=>{try{await e.stop();}catch(t){re.error("Error stopping server",{type:e.type,error:errorMeta(t)});}}));}async function Ye(s){await $t([s]);}function Fs(s){return {type:s.channel,server:null,agent:null,stop:async()=>{re.warn("Server not started, nothing to stop");},healthCheck:async()=>false}}var Yt=fileURLToPath(import.meta.url),Jt=dirname(Yt),Xe="0.0.0";try{let s=join(Jt,"..","package.json");Xe=JSON.parse(readFileSync(s,"utf-8")).version??"0.0.0";}catch{}var U=Log.create({service:"acp.easbot-agent"}),ie=class s extends se{constructor(t,n){super(t,n);a(this,"acpEventBridge",null);a(this,"server",null);a(this,"isAgentInitialized",false);U.info("EasBotAgent instance created",{serviceMode:this.serviceMode});}static async create(t){U.info("creating EasBotAgent",{serviceMode:t.serviceMode});let n=t.serviceMode==="stdio",r=new s(void 0,t);if(n&&t.stdioStream){let{stream:o}=t.stdioStream,d={initialize:async l=>r.initialize(l),newSession:async l=>r.newSession(l),loadSession:async l=>r.loadSession(l),prompt:async l=>r.prompt(l),cancel:async l=>r.cancel(l),authenticate:async l=>r.authenticate(l),setSessionMode:async l=>r.setSessionMode(l),setSessionConfigOption:async l=>r.setSessionConfigOption(l),listSessions:async l=>r.listSessions(l),unstable_forkSession:async l=>r.unstable_forkSession(l),resumeSession:async l=>r.resumeSession(l),closeSession:async l=>r.closeSession(l)},p=new AgentSideConnection(()=>d,o);r.setConnection(p);}return U.info("EasBotAgent created successfully",{serviceMode:t.serviceMode,hasConnection:n&&!!t.stdioStream}),r}async initialize(t){return U.info("ACP initialize requested",{protocolVersion:t.protocolVersion}),this.isAgentInitialized||await this.initializeAgent(),{protocolVersion:t.protocolVersion,agentCapabilities:{loadSession:true,positionEncoding:"utf-8",mcpCapabilities:{http:true,sse:true},promptCapabilities:{image:true,embeddedContext:true,audio:false},sessionCapabilities:{close:{},fork:{},list:{},resume:{}},_meta:{history_scope:true,session_management:true}},agentInfo:{name:"EasBot Agent",version:Xe,title:"Multi-Agent Collaboration Ecosystem Agent"},authMethods:[{id:"easbot-token",name:"EasBot Token Authentication",description:"Authenticate using EasBot API token"}]}}async initializeAgent(){if(this.isAgentInitialized){U.warn("EasBotAgent already initialized");return}U.info("initializing EasBotAgent internals");try{await this.initializeExecutor(),this.config.acpServerConfig||await this.initializeAcpEventBridge(),this.isAgentInitialized=!0,this.setStatus("ready"),U.info("EasBotAgent internals initialized successfully");}catch(t){throw this.setStatus("error"),U.error("failed to initialize EasBotAgent",{error:errorMeta(t)}),t}}async start(){if(this.status==="running"){U.warn("EasBotAgent already running");return}this.isAgentInitialized||await this.initializeAgent();let t=this.config;t.acpServerConfig&&!this.server&&(this.server=await Ke(this,t.acpServerConfig)),this.setStatus("running"),U.info("EasBotAgent started");}async stop(){if(this.status==="stopped"){U.warn("EasBotAgent already stopped");return}U.info("stopping EasBotAgent");try{this.server&&(await Ye(this.server),this.server=null),this.acpEventBridge&&(await this.acpEventBridge.stop(),this.acpEventBridge=null),await this.dispose(),this.setStatus("stopped"),this.isAgentInitialized=!1,U.info("EasBotAgent stopped successfully");}catch(t){throw this.setStatus("error"),U.error("error stopping EasBotAgent",{error:errorMeta(t)}),t}}async initializeAcpEventBridge(){if(this.acpEventBridge){U.warn("ACP event bridge already initialized");return}let n=this.config.acp?.sdk,r=this.getConnection();if(!n)throw U.error("Cannot initialize ACP event bridge: missing SDK client"),new NameErrors.MissingFieldError({message:"SDK client is required for ACP event bridge",field:"sdk"});if(!r)throw U.error("Cannot initialize ACP event bridge: missing ACP connection"),new NameErrors.MissingFieldError({message:"ACP connection is required for ACP event bridge",field:"acpConnection"});this.acpEventBridge=new G(n,r),this.acpEventBridge.setService(this),await this.acpEventBridge.start(),U.info("ACP event bridge initialized");}getServiceMode(){return this.serviceMode}getServerInstance(){return this.server}getSDK(){return this.sdk}};var $=Log.create({service:"acp.bootstrap.gateway"}),tt=6e4;function tn(s){if(s.channel===b.WS){let t$1=s.ws?.url??t({channel:"websocket",hostname:s.hostname,port:s.port});return t$1?t$1.includes("/acp")?t$1:`${t$1.replace(/\/$/,"")}/acp`:`unknown://${s.hostname}:${s.port}`}return s.channel===b.HTTP&&s.http?.baseUrl?s.http.baseUrl:t({channel:s.channel,hostname:s.hostname,port:s.port})??`unknown://${s.hostname}:${s.port}`}var ae=null;async function nt(s){if(s.channel===b.STDIO)return $.debug("Skipping gateway registration for stdio mode"),false;let e=l();if(!e)return $.debug("No gateway URL configured, skipping registration"),false;if(!e.autoRegister)return $.debug("Gateway auto-registration disabled, skipping registration"),false;if(ae)return $.debug("Gateway registration already active, skipping"),false;let t=s.agentId||Identifier.ascending("agent"),n=s.name||"ACP Agent",r=tn(s),o={client:null,agentId:t,cycleTimer:null,registered:false,epoch:0,registerChain:Promise.resolve(),attemptRegister:async()=>{},active:true};ae=o;let d=async()=>{if(!o.active)throw new NameErrors.OperationFailedError({operation:"acp-gateway-register",message:"Registration session is no longer active"});if(o.client.getState()!=="connected")throw new NameErrors.OperationFailedError({operation:"acp-gateway-register",message:"Gateway not connected"});await o.client.registerAgent({agentId:t,name:n,address:r,capabilities:[s.channel],metadata:{hostname:s.hostname,port:s.port,channel:s.channel}});},p=async()=>{!o.active||o.registered||o.client.getState()==="connected"&&(o.registerChain=o.registerChain.then(async()=>{if(!o.active||o.registered||o.client.getState()!=="connected")return;let h=o.epoch;try{if(await d(),h!==o.epoch){$.debug("Discarding stale registration result",{agentId:t,epochAtStart:h,epoch:o.epoch});return}o.registered=!0,$.info("Registered to gateway",{agentId:t,agentName:n,address:r});}catch(b){o.registered=false,$.errorDegradable("Agent registration failed, will retry on next cycle",{error:errorMeta(b),agentId:t});}}),await o.registerChain);};o.attemptRegister=p;let l$1=h=>{o.active&&(h==="connected"?(o.epoch+=1,o.registered=false,p(),nn(o)):h==="disconnected"&&(o.registered=false));};return o.client=new GatewayClient({baseUrl:e.url,type:"acp",id:`acp-${t}`,heartbeat:{enabled:true,interval:tt},onStateChange:h=>{l$1(h);}}),true}function nn(s){s.cycleTimer||(s.cycleTimer=setInterval(()=>{sn(s);},tt));}async function sn(s){if(s.active&&s.client.getState()==="connected"){if(!s.registered){await s.attemptRegister();return}try{await s.client.agentHeartbeat(s.agentId);}catch(e){$.errorDegradable("Agent heartbeat failed",{error:errorMeta(e)});}}}function on(s){s.cycleTimer&&(clearInterval(s.cycleTimer),s.cycleTimer=null);}async function st(){let s=ae;if(s){s.active=false,ae=null,on(s);try{await s.client.deregisterAgent(s.agentId),$.debug("Agent deregistered from gateway",{agentId:s.agentId});}catch(e){$.errorDegradable("Failed to deregister agent",{error:errorMeta(e)});}try{await s.client.disconnect();}catch(e){$.errorDegradable("Failed to disconnect from gateway",{error:errorMeta(e)});}}}function vo(){return ae!==null}function ot(s,e,t){return new c.AdapterEnvironmentInitializationError({message:s,stage:e},t?{cause:t}:void 0)}var Y=Log.create({service:"acp.bootstrap"}),it=State.holder(()=>{try{let s=f().directory;return s?Filesystem.normalize(s):"__acp_bootstrap_global__"}catch{return "__acp_bootstrap_global__"}},async()=>({initialized:false,initPromise:null,instancePromise:null,handlersInstalled:false,unhandledRejectionHandler:null,uncaughtExceptionHandler:null,stdinDataHandler:null,stdinEndHandler:null,stdinErrorHandler:null,directory:".easbot",sdk:null,activeChannel:null,agent:null,acpConnection:null}),async s=>{let e=s.agent;e&&await e.stop().catch(()=>{}),at(s),ct(s),s.agent=null,s.sdk=null,s.acpConnection=null;});async function W(){return it.get()}function rt(s){let e=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],t=s.code;return e.includes(t??"")}function un(s){if(s.handlersInstalled)return;let e=n=>{let r=n instanceof Error?n:new Error(errorMeta(n).message);rt(r)||Y.error("unhandled promise rejection",{error:errorMeta(r)});},t=n=>{rt(n)||(Y.error("uncaught exception",{error:errorMeta(n)}),process.exit(1));};process.on("unhandledRejection",e),process.on("uncaughtException",t),s.unhandledRejectionHandler=e,s.uncaughtExceptionHandler=t,s.handlersInstalled=true;}function at(s){s.handlersInstalled&&(s.unhandledRejectionHandler&&(process.off("unhandledRejection",s.unhandledRejectionHandler),s.unhandledRejectionHandler=null),s.uncaughtExceptionHandler&&(process.off("uncaughtException",s.uncaughtExceptionHandler),s.uncaughtExceptionHandler=null),s.handlersInstalled=false);}function ct(s){s.stdinDataHandler&&(process.stdin.off("data",s.stdinDataHandler),s.stdinDataHandler=null),s.stdinEndHandler&&(process.stdin.off("end",s.stdinEndHandler),s.stdinEndHandler=null),s.stdinErrorHandler&&(process.stdin.off("error",s.stdinErrorHandler),s.stdinErrorHandler=null);try{process.stdin.pause();}catch{}}async function pn(s){return s.instancePromise||(s.instancePromise=(async()=>{let e=f();(!e.directory||e.directory===process.cwd())&&d({directory:s.directory,worktree:s.directory}),Y.debug("instance bootstrap completed",{directory:s.directory});})()),s.instancePromise}async function gn(){try{e(),Y.debug("instance adapter reset");}catch(s){Y.debug("instance dispose skipped",{error:errorMeta(s)});}}var Ee;(y=>{async function s(c,i){if(c.sdk)return c.sdk;let{getSdk:g}=await import('./interfaces-HUTPEB67.mjs');return c.sdk=await g(),c.sdk}function e(c){switch(c){case b.STDIO:return "stdio";case b.HTTP:return "http";case b.WS:return "websocket";default:return "stdio"}}function t(){it.clear();}y.resetState=t;async function n(c){let i=await W();if(i.initialized)return;if(i.initPromise)return i.initPromise;let g={directory:c?.directory??".easbot",initModels:c?.initModels??true,printLogs:c?.printLogs??false,logLevel:c?.logLevel??"INFO",channel:c?.channel??b.STDIO};if(i.directory=g.directory,await s(i,i.directory),i.activeChannel&&i.activeChannel!==g.channel)throw new NameErrors.OperationFailedError({message:`Adapter already initialized with channel ${i.activeChannel}, cannot re-init with ${g.channel}`,operation:"adapter-init"});return i.activeChannel=g.channel,i.initPromise=(async()=>{try{un(i);}catch(a){throw ot("Failed to install unhandled exception handlers","handlers",a instanceof Error?a:void 0)}try{await pn(i);}catch(a){throw ot("Failed to initialize instance","instance",a instanceof Error?a:void 0)}try{await r.init();}catch(a){Y.warn("AcpCache init failed, falling back to lazy load",{error:errorMeta(a)});}ConfigFileWatcher.init(),a$1.init(),i.initialized=true;})(),i.initPromise}y.init=n;async function r$1(){let c=await W();c.initialized&&(c.agent&&(await c.agent.stop().catch(()=>{}),c.agent=null),await st(),at(c),ct(c),await gn(),c.initialized=false,c.initPromise=null,c.instancePromise=null,c.activeChannel=null,c.sdk=null,c.agent=null,c.acpConnection=null);}y.destroy=r$1;async function o(){return (await W()).initialized}y.isInitialized=o;async function d(c){let i=await W();i.agent=c;}y.setAgent=d;async function p(){return (await W()).agent}y.getAgent=p;async function l(){let i=(await W()).agent?.getServerInstance();return i||null}y.getServer=l;async function h(){return (await W()).sdk}y.getSDK=h;async function b$1(){return (await W()).acpConnection}y.getACPConnection=b$1;async function I(){let c=await W(),i=!!c.agent?.getServerInstance();return {initialized:c.initialized,directory:c.directory,activeChannel:c.activeChannel,hasSDK:!!c.sdk,hasAgent:!!c.agent,hasACPConnection:!!c.acpConnection,hasServer:i}}y.getState=I;async function C(c){await n({channel:c.channel,directory:c.directory});let i=await W(),g=await s(i,i.directory);if(c.channel===b.STDIO)return x({directory:c.directory});if(i.agent?.getServerInstance()&&i.activeChannel&&i.activeChannel!==c.channel)throw new NameErrors.OperationFailedError({message:`ACP service already started with channel ${i.activeChannel}, cannot switch to ${c.channel}`,operation:"adapter-switch-channel"});if(i.agent){let P=i.agent.getServerInstance();if(P)return {sdk:g,agent:i.agent,server:P}}let u=await ie.create({serviceMode:e(c.channel),acp:{sdk:g},acpServerConfig:c,channel:{type:c.channel,timeout:c.timeout}});await u.start();let m=u.getServerInstance();if(!m)throw new NameErrors.OperationFailedError({message:"ACP server failed to start",operation:"acp-server-start"});return i.agent=u,i.activeChannel=c.channel,await nt(c),{sdk:g,agent:u,server:m}}y.ensureACPService=C;async function x(c){await n({channel:b.STDIO,directory:c.directory});let i=await W(),g=await s(i,i.directory);if(i.agent)return {sdk:g,agent:i.agent};let a=new WritableStream({write(f){return new Promise((v,S)=>{try{process.stdout.write(f)?v():process.stdout.once("drain",v);}catch(_){let k=_;k.code==="EPIPE"||k.code==="EIO"?S(new Error("stdout pipe broken")):S(_);}})}}),u=new ReadableStream({start(f){i.stdinDataHandler=v=>{try{f.enqueue(new Uint8Array(v));}catch{}},i.stdinEndHandler=()=>{try{f.close();}catch{}},i.stdinErrorHandler=v=>{try{f.error(v);}catch{}},process.stdin.on("data",i.stdinDataHandler),process.stdin.on("end",i.stdinEndHandler),process.stdin.on("error",i.stdinErrorHandler);}}),m=ndJsonStream(a,u),P=await ie.create({serviceMode:b.STDIO,acp:{sdk:g},channel:{type:b.STDIO,timeout:3e5},stdioStream:{stream:m}});return i.acpConnection=P.getConnection()??null,await P.start(),i.agent=P,i.activeChannel=b.STDIO,Y.info("Stdio ACP service started, waiting for client..."),process.stdin.resume(),{sdk:g,agent:P}}y.ensureACPServiceStdio=x;})(Ee||(Ee={}));var To=Ee;
8
- export{G as a,le as b,vt as c,ue as d,Ae as e,pe as f,F as g,Be as h,kt as i,Fe as j,cs as k,ee as l,Ge as m,Qe as n,Ke as o,Fs as p,ie as q,tn as r,nt as s,st as t,vo as u,ot as v,Ee as w,To as x};