Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

66.7 KB
Raw Blame
import { pendingGhostCardFormDelivery } from '@cindy/maker-shared/ghost-card-form';
import {
  tryMobilePeerFile,
  peerMediaUri,
  releasePeerMedia,
} from "./peerFileRegistry";
import { withTransientRemoteRetry } from "./remoteRetry";
import { getActiveMobileSessionRealm } from '@/config/env';
import { expandGhostCommand, parseGhostCommandWord, splitGhostDirective } from '@cindy/maker-shared/ghost-command';
import { composerPluginListSchema, isComposerPluginCatalogUnsupportedError, type ComposerPlugin } from '@/session/remoteComposerPlugins';
import type { OrcaWorkerAgentKind, OrcaWorkerPermissionMode } from "@cindy/maker-shared/orca-team";
import { fetchAgentCapabilities } from "@/session/agentCapabilitiesCache";
import {
  getMobileAuthOwner,
  isMobileAuthOwnerCurrent,
} from "@/auth/authOwnerGeneration";
import type {
  ConversationSearchRequest,
  ConversationSearchResponse,
} from "@cindy/maker-shared/conversation-search";
import type {
  InputProjection,
  PendingInteraction,
  QueuedRemoteMessage,
  RemoteMessage,
  RemoteSession,
} from "@/session/types";
import type {
  MobileSessionReference,
  MobileSessionReferenceContext,
} from "@/session/sessionReferences";
import {
  DEVICE_LINK_MEDIA_FETCH_CHANNEL,
  DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL,
  DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL,
  DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL,
  MOBILE_REMOTE_INVOKE_CHANNELS,
} from "@cindy/maker-shared/device-link-contract";
import {
  CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2,
  ORCA_EXECUTION_DEVICES_CHANNEL,
  isSharedTaskPeer,
  readDeviceFile,
  FILE_PEER_MAX_BYTES,
  createDeviceFileOperations,
  exportDeviceFile,
  assertFileReadActive,
  validFileVersion,
  type DeviceFileResult,
} from "@cindy/device-link";
import { errorText, mediaExtOf, nextFileTrace } from "@/debug/fileDiagnostics";
import { mobileDebugLog } from "@/debug/mobileDebugLog";
import type {
  HistoryViewPage,
  HistoryDetailPage,
  HistoryWorkSummary,
} from "@cindy/maker-shared/message-window";
import type {
  MobileGoalLimitsInput,
  MobileGoalStatusPayload,
  MobileCodexRateLimitResetResult,
  MobileCodexRateLimitsResult,
  CodexResetAutoUseSettings,
  MobileSessionAgentSwitchIntent,
  MobileSessionAgentSwitchResult,
  MobileVoiceDictionaryLearningRequest,
  MobileVoiceDictionarySnapshotResult,
  MobileVoiceDictionaryLearningResult,
} from "@cindy/maker-shared/device-link-contract";
import type { ProviderView } from "@cindy/model-providers/registry";
import {
  NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS,
  type NativeSubscriptionAuth,
} from "@cindy/model-providers/types";
import type { RewindPreviewPayload } from "@/session/rewindPreview";
import type {
  MobileRemoteMediaFetchOptions,
  MobileRemoteMediaFetchResult,
} from "@/session/remoteMedia";
import type {
  RemoteSchedule,
  RemoteScheduleCreateFromTemplateInput,
  RemoteScheduleRun,
  RemoteScheduleTemplate,
  RemoteScheduleWriteInput,
  ScheduleListFilter,
} from "@/scheduler/types";

export type RemoteInvoke = <T = unknown>(
  deviceId: string,
  channel: string,
  args?: unknown[],
) => Promise<T>;

export interface MobileMakerTransportDeps {
  deviceId: string;
  invoke: RemoteInvoke;
  isCurrent?: () => boolean;
}

export interface SendOptions {
  messageUuid?: string;
  userName?: string;
  throwOnStartFailure?: boolean;
}

export interface CreateSessionOptions {
  agentKind: "claude-code" | "codex" | "pi";
  /**
   * 控制端预生成的 sessionId(新建会话乐观管线用):被控端 readCreateSessionOpts
   * 自手机远控首版(2026-06-21)起透传 body.id,maker-core createSession 对
   * provided id 幂等(active 复用 / storage 命中跳过 insert)——乐观会话行、路由、
   * 订阅从一开始就用最终 id,无需 rekey。省略 = 被控端生成。
   */
  id?: string;
  workingDir?: string;
  model: string;
  effort?: string;
  permissionMode?: string;
  fastMode?: boolean | 'ultrafast';
  workspaceKind?: "project" | "dialogue";
  extraDirs?: string[];
  /**
   * 显式选中的供应商(来源)id。仅当用户在模型下拉里选了非默认来源时带上;
   * 被控端据此把 sessions.provider_id 落库,使新会话首个请求即按该来源路由。
   * 省略 = NULL = 跟随被控端默认路由(对齐桌面 deviceLinkCreateArgs)。
   */
  providerId?: string;
  [key: string]: unknown;
}

export interface CreateSessionResult {
  sessionId: string;
  agentKind?: string;
  workDir?: string;
  capabilities?: unknown;
  usedProjectContext?: boolean;
}

export type MobileAgentKind = "claude-code" | "codex" | "pi";

/**
 * 订阅家族 → 被控端余量快照 channel。ChatGPT 走 Codex 自有控制面
 * (getCodexRateLimits / getAccountUsage),其余家族各有一个只读快照 channel。
 * 以 NativeSubscriptionAuth 为键:新增订阅家族时这里漏接会直接编译失败。
 */
export type SubscriptionUsageKind = Exclude<NativeSubscriptionAuth, "codex">;
export const SUBSCRIPTION_USAGE_CHANNELS = {
  claude: "maker:usage:claude-subscription",
  xai: "maker:usage:xai-subscription",
} as const satisfies Record<SubscriptionUsageKind, string>;

export type MobileSlashCommand =
  | { kind: "agent-builtin"; name: string; description: string }
  | {
      kind: "agent-skill";
      name: string;
      description?: string;
      source: "user" | "skill";
      path?: string;
      scope?: string;
      enabled?: boolean;
    }
  // desktop 自有命令(被控端 main 的 DesktopCommandRegistry,如 /learn):
  // 由控制端按名字分流执行,不转发给 agent。
  | { kind: "desktop"; name: string; description: string };

export interface MobileAgentCommandListResult {
  success: boolean;
  error?: string;
  commands?: MobileSlashCommand[];
}

export interface MobileDesktopCommandListResult {
  success: boolean;
  error?: string;
  commands?: MobileSlashCommand[];
}

/** learn:start 请求(形状对齐被控端 learn-host 的 LearnStartRequest 校验)。 */
export interface MobileLearnStartRequest {
  input: string;
  sourceKind: "freetext" | "session" | "hub";
  hubSlug?: string;
  hubCatalogScope?: "market" | "team";
  originSessionId?: string;
}

export interface MobileAgentSkillListResult {
  success: boolean;
  error?: string;
  skills?: MobileSlashCommand[];
}

export interface MobileAtResourceItem {
  type: "file" | "dir" | "agent";
  name: string;
  relPath: string;
  description?: string;
}

export interface MobileAtResourceScanResult {
  success: boolean;
  error?: string;
  items?: MobileAtResourceItem[];
  truncated?: boolean;
}

export interface MessageListOptions {
  limit?: number;
  before?: string;
  beforeTs?: number;
  /** 只拉该 host 行之后的新消息;旧被控端会忽略未知可选字段并退化为最新页。 */
  after?: string;
}

export interface MessageAroundOptions {
  radius?: number;
}

export interface RemoteDirectoryEntry {
  name: string;
  kind: "dir" | "symlink" | "file";
  path: string;
}

/** Windows 被控端的盘符(fs:list-dir 可选回传);path 为 host-native 根路径,直接用于导航。 */
export interface RemoteDirectoryDrive {
  name: string;
  path: string;
  current: boolean;
}

export interface RemoteDirectoryListResult {
  resolvedPath: string;
  entries: RemoteDirectoryEntry[];
  parent: string | null;
  /** 仅 Windows 新版被控端回传;旧被控端缺省时不显示盘符切换。 */
  drives?: RemoteDirectoryDrive[];
  /** 仅 Windows:盘符枚举仍在后台进行,控制端应再拉一次当前目录。旧端忽略。 */
  drivesPending?: boolean;
}

export interface RemotePathStatResult {
  kind: "dir" | "file" | "missing";
  resolvedPath: string;
}

export interface RemoteTextFilePreviewResult {
  success: boolean;
  error?: string;
  reason?: "oversize" | "not_found" | "forbidden" | "read_failed";
  data?: string;
  /** Only returned when the caller opts into the existing file transfer path. */
  transferRequired?: boolean;
  size: number;
  limitMb?: number;
}

/* ---- file-browser:remote-op(完整文件浏览通道)响应形状 ----
 * 与被控端 apps/desktop/src/main/file-browser/device-op.ts 逐字段一致;
 * listDir 返回裸 entries 数组,归一化交给 maker-shared 的
 * normalizeRemoteOpDirEntries(跨版本被控端防御)。 */

export interface FileBrowserCapsResult {
  ok: boolean;
  gzip?: boolean;
  completeDirectoryListing?: boolean;
  /** 老被控端对未知 op 返回 {ok:false,message:'unknown op: caps'}。 */
  message?: string;
}

export interface FileBrowserReadFileData {
  relPath: string;
  /** contentEncoding 为 'gzip' 时是 gzip+base64,需用 pako 解压。 */
  content: string;
  size: number;
  mtimeMs: number;
  truncated?: boolean;
  contentEncoding?: "gzip";
}

export type FileBrowserReadFileResult =
  | { ok: true; data: FileBrowserReadFileData }
  | {
      ok: false;
      code?: "OVERSIZE" | "BINARY_FILE" | "READ_FAILED";
      message?: string;
      stat?: { relPath: string; type: "file"; size: number; mtimeMs: number };
    };

export type FileBrowserThumbnailResult =
  | {
      ok: true;
      dataBase64: string;
      mimeType: "image/webp";
      width: number;
      height: number;
      size: number;
      mtimeMs: number;
    }
  | {
      ok: false;
      code?: "THUMB_UNSUPPORTED" | "THUMB_TOO_LARGE" | "THUMB_FAILED";
      message?: string;
    };

export interface FileBrowserListAllFilesResult {
  files: string[];
  truncated: boolean;
  elapsedMs: number;
  error?: string;
}

export type FileBrowserExportStartResult =
  | { ok: true; transferId: string; size: number; mtimeMs: number }
  | { ok: false; message?: string };

export type FileBrowserExportStatusResult =
  | {
      ok: true;
      state: "uploading" | "done" | "error";
      key?: string;
      message?: string;
      size: number;
      uploaded: number;
    }
  | { ok: false; message?: string };

export interface FileBrowserSearchMatch {
  relPath: string;
  lineNumber: number;
  lineText: string;
}

export interface FileBrowserSearchCollectResult {
  matches: FileBrowserSearchMatch[];
  truncated: boolean;
  totalMatches: number;
  totalFiles: number;
}

export interface MobileVoiceTranscribeRequest {
  ossKey: string;
  mimeType?: string;
  fileName?: string;
  sourceLanguage?: string;
}

export interface MobileVoiceTranscribeResult {
  text: string;
  provider?: string;
  model?: string;
  audioBytes?: number;
}

export interface MobileActiveSessionSnapshot {
  sessionId: string;
  agentKind?: string;
  workDir?: string;
  capabilities?: unknown;
  isTurnRunning?: boolean;
}

export type MobileActiveSessionSnapshotResult = MobileActiveSessionSnapshot[] | {
  format: 'active-sessions-v2';
  sessions: MobileActiveSessionSnapshot[];
};

/** 被控端视角的模型单价(USD / 百万 token,同桌面 useModelPricing 形状)。 */
export interface MobileModelPrice {
  inputUsdPerMtok: number;
  outputUsdPerMtok: number;
  /** Gateway 折扣比例 0..1;旧被控端不下发。计费金额 = 原价 × (1 - costDiscount)。 */
  costDiscount?: number;
}

export type MobileModelPricingMap = Record<string, MobileModelPrice>;

/**
 * 会话「非选中模型」effort/fast 写穿入参(隧道 maker:set-session-model-pref,形状对齐被控端
 * register.ts 的 SET_SESSION_MODEL_PREF 校验)。被控端 renderer 写真实会话记忆后经
 * maker:session-model-pref:changed push 回流刷新手机镜像。
 */
export interface MobileSessionModelPref {
  sessionId: string;
  agent: MobileAgentKind;
  providerId: string;
  model: string;
  effort?: string;
  fast?: boolean | 'ultrafast';
}

/**
 * 草稿「模型 effort/fast」写穿入参(隧道 maker:apply-new-maker-draft-pref,形状对齐被控端
 * APPLY_NEW_MAKER_DRAFT_PREF 校验)。
 *  - active=false:会话里非选中行双写,被控端草稿默认随之更新,使「下次在被控端 / 桌面控制端
 *    选中该模型」拿到同一份 effort/fast(providerId 必填)。
 *  - active=true:新建任务页的当前选择写回被控端新建任务默认(与桌面远程新建同一写法);
 *    markModelChoice=true 表示用户明确选了这个模型,false 只同步档位 / Fast、不打选模标记。
 */
export type MobileNewMakerDraftPref =
  | {
      agent: MobileAgentKind;
      providerId: string;
      modelId: string;
      active: false;
      effort?: string;
      fast?: boolean | 'ultrafast';
    }
  | {
      agent: MobileAgentKind;
      /** '' = 跟随被控端默认来源。 */
      providerId: string;
      modelId: string;
      active: true;
      markModelChoice: boolean;
      effort?: string;
      fast?: boolean | 'ultrafast';
    };

/**
 * 工作端 maker:get-new-maker-defaults 回包的手机端消费子集。完整形状是被控端
 * RemoteNewMakerDefaults(model/effort 等手机另有 capabilities / 会话推断读源,暂不消费);
 * 手机当前只取 vendor 无关的 worktreeEnabled 播种新建页 worktree 开关。
 * 旧被控端不回该字段 → undefined → 调用方按未勾选兜底。
 */
export interface MobileNewMakerDefaults {
  worktreeEnabled?: boolean;
  [key: string]: unknown;
}

/**
 * 工作端拥有的 New Maker worktree 源分支镜像。revision 由工作端按 canonical
 * baseRepo 独立递增;手机只用它做 pull / push / apply 回包的乱序收敛,不自行生成。
 */
export interface MobileWorktreeBranchPreferenceSnapshot {
  baseRepo: string;
  sourceBranch: string;
  revision: number;
}

/** 工作端 worktree:detect-cwd 资格探测回包(形状对齐被控端 DetectCwdResp)。 */
export interface MobileWorktreeDetectCwdResult {
  isGitRepo: boolean;
  isInsideWorktree: boolean;
  gitInstalled: boolean;
  currentBranch?: string;
  /** git rev-parse --show-toplevel 结果(被控端绝对路径);worktree:create 的 baseRepo 用它。 */
  repoRoot?: string;
  /**
   * 新版 Desktop 才会返回 true。旧端可能接受 worktree:create 的未知 recoveryKey
   * 字段却不把它写入元数据,因此省略必须在副作用前视为不支持。
   */
  supportsRecoveryKeyDiscard?: boolean;
}

/** 工作端 worktree:list-branches 回包(本地分支列表 + 当前 HEAD 分支)。 */
export interface MobileWorktreeListBranchesResult {
  branches: string[];
  current: string;
}

/** 工作端 worktree:create 元信息(形状对齐被控端 WorktreeMeta)。 */
export interface MobileWorktreeMeta {
  sessionId: string;
  name: string;
  path: string;
  baseRepo: string;
  branch: string;
  sourceBranch: string;
  createdAt: string;
  recoveryKey?: string;
}

/** 工作端 worktree:create 回包(error.message 为被控端生成的可展示文案)。 */
export type MobileWorktreeCreateResult =
  | { ok: true; meta: MobileWorktreeMeta }
  | {
      ok: false;
      error: {
        kind: string;
        message: string;
        hint?: string;
        rawStderr?: string;
      };
    };

export interface MobileMakerTransport {
  listComposerPlugins(workingDir?: string): Promise<ComposerPlugin[]>;
  /** 在被控端生成当前任务完成后的输入框推荐提示词。 */
  predictNextPrompt(request: {
    sessionId: string;
    agentKind: MobileAgentKind;
    turnGen: number;
    completionRevision: number;
    cacheOnly?: boolean;
  }): Promise<{ prompt: string | null }>;
  createSession(opts: CreateSessionOptions): Promise<CreateSessionResult>;
  getCapabilities(agentKind: MobileAgentKind): Promise<unknown>;
  /**
   * 被控端 runtime 已注册的 agent 集合(maker:list-available-agents,在 REMOTE_INVOKE_ALLOWLIST 内)。
   * 新建会话入口据此过滤:Pi 二进制缺失时被控端 agent map 无 pi,但模型目录仍投影 Pi,不过滤
   * 会让用户建出最终 requireAgent 报 not-registered 的会话(codex review P2)。
   */
  listAvailableAgents(): Promise<MobileAgentKind[]>;
  getSessionTree(sessionId: string): Promise<unknown | null>;
  navigateSessionTree(
    sessionId: string,
    entryId: string,
    options?: { summarize?: boolean; customInstructions?: string },
  ): Promise<{ tree: unknown; draftText?: string; cancelled?: boolean } | null>;
  /**
   * 列被控端的供应商(来源)结构,用于 provider-aware 模型下拉(隧道 maker:provider:list)。
   * modelVisibilityOverrides = 被控端「模型显示/隐藏」override 快照(旧被控端不回传)。
   */
  listProviders(): Promise<{
    providers: ProviderView[];
    providerOrder?: string[];
    modelVisibilityOverrides?: Record<string, boolean>;
  }>;
  getSession(sessionId: string): Promise<RemoteSession>;
  /**
   * 输入框开始打字时请被控端提前启动该任务的 Agent。尽力而为:旧被控端返回
   * CHANNEL_NOT_ALLOWED,调用方忽略即可。
   */
  prewarmSession(sessionId: string, createOpts: unknown): Promise<unknown>;
  createSideChat(sessionId: string): Promise<RemoteSession>;
  listSideChats(sessionId: string): Promise<Array<{ id: string }>>;
  searchConversations(
    request: ConversationSearchRequest,
  ): Promise<ConversationSearchResponse>;
  patchSessionMeta(
    sessionId: string,
    patch: SessionMetaPatch,
  ): Promise<RemoteSession>;
  /**
   * error-tail「忽略」:被控端把该 role='error' 行的 content merge dismissed:true
   * 持久化(不丢原字段),重连/历史重拉后 banner 不复活。老被控端无此 channel →
   * CHANNEL_NOT_ALLOWED,调用方吞掉降级为本视图内存隐藏。
   */
  dismissErrorMessage(sessionId: string, clientId: string): Promise<void>;
  /**
   * interrupted「忽略」:被控端写 ended 时间戳,双时间戳判定跨重启不再命中。
   * 老被控端无此 channel → 调用方吞掉降级(本视图内存 acked)。
   */
  ackInterruptedTurn(sessionId: string): Promise<void>;
  /**
   * 自动起名:被控端读该会话最新对话素材重新生成标题(与桌面重命名 Magic 按钮同一
   * handler)。只生成不落库,持久化仍走 patchSessionMeta;失败/无素材时 title 为 null。
   */
  regenerateSessionTitle(sessionId: string): Promise<{ title: string | null }>;
  listMessages(
    sessionId: string,
    opts?: MessageListOptions,
  ): Promise<RemoteMessage[]>;
  readHistoryView(
    sessionId: string,
    before?: string,
  ): Promise<HistoryViewPage<RemoteMessage>>;
  readWorkDetails(
    sessionId: string,
    ref: HistoryWorkSummary,
    after?: string,
  ): Promise<HistoryDetailPage<RemoteMessage>>;
  setHistoryExpanded(
    sessionId: string,
    refs: readonly HistoryWorkSummary[],
  ): Promise<void>;
  aroundMessages(
    sessionId: string,
    messageId: string,
    opts?: MessageAroundOptions,
  ): Promise<RemoteMessage[]>;
  aroundMessagesByClientId(
    sessionId: string,
    clientId: string,
    opts?: MessageAroundOptions,
  ): Promise<RemoteMessage[]>;
  send(
    sessionId: string,
    message: string | { type: "user"; content: unknown },
    createOpts?: CreateSessionOptions,
    sendOpts?: SendOptions,
  ): Promise<{ accepted: true } | { accepted: false; reason?: string }>;
  listActiveSessions(): Promise<MobileActiveSessionSnapshotResult>;
  /**
   * 切模型。可选第 3 参 providerId = 同时切来源(被控端按其路由 + 持久化 provider_id)。
   * 不传 providerId = 老 2 参语义,不动会话当前来源选择。
   */
  setModel(
    sessionId: string,
    model: string,
    providerId?: string,
    selection?: { effort: string | null; fastMode: boolean | 'ultrafast' },
  ): Promise<{ deferred?: boolean; superseded?: boolean } | undefined>;
  /**
   * 登记跨 Agent 切换意图;真正切换在下一条消息发送时由 desktop main 执行。
   * 可选 options.agentDeviceId(远程 Agent)同时换 Agent 所在电脑:null = 改回被控电脑本机
   * 运行;只在显式传入时作为第 7 个 wire 参数发送,缺省 = 位置不变(旧被控端忽略多余参数)。
   */
  switchSessionAgent(
    sessionId: string,
    targetAgentKind: MobileAgentKind,
    model: string,
    providerId: string | null,
    effort?: string,
    fastMode?: boolean | 'ultrafast',
    options?: { agentDeviceId?: string | null },
  ): Promise<MobileSessionAgentSwitchResult>;
  /** 读取 desktop main 的权威 pending intent,用于重连 / 重进页面恢复。 */
  getSessionAgentSwitchIntent(
    sessionId: string,
  ): Promise<MobileSessionAgentSwitchIntent | null>;
  setEffort(sessionId: string, effort: string): Promise<void>;
  setPermissionMode(sessionId: string, mode: string): Promise<void>;
  /** 计划模式一级开关(#494 新协议,capabilities.planMode.supported 时可用);
   *  被控端武装 live 会话并持久化 planModeEnabled,一次性消耗后经 sessions:patched 回流。 */
  setPlanMode(sessionId: string, enabled: boolean): Promise<void>;
  setFastMode(sessionId: string, enabled: boolean | 'ultrafast'): Promise<void>;
  setExtraDirs(sessionId: string, dirs: string[]): Promise<void>;
  /** 被控端视角的模型单价表(只读;老被控端 CHANNEL_NOT_ALLOWED → 调用方隐藏价格)。 */
  getModelPricing(): Promise<MobileModelPricingMap | null>;
  /**
   * 被控端账号级限额/用量快照(只读):codex → RateLimitSnapshot(窗口构成以上游
   * 接口返回为准,shape 见 maker-shared summarizeAccountRateLimits),claude-code →
   * 网关配额。老被控端 CHANNEL_NOT_ALLOWED → 调用方隐藏限额区块。
   */
  getAccountUsage(
    agentKind: MobileAgentKind,
    providerId?: string,
  ): Promise<unknown>;
  getSessionEstimatedValue(
    sessionId: string,
  ): Promise<{ totalValueMoney?: unknown; totalValueUsd?: number }>;
  /** Codex app-server authoritative windows plus banked reset credits and a bound reset offer. */
  getCodexRateLimits(providerId?: string): Promise<MobileCodexRateLimitsResult>;
  setCodexResetAutoUse(patch: Partial<CodexResetAutoUseSettings> | null, accountKey: string, providerId?: string): Promise<MobileCodexRateLimitsResult>;
  /**
   * 被控端订阅账号余量快照(只读,cached-first;Claude 5h/周/分模型窗口、SuperGrok 周用量)。
   * 默认账号不传 providerId;独立账号的回包必须回显同一 providerId,否则按旧被控端处理。
   * 老被控端 CHANNEL_NOT_ALLOWED → 调用方保留「暂未获取」提示。
   */
  getSubscriptionUsage(
    kind: SubscriptionUsageKind,
    providerId?: string,
  ): Promise<unknown>;
  /** cc 默认路由会话在被控端 proxy 观察到的生效计费路由('gateway' | 'subscription' | null)。 */
  getClaudeSessionRoute(sessionId: string): Promise<unknown>;
  /** Consume the desktop-issued offer; retries must pass the same idempotency key. */
  resetCodexRateLimits(
    idempotencyKey: string,
    providerId?: string,
  ): Promise<MobileCodexRateLimitResetResult>;
  /** 网关 API key presence-only 探测(只回 boolean;老被控端 → 调用方按 unknown 处理)。 */
  getApiKeyPresent(): Promise<{ present: boolean }>;
  /** 会话「非选中模型」effort/fast 写穿(老被控端 → 调用方吞掉降级)。 */
  setSessionModelPref(pref: MobileSessionModelPref): Promise<void>;
  /** 草稿「模型 effort/fast」写穿(active 恒 false;老被控端 → 调用方吞掉降级)。 */
  applyNewMakerDraftPref(pref: MobileNewMakerDraftPref): Promise<void>;
  /** 工作端 New Maker 草稿默认值镜像(只读;手机当前只消费 worktreeEnabled)。 */
  getNewMakerDefaults(
    agentKind: MobileAgentKind,
  ): Promise<MobileNewMakerDefaults>;
  /** 「新建会话默认启用 worktree」写穿工作端(老被控端 → 调用方吞掉降级)。 */
  applyNewMakerWorktreePref(worktreeEnabled: boolean): Promise<void>;
  /** 读取工作端某 canonical repo 的 New Maker worktree 源分支;未选择过返回 null。 */
  getNewMakerWorktreeBranchPref(
    baseRepo: string,
  ): Promise<MobileWorktreeBranchPreferenceSnapshot | null>;
  /**
   * 把源分支选择写穿工作端;回包是工作端接受后的权威 snapshot。
   * 与 worktree checkbox 使用独立 channel,选择分支不会改动开关偏好。
   */
  applyNewMakerWorktreeBranchPref(
    baseRepo: string,
    sourceBranch: string,
  ): Promise<MobileWorktreeBranchPreferenceSnapshot>;
  /**
   * worktree 两步建会话的工作端通道(git/fs 全在被控端执行):detect-cwd 做资格探测,
   * suggest-name 生成名字,create 以预生成 sessionId 建 worktree 拿路径(第二步再以该
   * 路径调 createSession)。老被控端 CHANNEL_NOT_ALLOWED → 调用方按「不可用」降级。
   */
  worktree: {
    detectCwd(cwd: string): Promise<MobileWorktreeDetectCwdResult>;
    listBranches(baseRepo: string): Promise<MobileWorktreeListBranchesResult>;
    suggestName(baseRepo: string): Promise<{ name: string }>;
    create(req: {
      sessionId: string;
      baseRepo: string;
      name: string;
      sourceBranch: string;
      recoveryKey: string;
    }): Promise<MobileWorktreeCreateResult>;
    /**
     * 两步创建的第二步确定失败、用户放弃返回编辑时,补偿回收尚未被 session 认领的
     * 精确 worktree。create 回包前恢复时可改用预先持久化的 recoveryKey;被控端会再次
     * 校验登记匹配、dirty 与 live ownership。
     */
    discardPrecreated(
      input:
        | { sessionId: string; path: string; recoveryKey?: never }
        | { sessionId: string; recoveryKey: string; path?: never },
    ): Promise<{ discarded: true; branchDeleted?: boolean }>;
    /** New hosts seal the creation id before discarding; never fall back to
     * discardPrecreated once a session-create request may have been sent. */
    cancelPrecreated?(
      input:
        | { sessionId: string; path: string; recoveryKey?: never }
        | { sessionId: string; recoveryKey: string; path?: never },
    ): Promise<{ discarded: true; branchDeleted?: boolean }>;
  };
  listAgentCommands(
    agentKind: MobileAgentKind,
    opts?: { sessionId?: string },
  ): Promise<MobileAgentCommandListResult>;
  /** 被控端 desktop 自有 slash 命令清单(palette 展示;移动端只放行可执行子集)。 */
  listDesktopCommands(): Promise<MobileDesktopCommandListResult>;
  /**
   * 触发被控端 learn-host 蒸馏(/learn):全流程(证据收集/staging/技能落盘)都在
   * 被控端执行,这里只拿 runId;评审 UI 暂只有桌面端,移动端以系统卡提示去桌面评审。
   */
  learnStart(req: MobileLearnStartRequest): Promise<{ runId: string }>;
  listAgentSkills(
    agentKind: MobileAgentKind,
    opts: { workingDir?: string; forceReload?: boolean; sessionId?: string },
  ): Promise<MobileAgentSkillListResult>;
  scanAtResources(
    agentKind: MobileAgentKind,
    opts: { workingDir: string; cap?: number; query?: string },
  ): Promise<MobileAtResourceScanResult>;
  fetchRemoteMedia(
    url: string,
    opts?: MobileRemoteMediaFetchOptions,
  ): Promise<MobileRemoteMediaFetchResult>;
  transcribeVoice(
    input: MobileVoiceTranscribeRequest,
  ): Promise<MobileVoiceTranscribeResult>;
  recordVoiceDictionaryLearning(
    input: MobileVoiceDictionaryLearningRequest,
  ): Promise<MobileVoiceDictionaryLearningResult>;
  /**
   * 拉取被控桌面的语音词典只读快照。老被控端不识别该 channel 会回
   * CHANNEL_NOT_ALLOWED,调用方据此静默回退到「无词典」,不打断语音输入。
   */
  getVoiceDictionary(): Promise<MobileVoiceDictionarySnapshotResult>;
  getPendingInteractions(sessionId: string): Promise<PendingInteraction[]>;
  resolveInteraction(
    requestId: string,
    decision: Record<string, unknown>,
  ): Promise<{ accepted: boolean } | void>;
  getContextUsage(
    sessionId: string,
    createOpts?: Record<string, unknown>,
  ): Promise<unknown>;
  fork(
    sourceSessionId: string,
    messageClientId: string,
  ): Promise<RemoteSession>;
  forkStripEncrypted(sourceSessionId: string): Promise<RemoteSession>;
  rewindPreview(
    sessionId: string,
    clientId: string,
  ): Promise<RewindPreviewPayload>;
  rewindCommit(
    sessionId: string,
    clientId: string,
    opts?: { allowFileRestore?: boolean },
  ): Promise<RemoteSession>;
  deleteMessage(
    sessionId: string,
    clientId: string,
  ): Promise<{ sessionId: string; clientId: string; clientIds?: string[] }>;
  closeSession(sessionId: string): Promise<void>;
  /**
   * Orca 协同编排:Lead / Worker / team 真身在被控端,这里只是隧道封装(与桌面控制端
   * makerTransport 的 remoteMakerApi / remoteOrcaWorkflows 同一组 channel 与参数形状)。
   * 写操作(enable / create / archive / disable)一律不自动重试:超时不代表被控端没执行。
   */
  orca: {
    listExecutionDevices(): Promise<unknown>;
    /** 被控端协同插件开关(项目级 / 对话用户级);结果形状见 readOrcaCollabPolicy。 */
    getCollabPolicy(workingDir: string | undefined, workspaceKind: 'project' | 'dialogue'): Promise<unknown>;
    enable(leadSessionId: string, options: MobileOrcaEnableOptions): Promise<MobileOrcaEnableResult>;
    disable(leadSessionId: string): Promise<unknown>;
    createWorker(input: MobileOrcaCreateWorkerInput): Promise<MobileOrcaCreateWorkerResult>;
    listWorkers(leadSessionId: string): Promise<unknown>;
    getTeamByWorkerSession(workerSessionId: string): Promise<unknown>;
    switchFocus(leadSessionId: string, workerIdOrLabel: string): Promise<unknown>;
    acknowledgeDone(leadSessionId: string, workerId: string): Promise<unknown>;
    archiveWorker(leadSessionId: string, workerId: string): Promise<unknown>;
    getCollaborationSettings(): Promise<unknown>;
  };
  /**
   * 会话未读已读回执:手机端真实展示会话内容后,清掉被控端该会话的未读态
   * (灵动岛 / Dock 角标 / 桌面侧栏红绿点)。被控端清完会经 sessions relay 推回
   * attention=false,手机端列表绿/红点随之收敛。intent 语义与桌面一致:
   * 'explicit' = 内容真实展示(可清 error 未读);'passive' = 导航类被动信号。
   * 老被控端无此 channel → CHANNEL_NOT_ALLOWED,调用方吞掉降级。
   */
  clearSessionAttention(
    sessionId: string,
    intent: "explicit" | "passive",
  ): Promise<void>;
  /** 目标模式:goal 状态机在被控端 GoalController 执行,这里只是隧道封装(路 A)。 */
  goal: {
    set(input: {
      sessionId: string;
      objective: string;
      limits?: MobileGoalLimitsInput;
    }): Promise<void>;
    clear(sessionId: string): Promise<void>;
    getStatus(sessionId: string): Promise<MobileGoalStatusPayload | null>;
    pause(sessionId: string): Promise<void>;
    resume(sessionId: string): Promise<void>;
    update(
      sessionId: string,
      patch: Partial<{ objective: string } & MobileGoalLimitsInput>,
    ): Promise<void>;
  };
  schedule: {
    listSidebarIndexRuns?(): Promise<{ runs?: unknown[] }>;
    list(filter?: ScheduleListFilter): Promise<RemoteSchedule[]>;
    get(id: string): Promise<RemoteSchedule>;
    listTemplates(): Promise<RemoteScheduleTemplate[]>;
    createFromTemplate(
      input: RemoteScheduleCreateFromTemplateInput,
    ): Promise<RemoteSchedule>;
    create(input: RemoteScheduleWriteInput): Promise<RemoteSchedule>;
    update(
      id: string,
      patch: Partial<RemoteScheduleWriteInput>,
    ): Promise<RemoteSchedule>;
    listRuns(id: string, limit?: number): Promise<RemoteScheduleRun[]>;
    runNow(id: string): Promise<void>;
    pause(id: string): Promise<RemoteSchedule>;
    resume(id: string): Promise<RemoteSchedule>;
    delete(id: string): Promise<void>;
    getInflightCount(id: string): Promise<number>;
    markRunRead(runId: string): Promise<void>;
    markScheduleRunsRead(scheduleId: string): Promise<void>;
    deleteRun(runId: string): Promise<void>;
  };
  projectAutomation: {
    removeSchedule(input: { workingDir: string; id: string }): Promise<unknown>;
  };
  /** 手动压缩会话上下文(pi 原生 compact,capability-aware 的 maker:compact-session;
   *  input.compact 是 Claude Code 专用的 maker:input:compact,两者不混)。 */
  compactSession(
    sessionId: string,
    instructions?: string,
  ): Promise<{
    tokensBefore?: number;
    estimatedTokensAfter?: number;
    noop?: boolean;
  } | null>;
  input: {
    getProjection(sessionId: string): Promise<InputProjection>;
    enqueue(
      sessionId: string,
      item: QueuedRemoteMessage,
      opts?: { sendAtMs?: number; expectedClearBoundaryMs?: number | null },
    ): Promise<InputProjection>;
    compact(sessionId: string): Promise<InputProjection>;
    steer(
      sessionId: string,
      item: QueuedRemoteMessage,
      opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },
    ): Promise<boolean>;
    stop(
      sessionId: string,
      opts?: { keepQueue?: boolean; pauseQueue?: boolean },
    ): Promise<InputProjection>;
    resume(sessionId: string): Promise<InputProjection>;
    retryImageDelivery(sessionId: string, imageId: string): Promise<void>;
    retryLastError(sessionId: string): Promise<InputProjection>;
    clearError(sessionId: string): Promise<InputProjection>;
    /** 取消账号限额重置后的自动继续;老被控端没有该通道时会被拒(调用方只在投影带等待时显示入口)。 */
    cancelUsageLimitWait(sessionId: string): Promise<InputProjection>;
    remove(sessionId: string, clientId: string): Promise<InputProjection>;
    updateText(
      sessionId: string,
      clientId: string,
      newText: string,
      sessionRefs?: MobileSessionReference[],
      trustedContexts?: MobileSessionReferenceContext[],
      workingDir?: string,
    ): Promise<InputProjection>;
    /** 整条内容替换(文本+附件),排队消息复用 composer 编辑的保存入口;老桌面端无此通道会抛 CHANNEL_NOT_ALLOWED。 */
    updateContent(
      sessionId: string,
      clientId: string,
      item: QueuedRemoteMessage,
    ): Promise<InputProjection>;
    move(
      sessionId: string,
      clientId: string,
      targetIndex: number,
    ): Promise<InputProjection>;
    setExpanded(sessionId: string, expanded: boolean): Promise<InputProjection>;
    setInteractionLock(
      sessionId: string,
      lockId: string,
      locked: boolean,
    ): Promise<InputProjection>;
    setEditLock(
      sessionId: string,
      clientId: string,
      locked: boolean,
    ): Promise<InputProjection>;
    clearSession(sessionId: string): Promise<InputProjection>;
  };
  fs: {
    listDir(path: string): Promise<RemoteDirectoryListResult>;
    statPath(path: string): Promise<RemotePathStatResult>;
    mkdirP(path: string): Promise<{ resolvedPath: string }>;
    readTextFilePreview(path: string, options?: { allowFileTransfer?: boolean; signal?: AbortSignal }): Promise<RemoteTextFilePreviewResult>;
  };
  /** 完整文件浏览(workdir 相对路径语义,被控端 file-browser:remote-op 聚合通道)。 */
  fileBrowser: {
    cacheScope: string;
    readBytes(
      workdir: string,
      relPath: string,
      signal?: AbortSignal,
      beforeInvoke?: () => Promise<unknown>,
      options?: {
        stream?: boolean;
        retainBackground?: MobileRemoteMediaFetchOptions['retainBackground'];
        /** Upload progress while the computer stages the file in cloud storage. */
        onProgress?: (uploaded: number, total: number) => void;
      },
    ): Promise<MobileRemoteMediaFetchResult>;
    caps(workdir: string): Promise<FileBrowserCapsResult>;
    /** 返回裸 entries(unknown),消费方用 normalizeRemoteOpDirEntries 归一化。 */
    listDir(
      workdir: string,
      relPath: string,
      opts?: { includeIgnored?: boolean; maxEntries?: number },
    ): Promise<unknown>;
    readFile(
      workdir: string,
      relPath: string,
      opts?: { acceptGzip?: boolean },
    ): Promise<FileBrowserReadFileResult>;
    listAllFiles(
      workdir: string,
      cap?: number,
    ): Promise<FileBrowserListAllFilesResult>;
    /** ripgrep 内容搜索(被控端 searchCollect,一次性收集,上限被控端封顶 500)。 */
    searchCollect(
      workdir: string,
      query: string,
      opts?: { caseSensitive?: boolean; maxMatches?: number },
    ): Promise<FileBrowserSearchCollectResult>;
    thumbnail(
      workdir: string,
      relPath: string,
    ): Promise<FileBrowserThumbnailResult>;
    exportFileStart(
      workdir: string,
      relPath: string,
    ): Promise<FileBrowserExportStartResult>;
    exportFileStatus(
      workdir: string,
      transferId: string,
    ): Promise<FileBrowserExportStatusResult>;
  };
}

/** `maker:session:enable-orca` 的 options(与桌面 preload maker.enableOrca 同形状)。 */
export interface MobileOrcaEnableOptions {
  workerAgent: OrcaWorkerAgentKind;
  role?: string;
  label?: string;
  model?: string;
  effort?: string;
  fast?: boolean | 'ultrafast';
  providerId?: string;
  delegateTask?: string;
  executionDeviceId?: string;
  workingDir?: string;
  workerPermissionMode: OrcaWorkerPermissionMode;
  /** 首个 Worker 的 Agent 所在电脑(远程供应商);null = 被控电脑。只发给声明 supportsOrcaWorkerAgentDevice 的被控端。 */
  agentDeviceId?: string | null;
}

export interface MobileOrcaEnableResult {
  teamId?: string;
  workerSessionId?: string;
  workerId?: string;
  dispatched?: boolean;
}

/** `maker:worker:create` 的 body(与桌面 useOrcaWorkerSelection 提交同形状)。 */
export interface MobileOrcaCreateWorkerInput {
  leadSessionId: string;
  role: string;
  label: string;
  agent: OrcaWorkerAgentKind;
  model?: string;
  effort?: string;
  fast?: boolean | 'ultrafast';
  providerId?: string;
  workerPermissionMode: OrcaWorkerPermissionMode;
  initialTask?: string;
  executionDeviceId?: string;
  workingDir?: string;
  /** Worker 的 Agent 所在电脑(远程供应商);null = 被控电脑。只发给声明 supportsOrcaWorkerAgentDevice 的被控端。 */
  agentDeviceId?: string | null;
}

export interface MobileOrcaCreateWorkerResult {
  ok?: boolean;
  workerId?: string;
  workerSessionId?: string;
  softLimitExceeded?: boolean;
}

export type SessionMetaPatch = Partial<
  Pick<RemoteSession, "status" | "title" | "pinnedAt">
>;

export const MOBILE_MAKER_CHANNELS = MOBILE_REMOTE_INVOKE_CHANNELS;
const fileReferences = new Map<string, string>();
let fileReferencesOwner = '';

export function createMobileMakerTransport({
  deviceId,
  invoke,
  isCurrent,
}: MobileMakerTransportDeps): MobileMakerTransport {
  const fileOwner = getMobileAuthOwner();
  const callerIsCurrent = isCurrent;
  const fileIsCurrent = () =>
    isMobileAuthOwnerCurrent(fileOwner) && callerIsCurrent?.() !== false;
  isCurrent = fileIsCurrent;
  const fileCacheOwner = JSON.stringify([getActiveMobileSessionRealm(), fileOwner.accountId]);
  const referenceOwner = JSON.stringify([fileOwner.accountKey, fileOwner.generation]);
  if (fileReferencesOwner !== referenceOwner) { fileReferences.clear(); fileReferencesOwner = referenceOwner; }
  const getFileCache = async () => {
    if (!fileOwner.accountId || !fileIsCurrent()) return null;
    const { createPeerFileCache } = await import('./peerFileCache');
    return createPeerFileCache(fileCacheOwner);
  };
  const call = <T>(channel: string, args: unknown[] = []): Promise<T> => {
    if (!deviceId)
      return Promise.reject(new Error("remote device id is required"));
    return invoke<T>(deviceId, channel, args);
  };
  const listComposerPlugins = async (workingDir?: string): Promise<ComposerPlugin[]> => {
    if (!isCurrent()) throw new Error('Plugin catalog read superseded');
    const result = await call('ghosts:composer-list', workingDir ? [workingDir] : []);
    if (!isCurrent()) throw new Error('Plugin catalog read superseded');
    return composerPluginListSchema.parse(result);
  };
  const expandPluginText = async (text: string, workingDir?: string): Promise<string> => {
    if (isSharedTaskPeer(deviceId) || !parseGhostCommandWord(text) || splitGhostDirective(text)) return text;
    try {
      return expandGhostCommand(text, await listComposerPlugins(workingDir));
    } catch (error) {
      if (isComposerPluginCatalogUnsupportedError(error)) return text;
      throw error;
    }
  };
  const expandPluginItem = async (item: QueuedRemoteMessage): Promise<QueuedRemoteMessage> => {
    const text = await expandPluginText(item.text, item.workingDir);
    // Expand only agent-bound text; retain the original queue/history echo.
    return text === item.text ? item : { ...item, text };
  };
  const fileOp = async <T>(args: Record<string, unknown>): Promise<T> => {
    if (isCurrent?.() === false) throw new Error("FILE_PEER_CANCELLED");
    const result = await call<T>("file-browser:remote-op", [args]);
    if (isCurrent?.() === false) throw new Error("FILE_PEER_CANCELLED");
    return result;
  };
  const files = createDeviceFileOperations(fileOp);
  const fetchMedia = (
    url: string,
    opts?: MobileRemoteMediaFetchOptions,
    fallback?: () => Promise<MobileRemoteMediaFetchResult>,
    stream = opts?.stream ?? true,
  ) => {
    const fetch = async (prepareOnly: boolean, metadataOnly = false) => {
      if (!fileIsCurrent() || opts?.signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
      await opts?.beforeFetch?.();
      if (!fileIsCurrent() || opts?.signal?.aborted) throw new Error('FILE_PEER_CANCELLED');
      return call<MobileRemoteMediaFetchResult>(DEVICE_LINK_MEDIA_FETCH_CHANNEL, [
        {
          url,
          prepareOnly,
          // Older shared hosts use a closed request-field allowlist.
          ...(metadataOnly && !isSharedTaskPeer(deviceId) ? { metadataOnly: true } : {}),
          ...(opts?.skipCache ? { skipCache: true } : {}),
          ...(opts?.thumbnail ? { thumbnail: true } : {}),
        },
      ]);
    };
    const withDownload = (result: MobileRemoteMediaFetchResult): MobileRemoteMediaFetchResult => {
      if (stream || opts?.thumbnail || !result.ossKey || !validFileVersion(result.version)) return result;
      return { ...result, cacheDownload: async (downloadUrl) => {
        const active = () => fileIsCurrent() && !opts?.signal?.aborted;
        if (!active()) throw new Error('FILE_PEER_CANCELLED');
        const cache = await getFileCache().catch(() => null);
        const local = await cache?.download(deviceId, url, result, downloadUrl, active, opts?.signal).catch(() => null);
        if (!active()) {
          const uri = local && peerMediaUri(local);
          if (uri) releasePeerMedia(uri);
          throw new Error('FILE_PEER_CANCELLED');
        }
        return local ?? null;
      } };
    };
    // Chat thumbnails are high-volume and already covered by the list; trace full-file reads only.
    const trace = opts?.thumbnail ? 0 : nextFileTrace();
    const stage = <T>(
      name: string,
      run: () => Promise<T>,
      describe: (value: T) => Record<string, unknown>,
    ): Promise<T> => {
      if (!trace) return run();
      const startedAt = Date.now();
      return run().then(
        (value) => {
          mobileDebugLog("debug", "files", `remote read ${name}`, {
            trace,
            ms: Date.now() - startedAt,
            ...describe(value),
          });
          return value;
        },
        (error: unknown) => {
          mobileDebugLog("warn", "files", `remote read ${name} failed`, {
            trace,
            ms: Date.now() - startedAt,
            error: errorText(error),
          });
          throw error;
        },
      );
    };
    const describeResult = (result: DeviceFileResult) => ({
      size: result.size,
      mime: result.mimeType,
      transferRequired: result.transferRequired === true,
      inline: typeof result.inlineBase64 === "string",
    });
    if (trace)
      mobileDebugLog("debug", "files", "remote read start", {
        trace,
        ext: mediaExtOf(url),
        stream,
      });
    return stage(
      "result",
      () =>
        readDeviceFile({
          cacheFirst: stream || opts?.revalidate || opts?.skipCache || opts?.thumbnail || isSharedTaskPeer(deviceId) ? undefined : {
            read: async () => (await getFileCache())?.readLatest(deviceId, url, () => fileIsCurrent() && !opts?.signal?.aborted) ?? null,
            retain: async (result) => { await opts?.retainBackground?.(withDownload(result), fileIsCurrent); },
          },
          stream,
          inline: () => fetch(true),
          revalidate: () => fetch(true, true),
          inlineCache: opts?.thumbnail ? undefined : {
            read: async (metadata) => {
              const cache = await getFileCache();
              if (opts?.skipCache) {
                await cache?.invalidate(deviceId, url);
                return null;
              }
              return cache?.readInline(deviceId, url, metadata, () => isCurrent() && !opts?.signal?.aborted) ?? null;
            },
            store: async (result) => {
              const cache = await getFileCache();
              if (isCurrent() && !opts?.signal?.aborted) await cache?.storeInline(deviceId, url, result);
            },
          },
          peerResultIsTransient: true,
          isCurrent,
          discard: (result) => {
            const uri = peerMediaUri(result);
            if (uri) releasePeerMedia(uri);
            else if (
              isMobileAuthOwnerCurrent(fileOwner) &&
              typeof result.ossKey === "string" &&
              result.ossKey.length > 0
            )
              opts?.onDiscardOssKey?.(result.ossKey);
          },
          signal: opts?.signal,
          prepare: () =>
            stage("prepare", () => fetch(!opts?.thumbnail, !opts?.thumbnail), describeResult),
          peer: (metadata) =>
            metadata.size <= FILE_PEER_MAX_BYTES
              ? stage(
                  "direct",
                  () => tryMobilePeerFile(deviceId, url, opts?.signal, trace || undefined,
                    opts?.skipCache ? { ...metadata, skipCache: true } : metadata, opts?.onProgress),
                  (result) => ({ hit: result !== null }),
                )
              : Promise.resolve(null),
          fallback: () => {
            try { opts?.onProgress?.(0, 0); } catch { /* Observer only; upload bytes are unavailable. */ }
            return stage("upload", fallback ?? (() => fetch(false)), describeResult);
          },
        }),
      (result) => ({
        route: peerMediaUri(result)
          ? "direct"
          : typeof result.inlineBase64 === "string"
            ? "inline"
            : "upload",
        size: result.size,
      }),
    ).then(withDownload);
  };

  return {
    listComposerPlugins,
    createSession: (opts) => call("maker:create-session", [opts]),
    getCapabilities: (agentKind) => fetchAgentCapabilities(deviceId, agentKind, () => {
      if (!isCurrent()) throw new Error("Capabilities read superseded");
      return call("maker:get-capabilities", [agentKind]);
    }),
    listAvailableAgents: () => call('maker:list-available-agents', []),
    // Pi 原生分支树通过 device-link 复用桌面端 runtime;移动会话页只在当前会话
    // 确认为 Pi 时展示入口,并在渲染前校验返回的树形状。
    getSessionTree: (sessionId) => call("maker:get-session-tree", [sessionId]),
    navigateSessionTree: (sessionId, entryId, options) =>
      call("maker:navigate-session-tree", [sessionId, entryId, options]),
    listProviders: () =>
      call("maker:provider:list", [
        {
          capabilities: [CONTROLLER_CAPABILITY_PROVIDER_LOGO_KINDS_V2],
        },
      ]),
    getSession: (sessionId) => call("local-db:sessions:get", [sessionId]),
    prewarmSession: (sessionId, createOpts) =>
      call("maker:session:prewarm", [sessionId, createOpts]),
    createSideChat: (sessionId) => call("maker:side-chat:v1", [sessionId]),
    listSideChats: (sessionId) => call("maker:side-chat:list:v1", [sessionId]),
    searchConversations: (request) =>
      call("local-db:conversations:search", [request]),
    patchSessionMeta: (sessionId, patch) =>
      call("local-db:sessions:patch-meta", [sessionId, patch]),
    dismissErrorMessage: (sessionId, clientId) =>
      call("local-db:messages:dismiss-error", [sessionId, clientId]),
    ackInterruptedTurn: (sessionId) =>
      call("local-db:sessions:ack-interrupted", [sessionId]),
    regenerateSessionTitle: (sessionId) =>
      call("maker:regenerate-title", [{ sessionId }]),
    listMessages: (sessionId, opts) =>
      call("local-db:messages:list", [sessionId, opts]),
    readHistoryView: (sessionId, before) =>
      // workLines: the Host projects running single-line activities and may send work patches.
      call("local-db:messages:view", [sessionId, { before, lazyDetails: true, workLines: true }]),
    readWorkDetails: (sessionId, ref, after) =>
      call("local-db:messages:work-details", [sessionId, ref, { after }]),
    setHistoryExpanded: (sessionId, refs) =>
      call("local-db:messages:view-intent", [sessionId, refs]),
    aroundMessages: (sessionId, messageId, opts) =>
      call("local-db:messages:around", [sessionId, messageId, opts]),
    aroundMessagesByClientId: (sessionId, clientId, opts) =>
      call("local-db:messages:around-client-id", [sessionId, clientId, opts]),
    send: async (sessionId, message, createOpts, sendOpts) => {
      const delivery = pendingGhostCardFormDelivery(JSON.stringify([deviceId, sessionId]));
      if (delivery && !await delivery) throw new Error((await import('@/i18n')).i18n.t('plugins.formSyncFailed'));
      const content = typeof message === 'string' ? message : message.content;
      const first = Array.isArray(content) ? content[0] : undefined;
      const head = typeof content === 'string' ? content
        : first?.type === 'text' && typeof first.text === 'string' ? first.text : null;
      if (head && parseGhostCommandWord(head) && !splitGhostDirective(head) && !isSharedTaskPeer(deviceId)) {
        const workingDir = createOpts?.workingDir ?? (await call<RemoteSession>('local-db:sessions:get', [sessionId]))?.workingDir;
        const text = await expandPluginText(head, workingDir ?? undefined);
        message = typeof message === 'string' ? text : {
          ...message,
          content: Array.isArray(content) ? [{ ...first, text }, ...content.slice(1)] : text,
        };
      }
      if (!isCurrent()) throw new Error('Message send superseded');
      return call("maker:send", [sessionId, message, createOpts, sendOpts]);
    },
    listActiveSessions: () => call("maker:list-active", [{ summary: true, snapshotVersion: 2 }]),
    setModel: async (sessionId, model, providerId, selection) => {
      const wireArgs = selection
        ? [sessionId, model, providerId ?? null, null, selection]
        : providerId
          ? [sessionId, model, providerId]
          : [sessionId, model];
      const result = await call<
        { deferred?: boolean; superseded?: boolean } | undefined
      >("maker:set-model", wireArgs);
      if (
        result !== null &&
        typeof result === "object" &&
        ("contextWindowConfirmationRequired" in result ||
          "contextTokensForConfirmation" in result)
      ) {
        throw Object.assign(
          new Error(
            "remote model-window confirmation is unsupported; runtime selection was not changed",
          ),
          { code: "PRECONDITION_FAILED" },
        );
      }
      return result;
    },
    switchSessionAgent: (
      sessionId,
      targetAgentKind,
      model,
      providerId,
      effort,
      fastMode,
      options,
    ) =>
      call(
        "maker:switch-session-agent",
        options?.agentDeviceId !== undefined
          ? [
              sessionId,
              targetAgentKind,
              model,
              providerId,
              effort ?? null,
              fastMode ?? null,
              { agentDeviceId: options.agentDeviceId },
            ]
          : [sessionId, targetAgentKind, model, providerId, effort, fastMode],
      ),
    getSessionAgentSwitchIntent: (sessionId) =>
      call("maker:get-session-agent-switch-intent", [sessionId]),
    setEffort: (sessionId, effort) =>
      call("maker:set-effort", [sessionId, effort]),
    setPermissionMode: (sessionId, mode) =>
      call("maker:set-permission-mode", [sessionId, mode]),
    setPlanMode: (sessionId, enabled) =>
      call("maker:set-plan-mode", [sessionId, enabled]),
    setFastMode: (sessionId, enabled) =>
      call("maker:set-fast-mode", [sessionId, enabled]),
    setExtraDirs: (sessionId, dirs) =>
      call("maker:set-extra-dirs", [sessionId, dirs]),
    getModelPricing: () => call("maker:usage:model-pricing"),
    getAccountUsage: async (agentKind, providerId) => {
      const result = await call<unknown>(
        "maker:usage:account",
        providerId ? [agentKind, providerId] : [agentKind],
      );
      if (
        providerId &&
        providerId !== "openai" &&
        result &&
        (result as { providerId?: string }).providerId !== providerId
      )
        throw new Error("PRECONDITION_FAILED: Account scope unsupported");
      return result;
    },
    getSessionEstimatedValue: (sessionId) =>
      call("local-db:messages:estimatedSessionValue", [sessionId]),
    getCodexRateLimits: async (providerId) => {
      const result = await call<MobileCodexRateLimitsResult>(
        "maker:usage:codex-rate-limits",
        providerId ? [providerId] : undefined,
      );
      if (
        providerId &&
        providerId !== "openai" &&
        result.providerId !== providerId
      )
        throw new Error("PRECONDITION_FAILED: Account scope unsupported");
      return result;
    },
    setCodexResetAutoUse: async (patch, accountKey, providerId) => {
      const result = await call<MobileCodexRateLimitsResult>('maker:usage:codex-reset-auto-use', [patch, accountKey, providerId ?? 'openai']);
      if (result.providerId !== (providerId ?? 'openai') || result.autoUse?.accountKey !== accountKey)
        throw new Error('PRECONDITION_FAILED: Account scope changed');
      return result;
    },
    getSubscriptionUsage: async (kind, providerId) => {
      // 默认账号不带参数,兼容只认默认账号的老被控端。
      const scoped =
        providerId && providerId !== NATIVE_SUBSCRIPTION_DEFAULT_PROVIDER_IDS[kind];
      const result = await call<unknown>(
        SUBSCRIPTION_USAGE_CHANNELS[kind],
        scoped ? [providerId] : undefined,
      );
      if (
        scoped &&
        result &&
        (result as { providerId?: string }).providerId !== providerId
      )
        throw new Error("PRECONDITION_FAILED: Account scope unsupported");
      return result;
    },
    getClaudeSessionRoute: (sessionId) =>
      call("maker:claude-session-route:get", [sessionId]),
    resetCodexRateLimits: async (idempotencyKey, providerId) => {
      const result = await call<MobileCodexRateLimitResetResult>(
        "maker:usage:codex-rate-limit-reset",
        providerId ? [idempotencyKey, providerId] : [idempotencyKey],
      );
      if (
        providerId &&
        providerId !== "openai" &&
        result.providerId !== providerId
      )
        throw new Error("PRECONDITION_FAILED: Account scope unsupported");
      return result;
    },
    getApiKeyPresent: () => call("maker:api-key:present"),
    setSessionModelPref: (pref) => call("maker:set-session-model-pref", [pref]),
    applyNewMakerDraftPref: (pref) =>
      call("maker:apply-new-maker-draft-pref", [pref]),
    getNewMakerDefaults: (agentKind) =>
      call("maker:get-new-maker-defaults", [agentKind]),
    predictNextPrompt: (request) => call('maker:predict-prompt', [request]),
    applyNewMakerWorktreePref: (worktreeEnabled) =>
      call("maker:apply-new-maker-worktree-pref", [{ worktreeEnabled }]),
    getNewMakerWorktreeBranchPref: (baseRepo) =>
      call("maker:get-new-maker-worktree-branch-pref", [{ baseRepo }]),
    applyNewMakerWorktreeBranchPref: (baseRepo, sourceBranch) =>
      call("maker:apply-new-maker-worktree-branch-pref", [
        { baseRepo, sourceBranch },
      ]),
    worktree: {
      detectCwd: (cwd) => call("worktree:detect-cwd", [{ cwd }]),
      listBranches: (baseRepo) =>
        call("worktree:list-branches", [{ baseRepo }]),
      suggestName: (baseRepo) => call("worktree:suggest-name", [{ baseRepo }]),
      create: (req) => call("worktree:create", [req]),
      discardPrecreated: (input) =>
        call("worktree:discard-precreated", [input]),
      cancelPrecreated: (input) =>
        call("worktree:cancel-precreated", [input]),
    },
    listAgentCommands: (agentKind, opts) =>
      call("maker:list-agent-commands", opts ? [agentKind, opts] : [agentKind]),
    listDesktopCommands: () => call("maker:list-desktop-commands", []),
    learnStart: (req) => call("learn:start", [req]),
    listAgentSkills: (agentKind, opts) =>
      call("maker:list-agent-skills", [agentKind, opts]),
    scanAtResources: (agentKind, opts) =>
      call("maker:scan-at-resources", [agentKind, opts]),
    // skipCache:上次拿到的 ossKey 已悬空(对象被删)时,强制被控端绕过上传去重缓存重传。
    // thumbnail:聊天列表只要缩略图,被控端缩到 1024px webp inline 回包(老被控端
    // 不识别该字段,回落原图 ossKey,消费方两种回包都兼容)。
    fetchRemoteMedia: fetchMedia,
    transcribeVoice: (input) =>
      call(DEVICE_LINK_VOICE_TRANSCRIBE_CHANNEL, [input]),
    recordVoiceDictionaryLearning: (input) =>
      call(DEVICE_LINK_VOICE_DICTIONARY_LEARNING_CHANNEL, [input]),
    getVoiceDictionary: () =>
      call(DEVICE_LINK_VOICE_DICTIONARY_GET_CHANNEL, []),
    getPendingInteractions: (sessionId) =>
      call("maker:get-pending-interactions", [sessionId]),
    resolveInteraction: (requestId, decision) =>
      call("maker:resolve-interaction", [requestId, decision]),
    getContextUsage: (sessionId, createOpts) =>
      call("maker:get-context-usage", [sessionId, createOpts]),
    fork: (sourceSessionId, messageClientId) =>
      call("maker:fork", [sourceSessionId, messageClientId]),
    forkStripEncrypted: (sourceSessionId) =>
      call("maker:fork-strip-encrypted", [sourceSessionId]),
    rewindPreview: (sessionId, clientId) =>
      call("maker:rewind:preview", [sessionId, clientId]),
    rewindCommit: (sessionId, clientId, opts) =>
      call(
        "maker:rewind:commit",
        opts ? [sessionId, clientId, opts] : [sessionId, clientId],
      ),
    deleteMessage: (sessionId, clientId) =>
      call("maker:message:delete", [sessionId, clientId]),
    closeSession: (sessionId) => call("maker:close-session", [sessionId]),
    orca: {
      listExecutionDevices: () => call(ORCA_EXECUTION_DEVICES_CHANNEL),
      getCollabPolicy: (workingDir, workspaceKind) =>
        call("maker:plugins:get-state", ["collab", workingDir, workspaceKind]),
      enable: (leadSessionId, options) =>
        call("maker:session:enable-orca", [leadSessionId, options]),
      disable: (leadSessionId) => call("maker:session:disable-orca", [leadSessionId]),
      createWorker: (input) => call("maker:worker:create", [input]),
      listWorkers: (leadSessionId) =>
        call("local-db:orca-workflows:list-workers-by-lead", [leadSessionId]),
      getTeamByWorkerSession: (workerSessionId) =>
        call("local-db:orca-workflows:get-by-worker-session", [workerSessionId]),
      switchFocus: (leadSessionId, workerIdOrLabel) =>
        call("maker:worker:switch-focus", [{ leadSessionId, workerIdOrLabel }]),
      acknowledgeDone: (leadSessionId, workerId) =>
        call("maker:worker:acknowledge-done", [{ leadSessionId, workerId }]),
      archiveWorker: (leadSessionId, workerId) =>
        call("maker:worker:archive", [{ leadSessionId, workerId }]),
      getCollaborationSettings: () => call("maker:collaboration-settings:get"),
    },
    clearSessionAttention: (sessionId, intent) =>
      call("notification:clear-session-attention", [sessionId, intent]),
    goal: {
      set: (input) => call("maker:goal:set", [input]),
      clear: (sessionId) => call("maker:goal:clear", [sessionId]),
      getStatus: (sessionId) => call("maker:goal:get-status", [sessionId]),
      pause: (sessionId) => call("maker:goal:pause", [sessionId]),
      resume: (sessionId) => call("maker:goal:resume", [sessionId]),
      update: (sessionId, patch) =>
        call("maker:goal:update", [{ sessionId, patch }]),
    },
    schedule: {
      listSidebarIndexRuns: () =>
        call("maker:schedule:list-sidebar-index-runs"),
      list: (filter) => call("maker:schedule:list", filter ? [filter] : []),
      get: (id) => call("maker:schedule:get", [id]),
      listTemplates: () => call("maker:schedule:list-templates"),
      createFromTemplate: (input) =>
        call("maker:schedule:create-from-template", [input]),
      create: (input) => call("maker:schedule:create", [input]),
      update: (id, patch) => call("maker:schedule:update", [id, patch]),
      listRuns: (id, limit) => call("maker:schedule:list-runs", [id, limit]),
      runNow: (id) => call("maker:schedule:run-now", [id]),
      pause: (id) => call("maker:schedule:pause", [id]),
      resume: (id) => call("maker:schedule:resume", [id]),
      delete: (id) => call("maker:schedule:delete", [id]),
      getInflightCount: (id) => call("maker:schedule:get-inflight-count", [id]),
      markRunRead: (runId) => call("maker:schedule:mark-run-read", [runId]),
      markScheduleRunsRead: (scheduleId) =>
        call("maker:schedule:mark-schedule-runs-read", [scheduleId]),
      deleteRun: (runId) => call("maker:schedule:delete-run", [runId]),
    },
    projectAutomation: {
      removeSchedule: (input) =>
        call("maker:project-automation:remove-schedule", [input]),
    },
    compactSession: (sessionId, instructions) =>
      call(
        "maker:compact-session",
        instructions === undefined ? [sessionId] : [sessionId, instructions],
      ),
    input: {
      getProjection: (sessionId) =>
        call("maker:input:get-projection", [sessionId]),
      enqueue: async (sessionId, item, opts) => {
        const expanded = await expandPluginItem(item);
        if (!isCurrent()) throw new Error('Message enqueue superseded');
        return call("maker:input:enqueue", [sessionId, expanded, opts]);
      },
      compact: (sessionId) => call("maker:input:compact", [sessionId]),
      steer: async (sessionId, item, opts) => {
        const expanded = await expandPluginItem(item);
        if (!isCurrent()) throw new Error('Message steer superseded');
        return call("maker:input:steer", [sessionId, expanded, opts]);
      },
      stop: (sessionId, opts) => call("maker:input:stop", [sessionId, opts]),
      resume: (sessionId) => call("maker:input:resume", [sessionId]),
      retryImageDelivery: (sessionId, imageId) => call("maker:images:retry", [sessionId, imageId]),
      retryLastError: (sessionId) =>
        call("maker:input:retry-last-error", [sessionId]),
      clearError: (sessionId) => call("maker:input:clear-error", [sessionId]),
      cancelUsageLimitWait: (sessionId) =>
        call("maker:input:cancel-usage-limit-wait", [sessionId]),
      remove: (sessionId, clientId) =>
        call("maker:input:remove", [sessionId, clientId]),
      updateText: async (
        sessionId,
        clientId,
        newText,
        sessionRefs,
        trustedContexts,
        workingDir,
      ) => {
        const text = await expandPluginText(newText, workingDir);
        if (!isCurrent()) throw new Error('Message update superseded');
        // Legacy text edits also replace the persisted draft and history.
        if (text !== newText) {
          throw Object.assign(new Error('[CHANNEL_NOT_ALLOWED] Plugin edits require update-content'), { code: 'CHANNEL_NOT_ALLOWED' });
        }
        return call(
          "maker:input:update-text",
          sessionRefs
            ? [sessionId, clientId, text, sessionRefs, trustedContexts]
            : [sessionId, clientId, text],
        );
      },
      updateContent: async (sessionId, clientId, item) => {
        const expanded = await expandPluginItem(item);
        if (!isCurrent()) throw new Error('Message update superseded');
        return call("maker:input:update-content", [sessionId, clientId, expanded]);
      },
      move: (sessionId, clientId, targetIndex) =>
        call("maker:input:move", [sessionId, clientId, targetIndex]),
      setExpanded: (sessionId, expanded) =>
        call("maker:input:set-expanded", [sessionId, expanded]),
      setInteractionLock: (sessionId, lockId, locked) =>
        call("maker:input:set-interaction-lock", [sessionId, lockId, locked]),
      setEditLock: (sessionId, clientId, locked) =>
        call("maker:input:set-edit-lock", [sessionId, clientId, locked]),
      clearSession: (sessionId) =>
        call("maker:input:clear-session", [sessionId]),
    },
    fs: {
      listDir: (path) => call("fs:list-dir", [{ path }]),
      statPath: (path) => call("fs:stat-path", [{ path }]),
      mkdirP: (path) => call("fs:mkdir-p", [{ path }]),
      readTextFilePreview: (filePath, options) =>
        call("text-file:read-preview", [{ filePath, ...(options?.allowFileTransfer ? { allowFileTransfer: true } : {}) }]),
    },
    fileBrowser: {
      cacheScope: JSON.stringify([fileOwner.accountKey, deviceId]),
      readBytes: async (workdir, relPath, signal, beforeInvoke, options) => {
        assertFileReadActive(signal);
        const retryOp = <T>(args: Record<string, unknown>) =>
          withTransientRemoteRetry(async () => {
            assertFileReadActive(signal);
            await beforeInvoke?.();
            assertFileReadActive(signal);
            return fileOp<T>(args);
          });
        const referenceKey = JSON.stringify([referenceOwner, deviceId, workdir, relPath]);
        const knownUrl = fileReferences.get(referenceKey);
        const fallback = () =>
          exportDeviceFile(retryOp, workdir, relPath, signal, options?.onProgress);
        const fetchOptions = { signal, beforeFetch: beforeInvoke, retainBackground: options?.retainBackground };
        if (knownUrl && !isSharedTaskPeer(deviceId))
          return fetchMedia(knownUrl, fetchOptions, fallback, options?.stream ?? false);
        const caps = await retryOp<{ fileRead?: boolean }>({
          op: "caps",
          workdir,
        });
        assertFileReadActive(signal);
        if (!caps.fileRead) {
          mobileDebugLog("debug", "files", "file export without direct read", {
            reason: "host-lacks-file-read",
          });
          return fallback();
        }
        const reference = await retryOp<{
          ok: boolean;
          url: string;
          message?: string;
        }>({ op: "fileUrl", workdir, relPath });
        assertFileReadActive(signal);
        if (!reference.ok)
          throw new Error(reference.message ?? "FILE_READ_FAILED");
        if (fileIsCurrent()) fileReferences.set(referenceKey, reference.url);
        return fetchMedia(reference.url, fetchOptions, fallback, options?.stream ?? false);
      },
      caps: (workdir) =>
        call("file-browser:remote-op", [{ op: "caps", workdir }]),
      listDir: (workdir, relPath, opts) =>
        files.listDir({ workdir, relPath, ...opts }),
      readFile: (workdir, relPath, opts) =>
        files.readFile({
          workdir,
          relPath,
          ...(opts?.acceptGzip ? { acceptGzip: true } : {}),
        }),
      listAllFiles: (workdir, cap) =>
        call("file-browser:remote-op", [
          { op: "listAllFiles", workdir, ...(cap ? { cap } : {}) },
        ]),
      searchCollect: (workdir, query, opts) =>
        call("file-browser:remote-op", [
          {
            op: "searchCollect",
            workdir,
            query,
            ...(opts?.caseSensitive ? { caseSensitive: true } : {}),
            ...(opts?.maxMatches ? { maxMatches: opts.maxMatches } : {}),
          },
        ]),
      thumbnail: (workdir, relPath) =>
        call("file-browser:remote-op", [{ op: "thumbnail", workdir, relPath }]),
      exportFileStart: (workdir, relPath) =>
        call("file-browser:remote-op", [
          { op: "exportFileStart", workdir, relPath },
        ]),
      exportFileStatus: (workdir, transferId) =>
        call("file-browser:remote-op", [
          { op: "exportFileStatus", workdir, transferId },
        ]),
    },
  };
}