All files / src/lib gateway-client.ts

9.84% Statements 78/792
55.55% Branches 5/9
5.88% Functions 3/51
9.84% Lines 78/792

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 12231x                                                                                                                                                                   1x 1x 5x 5x 5x 1x         1x 1x     1x           1x         1x 1x   1x         1x         1x 1x   1x         1x                 1x 9x 3x 3x 3x 3x 3x 9x                     1x 1x                                                                 1x 1x     1x 1x   1x                             1x                                                 1x             1x                                               1x                                                                                                                                                                               1x                       1x                                           1x     1x                                     1x           1x         1x                                                                     1x                                                                                             1x                                                                                                                                                             1x                                                                                                                                                                                                 1x                         1x                       1x                       1x                                                 1x                         1x                     1x                               1x                         1x               1x                           1x                       1x                                                                                                                                                                                                                                   1x                         1x           1x                               1x           1x                                                           1x                             1x                             1x                                                               1x                 1x   1x                                                                   1x             1x             1x     1x     1x     1x   1x                                                                                                                                                        
/**
 * ZCLAW Gateway Client (Browser/Tauri side)
 *
 * Core WebSocket client for OpenFang Kernel protocol.
 * Handles connection management, WebSocket framing, heartbeat,
 * event dispatch, and chat/stream operations.
 *
 * Module structure:
 * - gateway-types.ts:   Protocol types, stream types, ConnectionState
 * - gateway-auth.ts:    Device authentication (Ed25519)
 * - gateway-storage.ts: URL/token persistence, normalization
 * - gateway-api.ts:     REST API method implementations (installed via mixin)
 * - gateway-client.ts:  Core client class (this file)
 */
 
// === Re-exports for backward compatibility ===
export type {
  GatewayRequest,
  GatewayError,
  GatewayResponse,
  GatewayEvent,
  GatewayPong,
  GatewayFrame,
  AgentStreamDelta,
  OpenFangStreamEvent,
  ConnectionState,
  EventCallback,
} from './gateway-types';
 
export {
  getLocalDeviceIdentity,
  clearDeviceKeys,
} from './gateway-auth';
export type { LocalDeviceIdentity } from './gateway-auth';
 
export {
  DEFAULT_GATEWAY_URL,
  REST_API_URL,
  FALLBACK_GATEWAY_URLS,
  normalizeGatewayUrl,
  isLocalhost,
  getStoredGatewayUrl,
  setStoredGatewayUrl,
  getStoredGatewayToken,
  setStoredGatewayToken,
} from './gateway-storage';
 
// === Internal imports ===
import type {
  GatewayRequest,
  GatewayFrame,
  GatewayResponse,
  GatewayEvent,
  OpenFangStreamEvent,
  ConnectionState,
  EventCallback,
  AgentStreamDelta,
} from './gateway-types';
 
import {
  loadDeviceKeys,
  signDeviceAuth,
  clearDeviceKeys,
  type DeviceKeys,
} from './gateway-auth';
 
import {
  normalizeGatewayUrl,
  isLocalhost,
  getStoredGatewayUrl,
  getStoredGatewayToken,
} from './gateway-storage';
 
import type { GatewayConfigSnapshot, GatewayModelChoice } from './gateway-config';
import { installApiMethods } from './gateway-api';
 
// === Security ===
 
/**
 * Security error for invalid WebSocket connections.
 * Thrown when non-localhost URLs use ws:// instead of wss://.
 */
export class SecurityError extends Error {
  constructor(message: string) {
    super(message);
    this.name = 'SecurityError';
  }
}
 
/**
 * Connection error for WebSocket/HTTP connection failures.
 */
export class ConnectionError extends Error {
  public readonly code?: string;
  public readonly recoverable: boolean;
 
  constructor(message: string, code?: string, recoverable: boolean = true) {
    super(message);
    this.name = 'ConnectionError';
    this.code = code;
    this.recoverable = recoverable;
  }
}
 
/**
 * Timeout error for request/response timeouts.
 */
export class TimeoutError extends Error {
  public readonly timeout: number;
 
  constructor(message: string, timeout: number) {
    super(message);
    this.name = 'TimeoutError';
    this.timeout = timeout;
  }
}
 
/**
 * Authentication error for handshake/token failures.
 */
export class AuthenticationError extends Error {
  public readonly code?: string;
 
  constructor(message: string, code?: string) {
    super(message);
    this.name = 'AuthenticationError';
    this.code = code;
  }
}
 
/**
 * Validate WebSocket URL security.
 * Ensures non-localhost connections use WSS protocol.
 *
 * @param url - The WebSocket URL to validate
 * @throws SecurityError if non-localhost URL uses ws:// instead of wss://
 */
export function validateWebSocketSecurity(url: string): void {
  if (!url.startsWith('wss://') && !isLocalhost(url)) {
    throw new SecurityError(
      'Non-localhost connections must use WSS protocol for security. ' +
      `URL: ${url.replace(/:[^:@]+@/, ':****@')}`
    );
  }
}
 
function createIdempotencyKey(): string {
  if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
    return crypto.randomUUID();
  }
  return `idem_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
}
 
// === Client ===
 
export class GatewayClient {
  private ws: WebSocket | null = null;
  private openfangWs: WebSocket | null = null;  // OpenFang stream WebSocket
  private state: ConnectionState = 'disconnected';
  private requestId = 0;
  private pendingRequests = new Map<string, {
    resolve: (value: unknown) => void;
    reject: (reason: unknown) => void;
    timer: number;
  }>();
  private eventListeners = new Map<string, Set<EventCallback>>();
  private reconnectAttempts = 0;
  private reconnectTimer: number | null = null;
  private deviceKeysPromise: Promise<DeviceKeys>;
  private streamCallbacks = new Map<string, {
    onDelta: (delta: string) => void;
    onTool?: (tool: string, input: string, output: string) => void;
    onHand?: (name: string, status: string, result?: unknown) => void;
    onComplete: () => void;
    onError: (error: string) => void;
  }>();
 
  // Options
  private url: string;
  private token: string;
  private autoReconnect: boolean;
  private reconnectInterval: number;
  private requestTimeout: number;
 
  // Heartbeat
  private heartbeatInterval: number | null = null;
  private heartbeatTimeout: number | null = null;
  private missedHeartbeats: number = 0;
  private static readonly HEARTBEAT_INTERVAL = 30000; // 30 seconds
  private static readonly HEARTBEAT_TIMEOUT = 10000;  // 10 seconds
  private static readonly MAX_MISSED_HEARTBEATS = 3;
 
  // State change callbacks
  onStateChange?: (state: ConnectionState) => void;
  onLog?: (level: string, message: string) => void;
 
  constructor(opts?: {
    url?: string;
    token?: string;
    autoReconnect?: boolean;
    reconnectInterval?: number;
    requestTimeout?: number;
  }) {
    this.url = normalizeGatewayUrl(opts?.url || getStoredGatewayUrl());
    this.token = opts?.token ?? getStoredGatewayToken();
    this.autoReconnect = opts?.autoReconnect ?? true;
    this.reconnectInterval = opts?.reconnectInterval || 3000;
    this.requestTimeout = opts?.requestTimeout || 30000;
    this.deviceKeysPromise = loadDeviceKeys();
  }
 
  updateOptions(opts?: {
    url?: string;
    token?: string;
    autoReconnect?: boolean;
    reconnectInterval?: number;
    requestTimeout?: number;
  }) {
    if (!opts) return;
    if (opts.url) {
      this.url = normalizeGatewayUrl(opts.url);
    }
    if (opts.token !== undefined) {
      this.token = opts.token;
    }
    if (opts.autoReconnect !== undefined) {
      this.autoReconnect = opts.autoReconnect;
    }
    if (opts.reconnectInterval !== undefined) {
      this.reconnectInterval = opts.reconnectInterval;
    }
    if (opts.requestTimeout !== undefined) {
      this.requestTimeout = opts.requestTimeout;
    }
  }
 
  getState(): ConnectionState {
    return this.state;
  }
 
  // === Connection ===
 
  /** Connect using REST API only (for OpenFang mode) */
  async connectRest(): Promise<void> {
    if (this.state === 'connected') {
      return;
    }
    this.setState('connecting');
    try {
      // Check if OpenFang API is healthy
      const health = await this.restGet<{ status: string; version?: string }>('/api/health');
      if (health.status === 'ok') {
        this.reconnectAttempts = 0;
        this.setState('connected');
        this.startHeartbeat(); // Start heartbeat after successful connection
        this.log('info', `Connected to OpenFang via REST API${health.version ? ` (v${health.version})` : ''}`);
        this.emitEvent('connected', { version: health.version });
      } else {
        throw new Error('Health check failed');
      }
    } catch (err: unknown) {
      this.setState('disconnected');
      const errorMessage = err instanceof Error ? err.message : String(err);
      throw new Error(`Failed to connect to OpenFang: ${errorMessage}`);
    }
  }
 
  connect(): Promise<void> {
    if (this.state === 'connected' || this.state === 'connecting' || this.state === 'handshaking') {
      return Promise.resolve();
    }
 
    // Check if URL is for OpenFang (port 4200 or 50051) - use REST mode
    if (this.url.includes(':4200') || this.url.includes(':50051')) {
      return this.connectRest();
    }
 
    // Security validation: enforce WSS for non-localhost connections
    validateWebSocketSecurity(this.url);
 
    this.autoReconnect = true;
    this.setState('connecting');
 
    return new Promise((resolve, reject) => {
      let settled = false;
      const settleResolve = () => {
        if (settled) return;
        settled = true;
        resolve();
      };
      const settleReject = (error: Error) => {
        if (settled) return;
        settled = true;
        reject(error);
      };
      const handshakeTimer = window.setTimeout(() => {
        this.log('error', `Handshake timed out after ${this.requestTimeout}ms`);
        this.cleanup();
        settleReject(new Error(`Gateway handshake timed out after ${this.requestTimeout}ms`));
      }, this.requestTimeout);
 
      try {
        this.ws = new WebSocket(this.url);
 
        this.ws.onopen = () => {
          this.setState('handshaking');
        };
 
        this.ws.onmessage = (evt) => {
          try {
            const frame: GatewayFrame = JSON.parse(evt.data);
            this.handleFrame(frame, () => {
              clearTimeout(handshakeTimer);
              settleResolve();
            }, (error) => {
              clearTimeout(handshakeTimer);
              settleReject(error);
            });
          } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            this.log('error', `Parse error: ${errorMessage}`);
          }
        };
 
        this.ws.onclose = (evt) => {
          const wasConnected = this.state === 'connected';
          const closedDuringConnect = !wasConnected && !settled;
          this.cleanup();
 
          if (wasConnected && this.autoReconnect) {
            this.scheduleReconnect();
          }
 
          this.emitEvent('close', { code: evt.code, reason: evt.reason });
          if (closedDuringConnect) {
            clearTimeout(handshakeTimer);
            settleReject(new Error(evt.reason || `WebSocket closed before handshake completed (code: ${evt.code})`));
          }
        };
 
        this.ws.onerror = () => {
          if (this.state === 'connecting' || this.state === 'handshaking') {
            clearTimeout(handshakeTimer);
            this.cleanup();
            settleReject(new Error('WebSocket connection failed'));
          }
        };
      } catch (err) {
        clearTimeout(handshakeTimer);
        this.cleanup();
        settleReject(err instanceof Error ? err : new Error(String(err)));
      }
    });
  }
 
  disconnect() {
    this.autoReconnect = false;
    this.cancelReconnect();
 
    if (this.ws) {
      this.ws.close(1000, 'Client disconnect');
    }
    this.cleanup();
  }
 
  // === Request/Response ===
 
  async request(method: string, params?: Record<string, unknown>): Promise<unknown> {
    if (this.state !== 'connected') {
      throw new Error(`Not connected (state: ${this.state})`);
    }
 
    const id = `req_${++this.requestId}`;
    const frame: GatewayRequest = { type: 'req', id, method, params };
 
    return new Promise((resolve, reject) => {
      const timer = window.setTimeout(() => {
        this.pendingRequests.delete(id);
        reject(new Error(`Request ${method} timed out`));
      }, this.requestTimeout);
 
      this.pendingRequests.set(id, { resolve, reject, timer });
      this.send(frame);
    });
  }
 
  // === High-level API ===
 
  // Default agent ID for OpenFang (will be set dynamically from /api/agents)
  private defaultAgentId: string = '';
 
  /** Try to fetch default agent ID from OpenFang /api/agents endpoint */
  async fetchDefaultAgentId(): Promise<string | null> {
    try {
      // Use /api/agents endpoint which returns array of agents
      const agents = await this.restGet<Array<{ id: string; name?: string; state?: string }>>('/api/agents');
      if (agents && agents.length > 0) {
        // Prefer agent with state "Running", otherwise use first agent
        const runningAgent = agents.find((a: { id: string; name?: string; state?: string }) => a.state === 'Running');
        const defaultAgent = runningAgent || agents[0];
        this.defaultAgentId = defaultAgent.id;
        this.log('info', `Fetched default agent from /api/agents: ${this.defaultAgentId} (${defaultAgent.name || 'unnamed'})`);
        return this.defaultAgentId;
      }
    } catch (err) {
      this.log('warn', `Failed to fetch default agent from /api/agents: ${err}`);
    }
    return null;
  }
 
  /** Set the default agent ID */
  setDefaultAgentId(agentId: string): void {
    this.defaultAgentId = agentId;
    this.log('info', `Default agent set to: ${agentId}`);
  }
 
  /** Get the current default agent ID */
  getDefaultAgentId(): string {
    return this.defaultAgentId;
  }
 
  /** Send message to agent (OpenFang chat API) */
  async chat(message: string, opts?: {
    sessionKey?: string;
    agentId?: string;
    idempotencyKey?: string;
    extraSystemPrompt?: string;
    model?: string;
    temperature?: number;
    maxTokens?: number;
  }): Promise<{ runId: string; sessionId?: string; response?: string }> {
    // OpenFang uses /api/agents/{agentId}/message endpoint
    let agentId = opts?.agentId || this.defaultAgentId;
 
    // If no agent ID, try to fetch from OpenFang status
    if (!agentId) {
      await this.fetchDefaultAgentId();
      agentId = this.defaultAgentId;
    }
 
    if (!agentId) {
      throw new Error('No agent available. Please ensure OpenFang has at least one agent.');
    }
 
    const result = await this.restPost<{ response?: string; input_tokens?: number; output_tokens?: number }>(`/api/agents/${agentId}/message`, {
      message,
      session_id: opts?.sessionKey,
    });
    // OpenFang returns { response, input_tokens, output_tokens }
    return {
      runId: createIdempotencyKey(),
      sessionId: opts?.sessionKey,
      response: result.response,
    };
  }
 
  /** Send message with streaming response (OpenFang WebSocket) */
  async chatStream(
    message: string,
    callbacks: {
      onDelta: (delta: string) => void;
      onTool?: (tool: string, input: string, output: string) => void;
      onHand?: (name: string, status: string, result?: unknown) => void;
      onComplete: () => void;
      onError: (error: string) => void;
    },
    opts?: {
      sessionKey?: string;
      agentId?: string;
    }
  ): Promise<{ runId: string }> {
    let agentId = opts?.agentId || this.defaultAgentId;
    const runId = createIdempotencyKey();
    const sessionId = opts?.sessionKey || `session_${Date.now()}`;
 
    // If no agent ID, try to fetch from OpenFang status (async, but we'll handle it in connectOpenFangStream)
    if (!agentId) {
      // Try to get default agent asynchronously
      this.fetchDefaultAgentId().then(() => {
        const resolvedAgentId = this.defaultAgentId;
        if (resolvedAgentId) {
          this.streamCallbacks.set(runId, callbacks);
          this.connectOpenFangStream(resolvedAgentId, runId, sessionId, message);
        } else {
          callbacks.onError('No agent available. Please ensure OpenFang has at least one agent.');
          callbacks.onComplete();
        }
      }).catch((err) => {
        callbacks.onError(`Failed to get agent: ${err}`);
        callbacks.onComplete();
      });
      return { runId };
    }
 
    // Store callbacks for this run
    this.streamCallbacks.set(runId, callbacks);
 
    // Connect to OpenFang WebSocket if not connected
    this.connectOpenFangStream(agentId, runId, sessionId, message);
 
    return { runId };
  }
 
  /** Connect to OpenFang streaming WebSocket */
  private connectOpenFangStream(
    agentId: string,
    runId: string,
    sessionId: string,
    message: string
  ): void {
    // Close existing connection if any
    if (this.openfangWs && this.openfangWs.readyState !== WebSocket.CLOSED) {
      this.openfangWs.close();
    }
 
    // Build WebSocket URL
    // In dev mode, use Vite proxy; in production, use direct connection
    let wsUrl: string;
    if (typeof window !== 'undefined' && window.location.port === '1420') {
      // Dev mode: use Vite proxy with relative path
      wsUrl = `ws://${window.location.host}/api/agents/${agentId}/ws`;
    } else {
      // Production: extract from stored URL
      const httpUrl = this.getRestBaseUrl();
      wsUrl = httpUrl.replace(/^http/, 'ws') + `/api/agents/${agentId}/ws`;
    }
 
    this.log('info', `Connecting to OpenFang stream: ${wsUrl}`);
 
    try {
      this.openfangWs = new WebSocket(wsUrl);
 
      this.openfangWs.onopen = () => {
        this.log('info', 'OpenFang WebSocket connected');
        // Send chat message using OpenFang actual protocol
        const chatRequest = {
          type: 'message',
          content: message,
          session_id: sessionId,
        };
        this.openfangWs?.send(JSON.stringify(chatRequest));
      };
 
      this.openfangWs.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          this.handleOpenFangStreamEvent(runId, data, sessionId);
        } catch (err: unknown) {
          const errorMessage = err instanceof Error ? err.message : String(err);
          this.log('error', `Failed to parse stream event: ${errorMessage}`);
        }
      };
 
      this.openfangWs.onerror = (_event) => {
        this.log('error', 'OpenFang WebSocket error');
        const callbacks = this.streamCallbacks.get(runId);
        if (callbacks) {
          callbacks.onError('WebSocket connection failed');
          this.streamCallbacks.delete(runId);
        }
      };
 
      this.openfangWs.onclose = (event) => {
        this.log('info', `OpenFang WebSocket closed: ${event.code} ${event.reason}`);
        const callbacks = this.streamCallbacks.get(runId);
        if (callbacks && event.code !== 1000) {
          callbacks.onError(`Connection closed: ${event.reason || 'unknown'}`);
        }
        this.streamCallbacks.delete(runId);
        this.openfangWs = null;
      };
    } catch (err: unknown) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      this.log('error', `Failed to create WebSocket: ${errorMessage}`);
      const callbacks = this.streamCallbacks.get(runId);
      if (callbacks) {
        callbacks.onError(errorMessage);
        this.streamCallbacks.delete(runId);
      }
    }
  }
 
  /** Handle OpenFang stream events */
  private handleOpenFangStreamEvent(runId: string, data: OpenFangStreamEvent, sessionId: string): void {
    const callbacks = this.streamCallbacks.get(runId);
    if (!callbacks) return;
 
    switch (data.type) {
      // OpenFang actual event types
      case 'text_delta':
        // Stream delta content
        if (data.content) {
          callbacks.onDelta(data.content);
        }
        break;
 
      case 'phase':
        // Phase change: streaming | done
        if (data.phase === 'done') {
          callbacks.onComplete();
          this.streamCallbacks.delete(runId);
          if (this.openfangWs) {
            this.openfangWs.close(1000, 'Stream complete');
          }
        }
        break;
 
      case 'response':
        // Final response with tokens info
        if (data.content) {
          // If we haven't received any deltas yet, send the full response
          // This handles non-streaming responses
        }
        // Mark complete if phase done wasn't sent
        callbacks.onComplete();
        this.streamCallbacks.delete(runId);
        if (this.openfangWs) {
          this.openfangWs.close(1000, 'Stream complete');
        }
        break;
 
      case 'typing':
        // Typing indicator: { state: 'start' | 'stop' }
        // Can be used for UI feedback
        break;
 
      case 'tool_call':
        // Tool call event
        if (callbacks.onTool && data.tool) {
          callbacks.onTool(data.tool, JSON.stringify(data.input || {}), data.output || '');
        }
        break;
 
      case 'tool_result':
        if (callbacks.onTool && data.tool) {
          callbacks.onTool(data.tool, '', String(data.result || data.output || ''));
        }
        break;
 
      case 'hand':
        if (callbacks.onHand && data.hand_name) {
          callbacks.onHand(data.hand_name, data.hand_status || 'triggered', data.hand_result);
        }
        break;
 
      case 'error':
        callbacks.onError(data.message || data.code || data.content || 'Unknown error');
        this.streamCallbacks.delete(runId);
        if (this.openfangWs) {
          this.openfangWs.close(1011, 'Error');
        }
        break;
 
      case 'connected':
        // Connection established
        this.log('info', `OpenFang agent connected: ${data.agent_id}`);
        break;
 
      case 'agents_updated':
        // Agents list updated
        this.log('debug', 'Agents list updated');
        break;
 
      default:
        // Emit unknown events for debugging
        this.log('debug', `Stream event: ${data.type}`);
    }
 
    // Also emit to general 'agent' event listeners
    this.emitEvent('agent', {
      stream: data.type === 'text_delta' ? 'assistant' : data.type,
      delta: data.content,
      content: data.content,
      runId,
      sessionId,
      ...data,
    });
  }
 
  /** Cancel an ongoing stream */
  cancelStream(runId: string): void {
    const callbacks = this.streamCallbacks.get(runId);
    if (callbacks) {
      callbacks.onError('Stream cancelled');
      this.streamCallbacks.delete(runId);
    }
    if (this.openfangWs && this.openfangWs.readyState === WebSocket.OPEN) {
      this.openfangWs.close(1000, 'User cancelled');
    }
  }
 
  // === REST API Helpers (OpenFang) ===
 
  public getRestBaseUrl(): string {
    // In browser dev mode, use Vite proxy (empty string = relative path)
    // In production Tauri, extract HTTP URL from WebSocket URL
    if (typeof window !== 'undefined' && window.location.port === '1420') {
      // Dev mode: use Vite proxy (requests go to /api/* which Vite proxies to backend)
      return '';
    }
    // Production: extract HTTP URL from WebSocket URL
    const wsUrl = this.url;
    return wsUrl.replace(/^ws/, 'http').replace(/\/ws$/, '');
  }
 
  public async restGet<T>(path: string): Promise<T> {
    const baseUrl = this.getRestBaseUrl();
    const response = await fetch(`${baseUrl}${path}`);
    if (!response.ok) {
      // For 404 errors, throw with status code so callers can handle gracefully
      const error = new Error(`REST API error: ${response.status} ${response.statusText}`);
      (error as any).status = response.status;
      throw error;
    }
    return response.json();
  }
 
  public async restPost<T>(path: string, body?: unknown): Promise<T> {
    const baseUrl = this.getRestBaseUrl();
    const url = `${baseUrl}${path}`;
    console.log(`[GatewayClient] POST ${url}`, body);
 
    const response = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: body ? JSON.stringify(body) : undefined,
    });
 
    if (!response.ok) {
      const errorBody = await response.text().catch(() => '');
      console.error(`[GatewayClient] POST ${url} failed: ${response.status} ${response.statusText}`, errorBody);
      const error = new Error(`REST API error: ${response.status} ${response.statusText}${errorBody ? ` - ${errorBody}` : ''}`);
      (error as any).status = response.status;
      (error as any).body = errorBody;
      throw error;
    }
 
    const result = await response.json();
    console.log(`[GatewayClient] POST ${url} response:`, result);
    return result;
  }
 
  public async restPut<T>(path: string, body?: unknown): Promise<T> {
    const baseUrl = this.getRestBaseUrl();
    const response = await fetch(`${baseUrl}${path}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: body ? JSON.stringify(body) : undefined,
    });
    if (!response.ok) {
      throw new Error(`REST API error: ${response.status} ${response.statusText}`);
    }
    return response.json();
  }
 
  public async restDelete<T>(path: string): Promise<T> {
    const baseUrl = this.getRestBaseUrl();
    const response = await fetch(`${baseUrl}${path}`, {
      method: 'DELETE',
    });
    if (!response.ok) {
      throw new Error(`REST API error: ${response.status} ${response.statusText}`);
    }
    return response.json();
  }
 
  public async restPatch<T>(path: string, body?: unknown): Promise<T> {
    const baseUrl = this.getRestBaseUrl();
    const response = await fetch(`${baseUrl}${path}`, {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: body ? JSON.stringify(body) : undefined,
    });
    if (!response.ok) {
      throw new Error(`REST API error: ${response.status} ${response.statusText}`);
    }
    return response.json();
  }
 
  // === Event Subscription ===
 
  /** Subscribe to a Gateway event (e.g., 'agent', 'chat', 'heartbeat') */
  on(event: string, callback: EventCallback): () => void {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, new Set());
    }
    this.eventListeners.get(event)!.add(callback);
 
    // Return unsubscribe function
    return () => {
      this.eventListeners.get(event)?.delete(callback);
    };
  }
 
  /** Subscribe to agent stream events */
  onAgentStream(callback: (delta: AgentStreamDelta) => void): () => void {
    return this.on('agent', (payload: unknown) => {
      callback(payload as AgentStreamDelta);
    });
  }
 
  // === Internal ===
 
  private handleFrame(frame: GatewayFrame, connectResolve?: () => void, connectReject?: (error: Error) => void) {
    // Handle pong responses for heartbeat
    if (frame.type === 'pong') {
      this.handlePong();
      return;
    }
 
    if (frame.type === 'event') {
      this.handleEvent(frame, connectResolve, connectReject);
    } else if (frame.type === 'res') {
      this.handleResponse(frame);
    }
  }
 
  private handleEvent(event: GatewayEvent, connectResolve?: () => void, connectReject?: (error: Error) => void) {
    // Handle connect challenge
    if (event.event === 'connect.challenge' && this.state === 'handshaking') {
      const payload = event.payload as { nonce?: string } | undefined;
      this.performHandshake(payload?.nonce || '', connectResolve, connectReject);
      return;
    }
 
    // Dispatch to listeners
    this.emitEvent(event.event, event.payload);
  }
 
  private async performHandshake(challengeNonce: string | undefined, connectResolve?: () => void, connectReject?: (error: Error) => void) {
    if (!challengeNonce) {
      this.log('error', 'No challenge nonce received');
      connectReject?.(new Error('Handshake failed: no challenge nonce'));
      return;
    }
    const connectId = `connect_${Date.now()}`;
    // Use a valid client ID from GATEWAY_CLIENT_ID_SET
    // Valid IDs: gateway-client, cli, webchat, node-host, test
    // 'cli' is for control UI / command-line clients
    const clientId = 'cli';
    // Valid modes: cli, webchat, backend, node
    // 'cli' is for command-line/Control UI clients
    const clientMode = 'cli';
    const role = 'operator';
    const scopes = ['operator.read', 'operator.write', 'operator.admin', 'operator.approvals', 'operator.pairing'];
 
    // Debug: log token status
    this.log('debug', `Handshake token: ${this.token ? `${this.token.substring(0, 8)}... (${this.token.length} chars)` : '(empty)'}`);
 
    try {
      const deviceKeys = await this.deviceKeysPromise;
 
      // Debug: log device auth details
      this.log('debug', `Device auth: deviceId=${deviceKeys.deviceId.substring(0, 8)}..., nonce=${challengeNonce.substring(0, 8)}...`);
 
      const { signature, signedAt } = signDeviceAuth({
        clientId,
        clientMode,
        deviceId: deviceKeys.deviceId,
        nonce: challengeNonce,
        role,
        scopes,
        secretKey: deviceKeys.secretKey,
        token: this.token,
      });
 
      // Debug: log signature details
      this.log('debug', `Signature created: signedAt=${signedAt}, sig=${signature.substring(0, 16)}...`);
 
      const connectReq: GatewayRequest = {
        type: 'req',
        id: connectId,
        method: 'connect',
        params: {
          minProtocol: 3,
          maxProtocol: 3,
          client: {
            id: clientId,
            version: '0.2.0',
            platform: this.detectPlatform(),
            mode: clientMode,
          },
          role,
          scopes,
 
          auth: this.token ? { token: this.token } : {},
          locale: 'zh-CN',
          userAgent: 'zclaw-tauri/0.2.0',
          device: {
            id: deviceKeys.deviceId,
            publicKey: deviceKeys.publicKeyBase64,
            signature,
            signedAt,
            nonce: challengeNonce,
          },
        },
      };
 
      const originalHandler = this.ws!.onmessage;
      this.ws!.onmessage = (evt) => {
        try {
          const frame = JSON.parse(evt.data);
          if (frame.type === 'res' && frame.id === connectId) {
            this.ws!.onmessage = originalHandler;
            if (frame.ok) {
              this.setState('connected');
              this.reconnectAttempts = 0;
              this.startHeartbeat(); // Start heartbeat after successful connection
              this.emitEvent('connected', frame.payload);
              this.log('info', 'Connected to Gateway');
              connectResolve?.();
            } else {
              const errorObj = frame.error;
              const errorMessage = errorObj?.message || errorObj?.code || JSON.stringify(errorObj);
              const error = new Error(`Handshake failed: ${errorMessage}`);
              this.log('error', error.message);
 
              // Check for signature-related errors and clear device keys if needed
              if (errorMessage.includes('signature') || errorMessage.includes('device')) {
                this.log('warn', 'Device signature failed, clearing cached keys for retry');
                clearDeviceKeys();
              }
 
              this.cleanup();
              connectReject?.(error);
            }
          } else {
            originalHandler?.call(this.ws!, evt);
          }
        } catch {
          // Ignore parse errors
        }
      };
 
      this.send(connectReq);
    } catch (err: unknown) {
      const error = err instanceof Error ? err : new Error(String(err));
      this.log('error', error.message);
      this.cleanup();
      connectReject?.(error);
    }
  }
 
  private handleResponse(res: GatewayResponse) {
    const pending = this.pendingRequests.get(res.id);
    if (pending) {
      clearTimeout(pending.timer);
      this.pendingRequests.delete(res.id);
      if (res.ok) {
        pending.resolve(res.payload);
      } else {
        pending.reject(new Error(JSON.stringify(res.error)));
      }
    }
  }
 
  private send(frame: GatewayFrame) {
    if (this.ws?.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(frame));
    }
  }
 
  private emitEvent(event: string, payload: unknown) {
    const listeners = this.eventListeners.get(event);
    if (listeners) {
      for (const cb of listeners) {
        try { cb(payload); } catch { /* ignore listener errors */ }
      }
    }
    // Also emit wildcard
    const wildcardListeners = this.eventListeners.get('*');
    if (wildcardListeners) {
      for (const cb of wildcardListeners) {
        try { cb({ event, payload }); } catch { /* ignore */ }
      }
    }
  }
 
  private setState(state: ConnectionState) {
    this.state = state;
    this.onStateChange?.(state);
    this.emitEvent('state', state);
  }
 
  private cleanup() {
    // Stop heartbeat on cleanup
    this.stopHeartbeat();
 
    for (const [, pending] of this.pendingRequests) {
      clearTimeout(pending.timer);
      pending.reject(new Error('Connection closed'));
    }
    this.pendingRequests.clear();
 
    if (this.ws) {
      this.ws.onopen = null;
      this.ws.onmessage = null;
      this.ws.onclose = null;
      this.ws.onerror = null;
      if (this.ws.readyState === WebSocket.OPEN || this.ws.readyState === WebSocket.CONNECTING) {
        try { this.ws.close(); } catch { /* ignore */ }
      }
      this.ws = null;
    }
 
    this.setState('disconnected');
  }
 
  // === Heartbeat Methods ===
 
  /**
   * Start heartbeat to keep connection alive.
   * Called after successful connection.
   */
  private startHeartbeat(): void {
    this.stopHeartbeat();
    this.missedHeartbeats = 0;
 
    this.heartbeatInterval = window.setInterval(() => {
      this.sendHeartbeat();
    }, GatewayClient.HEARTBEAT_INTERVAL);
 
    this.log('debug', 'Heartbeat started');
  }
 
  /**
   * Stop heartbeat.
   * Called on cleanup or disconnect.
   */
  private stopHeartbeat(): void {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
      this.heartbeatInterval = null;
    }
    if (this.heartbeatTimeout) {
      clearTimeout(this.heartbeatTimeout);
      this.heartbeatTimeout = null;
    }
    this.log('debug', 'Heartbeat stopped');
  }
 
  /**
   * Send a ping heartbeat to the server.
   */
  private sendHeartbeat(): void {
    if (this.ws?.readyState !== WebSocket.OPEN) {
      this.log('debug', 'Skipping heartbeat - WebSocket not open');
      return;
    }
 
    this.missedHeartbeats++;
    if (this.missedHeartbeats > GatewayClient.MAX_MISSED_HEARTBEATS) {
      this.log('warn', `Max missed heartbeats (${GatewayClient.MAX_MISSED_HEARTBEATS}), reconnecting`);
      this.stopHeartbeat();
      this.ws.close(4000, 'Heartbeat timeout');
      return;
    }
 
    // Send ping frame
    try {
      this.ws.send(JSON.stringify({ type: 'ping' }));
      this.log('debug', `Ping sent (missed: ${this.missedHeartbeats})`);
 
      // Set timeout for pong
      this.heartbeatTimeout = window.setTimeout(() => {
        this.log('warn', 'Heartbeat pong timeout');
        // Don't reconnect immediately, let the next heartbeat check
      }, GatewayClient.HEARTBEAT_TIMEOUT);
    } catch (error) {
      this.log('error', `Failed to send heartbeat: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
 
  /**
   * Handle pong response from server.
   */
  private handlePong(): void {
    this.missedHeartbeats = 0;
    if (this.heartbeatTimeout) {
      clearTimeout(this.heartbeatTimeout);
      this.heartbeatTimeout = null;
    }
    this.log('debug', 'Pong received, heartbeat reset');
  }
 
  private static readonly MAX_RECONNECT_ATTEMPTS = 10;
 
  private scheduleReconnect() {
    if (this.reconnectAttempts >= GatewayClient.MAX_RECONNECT_ATTEMPTS) {
      this.log('error', `Max reconnect attempts (${GatewayClient.MAX_RECONNECT_ATTEMPTS}) reached. Please reconnect manually.`);
      this.setState('disconnected');
      this.emitEvent('reconnect_failed', {
        attempts: this.reconnectAttempts,
        maxAttempts: GatewayClient.MAX_RECONNECT_ATTEMPTS
      });
      return;
    }
 
    this.reconnectAttempts++;
    this.setState('reconnecting');
    const delay = Math.min(this.reconnectInterval * Math.pow(1.5, this.reconnectAttempts - 1), 30000);
 
    this.log('info', `Scheduling reconnect attempt ${this.reconnectAttempts} in ${delay}ms`);
 
    // Emit reconnecting event for UI
    this.emitEvent('reconnecting', {
      attempt: this.reconnectAttempts,
      delay,
      maxAttempts: GatewayClient.MAX_RECONNECT_ATTEMPTS
    });
 
    this.reconnectTimer = window.setTimeout(async () => {
      try {
        await this.connect();
      } catch {
        /* close handler will trigger another reconnect */
        this.log('warn', `Reconnect attempt ${this.reconnectAttempts} failed`);
      }
    }, delay);
  }
 
  private cancelReconnect() {
    if (this.reconnectTimer !== null) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }
  }
 
  private detectPlatform(): string {
    const ua = navigator.userAgent.toLowerCase();
    if (ua.includes('win')) return 'windows';
    if (ua.includes('mac')) return 'macos';
    return 'linux';
  }
 
  private log(level: string, message: string) {
    this.onLog?.(level, message);
  }
}
 
// Install REST API methods from gateway-api.ts onto GatewayClient prototype
installApiMethods(GatewayClient);
 
// Singleton instance
let _client: GatewayClient | null = null;
 
export function getGatewayClient(opts?: ConstructorParameters<typeof GatewayClient>[0]): GatewayClient {
  if (!_client) {
    _client = new GatewayClient(opts);
  } else if (opts) {
    _client.updateOptions(opts);
  }
  return _client;
}
 
// === API Method Type Declarations ===
// These methods are installed at runtime by installApiMethods() in gateway-api.ts.
// We declare them here so TypeScript knows they exist on GatewayClient.
export interface GatewayClient {
  health(): Promise<any>;
  status(): Promise<any>;
  listClones(): Promise<any>;
  createClone(opts: { name: string; role?: string; nickname?: string; scenarios?: string[]; model?: string; workspaceDir?: string; restrictFiles?: boolean; privacyOptIn?: boolean; userName?: string; userRole?: string; emoji?: string; personality?: string; communicationStyle?: string; notes?: string }): Promise<any>;
  updateClone(id: string, updates: Record<string, any>): Promise<any>;
  deleteClone(id: string): Promise<any>;
  getUsageStats(): Promise<any>;
  getSessionStats(): Promise<any>;
  getWorkspaceInfo(): Promise<any>;
  getPluginStatus(): Promise<any>;
  getQuickConfig(): Promise<any>;
  saveQuickConfig(config: Record<string, any>): Promise<any>;
  listSkills(): Promise<any>;
  getSkill(id: string): Promise<any>;
  createSkill(skill: { name: string; description?: string; triggers: Array<{ type: string; pattern?: string }>; actions: Array<{ type: string; params?: Record<string, unknown> }>; enabled?: boolean }): Promise<any>;
  updateSkill(id: string, updates: { name?: string; description?: string; triggers?: Array<{ type: string; pattern?: string }>; actions?: Array<{ type: string; params?: Record<string, unknown> }>; enabled?: boolean }): Promise<any>;
  deleteSkill(id: string): Promise<any>;
  listChannels(): Promise<any>;
  getChannel(id: string): Promise<any>;
  createChannel(channel: { type: string; name: string; config: Record<string, unknown>; enabled?: boolean }): Promise<any>;
  updateChannel(id: string, updates: { name?: string; config?: Record<string, unknown>; enabled?: boolean }): Promise<any>;
  deleteChannel(id: string): Promise<any>;
  getFeishuStatus(): Promise<any>;
  listScheduledTasks(): Promise<any>;
  createScheduledTask(task: { name: string; schedule: string; scheduleType: 'cron' | 'interval' | 'once'; target?: { type: 'agent' | 'hand' | 'workflow'; id: string }; description?: string; enabled?: boolean }): Promise<{ id: string; name: string; schedule: string; status: string }>;
  deleteScheduledTask(id: string): Promise<void>;
  toggleScheduledTask(id: string, enabled: boolean): Promise<{ id: string; enabled: boolean }>;
  listHands(): Promise<{ hands: { id?: string; name: string; description?: string; status?: string; requirements_met?: boolean; category?: string; icon?: string; tool_count?: number; tools?: string[]; metric_count?: number; metrics?: string[] }[] }>;
  getHand(name: string): Promise<any>;
  triggerHand(name: string, params?: Record<string, unknown>): Promise<{ runId: string; status: string }>;
  getHandStatus(name: string, runId: string): Promise<{ status: string; result?: unknown }>;
  approveHand(name: string, runId: string, approved: boolean, reason?: string): Promise<{ status: string }>;
  cancelHand(name: string, runId: string): Promise<{ status: string }>;
  listHandRuns(name: string, opts?: { limit?: number; offset?: number }): Promise<{ runs: { runId: string; status: string; startedAt: string }[] }>;
  listWorkflows(): Promise<{ workflows: { id: string; name: string; steps: number }[] }>;
  getWorkflow(id: string): Promise<{ id: string; name: string; steps: unknown[] }>;
  executeWorkflow(id: string, input?: Record<string, unknown>): Promise<{ runId: string; status: string }>;
  getWorkflowRun(workflowId: string, runId: string): Promise<{ status: string; step: string; result?: unknown }>;
  listWorkflowRuns(workflowId: string, opts?: { limit?: number; offset?: number }): Promise<{ runs: Array<{ runId: string; status: string; startedAt: string; completedAt?: string; step?: string; result?: unknown; error?: string }> }>;
  cancelWorkflow(workflowId: string, runId: string): Promise<{ status: string }>;
  createWorkflow(workflow: { name: string; description?: string; steps: Array<{ handName: string; name?: string; params?: Record<string, unknown>; condition?: string }> }): Promise<{ id: string; name: string }>;
  updateWorkflow(id: string, updates: { name?: string; description?: string; steps?: Array<{ handName: string; name?: string; params?: Record<string, unknown>; condition?: string }> }): Promise<{ id: string; name: string }>;
  deleteWorkflow(id: string): Promise<{ status: string }>;
  listSessions(opts?: { limit?: number; offset?: number }): Promise<{ sessions: Array<{ id: string; agent_id: string; created_at: string; updated_at?: string; message_count?: number; status?: 'active' | 'archived' | 'expired' }> }>;
  getSession(sessionId: string): Promise<any>;
  createSession(opts: { agent_id: string; metadata?: Record<string, unknown> }): Promise<{ id: string; agent_id: string; created_at: string }>;
  deleteSession(sessionId: string): Promise<{ status: string }>;
  getSessionMessages(sessionId: string, opts?: { limit?: number; offset?: number }): Promise<{ messages: Array<{ id: string; role: 'user' | 'assistant' | 'system'; content: string; created_at: string; tokens?: { input?: number; output?: number } }> }>;
  listTriggers(): Promise<{ triggers: { id: string; type: string; enabled: boolean }[] }>;
  getTrigger(id: string): Promise<any>;
  createTrigger(trigger: { type: string; name?: string; enabled?: boolean; config?: Record<string, unknown>; handName?: string; workflowId?: string }): Promise<{ id: string }>;
  updateTrigger(id: string, updates: { name?: string; enabled?: boolean; config?: Record<string, unknown>; handName?: string; workflowId?: string }): Promise<{ id: string }>;
  deleteTrigger(id: string): Promise<{ status: string }>;
  getAuditLogs(opts?: { limit?: number; offset?: number }): Promise<{ logs: unknown[] }>;
  verifyAuditLogChain(logId: string): Promise<{ valid: boolean; chain_depth?: number; root_hash?: string; broken_at_index?: number }>;
  getSecurityStatus(): Promise<{ layers: { name: string; enabled: boolean }[] }>;
  getCapabilities(): Promise<{ capabilities: string[] }>;
  listApprovals(status?: string): Promise<{ approvals: { id: string; hand_name: string; run_id: string; status: string; requested_at: string; requested_by?: string; reason?: string; action?: string; params?: Record<string, unknown>; responded_at?: string; responded_by?: string; response_reason?: string }[] }>;
  respondToApproval(approvalId: string, approved: boolean, reason?: string): Promise<{ status: string }>;
  listModels(): Promise<{ models: GatewayModelChoice[] }>;
  getConfig(): Promise<GatewayConfigSnapshot | Record<string, any>>;
  applyConfig(raw: string, baseHash?: string, opts?: { sessionKey?: string; note?: string; restartDelayMs?: number }): Promise<any>;
}