Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

21.1 KB
Raw Blame
/**
 * Types for the device-control RPC surface. These mirror the shapes in
 * `@lobechat/electron-client-ipc` (desktop) and `@lobechat/types` (server), but
 * are re-declared here so this package stays a leaf with no UI / server
 * dependency. They are structurally compatible with their counterparts, so the
 * desktop wiring can pass its own IPC-typed implementations directly.
 */

import type { DeviceClient, DeviceCliRestartParams, DeviceCliUpdateState } from '@lobechat/types';

// ─── Workspace scan ───

export type ProjectSkillScope = 'device' | 'project';
export type ProjectSkillSource = '.agents/skills' | '.claude/skills' | '.codex/skills';

export interface ProjectSkillItem {
  description?: string;
  /** SKILL.md declares that the model must not invoke this skill automatically. */
  disableModelInvocation?: boolean;
  name: string;
  /** Absolute path to the SKILL.md file. */
  path: string;
  /** Approved root used by the host preview protocol for this skill. */
  previewRoot: string;
  /** Skill filesystem scope: project cwd or execution-device home. */
  scope: ProjectSkillScope;
  /** Directory containing the SKILL.md. */
  skillDir: string;
  /** Source directory the skill was discovered in. */
  source: ProjectSkillSource;
}

export interface InitWorkspaceParams {
  /** Working directory; omitted to discover only device-level skills. */
  scope?: string;
}

export interface WorkspaceInstructionsItem {
  content: string;
  /** Absolute path of the file; the working directory or one of its parents. */
  path: string;
  source: 'AGENTS.md' | 'CLAUDE.md';
}

export interface InitWorkspaceResult {
  instructions: WorkspaceInstructionsItem[];
  /** Absent for a device-only scan; no working directory is selected implicitly. */
  root?: string;
  skills: ProjectSkillItem[];
}

export interface ListProjectSkillsParams {
  /** Working directory used to resolve the project root. */
  scope: string;
}

export interface ListProjectSkillsResult {
  root: string;
  skills: ProjectSkillItem[];
  /** Legacy source hint. Per-skill `scope` / `source` fields are authoritative. */
  source: ProjectSkillSource | null;
}

/** The run env keys that move where Claude Code keeps auto memory. */
export interface ClaudeCodeMemoryRunEnv {
  CLAUDE_CODE_PROJECT_DIR_NAME?: string;
  CLAUDE_CONFIG_DIR?: string;
}

export interface ListClaudeCodeMemoryParams {
  /**
   * The agent's own values for these keys (`heterogeneousProvider.env`). A run
   * spreads that env over the device's, so a set value wins here too.
   */
  env?: ClaudeCodeMemoryRunEnv;
  /** Working directory of the Claude Code project. */
  scope: string;
}

export interface ClaudeCodeMemoryFile {
  description?: string;
  /** The `MEMORY.md` index Claude Code loads into every session. */
  isIndex: boolean;
  /** Frontmatter `name`; the file name when absent. */
  name: string;
  /** Absolute path to the memory file. */
  path: string;
  /** Path within the memory directory, `/`-separated. */
  relativePath: string;
  size: number;
  /** Frontmatter `metadata.type` (or top-level `type`): user / feedback / project / reference. */
  type?: string;
  /** Last modification time, epoch ms. */
  updatedAt: number;
}

export interface ListClaudeCodeMemoryResult {
  files: ClaudeCodeMemoryFile[];
  /**
   * Claude Code's auto-memory directory for this project
   * (`~/.claude/projects/<sanitized project root>/memory`). Reported even when
   * it does not exist yet, so the UI can say where memory will land.
   */
  memoryDir: string;
}

export interface StatPathResult {
  /** Device-resolved path; aliases and symlinks share one execution-directory lock. */
  canonicalPath?: string;
  exists: boolean;
  isDirectory: boolean;
  repositoryUrl?: string;
  repoType?: 'git' | 'github';
}

export interface BrowseDirectoryParams {
  cursor?: string;
  limit?: number;
  path?: string;
}

export interface BrowseDirectoryEntry {
  isSymlink: boolean;
  name: string;
  path: string;
  readable: boolean;
}

export interface BrowseDirectoryResult {
  entries: BrowseDirectoryEntry[];
  nextCursor?: string;
  parentPath: string | null;
  path: string;
  pathSeparator: '/' | '\\';
  roots: string[];
  truncated: boolean;
}

// ─── File preview ───

export type LocalFilePreviewAccept = 'image';

export interface LocalFilePreviewUrlParams {
  accept?: LocalFilePreviewAccept;
  path: string;
  workingDirectory: string;
}

export interface CopyAssetForPublishParams {
  from: string;
  to: string;
  workingDirectory: string;
}

export interface CopyAssetForPublishResult {
  error?: string;
  success: boolean;
}

export interface ExternalAssetForPublishParams {
  path: string;
  workingDirectory: string;
}

export interface ExternalAssetForPublishResult {
  base64?: string;
  contentType?: string;
  error?: string;
  success: boolean;
}

export interface LocalFilePreviewText {
  content: string;
  contentType: string;
  type: 'text';
}

export interface LocalFilePreviewImage {
  base64: string;
  contentType: string;
  type: 'image';
}

/**
 * Binary document (pdf / office) small enough to preview in-app, carried as
 * base64 so it survives RPC serialization. Oversized documents stay on the
 * `binary` / `pdf` unsupported variants.
 */
export interface LocalFilePreviewDocument {
  base64: string;
  contentType: string;
  type: 'document';
}

export interface LocalFilePreviewUnsupported {
  contentType: string;
  type: 'binary' | 'pdf' | 'video';
}

export type LocalFilePreview =
  | LocalFilePreviewDocument
  | LocalFilePreviewImage
  | LocalFilePreviewText
  | LocalFilePreviewUnsupported;

/** Terminal reasons a file preview failed (see `LocalFilePreviewResult.code`). */
export type LocalFilePreviewFailureCode = 'forbidden' | 'not_found';

export interface LocalFilePreviewResult {
  /**
   * Set when the failure is terminal for this file: `not_found` (deleted /
   * moved) or `forbidden` (outside the approved roots, permission denied).
   * Absent for transient failures, so a cached preview survives those.
   */
  code?: LocalFilePreviewFailureCode;
  error?: string;
  preview?: LocalFilePreview;
  success: boolean;
}

// ─── Project file index ───

export interface ProjectFileIndexEntry {
  /**
   * Directory whose children were deliberately left out of the index because
   * Git collapsed it (`git ls-files --directory` reports a fully ignored
   * directory as a single entry). The row is expandable, but its children must
   * be fetched on demand via `listProjectDirectory`.
   */
  collapsed?: boolean;
  /** Whether Git ignore rules match this file or directory. */
  gitIgnored?: boolean;
  isDirectory: boolean;
  name: string;
  path: string;
  relativePath: string;
}

export interface ProjectFileIndexParams {
  /** Working directory used to resolve the project root. */
  scope?: string;
}

export interface ProjectFileIndexResult {
  entries: ProjectFileIndexEntry[];
  indexedAt: string;
  root: string;
  source: 'git' | 'glob';
}

export interface ProjectDirectoryListParams {
  /** Cap on returned children; the caller is told when more exist. */
  limit?: number;
  /** Directory to list, relative to `root`. A trailing slash is tolerated. */
  relativePath: string;
  /** Project root the returned `relativePath`s are resolved against. */
  root: string;
}

export interface ProjectDirectoryListResult {
  entries: ProjectFileIndexEntry[];
  /** True when the directory holds more children than `limit` returned. */
  truncated: boolean;
}

export interface ProjectFileSearchParams extends ProjectFileIndexParams {
  changedOnly?: boolean;
  excludeIgnored?: boolean;
  limit?: number;
  query: string;
}

export interface ProjectFileSearchResult {
  entries: ProjectFileIndexEntry[];
  root: string;
  searchedAt: string;
  source: 'git' | 'glob';
}

// ─── Skill directory ───

export interface PrepareSkillDirectoryParams {
  forceRefresh?: boolean;
  /** Presigned download URL of the skill zip archive. */
  url: string;
  /** Content hash of the archive β€” the idempotency key for the local cache. */
  zipHash: string;
}

export interface PrepareSkillDirectoryResult {
  error?: string;
  /** Device-local directory the archive was extracted into. */
  extractedDir: string;
  success: boolean;
  zipPath: string;
}

/**
 * Host hooks for the skill-archive cache. Both are optional: the CLI daemon
 * runs on the portable defaults; the desktop injects both so the gateway RPC
 * path shares the cache (and proxy-aware fetch) with its renderer-IPC path.
 */
export interface SkillDirectoryDeps {
  /** Fetch used to download skill archives. Desktop injects Electron's `net` fetch (proxy-aware); defaults to global `fetch`. */
  fetchSkillArchive?: (url: string) => Promise<Response>;
  /** Skill zip cache root. Desktop: `<appStoragePath>/file-storage/skills`; defaults to `~/.lobehub/skills`. */
  skillCacheRoot?: string;
}

/**
 * The subset of platform hooks the workspace-scan helpers need. Kept narrow so
 * the desktop's local-IPC `WorkspaceCtr` can reuse `initWorkspace` /
 * `listProjectSkills` without supplying the file preview / index handlers.
 */
export interface WorkspaceScanDeps {
  /**
   * Approve a resolved project root for the host's file-preview protocol. Called
   * after workspace scans so a later click-through resolves. No-op on the CLI.
   */
  approveProjectRoot?: (root: string) => Promise<void>;
}

/**
 * Platform-specific handlers the device-control dispatcher delegates to. Git and
 * workspace-scan methods are implemented inside this package (over
 * `@lobechat/local-file-shell`); the handlers below differ per host:
 *
 * - Desktop injects implementations backed by its `localFileProtocolManager`
 *   (preview-protocol approval, secure file reads).
 * - The CLI uses the portable defaults exported from this package
 *   (`defaultGetLocalFilePreview`, `defaultGetProjectFileIndex`).
 */
// ─── Trash ───

/** Mirrors `@lobechat/electron-client-ipc` `TrashLocalFilesParams`. */
export interface TrashLocalFilesParams {
  paths: string[];
}

export interface TrashLocalFilesResultItem {
  error?: string;
  /** The path as it was requested, so the caller can reconcile its own rows. */
  path: string;
  success: boolean;
}

/** Per-path outcome in request order; `success` is true only when every path was trashed. */
export interface TrashLocalFilesResult {
  items: TrashLocalFilesResultItem[];
  success: boolean;
}

export interface DeviceControlDeps extends SkillDirectoryDeps, WorkspaceScanDeps {
  /**
   * Start an app update check on this client; an available update downloads
   * automatically. Returns right away with the updated state β€” callers poll
   * {@link DeviceControlDeps.getAppUpdateState} for progress. Optional: only
   * the desktop app can update itself, so the CLI omits the three app-update
   * handlers and the dispatcher fails the RPC with a stable reason.
   */
  checkAppUpdate?: () => Promise<AppUpdateState>;
  checkCliUpdate?: () => Promise<DeviceCliUpdateState>;
  /**
   * Interactive PTY handlers. Optional: a host without a PTY implementation
   * (or one whose runtime forbids spawning shells) omits them, and the
   * dispatcher fails the RPC with {@link TERMINAL_UNSUPPORTED_MESSAGE} rather
   * than leaving a terminal panel waiting on a session that will never appear.
   */
  closeTerminal?: (params: CloseTerminalParams) => Promise<CloseTerminalResult>;
  /** Copy a publish asset (possibly outside the workspace) to a path inside the workspace. */
  copyAssetForPublish?: (params: CopyAssetForPublishParams) => Promise<CopyAssetForPublishResult>;
  createTerminalSession?: (
    params: CreateTerminalSessionParams,
  ) => Promise<CreateTerminalSessionResult>;
  /**
   * Enroll this machine into a workspace pool: derive the workspace-scoped
   * deviceId and open a second gateway connection authenticated with `token`
   * (a short-lived workspace-device connect token minted server-side), then
   * return the derived identity so the server can register the workspace row.
   * Optional β€” hosts that manage a single fixed connection (e.g. a CLI daemon
   * already running in workspace mode) may omit it; the dispatcher then fails
   * the RPC with a clear reason.
   */
  enrollWorkspace?: (params: EnrollWorkspaceParams) => Promise<EnrollWorkspaceResult>;
  /** Where this client's app update stands: current version, stage, progress. */
  getAppUpdateState?: () => Promise<AppUpdateState>;
  getCliUpdateState?: () => Promise<DeviceCliUpdateState>;
  /** Read a local file preview (host-gated on desktop; disk read on CLI). */
  getLocalFilePreview: (params: LocalFilePreviewUrlParams) => Promise<LocalFilePreviewResult>;
  /** Build the project file index. */
  getProjectFileIndex: (params: ProjectFileIndexParams) => Promise<ProjectFileIndexResult>;
  /**
   * Restart into a downloaded update. Resolves before the app quits so the
   * response still reaches the caller; rejects when nothing is downloaded.
   */
  installAppUpdate?: () => Promise<InstallAppUpdateResult>;
  /** Query a heterogeneous CLI's model catalog on this execution host. */
  listHeterogeneousAgentModels?: (
    params: ListHeterogeneousAgentModelsParams,
  ) => Promise<HeterogeneousAgentModelCatalog>;
  /**
   * List the tools of an MCP server only this machine reaches (stdio, or an
   * HTTP endpoint on its network), for a server that must not connect to it
   * itself. Optional: a client that runs no MCP servers omits it, and the
   * dispatcher fails the RPC with {@link MCP_UNSUPPORTED_MESSAGE}.
   */
  listMcpTools?: (params: ListMcpToolsParams) => Promise<ListedMcpServerTool[]>;
  /** Read raw bytes after the user explicitly approved an external publish closure. */
  readExternalAssetForPublish?: (
    params: ExternalAssetForPublishParams,
  ) => Promise<ExternalAssetForPublishResult>;
  readTerminal?: (params: ReadTerminalParams) => Promise<ReadTerminalResult>;
  resizeTerminal?: (params: ResizeTerminalParams) => Promise<void>;
  restartCli?: (params: DeviceCliRestartParams) => Promise<DeviceCliUpdateState>;
  /** Search project files without shipping the whole index to the caller. */
  searchProjectFiles: (params: ProjectFileSearchParams) => Promise<ProjectFileSearchResult>;
  /**
   * Move files/folders to the OS trash. Optional: only a host with a desktop
   * shell (Electron `shell.trashItem`) has a recoverable trash, so the CLI omits
   * it and the dispatcher fails the RPC with {@link TRASH_UNSUPPORTED_MESSAGE}
   * rather than degrading to a permanent delete.
   */
  trashLocalFiles?: (params: TrashLocalFilesParams) => Promise<TrashLocalFilesResult>;
  /**
   * Drop this machine's enrollment in a workspace pool: close the
   * workspace-principal connection and clear any persisted auto-reconnect
   * state. Optional, mirroring {@link DeviceControlDeps.enrollWorkspace}.
   */
  unenrollWorkspace?: (params: UnenrollWorkspaceParams) => Promise<{ success: boolean }>;
  writeTerminal?: (params: WriteTerminalParams) => Promise<void>;
}

// ─── Heterogeneous agent model discovery ───

/**
 * Structural mirrors of the canonical `@lobechat/types` catalog contracts.
 * Kept local so device-control remains a leaf package with no app/type-layer dependency.
 */
/**
 * An MCP server's connection, as the server forwards it for `listMcpTools`
 * (the shape tunneled MCP tool calls forward). Credentials travel decrypted and
 * narrowed to the token fields; the device stores nothing.
 */
export type ListMcpToolsConnection =
  | {
      auth?: { accessToken?: string; token?: string; type: 'none' | 'bearer' | 'oauth2' };
      headers?: Record<string, string>;
      name: string;
      type: 'http';
      url: string;
    }
  | {
      args: string[];
      command: string;
      env?: Record<string, string>;
      name: string;
      type: 'stdio';
    };

export interface ListMcpToolsParams {
  /** List on a session that announces MCP Apps, so view-only tools are listed too. */
  mcpApps?: boolean;
  params: ListMcpToolsConnection;
}

/**
 * A tool as the MCP server's `tools/list` returns it. Returned as listed, so
 * the server maps it exactly as it maps a listing it ran itself.
 */
export interface ListedMcpServerTool {
  _meta?: Record<string, unknown>;
  description?: string;
  inputSchema: object;
  name: string;
}

export interface ListHeterogeneousAgentModelsParams {
  args?: string[];
  command?: string;
  cwd?: string;
  env?: Record<string, string>;
  type:
    | 'antigravity'
    | 'codebuddy'
    | 'codex'
    | 'copilot'
    | 'cursor'
    | 'devin'
    | 'droid'
    | 'grok-build'
    | 'kimi-code'
    | 'opencode'
    | 'pi'
    | 'qoder'
    | 'trae';
}

export interface HeterogeneousAgentModelCatalogItem {
  id: string;
  label?: string;
  modelId: string;
  providerId: string;
}

export type HeterogeneousAgentModelCatalog =
  | {
      error: {
        code:
          | 'auth_required'
          | 'cli_not_found'
          | 'command_failed'
          | 'device_unavailable'
          | 'timeout'
          | 'unsupported_client'
          | 'unsupported_configuration';
        message: string;
      };
      status: 'error';
      updatedAt: number;
    }
  | {
      models: HeterogeneousAgentModelCatalogItem[];
      status: 'success';
      updatedAt: number;
    };

// ─── Workspace enrollment (remote share) ───

export interface EnrollWorkspaceParams {
  /**
   * Only derive and return the workspace identity β€” do NOT open a share
   * connection or persist enrollment state. Lets the server check for an
   * existing enrollment (and ask the user to confirm an overwrite) before the
   * device mutates anything. Older clients ignore this flag and enroll on the
   * probe, which degrades to the pre-flag behaviour.
   */
  identityOnly?: boolean;
  /** Short-lived workspace-device connect token (carries the workspace claim). */
  token: string;
  workspaceId: string;
}

export interface EnrollWorkspaceResult {
  /** The workspace-scoped deviceId this machine derived for the pool. */
  deviceId: string;
  identitySource: 'fallback' | 'machine-id';
}

export interface UnenrollWorkspaceParams {
  workspaceId: string;
}

// ─── Remote app update ───

/**
 * Structural mirror of the desktop updater's stage, plus `unsupported` for a
 * client that can't update itself (a dev build, or updates turned off).
 */
export type AppUpdateStage =
  'checking' | 'downloaded' | 'downloading' | 'error' | 'idle' | 'latest' | 'unsupported';

export interface AppUpdateState {
  /** Version the client is running right now. */
  currentVersion: string;
  errorMessage?: string;
  /** Download progress, 0–100. Present while `stage` is `downloading`. */
  progress?: number;
  stage: AppUpdateStage;
  /** Version being downloaded or ready to install. */
  targetVersion?: string;
}

export interface InstallAppUpdateResult {
  /** Version the client restarts into. */
  targetVersion: string;
}

// ─── Interactive terminal (PTY) ───
//
// The device RPC surface is strictly request/response, so an interactive shell
// is expressed as a session plus polling rather than a byte stream: the host
// spawns a real PTY, keeps its output in a bounded ring buffer, and the caller
// drains that buffer with a cursor. A real PTY (rather than a piped child) is
// the whole point β€” `sudo` reads the password from `/dev/tty`, so it prompts
// and accepts input exactly as it would in a local shell, and no credential
// ever leaves the device.
//
// Runnable bytes are base64 in both directions: PTY output is not guaranteed to
// be valid UTF-8 at chunk boundaries, and JSON strings cannot carry arbitrary
// bytes. Mirrors the tunnel frames' own `data` encoding.

export interface CreateTerminalSessionParams {
  /** Initial grid width. Re-sent later through {@link ResizeTerminalParams}. */
  cols: number;
  /** Directory to start in; the host falls back to the home directory. */
  cwd?: string;
  /** Initial grid height. */
  rows: number;
}

export interface CreateTerminalSessionResult {
  /** The client hosting the session, so callers can keep its later calls there. */
  client: DeviceClient;
  /** Directory the shell actually started in (the request's `cwd` may not exist). */
  cwd: string;
  id: string;
  pid: number;
  /** Absolute path of the shell binary that was spawned. */
  shell: string;
}

export interface WriteTerminalParams {
  /** Base64-encoded bytes to write to the PTY. */
  data: string;
  id: string;
}

export interface ReadTerminalParams {
  /**
   * Only output produced after this point is returned. Pass the previous
   * response's `nextCursor`; start at 0. A caller that fell behind the ring
   * buffer is clamped forward rather than refused, so the terminal resumes at
   * the oldest output still held.
   */
  cursor: number;
  id: string;
}

export interface ReadTerminalResult {
  /**
   * Base64-encoded output produced since `cursor` (empty when nothing new).
   * Capped per call; keep reading while it is non-empty to drain a burst.
   */
  chunk: string;
  /** Present once the shell has exited. */
  exitCode?: number;
  /** Whether the shell has exited. */
  exited: boolean;
  /** Cursor for the next read. */
  nextCursor: number;
}

export interface ResizeTerminalParams {
  cols: number;
  id: string;
  rows: number;
}

export interface CloseTerminalParams {
  id: string;
}

export interface CloseTerminalResult {
  /** False when the session was already gone (exited, reaped, or never existed). */
  closed: boolean;
}