/** * ============================================================ * src/web/protocol.ts —— Web/Gateway WebSocket 线路协议(ClientFrame/ServerFrame) * ------------------------------------------------------------ * ⚠️ 不变量:本文件必须保持**纯 type-only**(只有 `import type` / `export type` / * `export interface`,零运行时 import/export)。webchat(浏览器)靠 * `export type … from '../../src/web/protocol.js'` **单一真源**引用这里, * 而它能安全 import 后端目录的唯一原因是:整条链全是 type,打包器(Vite/esbuild) * 在编译期把它擦除干净,绝不把 `node:*` 依赖拉进浏览器 bundle。 * * 一旦这里出现**任何运行时** import/export(哪怕一个 helper 函数), * webchat bundle 就会顺着链把 `src/types.ts`→`plugins/**` 的 node 代码拖进浏览器 → * **静默**打断前端构建。`test/webProtocolTypeOnly.test.ts` 守这条线(改动会报红)。 * * 同理它 `import type` 了具体插件 `cron-runner` 的类型:仅因 type-only 才不构成 * 内核对插件的运行时耦合;下游若要新增插件资源帧,务必同样只引 type。 * ============================================================ */ import type { AskAnswer, AskOption, AskQuestionSpec, AskSource, } from '../askBridge.js'; import type { HumanInterventionReason } from '../humanIntervention.js'; import type { ModelFallbackReason, ModelRef } from '../modelRef.js'; import type { OnlineModelAvailability } from '../team/onlineToolContract.js'; export type { ModelFallbackReason, ModelRef, SessionModelPreference, } from '../modelRef.js'; import type { ConversationSearchResult, MemoryCategory, MemoryDiagnostic, MemoryEditablePatch, MemoryRecord, MemorySettings, MemoryUpdate, PersonaDocument, } from '../memory/memoryService.js'; import type { PluginEvent } from '../plugins/pluginApi.js'; import type { AgentResultMetadata, ConversationFilePurpose, DeliverableManifest, FileActivityMetadata, LoopEvent, Message, MessageAttachmentRef, MessageBrowserReference, ProgressStage, SubagentProgress, ToolCall, ToolProgressDetail, ToolResultMetadata, } from '../types.js'; /** * 桌面控制的**线路观测形状**(协议自持,不 import 具体工具)。 * * 为什么不直接引 `tools/computeruse/protocol.ts` 的 `ComputerState`: * 那会让协议真值反向依赖某一个工具的内部模块,而 desktop / server 都从这里 * 取类型 —— 一个工具的重构会顺着协议波及两个消费方。方向必须是 * **工具依赖协议**,不是协议依赖工具。 * * 为什么不写成 `unknown`:desktop 面板真的在读 `activeApp?.name` / * `windows.length` / `screenshot?.path`,降级成 unknown 只是把破坏推给消费方。 * 所以这里声明**结构子集**:协议承诺的字段写在这儿,工具侧那份更丰富的 * `ComputerState` 由 `tools/computeruse/protocol.ts` 的编译期断言自证兼容 * (搜 `ComputerObservation` 找到那处断言)。两边一旦漂移,编译就红。 */ export interface ComputerObservation { revision: string; epoch: number; /** Transport metadata is exposed for diagnostics; clients must not infer authority from it. */ backend?: 'native' | 'degraded' | 'mock'; displays?: unknown[]; activeApp?: { id?: string; name?: string }; windows: unknown[]; screenshot?: { path: string; width: number; height: number }; changedRegions?: unknown[]; } /** * 浏览器控制权状态(协议自持)。 * * 与上面的 `ComputerObservation` 同一条理由,但这里是**真搬过来**而不是声明子集: * 它是个判别联合,desktop 会按 `status` 逐分支读 `reason`/`interventionId`/ * `resumeToken` 等字段,写子集会漏掉分支之间的关联。整体搬迁后 * `tools/webbrowser/browserControl.ts` 改为从这里 re-export, * 工具侧所有既有 import 路径不变。 */ export type BrowserControlState = | { owner: 'none'; status: 'idle' } | { owner: 'agent'; status: 'running'; runId: string; conversationKey?: string; action?: string; } | { owner: 'user'; status: 'waiting_human'; runId: string; conversationKey: string; reason: HumanInterventionReason; interventionId: string; resumeToken: string; ownerId: string; } | { owner: 'user'; status: 'interactive'; runId?: string; conversationKey?: string; }; export type { ConversationFilePurpose, DeliverableManifest, FileActivityMetadata, MessageAttachmentRef, ResultManifestMetadata, } from '../types.js'; export type { ConversationSearchResult, MemoryCategory, MemoryRecord, MemoryEditablePatch, MemorySettings, MemoryUpdate, PersonaDocument, } from '../memory/memoryService.js'; import type { CronListFilter, CronMissedRecord, CronRunRecord, CronTask, CronTaskDraft, CronTaskPatch, } from '../../plugins/cron-runner/src/types.js'; export type AgentEvent = LoopEvent | PluginEvent; export interface RecentDir { workspaceId?: string; path: string; name: string; lastUsedAt: number; title?: string; available?: boolean; } export interface MemoryRecordView extends MemoryRecord { version: string; } export interface MemoryPersonaView extends PersonaDocument { version: string; } export interface MemoryWorkspaceSummary { workspaceId: string; name: string; path: string; available: boolean; total: number; active: number; needsReview: number; superseded: number; } export interface MemoryOverview { total: number; active: number; needsReview: number; superseded: number; globalCount: number; workspaceCount: number; categories: Record; workspaces: MemoryWorkspaceSummary[]; diagnostics: MemoryDiagnostic[]; } export interface MemoryManagementState { records: MemoryRecordView[]; overview: MemoryOverview; settings: MemorySettings; settingsVersion: string; persona: MemoryPersonaView | null; refreshedAt: number; } export type MemoryLifecycleFilter = 'all' | 'active' | 'review' | 'superseded'; export interface MemoryScopeSummary { total: number; active: number; needsReview: number; superseded: number; diagnostics: MemoryDiagnostic[]; } export interface MemoryWorkspaceDescriptor { workspaceId: string; name: string; path: string; available: boolean; sessionIds: string[]; summary?: MemoryScopeSummary; } export interface MemoryCenterOverview { personal: MemoryScopeSummary; currentWorkspaceId?: string; currentWorkspace?: MemoryScopeSummary; workspaces: MemoryWorkspaceDescriptor[]; settings: MemorySettings; settingsVersion: string; persona: MemoryPersonaView | null; refreshedAt: number; } /** A list-safe topic projection. Sensitive statement text is intentionally omitted. */ export interface MemoryTopicSummary { id: string; topicKey: string; scope: 'personal' | 'workspace'; workspaceId?: string; category: MemoryCategory; subject: string; statementPreview?: string; sensitivity: 'normal' | 'sensitive'; lifecycle: Exclude; revision: number; updatedAt: number; lastConfirmedAt: number; supersededCount: number; } export interface MemoryTopicPage { scope: 'personal' | 'workspace'; workspaceId?: string; snapshotGeneration: string; topics: MemoryTopicSummary[]; total: number; nextCursor?: string; } export interface MemoryTopicDetail { topicKey: string; current: MemoryRecordView; history: MemoryRecordView[]; editable: boolean; } export interface ContextStatusView { target: { kind: 'plain' | 'workspace'; sessionId: string; dir?: string }; model?: string; usedTokens: number; contextWindow: number; remainingTokens: number; compactThreshold: number; source: 'actual' | 'estimated'; cachedPromptTokens?: number; cacheMissTokens?: number; cacheWriteTokens?: number; promptCacheUsage?: import('../types.js').PromptCacheUsage; } export type MemoryManagementAction = | 'load' | 'update' | 'confirm' | 'persona-update' | 'persona-clear' | 'settings-update' | 'forget' | 'clear'; export interface WorkspaceTreeEntry extends RecentDir { workspaceId: string; activeSessionId?: string; sessions: SessionSummary[]; } export interface SkillInfo { name: string; description: string; source?: 'builtin' | 'workspace'; unavailableReason?: string; } export type ApiFormat = 'openai' | 'openai-responses' | 'anthropic'; /** 推理强度;缺省 = 不发送,沿用服务端对该模型的默认强度。 */ export type ReasoningEffort = 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'; /** 模型列表的一个条目(脱敏视图——apiKey 只给 configured 布尔位,不下发原文)。 */ export interface ModelView { id: string; /** 展示来源;本机模型省略此字段以兼容旧 Runtime。 */ source?: 'local' | 'gateway'; /** Server catalog only; local model lists leave this unset. */ isDefault?: boolean; maxToolCategories?: string[]; defaultToolCategories?: string[]; capabilities?: { vision: boolean; tools: boolean; structuredOutput: boolean }; availability?: OnlineModelAvailability; apiFormat: ApiFormat; displayName?: string; /** Only local model views include provider endpoint metadata. */ baseURL?: string; apiKeyConfigured?: boolean; model: string; contextWindow: number; maxTokens?: number; supportsVision?: boolean; reasoningEffort?: ReasoningEffort; promptCache?: { mode: 'auto' | 'session-key' | 'disabled' }; enabled: boolean; updatedAt: number; } export interface WebchatConfig { /** Stable cross-process revision. Backed by config.json savedAt. */ revision?: number; models: ModelView[]; /** 当前被标记为基座(主循环)的模型 id;null = 尚未选定。 */ baseModelId: string | null; compactRatio?: number; /** * 只读镜像:解析出的当前基座 model/contextWindow——让「显示当前用的什么模型」这类 * 读取点(cron 草稿标签、ScheduledTasksView 等)不用学会去 models[] 按 baseModelId 查。 * 不是独立可编辑字段,改基座走 baseModelId patch。 */ model?: string; contextWindow?: number; tavilyApiKey?: string; tavilyApiKeyConfigured?: boolean; clearTavilyApiKey?: boolean; source?: 'json' | 'environment' | 'none'; readOnly?: boolean; /** Incomplete sections persisted securely without replacing the active config. */ draftFields?: string[]; advisor?: { configured: boolean; enabled: boolean; mode: 'auto' | 'manual'; /** remind = 只提醒;followup = 实质回答未复核时再请求一次,让模型自己补问顾问。 */ enforcement: 'remind' | 'followup'; /** 引用 models[].id;null = 未选。顾问不再自带一整套独立凭据。 */ modelId: string | null; contextPolicy: 'full-relevant'; /** @deprecated Compatibility only; runtime capacity follows the selected model. */ inputTokenBudget: number; timeoutMs: number; }; subagents?: { enabled: boolean; maxCallsPerTurn: number; maxConcurrent: number; defaultWriteIsolation: 'none' | 'worktree'; timeoutMs: number; exploreMaxTurns: number; generalMaxTurns: number; }; browser?: { enabled: boolean; profileId: 'default'; developerMode: boolean; allowedCdpOrigins: string[]; }; computerUse?: { enabled: boolean; imagePolicy: 'single-adaptive'; maxImagePixels: number; observationFrames: number; }; tools?: { webSearch: ToolConfigView; imageGeneration: ToolConfigView & { provider?: string; baseURL?: string; model?: string; protocol?: 'auto' | 'chat' | 'images'; }; openRouter: ToolConfigView; textToSpeech: ToolConfigView & { groupIdConfigured?: boolean }; }; toolInput?: { webSearchApiKey?: string; clearWebSearch?: boolean; imageProvider?: string; imageBaseURL?: string; imageApiKey?: string; imageModel?: string; imageProtocol?: 'auto' | 'chat' | 'images'; clearImageGeneration?: boolean; openRouterApiKey?: string; clearOpenRouter?: boolean; ttsApiKey?: string; ttsGroupId?: string; clearTextToSpeech?: boolean; }; } export interface ModelPatchFields { apiFormat?: ApiFormat; displayName?: string; baseURL?: string; apiKey?: string; clearApiKey?: boolean; model?: string; contextWindow?: number; maxTokens?: number; supportsVision?: boolean; /** update 时 null = 清除,回到服务端对该模型的默认强度。 */ reasoningEffort?: ReasoningEffort | null; promptCache?: { mode: 'auto' | 'session-key' | 'disabled' }; enabled?: boolean; } export type ModelPatchOp = | { op: 'add'; model: ModelPatchFields } | { op: 'update'; id: string; patch: ModelPatchFields } | { op: 'remove'; id: string }; export interface WebchatConfigPatch { models?: ModelPatchOp[]; /** 设为基座模型;null = 清空(正常流程不会用到,保留给完整性)。 */ baseModelId?: string | null; compactRatio?: number; advisor?: { clear?: boolean; enabled?: boolean; mode?: 'auto' | 'manual'; enforcement?: 'remind' | 'followup'; modelId?: string | null; /** @deprecated Accepted for old clients, but never limits advisor requests. */ inputTokenBudget?: number; timeoutMs?: number; }; subagents?: Partial>; browser?: Partial>; computerUse?: Partial>; tools?: NonNullable; } export interface ToolConfigView { state: 'unconfigured' | 'configured' | 'incomplete' | 'error'; configured: boolean; message?: string; } export type ToolConfigName = | 'advisor' | 'webSearch' | 'imageGeneration' | 'openRouter' | 'textToSpeech'; /** 'provider' 分区已删除——models/baseModelId/advisor 都走立即生效的 config/update,不再自动保存。 */ export type ConfigAutosaveSection = 'general' | 'tools' | 'browser'; export interface ArchiveEntry { id: string; updatedAt: number; msgCount: number; firstUserPreview: string; } export interface DirEntry { name: string; path: string; kind?: | 'home' | 'desktop' | 'documents' | 'downloads' | 'cloud' | 'volume' | 'network' | 'root'; } export interface DirListing { cwd: string; parent: string | null; entries: DirEntry[]; roots: DirEntry[]; error?: string; } export interface FileBrowserEntry { name: string; path: string; kind: 'directory' | 'file'; size?: number; modifiedAt?: number; } export interface FileBrowserListing { cwd: string; parent: string | null; entries: FileBrowserEntry[]; roots: DirEntry[]; error?: string; } /** * Stable, conversation-scoped reference to an element in the supervised browser. * Credentials, cookies and arbitrary DOM HTML are deliberately excluded. */ export type BrowserElementReference = MessageBrowserReference; export interface SessionSummary { id: string; active: boolean; title: string; createdAt: number; updatedAt: number; lastMessagePreview?: string; modelId?: string; preferredModel?: ModelRef; effectiveModel?: ModelRef; fallbackReason?: ModelFallbackReason; restoreWhenAvailable?: boolean; onlineToolCategories?: string[]; } export type ConversationTarget = | { kind: 'plain' } | { kind: 'workspace'; path: string }; export interface ConversationStartResult { requestId: string; runId: string; conversationKind: 'plain' | 'workspace'; sessionId: string; session: SessionSummary; sessions: SessionSummary[]; workspace?: RecentDir; workspacePath?: string; workspaceDisplayName?: string; } export interface QueuedUserInput { id: string; target: { kind: 'plain' } | { kind: 'workspace'; dir: string }; sessionId: string; text: string; attachmentIds: string[]; browserReferences?: BrowserElementReference[]; priority: 'next' | 'interrupt'; createdAt: number; /** Restored entries require an explicit user action before execution. */ restored?: boolean; } export type LocalConversationRef = | { kind: 'plain'; sessionId: string } | { kind: 'workspace'; workspaceId: string; dir: string; sessionId: string }; export type ConversationRunStatus = | 'queued' | 'running' | 'waiting_user' | 'waiting_human' | 'completed' | 'failed' | 'cancelled' | 'interrupted'; export interface PendingAskSummary { requestId: string; title?: string; questionCount: number; source?: AskSource; } export interface PendingHumanInterventionSummary { id: string; surface: 'browser' | 'computer'; reason: | 'password' | 'otp' | 'captcha' | 'qr_login' | 'login' | 'permission' | 'security_warning' | 'blocked' | 'manual'; sanitizedSummary: string; requestedAt: number; target?: { tabId?: string; origin?: string; appId?: string; windowId?: string; }; } /** * Reconnect-safe, in-memory view of the current turn. Events are bounded by the * Desktop Runtime and are never persisted to the run-state file. */ export interface LiveTurnSnapshot { sequence: number; /** Current turn projected into render-ready state. */ userMessage?: Extract; committedMessages: Message[]; streamingText: string; reasoningText: string; tools: LiveToolSnapshot[]; progressStage?: ProgressStage; contextUsage?: Extract; pendingAsk?: PendingAskSummary; ask?: Extract; /** Compatibility/debug tail. The materialized fields above are authoritative. */ events: AgentEvent[]; } export interface LiveToolSnapshot { toolCallId: string; toolName: string; status: 'running' | 'ok' | 'error'; argsPreview?: string; argsFriendly?: string; progress?: string; progressDetail?: ToolProgressDetail; content?: string; ok?: boolean; metadata?: ToolResultMetadata; startedAt?: number; durationMs?: number; } export interface ConversationRunSnapshot { usage?: import('../types.js').TurnResourceUsage; completionStatus?: Extract['completionStatus']; managedStatus?: string; warning?: string; conversation: LocalConversationRef; runId: string; status: ConversationRunStatus; phase?: string; queuePosition?: number; startedAt?: number; finishedAt?: number; elapsedMs?: number; pendingInputCount: number; unreadResult: boolean; error?: string; pendingAsk?: PendingAskSummary; pendingHuman?: PendingHumanInterventionSummary; live: LiveTurnSnapshot; } export interface LocalAttachmentRef { id: string; name: string; mime: string; size: number; sha256: string; previewUrl?: string; image: boolean; } export interface CronTaskWithRuns { task: CronTask; recentRuns: CronRunRecord[]; unreadCount: number; } export interface CronDraftResult { requestId: string; task: CronTaskDraft | null; missing: Array<'workspace' | 'session' | 'schedule' | 'action'>; error?: string; scheduleHuman?: string; nextRunAt?: string; } export interface ToolStatusState { toolName: string; argsPreview: string; status: 'running'; argsFriendly?: string; } // ---- 社交层:账号 / 好友(webchat 自建,见 web/adapter.ts + core/social/*) ---- export interface UserProfile { id: string; email: string; /** 旧版账号兼容显示;新账号不再依赖 username 作为身份。 */ username?: string; displayName: string; /** Small user avatar stored as a validated image data URL. */ avatarData?: string; createdAt: number; /** 站长(首个注册用户):可操作服务器本地工作目录/配置/cron;普通用户经 Agent Node 挂自己的 agent。 */ isAdmin?: boolean; /** 初始引导密码或管理员重置密码后,必须先完成改密。 */ passwordChangeRequired?: boolean; } export interface FriendEntry { id: string; email: string; username?: string; displayName: string; status: 'accepted' | 'pending_outgoing' | 'pending_incoming'; } // ---- 社交层:群组(webchat 自建,见 core/social/groups.ts + core/social/messages.ts) ---- // 成员 id 用带前缀字符串做多态标识:'user:' | 'agent:'。 // agent 成员只剩远程 Session Agent 一种(本机 cwd agent 已随中央服务收敛删除): // 经 group/addAgent(workspaceSessionId)填充,workspaceAgentId/workspaceSessionId/ // groupPolicy 字段有值,cwd/sessionId 为历史遗留、新成员不再写入。 export interface GroupMemberEntry { id: string; kind: 'human' | 'agent'; displayName: string; cwd?: string; ownerUserId?: string; workspaceAgentId?: string; workspaceSessionId?: string; groupPolicy?: 'mention' | 'proactive' | 'all' | 'disabled'; /** agent 成员透明度:该 agent 同时还在几个别的群(共享同一份工作目录上下文)。 */ otherGroupCount?: number; } export interface DirectConversationSummary { id: string; peer: UserProfile; /** 会话创建时间:统一消息列表的排序兜底(尚无消息的新会话不沉底)。 */ createdAt?: number; lastMessageAt?: number; lastMessagePreview?: string; unreadCount: number; writable: boolean; } export interface DirectChatMessage { id: string; conversationId: string; senderId: string; senderName: string; text: string; attachments?: GroupMessageAttachment[]; createdAt: number; } export interface WorkspaceAgent { id: string; ownerUserId: string; nodeId: string; workspaceKey: string; displayName: string; status: 'online' | 'offline' | 'busy'; lastActiveAt?: number; } /** A publishable Agent identity: one local workspace plus one isolated session. */ export interface WorkspaceSessionAgent { id: string; workspaceAgentId: string; ownerUserId: string; displayName: string; status: 'online' | 'offline' | 'busy'; lastActiveAt?: number; } export interface AgentNodeSummary { id: string; name: string; status: 'online' | 'offline'; lastSeenAt?: number; } export interface AgentDirectMessage { id: string; workspaceSessionId: string; ownerUserId: string; role: 'user' | 'assistant'; text: string; createdAt: number; } export interface ConversationActionSuggestion { id: string; label: string; prompt: string; reason: string; source: 'ai' | 'system'; } export interface NavigationConversation { kind: 'group' | 'project-space'; id: string; projectId?: string; title: string; preview?: string; unreadCount: number; mentioned: boolean; lastActivityAt?: number; } export interface NavigationWorkspace { id: string; displayName: string; source: 'gateway-local' | 'agent-node'; status: 'online' | 'offline' | 'busy'; lastActivityAt?: number; directTarget: { kind: 'local' | 'agent'; id: string; }; sessions?: WorkspaceSessionAgent[]; conversations: NavigationConversation[]; } export interface ConversationNavigation { workspaces: NavigationWorkspace[]; capabilities: { canManageProvider: boolean; canManageCron: boolean; canUseGatewayLocalDirs: boolean; }; } // ---- 项目协作层:项目 / 角色 / 工作项 / 交接 / 决策 ---- export type ProjectStatus = 'active' | 'archived'; export type ProjectProvider = 'github' | 'gitlab' | 'local-git'; export type ParticipantKind = 'human' | 'agent'; export type RoleScope = 'project' | 'task'; /** * 任务卡状态。`proposed`=方案待审,是"人只对方案负责"的强制停顿点; * `review`=待验收。流转规则与拍板权限的唯一真值在 `minimal-agent/task-flow`。 */ export type WorkItemStatus = | 'backlog' | 'ready' | 'proposed' | 'in_progress' | 'review' | 'blocked' | 'done'; export type CollaborationMode = 'parallel' | 'alternative' | 'pair' | 'review'; export type HandoffStatus = | 'offered' | 'accepted' | 'changes_requested' | 'completed'; export interface ProjectRepository { id: string; projectId: string; provider: ProjectProvider; remoteUrl: string; defaultBranch: string; name: string; createdAt: number; } export interface RoleAssignment { id: string; projectId: string; memberId: string; roleKey: string; roleName: string; scope: RoleScope; taskId?: string; responsibilities: string[]; createdAt: number; } export interface ProjectParticipant { memberId: string; kind: ParticipantKind; displayName: string; ownerUserId?: string; workspaceAgentId?: string; roles: RoleAssignment[]; joinedAt: number; } export interface WorkspaceRepositoryStatus { workspaceAgentId: string; /** 本机归一化仓库 remote 的不可逆指纹;联合 workspaceAgentId 唯一标识状态。 */ repositoryFingerprint?: string; repositoryId?: string; remoteFingerprint?: string; branch?: string; headSha?: string; dirty: boolean; ahead?: number; behind?: number; sparseScopes?: string[]; checkedAt: number; } export type DelegationScope = 'discussion' | 'read' | 'execute'; export interface DelegationGrant { scope: DelegationScope; /** Workspace-relative paths or directory prefixes approved by the Agent owner. */ readScopes: string[]; /** Explicit capabilities approved for this delegation, such as Bash or Write. */ capabilities: string[]; expiresAt?: number; } export interface ProjectSummary { id: string; name: string; description?: string; status: ProjectStatus; ownerUserId: string; primarySpaceId?: string; participantCount: number; openWorkItemCount: number; updatedAt: number; createdAt: number; } export interface ProjectDetail extends ProjectSummary { repositories: ProjectRepository[]; participants: ProjectParticipant[]; spaceIds: string[]; } export interface WorkItem { id: string; projectId: string; title: string; description: string; acceptanceCriteria: string[]; status: WorkItemStatus; collaborationMode?: CollaborationMode; ownerMemberId: string; contributorIds: string[]; reviewerIds: string[]; dependencies: string[]; repositoryId?: string; branch?: string; fileScopes: string[]; sourceMessageId?: string; dueAt?: number; createdBy: string; createdAt: number; updatedAt: number; } export interface WorkItemDraft { id?: string; projectId: string; title: string; description?: string; acceptanceCriteria?: string[]; status?: WorkItemStatus; collaborationMode?: CollaborationMode; ownerMemberId: string; contributorIds?: string[]; reviewerIds?: string[]; dependencies?: string[]; repositoryId?: string; branch?: string; fileScopes?: string[]; sourceMessageId?: string; dueAt?: number; } export interface ProjectHandoff { id: string; projectId: string; workItemId: string; fromMemberId: string; toMemberIds: string[]; status: HandoffStatus; summary: string; changedFiles: string[]; tests: string[]; risks: string[]; commitSha?: string; branch?: string; pullRequestUrl?: string; artifactIds: string[]; createdAt: number; updatedAt: number; } export interface ProjectDecision { id: string; projectId: string; title: string; summary: string; rationale: string; sourceMessageIds: string[]; createdBy: string; confirmedBy?: string; createdAt: number; updatedAt: number; } export interface ProjectActivity { id: string; projectId: string; actorMemberId: string; kind: string; entityType: string; entityId: string; summary: string; createdAt: number; } export interface ProjectArtifact { id: string; projectId: string; workItemId?: string; kind: | 'diff' | 'commit' | 'pull_request' | 'test_report' | 'document' | 'design' | 'database_script' | 'file'; title: string; contentHash?: string; attachmentId?: string; metadata: Record; createdBy: string; createdAt: number; } export interface WorkConflict { workItemId: string; conflictsWithId: string; overlappingScopes: string[]; reason: 'file_scope' | 'branch'; } export interface ProjectWorkspace { project: ProjectDetail; workItems: WorkItem[]; handoffs: ProjectHandoff[]; decisions: ProjectDecision[]; activities: ProjectActivity[]; artifacts: ProjectArtifact[]; workspaceStatuses: WorkspaceRepositoryStatus[]; conflicts: WorkConflict[]; } export type ConversationRef = | { kind: 'plain'; sessionId: string } | { kind: 'workspace'; sessionId: string } | { kind: 'direct'; conversationId: string } | { kind: 'group'; groupId: string } | { kind: 'agent'; workspaceSessionId: string }; /** A lazily-created collaboration context attached to an existing conversation. */ export interface ConversationWorkspace { conversation: ConversationRef; workspaceId: string; title: string; ownerUserId: string; participants: ProjectParticipant[]; repositories: ProjectRepository[]; tasks: WorkItem[]; handoffs: ProjectHandoff[]; decisions: ProjectDecision[]; activities: ProjectActivity[]; artifacts: ProjectArtifact[]; workspaceStatuses: WorkspaceRepositoryStatus[]; conflicts: WorkConflict[]; } export type NodeClientFrame = | { t: 'node/register'; token: string; name: string } | { t: 'node/heartbeat' } | { t: 'workspace/publish'; workspaceKey: string; displayName: string } | { t: 'session/publish'; workspaceAgentId: string; sessionKey: string; displayName: string; /** 由 session/create 触发时回带,服务端据此把新会话自动加进发起的那个群。 */ requestId?: string; } | { t: 'session/createFailed'; requestId: string; error: string } | { t: 'session/revoke'; workspaceSessionId: string } | { t: 'workspace/revoke'; workspaceAgentId: string } | { t: 'workspace/status'; workspaceAgentId: string; status: WorkspaceRepositoryStatus; } | { t: 'group/ack'; deliveryId: string } | { t: 'agent/event'; requestId: string; event: AgentEvent } | { t: 'agent/question'; requestId: string; deliveryId: string; questions: AskQuestionSpec[]; source?: AskSource; } | { t: 'agent/questionResolved'; requestId: string; deliveryId: string; state: 'answered' | 'cancelled'; } | { t: 'agent/reply'; requestId: string; text: string; files?: AgentFileMetadata[]; error?: string; } | { t: 'agent/groupUpdate'; requestId: string; deliveryId: string; update: GroupAgentUpdate; } | { t: 'agent/groupDelegate'; requestId: string; deliveryId: string; delegation: GroupAgentDelegation; } | { /** 外部成员委托必须在 LLM 启动前获得主人批准。 */ t: 'agent/delegationRequest'; requestId: string; deliveryId: string; } | { /** 节点侧同意闸门:本机 agent 被别人(非 owner)@ 且要执行副作用操作,请求 owner 批准。 * 服务端反查 owner 并路由到 owner 客户端,回答经 agent/consentRespond 下发。 */ t: 'agent/consentRequest'; requestId: string; deliveryId: string; toolName: string; argsPreview: string; } | { /** 取一条群消息里引用的附件(publicContext 里的 `[attachment:]` 句柄)。 * 服务端只回一次性下载票据,字节由节点自己走 HTTP GET —— 不把大二进制塞进这条 * 「都是小 JSON 控制帧」的连接(base64 还膨胀 33%,且会队头阻塞)。 */ t: 'attachment/fetch'; requestId: string; deliveryId: string; fileId: string; } | { /** 请求把一个**交付物**上传成群附件的一次性票据(导出前的同意已在节点侧问过主人)。 * 同样只发票据,字节由节点自己 PUT 上去。 */ t: 'attachment/uploadRequest'; requestId: string; deliveryId: string; name: string; mime: string; }; export type NodeServerFrame = | { t: 'node/registered'; nodeId: string } | { t: 'workspace/published'; workspaceAgent: WorkspaceAgent } | { t: 'session/published'; workspaceSession: WorkspaceSessionAgent; sessionKey: string; } | { t: 'node/error'; message: string } /** The server accepted and durably published this Agent reply. */ | { t: 'agent/replyAck'; requestId: string } /** Server could no longer deliver a queued turn before its retention TTL. */ | { t: 'agent/deliveryExpired'; deliveryId: string; workspaceAgentId: string; workspaceSessionId?: string; eventId?: string; groupId?: string; agentMemberId?: string; displayName?: string; kind: 'group' | 'direct'; } | { t: 'group/deliver'; deliveryId: string; workspaceAgentId: string; /** 不透明的中央 Session Agent 标识;本机节点据此选择真实 cwd + sessionId。 */ workspaceSessionId?: string; message: GroupChatMessage; respond: boolean; /** Public group context for this turn only. Never contains private Session history. */ publicContext?: string; /** 该 agent 的 owner(本机主人)userId:节点侧同意闸门用它判定"这条 @ 是不是主人发的"。 */ ownerUserId?: string; } | { t: 'agent/turn'; requestId: string; workspaceAgentId: string; workspaceSessionId?: string; text: string; } | { t: 'agent/abort'; requestId: string } | { /** 请节点在某个工作目录下新建一个会话(用户按"工作目录"入群时由服务端发起)。 * 节点建好后用 session/publish 回带同一个 requestId;失败发 session/createFailed。 */ t: 'session/create'; requestId: string; workspaceAgentId: string; title: string; } | { t: 'agent/answer'; requestId: string; deliveryId: string; answers: AskAnswer[]; } | { t: 'agent/questionCancel'; requestId: string; deliveryId: string } | { /** 节点侧同意请求的裁决下发(服务端 → 节点);节点据此 resolve 挂起的 toolGate。 */ t: 'agent/consentRespond'; requestId: string; decision: 'approve' | 'deny'; } | { t: 'agent/delegationRespond'; requestId: string; grant: DelegationGrant | null; } | { t: 'agent/groupActionResult'; requestId: string; ok: boolean; referenceId?: string; error?: string; } | { /** attachment/fetch 的应答:一次性下载票据 + 文件元信息,或拒绝原因。 * 节点拿 ticket 自己拼 `/api/files/?ticket=…` 去 GET * —— URL 由节点侧拼装,服务端因此不需要知道自己在反代后的对外地址。 */ t: 'attachment/ticket'; requestId: string; fileId: string; ticket?: string; name?: string; mime?: string; size?: number; error?: string; } | { /** attachment/uploadRequest 的应答:一次性上传票据,或拒绝原因。 */ t: 'attachment/uploadTicket'; requestId: string; ticket?: string; error?: string; }; export interface GroupSummary { id: string; name: string; announcement?: string; /** 群主的成员 id('user:' 格式),前端据此判断是否显示"解散群"等群主专属操作。 */ createdBy: string; memberCount: number; /** 建群时间:统一消息列表的排序兜底(尚无消息的空群不沉底)。 */ createdAt?: number; lastMessageAt?: number; lastMessagePreview?: string; /** 查询者视角的未读消息数(仅 group/list 计算;group/detail 不带,前端合并时保留旧值)。 */ unreadCount?: number; } export interface GroupDetail extends GroupSummary { members: GroupMemberEntry[]; } export interface GroupMessageAttachment { fileId: string; name: string; mime: string; size: number; } export type ConversationFileKind = | 'workspace-file' | 'user-attachment' | 'group-attachment' | 'agent-file'; export type ConversationFileActivity = | 'referenced' | 'read' | 'created' | 'modified' | 'generated' | 'deleted'; /** Safe metadata an Agent Node may publish to a group. Absolute paths and file bytes are forbidden. */ export interface AgentFileMetadata { id: string; ownerAgentId: string; name: string; relativePath: string; mime?: string; activity: ConversationFileActivity; purpose?: ConversationFilePurpose; /** * 该交付物已被导出为群附件时的 fileId(群成员据此下载)。 * 只有 `purpose === 'deliverable'` 且经本机主人批准导出的文件才有; * 其余文件只有元信息,拿不到内容。 */ fileId?: string; lastSeenAt: number; } /** A local-safe file reference shown beside a conversation. Absolute paths never cross this boundary. */ export interface ConversationFileRef { id: string; conversationKey: string; kind: ConversationFileKind; name: string; relativePath?: string; mime?: string; size?: number; activity: ConversationFileActivity; purpose: ConversationFilePurpose; lastTurnId?: string; lastSeenAt: number; pinned: boolean; ownerAgentId?: string; available: boolean; previewable: boolean; previewUrl?: string; verification?: import('../types.js').FileVerification; sourceToolCallId?: string; sha256?: string; modifiedAt?: number; contentChanged?: boolean; originalAvailable?: boolean; archivedAvailable?: boolean; previewSource?: 'original' | 'archive' | 'upload'; } /** A durable, turn-scoped formal delivery. File refs are resolved at read time. */ export interface ConversationDelivery { id: string; turnId: string; toolCallId?: string; createdAt: number; manifest: DeliverableManifest; resolvedFiles: ConversationFileRef[]; } /** Durable user-supplied and formally delivered artifacts for one user turn. */ export interface ConversationArtifactGroup { turnId: string; createdAt: number; compacted: boolean; userAttachments: MessageAttachmentRef[]; deliveries: ConversationDelivery[]; } export type ConversationAssetCategory = | 'document' | 'code' | 'image' | 'link' | 'other'; export type ConversationAssetOrigin = | 'user-upload' | 'user-reference' | 'ai-delivery'; export type ConversationAssetKind = | 'workspace-file' | 'user-attachment' | 'web-link'; /** A durable, session-scoped item explicitly supplied by the user or formally delivered by the Agent. */ export interface ConversationAsset { id: string; conversationKey: string; kind: ConversationAssetKind; category: ConversationAssetCategory; name: string; origins: ConversationAssetOrigin[]; firstTurnId: string; lastTurnId: string; firstSeenAt: number; lastSeenAt: number; pinned: boolean; available: boolean; previewable: boolean; relativePath?: string; url?: string; domain?: string; mime?: string; size?: number; previewUrl?: string; verification?: import('../types.js').FileVerification; sha256?: string; modifiedAt?: number; contentChanged?: boolean; /** The original workspace file still exists at its submitted path. */ originalAvailable?: boolean; /** An immutable, content-addressed copy of the submitted file is available. */ archivedAvailable?: boolean; /** Which bytes are opened by the default preview action. */ previewSource?: 'original' | 'archive' | 'upload'; } export interface GroupChatMessage { id: string; groupId: string; senderId: string; senderKind: 'human' | 'agent'; senderName: string; text: string; mentions: string[]; attachments?: GroupMessageAttachment[]; agentFiles?: AgentFileMetadata[]; createdAt: number; /** 'system' = 群事件系统消息(谁邀请了谁/agent 入群/改名等),居中灰字渲染, * 不触发 agent 路由、不计未读。缺省 = 普通聊天消息。 */ kind?: 'system'; } export type CollaborationEventVisibility = 'public' | 'owner-private'; export type CollaborationConversationKind = 'group' | 'direct' | 'agent'; export interface CollaborationConversationRef { kind: CollaborationConversationKind; id: string; } export interface CollaborationArtifactRef { id: string; name: string; mime: string; size: number; sha256?: string; version?: number; } export interface CollaborationEventPayloads { 'message.created': { text: string; mentions: string[]; attachments?: CollaborationArtifactRef[]; senderKind: 'human' | 'agent' | 'system'; }; 'goal.drafted': { title: string; objective: string; deliverables: string[]; acceptanceCriteria: string[]; scope?: string; }; 'goal.confirmed': { goalId: string; contractVersion?: number; contractHash?: string; }; 'task.created': { title: string; objective: string; acceptanceCriteria: string[]; parentTaskId?: string; assigneeIds?: string[]; /** 目标确认后默认直接运行;保留 planned 只用于显式暂存。 */ initialState?: 'planned' | 'running'; }; 'task.updated': { state: | 'planned' | 'running' | 'stopped' | 'blocked' | 'verifying' | 'awaiting_acceptance' | 'completed' | 'cancelled'; summary?: string; reason?: string; assigneeIds?: string[]; }; 'decision.recorded': { title: string; conclusion: string; sourceIds: string[]; }; 'activity.recorded': { phase: | 'planning' | 'producing' | 'checking' | 'handoff' | 'waiting' | 'blocked'; summary: string; agentMemberId?: string; }; 'artifact.published': { artifact: CollaborationArtifactRef; summary?: string; }; 'verification.recorded': { verifier: string; passed: boolean; summary: string; evidenceIds: string[]; criterionResults?: Array<{ criterion: string; passed: boolean; evidence?: string; }>; }; 'acceptance.requested': { artifactIds: string[]; selfCheck: Array<{ criterion: string; passed: boolean; evidence?: string }>; risks?: string[]; }; 'acceptance.resolved': { decision: 'accepted' | 'rework'; reason?: string; }; 'attention.raised': { reason: | 'business_ambiguity' | 'scope_exceeded' | 'irreversible_action' | 'sensitive_export' | 'execution_failed'; summary: string; requestedFromUserId: string; }; 'attention.resolved': { resolution: string }; 'approval.requested': { requestId: string; agentMemberId: string; agentDisplayName?: string; reason: string; capability: string; argsPreview?: string; }; 'approval.status': { requestId: string; agentMemberId: string; agentDisplayName?: string; state: | 'waiting' | 'approved' | 'denied' | 'expired' | 'revoked' | 'stopped'; ownerDisplayName?: string; }; 'membership.changed': { memberId: string; action: 'joined' | 'left' | 'removed'; displayName: string; memberKind: 'human' | 'agent'; }; } export type CollaborationEventType = keyof CollaborationEventPayloads; interface CollaborationEventBase { version: 1; id: string; type: T; conversation: CollaborationConversationRef; author: { id: string; name: string; kind: 'human' | 'agent' | 'system' }; visibility: CollaborationEventVisibility; createdAt: number; causedBy: string[]; taskId?: string; objectId?: string; revision?: number; /** Optional Goal Runtime correlation. Older clients treat a missing version as v1. */ contractVersion?: number; contractHash?: string; attemptId?: string; agentMemberId?: string; payload: CollaborationEventPayloads[T]; } export type CollaborationEvent = { [T in CollaborationEventType]: CollaborationEventBase; }[CollaborationEventType]; /** Client-authored events are always public; owner-private events are server-authored. */ export type CollaborationEventDraft = { [T in CollaborationEventType]: Omit< CollaborationEventBase, 'id' | 'author' | 'createdAt' | 'visibility' > & { clientEventId: string }; }[CollaborationEventType]; /** Durable local-only batch awaiting a relay acknowledgement. */ export interface CollaborationOutboxItem { id: string; serverUrl: string; userId: string; events: CollaborationEventDraft[]; createdAt: number; } export interface RelayDelivery { deliveryId: string; /** Device-local monotonic sequence. Required on the PostgreSQL relay path. */ sequence?: number; /** Identifies which device continuity stream owns sequence. */ deviceId?: string; event: CollaborationEvent; } export interface RelayContinuityState { deviceId: string; highestAssignedSequence: number; /** More unacknowledged rows remain after this batch. */ hasMore: boolean; } export interface RelayMissingRange { from: number; to: number; } /** Content-free metadata used to repair a settled device-local relay gap. */ export interface RelayGapCandidate { eventId: string; sequence: number; conversationKind: 'group' | 'direct' | 'agent'; conversationId: string; eventType: string; payloadHash: string; attachmentIds: string[]; createdAt: number; /** Devices that originally received the same event and may have a local copy. */ sourceDeviceIds: string[]; } export interface RelayGapRepairRequest { requestId: string; targetDeviceId: string; candidate: RelayGapCandidate; } export interface LocalRelayContinuity { deviceId: string; highestStoredSequence: number; missing: RelayMissingRange[]; /** False until the Server reports that all current rows have been pulled. */ settled: boolean; } export type GroupUpdateKind = | 'progress' | 'decision' | 'artifact' | 'verification' | 'handoff'; export interface GroupAgentUpdate { kind: GroupUpdateKind; summary: string; parentTaskId?: string; references?: string[]; /** Required for verification updates; omitted means the check did not pass. */ passed?: boolean; /** Stable evidence/artifact ids supporting the check. */ evidenceIds?: string[]; } export interface GroupAgentDelegation { /** * Optional: when omitted the server chooses an eligible Agent in the same * group. An explicit offline target may also be replaced by an eligible * online/busy Agent so a temporary device outage does not stop the parent * task. */ targetAgentMemberId?: string; parentTaskId: string; objective: string; acceptanceCriteria?: string[]; references?: string[]; } /** Local, read-only social snapshot. It never contains auth tokens, absolute paths or Agent private history. */ export interface OfflineSocialCache { version: 1; serverUrl: string; user: UserProfile; updatedAt: number; groups: GroupSummary[]; groupDetails: Record; groupMessages: Record; } /** * A durable, local-only social send waiting for a server acknowledgement. * The server never stores this queue; the stable id is used only for * at-least-once delivery and duplicate suppression. */ export interface SocialOutboxItem { id: string; serverUrl: string; userId: string; kind: 'group' | 'direct'; conversationId: string; text: string; mentions?: string[]; attachments?: string[]; createdAt: number; } /** * A conversation read marker, owned entirely by Desktop. Under the relay-only server design * the server never persists message bodies, so it has no place to keep a per-user read cursor * either — `unreadCount`/`mentioned` on `GroupSummary`/`ConversationNavigation` are honestly `0`/ * `false` from the server. Desktop derives the real values from its own local event replica plus * this cursor (see minimal-desktop's `runtime/unreadProjection.ts` / `runtime/readCursors.ts`). */ export interface ReadCursor { eventId: string; at: number; } /** * 用户级事件:不管用户当前打开哪个群都会推送(连接建立、解析出登录身份后订阅)。 * 与 group/message(只推给"正打开该群"的连接)互补——未读徽标、被 @ 提醒、 * agent 忙碌/完成通知靠这条通道。 */ export type UserSocialEvent = | { t: 'group/bump'; groupId: string; lastMessageAt: number; lastMessagePreview: string; /** 这条消息是否 @ 了收件人本人。 */ mentioned: boolean; /** true = 来自系统消息(改名/进出群等):前端只刷预览/时间,不 ++未读 * (服务端 unreadCount 同样排除系统消息,两端一致防幽灵未读)。 */ fromSystem?: boolean; } | { t: 'group/agentBusy'; groupId: string; agentMemberId: string; displayName: string; busy: boolean; } | { t: 'conversation/bump'; conversationId: string; lastMessageAt: number; lastMessagePreview: string; fromDisplayName: string; } | { /** 好友关系变化(申请/接受/删除)的"去刷新"信号——前端收到即重拉好友列表。 */ t: 'social/friendsChanged'; } | { /** 当前会话的任务、决策、仓库或交付物变化,在线成员按会话重拉。 */ t: 'conversation/workspace/changed'; conversation: ConversationRef; } | { t: 'agent/directMessage'; workspaceSessionId: string; message: AgentDirectMessage; } | { t: 'agent/directEvent'; workspaceSessionId: string; event: AgentEvent } | { /** 群 Agent 的完整运行事件,仅推送给该 Agent 所有者。 */ t: 'group/agentEvent'; groupId: string; agentMemberId: string; displayName: string; event: AgentEvent; } | { /** 面向群成员的脱敏子任务阶段;不含工具参数、路径或私有上下文。 */ t: 'group/agentProgress'; groupId: string; agentMemberId: string; displayName: string; toolCallId: string; phase: | 'queued' | 'preparing' | 'analyzing' | 'using_tool' | 'drafting' | 'waiting_owner' | 'completed' | 'failed'; } | { t: 'agent/question'; requestId: string; deliveryId: string; questions: AskQuestionSpec[]; source?: AskSource; context: | { kind: 'group'; groupId: string; agentMemberId: string; agentDisplayName: string; } | { kind: 'direct'; workspaceSessionId: string }; } | { t: 'agent/questionStatus'; requestId: string; state: 'queued' | 'waiting' | 'answered' | 'cancelled'; groupId?: string; agentMemberId?: string; agentDisplayName?: string; queuePosition?: number; /** 仅 Agent 所有者客户端为 true;用于本人的问答队列,不影响群内公共状态。 */ ownerQuestion?: boolean; } | { /** * 跨机指令同意请求:别人 @ 了我拥有的 agent,且这一轮要执行副作用操作(写文件/Bash/删除等)。 * 只推给该 agent 的 owner(本机主人)。owner 客户端弹审批卡 → group/consentRespond 回。 * 见 core/social/consent.ts 与 host 的 pendingConsents。 */ t: 'group/consentRequest'; requestId: string; groupId: string; agentMemberId: string; agentDisplayName: string; /** 发起该 @ 指令的用户显示名("是谁想驱使你的 agent")。 */ requesterName: string; /** 即将执行的工具名与参数摘要(供 owner 判断风险,如 Bash: rm -rf src)。 */ toolName: string; argsPreview: string; /** delegation 在 LLM 启动前审批;tool 是回合中的高风险工具审批。 */ phase?: 'delegation' | 'tool'; messagePreview?: string; }; export type ClientFrame = | { t: 'resource/learning/manage'; requestId: string; workspaceId: string; request: import('../memory/managementService.js').LearningManagementRequest } | { t: 'runtime/hello' } | { t: 'goal/get'; requestId: string; workspaceId: string; sessionId: string; } | { t: 'goal/control'; requestId: string; workspaceId: string; sessionId: string; action: | 'start' | 'pause' | 'resume' | 'update' | 'cancel' | 'accept' | 'rework'; actorId: string; objective?: string; expectedGoalId?: string; expectedRevision?: number; tokenBudget?: number | null; sourceRefs?: string[]; deliverables?: string[]; acceptanceCriteria?: string[]; scope?: string; reason?: string; source?: import('../goal/types.js').GoalSource; acceptorHumanIds?: string[]; } | { t: 'local/conversation/start'; requestId: string; target: ConversationTarget; text: string; attachments?: string[]; browserReferences?: BrowserElementReference[]; modelId?: string; } | { t: 'plain/list' } | { t: 'plain/open'; sessionId: string; requestId?: string } | { t: 'plain/send'; sessionId: string; text: string; attachments?: string[]; browserReferences?: BrowserElementReference[]; requestId?: string; modelId?: string; } | { t: 'plain/clear'; sessionId: string } | { t: 'plain/compact'; sessionId: string; requestId?: string; customInstructions?: string } | { t: 'plain/rename'; sessionId: string; title: string } | { t: 'plain/delete'; sessionId: string } | { t: 'resource/files/list'; dir: string; sessionId: string } | { t: 'resource/assets/list'; requestId: string; target: ConversationTarget & { sessionId: string }; } | { t: 'resource/assets/pin'; requestId: string; target: ConversationTarget & { sessionId: string }; assetId: string; pinned: boolean; } | { t: 'resource/assets/open'; requestId: string; target: ConversationTarget & { sessionId: string }; assetId: string; source?: 'default' | 'original' | 'archive'; } | { t: 'resource/assets/reveal'; requestId: string; target: ConversationTarget & { sessionId: string }; assetId: string; source?: 'original' | 'archive'; } | { t: 'resource/files/open'; requestId: string; target: ConversationTarget & { sessionId: string }; relativePath: string; } | { t: 'resource/files/pin'; dir: string; sessionId: string; relativePath: string; pinned: boolean; } | { t: 'resource/files/reveal'; requestId?: string; dir?: string; target?: ConversationTarget & { sessionId: string }; relativePath: string; } | { t: 'resource/memories/list'; workspaceId?: string; query?: string } | { t: 'resource/memories/settings/update'; autoRemember: boolean; workspaceId?: string; } | { t: 'resource/memories/update'; id: string; scope: 'personal' | 'workspace'; expectedVersion: string; patch: MemoryUpdate; workspaceId?: string; } | { t: 'resource/memories/confirm'; id: string; scope: 'personal' | 'workspace'; expectedVersion: string; evidenceQuote: string; sourceSessionId: string; sourceMessageId: string; workspaceId?: string; } | { t: 'resource/memories/review'; scope?: 'personal' | 'workspace'; workspaceId?: string; } | { t: 'resource/memories/persona/set'; content: string; evidenceQuote: string; sourceSessionId: string; sourceMessageId: string; } | { t: 'resource/memories/persona/clear' } | { t: 'resource/memories/conversations/search'; requestId: string; query: string; workspaceId: string; scope?: 'workspace' | 'all'; explicitCrossWorkspace?: boolean; limit?: number; } | { t: 'resource/memories/forget'; id: string; scope: 'personal' | 'workspace'; workspaceId?: string; } | { t: 'resource/memories/clear'; scope: 'personal' | 'workspace'; workspaceId?: string; } | { t: 'resource/memories/manage/load'; requestId: string } | { t: 'resource/memories/manage/update'; requestId: string; id: string; scope: 'personal' | 'workspace'; workspaceId?: string; expectedVersion: string; patch: MemoryEditablePatch; includeState?: boolean; } | { t: 'resource/memories/manage/confirm'; requestId: string; id: string; scope: 'personal' | 'workspace'; workspaceId?: string; expectedVersion: string; includeState?: boolean; } | { t: 'resource/memories/manage/persona/update'; requestId: string; content: string; expectedVersion: string; includeState?: boolean; } | { t: 'resource/memories/manage/persona/clear'; requestId: string; expectedVersion: string; includeState?: boolean; } | { t: 'resource/memories/manage/settings/update'; requestId: string; patch: Partial; expectedVersion: string; includeState?: boolean; } | { t: 'resource/memories/manage/forget'; requestId: string; id: string; scope: 'personal' | 'workspace'; workspaceId?: string; expectedVersion: string; includeState?: boolean; } | { t: 'resource/memories/manage/clear'; requestId: string; scope: 'personal' | 'workspace'; workspaceId?: string; includeState?: boolean; } | { t: 'resource/memories/overview/load'; requestId: string; currentWorkspaceId?: string; } | { t: 'resource/memories/topics/list'; requestId: string; scope: 'personal' | 'workspace'; workspaceId?: string; query?: string; category?: MemoryCategory | 'all'; lifecycle?: MemoryLifecycleFilter; cursor?: string; limit?: number; } | { t: 'resource/memories/topic/detail'; requestId: string; scope: 'personal' | 'workspace'; workspaceId?: string; topicKey: string; } | { t: 'resource/context/status'; requestId: string; target: | { kind: 'plain'; sessionId: string } | { kind: 'workspace'; dir: string; sessionId: string }; } | { t: 'resource/subagents/worktrees/diff'; requestId: string; dir: string; id: string; } | { t: 'resource/subagents/worktrees/apply'; requestId: string; dir: string; id: string; } | { t: 'resource/subagents/worktrees/discard'; requestId: string; dir: string; id: string; } | { t: 'open'; dir: string; sessionId?: string; requestId?: string } | { t: 'send'; dir: string; text: string; sessionId?: string; attachments?: string[]; browserReferences?: BrowserElementReference[]; requestId?: string; modelId?: string; } | { t: 'session/model/set'; target: { kind: 'plain' } | { kind: 'workspace'; dir: string }; sessionId: string; modelId: string | null; } | { t: 'session/tools/set'; target: { kind: 'plain' } | { kind: 'workspace'; dir: string }; sessionId: string; categories: string[]; } | { t: 'input/queue'; item: Omit; } | { t: 'input/queue/update'; id: string; text?: string; attachmentIds?: string[]; browserReferences?: BrowserElementReference[]; priority?: 'next' | 'interrupt'; activate?: boolean; } | { t: 'input/queue/remove'; id: string } | { t: 'input/queue/get' } | { t: 'conversation/run/list' } | { t: 'conversation/view/open'; requestId: string; target: | { kind: 'plain'; sessionId: string } | { kind: 'workspace'; dir: string; sessionId: string }; } | { t: 'conversation/run/abort'; conversation: LocalConversationRef; runId: string; } /** Retry the last persisted user turn in the same Session after a failed/interrupted run. */ | { t: 'conversation/run/retry'; conversation: LocalConversationRef; runId: string; } | { t: 'conversation/run/answer'; conversation: LocalConversationRef; runId: string; requestId: string; answers: AskAnswer[]; } | { t: 'conversation/run/cancel-ask'; conversation: LocalConversationRef; runId: string; requestId: string; } | { t: 'conversation/result/mark-seen'; conversation: LocalConversationRef; runId?: string; } | { t: 'conversation/run/configure'; maxConcurrent: number } | { t: 'answer'; requestId: string; answers: AskAnswer[] } | { t: 'cancelAsk'; requestId: string } | { t: 'abort' } | { t: 'compact/abort'; requestId: string } | { t: 'new'; dir: string; sessionId?: string } | { t: 'compact'; dir: string; sessionId?: string; requestId?: string; customInstructions?: string } | { t: 'listDirs' } /** 探测局域网内的 minimal-server(UDP 只能在本机 Runtime 里发,浏览器上下文发不了)。 */ | { t: 'server/discover' } | { t: 'workspace/index/get' } | { t: 'workspace/recovery/preview' } | { t: 'workspace/recovery/apply' } | { t: 'social/cache/get'; serverUrl: string } | { t: 'social/cache/save'; cache: OfflineSocialCache } | { t: 'social/cache/clear'; serverUrl: string; userId?: string } | { t: 'social/outbox/get'; requestId: string; serverUrl: string; userId: string; } | { t: 'social/outbox/save'; requestId: string; serverUrl: string; userId: string; items: SocialOutboxItem[]; } | { t: 'social/outbox/clear'; requestId: string; serverUrl: string; userId?: string; } | { t: 'collaboration/outbox/get'; requestId: string; serverUrl: string; userId: string; } | { t: 'collaboration/outbox/save'; requestId: string; serverUrl: string; userId: string; items: CollaborationOutboxItem[]; } | { t: 'collaboration/outbox/clear'; requestId: string; serverUrl: string; userId?: string; } | { t: 'collaboration/read/get'; requestId: string; serverUrl: string; userId: string; } /** * Fire-and-forget: Desktop advances its own read cursor (conversation opened, or a real-time * bump arrived while it was open). No reply — losing one on a crash just means one extra * unread badge next launch, never a false "read" state. */ | { t: 'collaboration/read/mark'; serverUrl: string; userId: string; conversationId: string; cursor: ReadCursor; } | { t: 'collaboration/device/get'; requestId: string } | { /** Local Runtime only: append before the social connection may ACK. */ t: 'collaboration/events/append'; requestId: string; serverUrl: string; userId: string; deliveries: RelayDelivery[]; continuity?: RelayContinuityState; } | { /** Local Runtime only: rebuild UI projections from the durable event log. */ t: 'collaboration/events/load'; requestId: string; serverUrl: string; userId: string; conversation?: CollaborationConversationRef; } | { t: 'collaboration/events/find'; requestId: string; serverUrl: string; userId: string; eventIds: string[]; } | { t: 'workspace/register'; requestId: string; path: string } | { t: 'browseDir'; path?: string } | { t: 'file/browse'; requestId: string; path?: string } | { t: 'removeDir'; dir: string } | { t: 'listArchives'; dir: string } | { t: 'restoreArchive'; dir: string; id: string; sessionId?: string } | { t: 'listSessions'; dir: string } | { t: 'switchSession'; dir: string; sessionId: string; requestId?: string } | { t: 'createSession'; dir: string; title?: string } | { t: 'renameSession'; dir: string; sessionId: string; title: string } | { t: 'copySession'; dir: string; sessionId: string; title?: string } | { t: 'deleteSession'; dir: string; sessionId: string } | { t: 'config/get' } | { t: 'config/update'; requestId: string; revision?: number; patch: WebchatConfigPatch; } | { t: 'config/autosave'; requestId: string; revision?: number; section: ConfigAutosaveSection; patch: WebchatConfigPatch; } | { t: 'config/tool/test'; tool: ToolConfigName } /** * 模型列表条目的连通性测试——跟 config/tool/test 同一先例的延伸(测试从来不是配置变更, * 一直走独立于 patch 的姊妹帧),只是模型是开放式按 id 索引的动态集合,ToolConfigName * 的封闭枚举表达不了。modelId 测已保存条目;draft 测弹窗里还没提交的正在填写的值。 */ | { t: 'config/model/test'; requestId: string; modelId?: string; draft?: { apiFormat: ApiFormat; baseURL: string; apiKey?: string; model: string; }; } | { t: 'getSkills'; dir?: string } | { t: 'resource/crons/list'; filter?: CronListFilter } | { t: 'resource/crons/show'; id: string } | { t: 'resource/crons/draft'; requestId: string; text: string; cwd?: string; sessionId?: string; model?: string; sessionMode?: 'persistent' | 'fresh'; } | { t: 'resource/crons/create'; requestId: string; task: CronTaskDraft } | { t: 'resource/crons/update'; requestId: string; patch: CronTaskPatch } | { t: 'resource/crons/delete'; requestId: string; id: string } | { t: 'resource/crons/pause'; requestId: string; id: string } | { t: 'resource/crons/resume'; requestId: string; id: string } | { t: 'resource/crons/run'; requestId: string; id: string } | { t: 'resource/crons/stop'; requestId: string; id: string } | { t: 'resource/crons/missed' } | { t: 'resource/crons/mark-read'; id: string } | { t: 'resource/crons/mark-all-read' } | { t: 'resource/commands/list'; workspaceAgentId?: string; dir?: string; requestId?: string } | { t: 'social/friends/list' } | { t: 'social/friends/search'; query: string } | { t: 'social/friends/request'; toUserId: string } | { t: 'social/friends/respond'; fromUserId: string; accept: boolean } | { t: 'social/friends/remove'; userId: string } | { t: 'conversation/list' } | { t: 'conversation/navigation/get' } | { t: 'conversation/open'; conversationId: string } | { t: 'conversation/start'; friendUserId: string } | { t: 'conversation/send'; conversationId: string; text: string; attachments?: string[]; requestId?: string; } | { t: 'conversation/history'; conversationId: string; beforeId?: string; limit?: number; } | { t: 'agent/direct/open'; workspaceSessionId: string } | { t: 'agent/direct/send'; workspaceSessionId: string; text: string } | { t: 'agent/direct/abort'; workspaceSessionId: string } | { t: 'conversation/actions/suggest'; kind: 'group' | 'direct' | 'agent'; id: string; } | { t: 'node/pairing/create'; name: string } | { t: 'node/list' } | { t: 'workspace/list' } | { t: 'conversation/workspace/open'; conversation: ConversationRef } | { t: 'conversation/task/save'; conversation: ConversationRef; task: Omit; } | { t: 'conversation/task/delete'; conversation: ConversationRef; taskId: string; } | { t: 'conversation/decision/save'; conversation: ConversationRef; decision: Omit< ProjectDecision, 'id' | 'projectId' | 'createdAt' | 'updatedAt' | 'createdBy' > & { id?: string }; } | { t: 'conversation/handoff/save'; conversation: ConversationRef; handoff: Omit< ProjectHandoff, 'id' | 'projectId' | 'createdAt' | 'updatedAt' > & { id?: string }; } | { t: 'conversation/handoff/status'; conversation: ConversationRef; handoffId: string; status: HandoffStatus; } | { t: 'conversation/repository/add'; conversation: ConversationRef; provider: ProjectProvider; remoteUrl: string; defaultBranch: string; name?: string; } | { t: 'conversation/repository/remove'; conversation: ConversationRef; repositoryId: string; } | { t: 'conversation/artifact/save'; conversation: ConversationRef; artifact: Omit< ProjectArtifact, 'id' | 'projectId' | 'createdAt' | 'createdBy' > & { id?: string }; } | { t: 'conversation/artifact/delete'; conversation: ConversationRef; artifactId: string; } | { t: 'group/list' } | { t: 'group/create'; name: string; memberIds: string[]; workspaceSessionIds?: string[]; } | { t: 'group/rename'; groupId: string; name: string } | { t: 'group/setAnnouncement'; groupId: string; announcement: string } | { t: 'group/transferOwner'; groupId: string; newOwnerUserId: string } | { t: 'group/delete'; groupId: string } | { t: 'group/addHuman'; groupId: string; friendUserId: string } /** * 把一个已有 Session Agent 拉进群。群聊和工作目录私聊共用同一 Session, * 只替换当前回合的会话模式提示词与可用工具集。 * `workspaceAgentId` 仅保留给旧客户端兼容,不应再由新 UI 发出。 */ | { t: 'group/addAgent'; groupId: string; workspaceSessionId?: string; workspaceAgentId?: string; } | { t: 'group/setMemberPolicy'; groupId: string; memberId: string; policy: 'mention' | 'proactive' | 'all' | 'disabled'; } | { t: 'group/removeMember'; groupId: string; memberId: string } /** 叫停某个 agent 成员当前的活(只停这一次,不改它以后是否响应)。 */ | { t: 'group/abort'; groupId: string; memberId: string; taskId?: string } | { t: 'group/open'; groupId: string } | { t: 'group/send'; groupId: string; text: string; mentions?: string[]; attachments?: string[]; requestId?: string; } | { t: 'group/history'; groupId: string; beforeId?: string; limit?: number } | { t: 'group/read'; groupId: string; messageId: string } | { t: 'relay/device/register'; installationId: string; label?: string } | { t: 'relay/pull'; limit?: number } | { t: 'relay/ack'; eventId: string } | { t: 'relay/gap/request'; ranges: RelayMissingRange[] } | { t: 'relay/repair'; requestId: string; targetDeviceId: string; event: CollaborationEvent; } | { t: 'relay/publish'; requestId: string; event: CollaborationEventDraft } /** Publish a small set of related facts atomically (goal/confirmation/task). */ | { t: 'relay/publishBatch'; requestId: string; events: CollaborationEventDraft[]; } | { /** owner 对跨机指令同意请求的裁决;remember 记住信任(免以后再问)。 */ t: 'group/consentRespond'; requestId: string; decision: 'approve' | 'deny'; remember?: 'person' | 'group' | '30m'; scope?: DelegationScope; readScopes?: string[]; capabilities?: string[]; } | { /** Agent 主人主动撤销一项已批准的授权,并停止仍在运行的对应投递。 */ t: 'group/consentRevoke'; requestId: string; } | { t: 'agent/answer'; requestId: string; answers: AskAnswer[] } | { t: 'agent/questionCancel'; requestId: string } | { t: 'human-intervention/get'; requestId?: string; conversationKey?: string; runId?: string; } | { t: 'human-intervention/resume'; requestId?: string; interventionId: string; resumeToken: string; ownerId: string; conversationKey: string; runId: string; } | { t: 'human-intervention/cancel'; requestId?: string; interventionId: string; resumeToken: string; ownerId: string; conversationKey: string; runId: string; } // ---- Browser automation frames (product-grade) ---- | { t: 'browser/context/set'; conversationKey: string; runId?: string; requestId?: string; } // Mode control | { t: 'browser/start'; requestId?: string; headless?: boolean; viewport?: { width: number; height: number }; } | { t: 'browser/stop'; requestId?: string } | { t: 'browser/mode'; mode: 'browse' | 'assist' | 'auto'; requestId?: string; } | { t: 'browser/control/get'; requestId?: string } | { t: 'browser/control/takeover'; requestId?: string } | { t: 'browser/control/resume'; requestId?: string; resumeToken?: string } | { t: 'browser/control/stop'; requestId?: string; resumeToken?: string } // Tab management | { t: 'browser/tab/new'; requestId?: string; url?: string } | { t: 'browser/tab/close'; requestId?: string; tabId?: string } | { t: 'browser/tab/switch'; tabId: string; requestId?: string } | { t: 'browser/tabs'; requestId?: string } // Navigation (user-facing) | { t: 'browser/navigate'; requestId?: string; url: string; newTab?: boolean } | { t: 'browser/back'; requestId?: string } | { t: 'browser/forward'; requestId?: string } | { t: 'browser/reload'; requestId?: string } // AI interaction (Agent actions) | { t: 'browser/snapshot'; requestId?: string; interactive?: boolean } | { t: 'browser/screenshot'; requestId?: string; annotate?: boolean; fullPage?: boolean; path?: string; } | { t: 'browser/eval'; requestId?: string; js: string } | { t: 'browser/click'; requestId?: string; selector: string; byRef?: boolean; } | { t: 'browser/fill'; requestId?: string; selector: string; value: string } | { t: 'browser/type'; requestId?: string; selector: string; value: string } | { t: 'browser/hover'; requestId?: string; selector: string } | { t: 'browser/scroll'; requestId?: string; x?: number; y?: number; selector?: string; direction?: 'up' | 'down' | 'top' | 'bottom'; } | { t: 'browser/select'; requestId?: string; selector: string; value: string | string[]; } | { t: 'browser/press'; requestId?: string; key: string; selector?: string } | { t: 'browser/wait'; requestId?: string; ms?: number; selector?: string; text?: string; } | { t: 'browser/upload'; requestId?: string; selector: string; files: string[]; } | { t: 'browser/drag'; requestId?: string; fromSelector: string; toSelector: string; } // User input (browse mode - direct interaction via canvas) | { t: 'browser/user/input'; eventType: | 'mouseMoved' | 'mousePressed' | 'mouseReleased' | 'mouseWheel' | 'keyDown' | 'keyUp' | 'char'; x?: number; y?: number; button?: string; clickCount?: number; deltaX?: number; deltaY?: number; key?: string; code?: string; text?: string; modifiers?: number; windowsVirtualKeyCode?: number; } // JS dialog handling (alert/confirm/prompt) | { t: 'browser/dialog/accept'; requestId?: string; text?: string } | { t: 'browser/dialog/dismiss'; requestId?: string } // Agent pointer visualization (sent FROM server to UI to show where AI is acting) // Element marking (UI markers / pick mode) | { t: 'browser/pick'; requestId?: string; x: number; y: number } | { t: 'browser/mark/element'; requestId?: string; selector: string; label?: string; color?: string; } | { t: 'browser/mark/clear'; requestId?: string } | { t: 'browser/mark/mode'; enabled: boolean; requestId?: string } // Viewport & device | { t: 'browser/viewport'; width: number; height: number; requestId?: string } | { t: 'browser/device'; preset?: string; width?: number; height?: number; requestId?: string; } | { t: 'browser/media'; scheme?: 'light' | 'dark' | 'no-preference'; offline?: boolean; requestId?: string; } // Recording | { t: 'browser/record/start'; requestId?: string; path?: string } | { t: 'browser/record/stop'; requestId?: string } // Content extraction | { t: 'browser/getContent'; requestId?: string; selector?: string } | { t: 'browser/pdf'; requestId?: string; path?: string } // Cookies & auth | { t: 'browser/cookies/get'; requestId?: string } | { t: 'browser/cookies/set'; requestId?: string; cookies: Array<{ name: string; value: string; domain?: string; path?: string; }>; } | { t: 'browser/cookies/clear'; requestId?: string } | { t: 'browser/profile/clear'; requestId?: string } // Read-only developer diagnostics. Full CDP access remains a separate, disabled-by-default setting. | { t: 'browser/debug/console'; requestId?: string } | { t: 'browser/debug/errors'; requestId?: string } | { t: 'browser/debug/network'; requestId?: string } | { t: 'browser/debug/styles'; requestId?: string; selector?: string } | { t: 'browser/debug/vitals'; requestId?: string; url?: string } | { t: 'browser/debug/trace/start'; requestId?: string } | { t: 'browser/debug/trace/stop'; requestId?: string; path?: string } // Agent pointer visualization control (sent to frontend to show agent cursor) | { t: 'browser/agent/pointer'; x: number; y: number; visible: boolean; action?: 'move' | 'click' | 'type' | 'scroll' | 'idle' | 'hover'; elementRef?: string; } // Native desktop Computer Use is controlled by the trusted host. | { t: 'computer/status'; requestId?: string; conversationKey?: string; runId?: string; } | { t: 'computer/permissions'; requestId?: string } | { t: 'computer/observe'; requestId?: string; conversationKey: string; runId: string; } | { t: 'computer/control/takeover'; requestId?: string; conversationKey: string; runId: string; } | { t: 'computer/control/resume'; requestId?: string; conversationKey: string; runId: string; interventionId?: string; resumeToken?: string; ownerId?: string; } | { t: 'computer/control/stop'; requestId?: string; conversationKey: string; runId: string; interventionId?: string; resumeToken?: string; ownerId?: string; } | { t: 'computer/control/emergency-stop-all'; requestId?: string } // 终端不走 WS:改由 Tauri 原生真 PTY(minimal-desktop src-tauri/src/pty.rs)承载。 // ---- 工作台任意路径文件预览(工作目录内) ---- | { t: 'file/preview/open'; requestId: string; path: string }; export type ServerFrame = | { t: 'resource/learning/result'; requestId: string; workspaceId: string; value?: import('../memory/managementService.js').LearningManagementSnapshot; error?: string } | { t: 'runtime/hello'; protocolVersion: number; runtimeVersion: string; capabilities: string[]; } | { t: 'goal/snapshot'; requestId: string; goal?: import('../goal/types.js').Goal; error?: string; } | { t: 'human-intervention/started' | 'human-intervention/changed'; intervention: PendingHumanInterventionSummary & { ownerId: string; conversationKey: string; runId: string; resumeToken: string; expiresAt?: number; }; } | { t: 'human-intervention/resolved'; resolution: import('../humanIntervention.js').HumanInterventionResolution; } | { t: 'conversation/started'; result: ConversationStartResult } | { t: 'plain/sessions'; sessions: SessionSummary[] } | { t: 'plain/history'; sessionId: string; messages: Message[] } | { t: 'conversation/view/opened'; requestId: string; conversationKey: string; session?: SessionSummary; historyRevision: string; messages: Message[]; deliveries?: ConversationDelivery[]; assets?: ConversationAsset[]; artifactGroups?: ConversationArtifactGroup[]; runSnapshot?: ConversationRunSnapshot; contextUsage?: Extract; } | { t: 'conversation/delivery/changed'; conversationKey: string; delivery: ConversationDelivery; } | { t: 'conversation/assets/changed'; conversationKey: string; assets: ConversationAsset[]; } | { t: 'resource/files/list'; dir: string; sessionId: string; files: ConversationFileRef[]; } | { t: 'resource/assets/list'; requestId: string; conversationKey: string; assets?: ConversationAsset[]; error?: string; } | { t: 'resource/assets/pinned'; requestId: string; ok: boolean; error?: string; } | { t: 'resource/assets/opened'; requestId: string; ref?: ConversationFileRef; error?: string; } | { t: 'resource/assets/revealed'; requestId: string; ok: boolean; error?: string; } | { t: 'resource/files/opened'; requestId: string; ref?: ConversationFileRef; error?: string; } | { t: 'resource/files/revealed'; requestId: string; ok: boolean; error?: string; } | { t: 'resource/memories'; records: MemoryRecord[]; settings: MemorySettings; workspaceId?: string; reviewRecords?: MemoryRecord[]; persona?: PersonaDocument | null; } | { t: 'resource/memories/conversations'; requestId: string; results: ConversationSearchResult[]; error?: string; } | { t: 'resource/memories/manage/state'; requestId: string; state: MemoryManagementState; } | { t: 'resource/memories/manage/result'; requestId: string; action: MemoryManagementAction; ok: boolean; state?: MemoryManagementState; error?: string; conflict?: boolean; } | { t: 'resource/memories/overview'; requestId: string; overview?: MemoryCenterOverview; error?: string; } | { t: 'resource/memories/topics'; requestId: string; page?: MemoryTopicPage; error?: string; errorCode?: 'stale_cursor'; } | { t: 'resource/memories/topic'; requestId: string; detail?: MemoryTopicDetail; error?: string; } | { t: 'resource/context/status'; requestId: string; status?: ContextStatusView; error?: string; } | { t: 'resource/subagents/worktree/result'; requestId: string; action: 'diff' | 'apply' | 'discard'; ok: boolean; id: string; diff?: string; changedFiles?: string[]; error?: string; } | { t: 'ready'; dirs: RecentDir[]; workspaceIndex?: WorkspaceTreeEntry[]; defaultDir?: string; localAttachmentToken?: string; } | { t: 'workspace/index'; workspaces: WorkspaceTreeEntry[] } | { t: 'workspace/index/changed'; workspaces: WorkspaceTreeEntry[] } | { t: 'workspace/recovery'; applied: boolean; workspaces: number; sessions: number; recoverable: Array<{ fileName: string; reason: string; suggestedPath?: string; }>; } | { t: 'social/cache'; serverUrl: string; cache: OfflineSocialCache | null } | { t: 'social/outbox'; requestId: string; serverUrl: string; userId: string; items: SocialOutboxItem[]; } | { t: 'collaboration/outbox'; requestId: string; serverUrl: string; userId: string; items: CollaborationOutboxItem[]; } | { t: 'collaboration/read'; requestId: string; cursors: Record; } | { t: 'collaboration/device'; requestId: string; installationId: string; label: string; } | { t: 'collaboration/events/persisted'; requestId: string; eventIds: string[]; continuity?: LocalRelayContinuity; } | { t: 'collaboration/events'; requestId: string; events: CollaborationEvent[]; } | { t: 'collaboration/events/found'; requestId: string; events: CollaborationEvent[]; } | { t: 'dirs'; dirs: RecentDir[] } /** 局域网发现结果;空数组 = 没找到(网络受限时也走这条,不是错误)。 */ | { t: 'server/discovered'; servers: Array<{ url: string; version: string; protocolVersion: number; /** 同一台服务器的其它网卡地址;首选地址不通时可切换,不必重搜。 */ alternativeUrls: string[]; }>; } | { t: 'workspace/registered'; requestId: string; dir?: RecentDir; dirs?: RecentDir[]; error?: string; } | { t: 'dirListing'; listing: DirListing } | { t: 'archives'; dir: string; entries: ArchiveEntry[] } | { t: 'sessions'; dir: string; sessions: SessionSummary[] } | { t: 'history'; dir: string; sessionId?: string; messages: Message[] } | { t: 'event'; event: AgentEvent; dir?: string; sessionId: string; runId: string; sequence?: number; } | { t: 'conversation/run/snapshot'; snapshot: ConversationRunSnapshot } | { t: 'conversation/run/changed'; snapshots: ConversationRunSnapshot[]; maxConcurrent: number; } | { t: 'input/queue/changed'; items: QueuedUserInput[] } | { t: 'input/queue/started'; item: QueuedUserInput } | { t: 'config'; config: WebchatConfig | null } | { t: 'config/updated'; requestId: string; revision: number; config: WebchatConfig; } | { t: 'config/autosaved'; requestId: string; revision: number; state: 'applied' | 'draft'; config: WebchatConfig; draftFields?: string[]; } | { t: 'config/update-failed'; requestId: string; message: string; fieldErrors?: Record; currentRevision?: number; } | { t: 'config/tool/tested'; tool: ToolConfigName; ok: boolean; message: string; } | { t: 'config/model/tested'; requestId: string; ok: boolean; message: string; } | { t: 'skills'; skills: SkillInfo[]; dir?: string | null } | { t: 'server_error'; message: string } | { t: 'resource/crons/list'; tasks: CronTaskWithRuns[]; missedCount: number } | { t: 'resource/crons/draft'; draft: CronDraftResult } | { t: 'resource/crons/mutation'; requestId: string; ok: boolean; error?: string } | { t: 'resource/crons/show'; task: CronTaskWithRuns | null } | { t: 'resource/crons/missed'; missed: CronMissedRecord[] } | { t: 'resource/crons/changed'; tasks: CronTaskWithRuns[]; missedCount: number; } | { t: 'resource/commands/list'; commands: CommandDescriptor[]; requestId?: string; error?: string } | { t: 'social/me'; user: UserProfile | null } | { t: 'social/friends'; friends: FriendEntry[] } | { t: 'social/searchResults'; users: UserProfile[] } | { t: 'social/error'; message: string; requestId?: string } | { t: 'conversation/list'; conversations: DirectConversationSummary[] } | { t: 'conversation/navigation'; navigation: ConversationNavigation } | { t: 'conversation/detail'; conversation: DirectConversationSummary } | { t: 'conversation/message'; conversationId: string; message: DirectChatMessage; } | { t: 'conversation/sent'; requestId: string; conversationId: string; message: DirectChatMessage; } | { t: 'conversation/history'; conversationId: string; messages: DirectChatMessage[]; hasMore: boolean; } | { t: 'agent/direct/history'; workspaceSessionId: string; messages: AgentDirectMessage[]; } | { t: 'agent/direct/message'; workspaceSessionId: string; message: AgentDirectMessage; } | { t: 'agent/direct/event'; workspaceSessionId: string; event: AgentEvent } | { t: 'agent/direct/error'; workspaceSessionId?: string; message: string } | { t: 'conversation/actions'; kind: 'group' | 'direct' | 'agent'; id: string; actions: ConversationActionSuggestion[]; } | { t: 'node/pairing'; code: string; expiresAt: number } | { t: 'node/list'; nodes: AgentNodeSummary[] } | { t: 'workspace/list'; agents: WorkspaceAgent[]; sessions: WorkspaceSessionAgent[]; } | { t: 'conversation/workspace'; workspace: ConversationWorkspace | null } | { t: 'conversation/workspace/error'; message: string } | { t: 'group/list'; groups: GroupSummary[] } | { t: 'group/detail'; group: GroupDetail } | { t: 'group/message'; groupId: string; message: GroupChatMessage } | { t: 'group/sent'; requestId: string; groupId: string; message: GroupChatMessage; } | { t: 'group/history'; groupId: string; messages: GroupChatMessage[]; hasMore: boolean; } | { t: 'relay/device/registered'; deviceId: string; /** This device cannot receive relay history authored before this instant. */ historyStartsAt: number; /** True only when this installation was first enrolled for the account. */ newDevice: boolean; } | { t: 'relay/events'; deliveries: RelayDelivery[]; continuity?: RelayContinuityState; } | { t: 'relay/gap/candidates'; targetDeviceId: string; candidates: RelayGapCandidate[]; } | { t: 'relay/gap/requested'; request: RelayGapRepairRequest } | { t: 'relay/repaired'; requestId: string; eventId: string; targetDeviceId: string; } | { t: 'relay/published'; requestId: string; eventId: string } | { t: 'relay/publishedBatch'; requestId: string; eventIds: string[] } | { t: 'relay/acked'; eventId: string } | { t: 'relay/error'; code: string; message: string; retryable: boolean; requestId?: string; } /** agent 回合的流式预览增量(只推给正打开该群的连接);尽力而为,最终 group/message 是真值。 */ | { t: 'group/agentStream'; groupId: string; agentMemberId: string; displayName: string; delta: string; } | UserSocialEvent // ---- Browser automation server frames (product-grade) ---- | { t: 'browser/context/changed'; requestId?: string; conversationKey: string; runId: string; tabId?: string; } | { t: 'browser/started'; requestId?: string; streamPort: number; pid?: number; sessionId?: string; conversationKey?: string; runId?: string; } | { t: 'browser/stopped'; requestId?: string } | { t: 'browser/mode'; mode: 'browse' | 'assist' | 'auto'; requestId?: string; } | { t: 'browser/status'; connected: boolean; screencasting: boolean; viewportWidth: number; viewportHeight: number; engine: string; recording?: boolean; mode?: 'browse' | 'assist' | 'auto'; url?: string; title?: string; } | { t: 'browser/frame'; data: string; metadata?: Record; sessionId?: string; tabId?: string; conversationKey?: string; runId?: string; frameWidth?: number; frameHeight?: number; viewportWidth?: number; viewportHeight?: number; deviceScaleFactor?: number; pageRevision?: string; } | { t: 'browser/tabs'; tabs: Array<{ id: string; url: string; title?: string; active: boolean; favicon?: string; }>; timestamp?: number; } | { t: 'browser/tab/activated'; tabId: string } | { t: 'browser/url'; url: string; tabId?: string } | { t: 'browser/title'; title: string; tabId?: string } | { t: 'browser/navigation'; url: string; state: 'start' | 'commit' | 'load' | 'domcontentloaded'; } | { t: 'browser/console'; level?: string; text: string; source?: string } | { t: 'browser/page_error'; text: string } | { t: 'browser/download'; url: string; filename?: string; path?: string; state: 'start' | 'progress' | 'complete' | 'failed' | 'canceled'; id?: string; mime?: string; error?: string; receivedBytes?: number; totalBytes?: number; } | { t: 'browser/dialog'; type: 'alert' | 'confirm' | 'prompt' | 'beforeunload'; message: string; defaultValue?: string; } | { t: 'browser/snapshot'; requestId?: string; tree: string } | { t: 'browser/screenshot'; requestId?: string; path?: string; data?: string; error?: string; } | { t: 'browser/content'; requestId?: string; text: string } | { t: 'browser/picked'; requestId?: string; reference?: BrowserElementReference; ref?: string; tag?: string; text?: string; boundingBox?: { x: number; y: number; width: number; height: number }; attributes?: Record; error?: string; } | { t: 'browser/marked/elements'; elements: Array<{ ref: string; tag: string; text?: string; boundingBox?: { x: number; y: number; width: number; height: number }; }>; } | { t: 'browser/agent/pointer'; x: number; y: number; visible: boolean; action?: 'move' | 'click' | 'type' | 'scroll' | 'idle' | 'hover'; elementRef?: string; } | { t: 'browser/agent/acting'; acting: boolean; action?: string; target?: string; } /** * 一次定位失败后,引擎从当前页面挑出的最像目标的元素。 * * 送到面板是为了让**人**参与:AI 卡住时人一眼就能看出哪个才对,点一下把 @eN 喂回 * 对话,比让模型再猜一轮便宜得多。候选只进对话时,盯着浏览器的人只看到 AI 忽然停住。 */ | { t: 'browser/agent/candidates'; candidates: Array<{ ref: string; line: string }>; selector?: string; } /** * 一次动作**做完之后**的生效结论。只在结论不是「变了」时发。 * * ⚠️ 刻意**不复用** `browser/agent/acting`。acting 是一个瞬态信号(动作进行中), * 生命周期由 `beginAgentAction`/`finally` 界定;而结论恰恰诞生于动作结束那一刻, * 塞进 acting 会被紧随其后的 `acting:false` 立刻抹掉——那正是它上一版**在面板上 * 完全不可见**的原因(单测还是绿的,因为测的是字符串拆分不是可见性)。 * 结论是有独立生命周期的状态,就该有独立的帧。 */ | { t: 'browser/agent/outcome'; action: string; effect: 'unchanged' | 'unknown'; selector?: string; /** 被当作页面噪声豁免掉的行数(>0 表示这个结论有保留)。 */ maskedLines?: number; } | { t: 'browser/verification'; verificationId: string; status: 'passed' | 'failed' | 'inconclusive' | 'cancelled'; } | { t: 'browser/control/changed'; state: BrowserControlState } | { t: 'browser/challenge/detected'; reason: Exclude< import('../humanIntervention.js').HumanInterventionReason, 'manual' >; summary: string; resumeToken: string; runId: string; conversationKey?: string; } | { t: 'browser/result'; requestId?: string; action: string; ok: boolean; conversationKey?: string; runId?: string; tabId?: string; content?: string; error?: string; data?: unknown; } | { t: 'browser/cookies'; requestId?: string; cookies: Array<{ name: string; value: string; domain?: string; path?: string; }>; } | { t: 'browser/device'; preset?: string; width: number; height: number } | { t: 'browser/profile/status'; configured: boolean; profileId: 'default'; developerMode: boolean; engine: string; } | { t: 'browser/error'; message: string; code?: string } | { t: 'computer/status'; requestId?: string; available: boolean; serviceVersion?: string; implementation?: string; capabilities?: string[]; error?: string; } | { t: 'computer/permissions'; requestId?: string; permissions?: unknown; error?: string; } | { t: 'computer/observed'; requestId?: string; conversationKey: string; runId: string; state?: ComputerObservation; data?: unknown; error?: string; } /** * A privacy-preserving live action cue for the supervised Computer Use * workbench. It intentionally carries neither typed text nor an absolute * screen coordinate: x/y stay in the existing 0-1000 display-relative space. */ | { t: 'computer/action'; conversationKey: string; runId: string; action: string; x?: number; y?: number; displayId?: string; occurredAt: number; } | { t: 'computer/control/changed'; /** * ⚠️ **每个变体都必须带 `conversationKey` + `runId`,`idle` 也不例外。** * * 早先 `idle` 是唯一无作用域的变体,于是一个运行结束就广播一条「谁也不知道 * 说的是哪个会话」的空闲状态:另一个会话明明还在移鼠标,它的工作台却显示 * 「已就绪」。屏幕是唯一物理资源,这种误报比看不到状态更危险 —— 用户会以为 * 可以安全地去动键盘。 * * 真正全局的状态(服务不可用、helper 缺失)走 `computer/status`,不混进来。 */ state: | { owner: 'none'; status: 'idle'; conversationKey: string; runId: string; } | { owner: 'agent'; status: 'running'; conversationKey: string; runId: string; action?: string; targetApp?: string; } | { owner: 'user'; status: 'interactive'; conversationKey: string; runId: string; } | { owner: 'user'; status: 'waiting_human'; conversationKey: string; runId: string; reason: PendingHumanInterventionSummary['reason']; ownerId: string; interventionId: string; resumeToken: string; sanitizedSummary: string; } | { owner: 'none'; status: 'error'; conversationKey: string; runId: string; message: string; }; } // 终端不走 WS:改由 Tauri 原生真 PTY 承载(server 帧无 terminal/*)。 | { t: 'file/preview/opened'; requestId: string; ref?: ConversationFileRef; error?: string; } | { t: 'file/browse/result'; requestId: string; listing: FileBrowserListing }; export interface CommandDescriptor { id: string; slash: string; title: string; description: string; category: 'context' | 'collaboration' | 'workflow' | 'schedule' | 'system'; requiresWorkspace: boolean; available: boolean; unavailableReason?: string; argumentHint?: string; /** Public input descriptions; discovery remains owned by workflow-runner. */ workflowInputs?: Array<{ name: string; description?: string; required?: boolean; default?: unknown; type?: 'string' | 'number' | 'enum' | 'resource'; values?: string[]; greedy?: boolean; }>; } export type { AskAnswer, AskOption, AskQuestionSpec, AskSource, CronMissedRecord, CronRunRecord, CronTask, CronTaskDraft, CronTaskPatch, CronListFilter, LoopEvent, Message, ProgressStage, ToolCall, ToolResultMetadata, AgentResultMetadata, SubagentProgress, ToolProgressDetail, };