workspace.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /** Application-owned identities. Hermes profile/session IDs never identify a chat. */
  2. export type WorkspaceApprovalPolicy = 'ask' | 'allow' | 'deny'
  3. export type WorkspaceVoice='concise'|'casual'|'rigorous'|'custom'
  4. export type WorkspaceActBias='ask_first'|'ask_key_then_act'|'act_now'
  5. export interface WorkspaceAgent {
  6. modelSettings?: import('./botModelSettings.js').BotModelSettings | null
  7. /** Server-owned acknowledgement, bound to the resolved provider/model. */
  8. modelSettingsConfirmation?: string
  9. /** Server-owned native warning discovered while preparing an idle session. */
  10. modelSettingsPendingConfirmation?: { target: string; message: string }
  11. /** 一句话职责:这个 Bot 只做的一件事。 */
  12. job?: string
  13. /** 反任务清单:任何情况下都不做的事。 */
  14. antiJobs?: string[]
  15. voice?: WorkspaceVoice
  16. voiceCustom?: string
  17. actBias?: WorkspaceActBias
  18. /** Applied to new upstream approval requests; absent on older Bots means ask. */
  19. approvalPolicy?: WorkspaceApprovalPolicy
  20. canCollaborate?: boolean
  21. memoryEnabled?: boolean
  22. memoryStatus?: 'ready' | 'upgrade_required'
  23. id: string
  24. name: string
  25. avatar: string
  26. instructions: string
  27. /** Short standing identity, injected every turn. Absent on older records. */
  28. description?: string
  29. /** Explicit account-owner grant; absent on older records means disabled. */
  30. execution?: 'profile' | 'computer'
  31. computer?: 'auto' | 'cloud' | 'vm' | 'local' | 'browser' | 'off'
  32. /** Parallel environment toggles. Absent on older records: derive from computer. */
  33. envs?: { vm?: boolean; cloud?: boolean; desktop?: boolean; browser?: boolean }
  34. /** Bound computer: 'local' (loopback App) or a paired desktop-host id. */
  35. desktopHost?: string | null
  36. allowHostEnvironment?: boolean
  37. /** Local VM execution backend; older records retain the isolated Worker. */
  38. vmExecution?: 'worker' | 'profile'
  39. browserProfile?: 'persistent' | 'temporary'
  40. computerEnvironmentId?:string
  41. computerEnvironmentName?:string
  42. canManageTeam?: boolean
  43. teamAuthorizationVersion?: number
  44. temporaryGoalId?:string
  45. helperActivation?:number
  46. helperRunnerId?:string
  47. retiredAt?:number
  48. cleanupState?:'pending'|'complete'
  49. createdByAgentId?: string
  50. createdFromRunId?: string
  51. nodeId: string
  52. profile: string
  53. remoteAgentId?: string
  54. archived: boolean
  55. revision: number
  56. createdAt: number
  57. updatedAt: number
  58. }
  59. export interface AgentEnvs { vm:boolean; cloud:boolean; desktop:boolean; browser:boolean }
  60. /** Normalized parallel environments; legacy single-choice agents derive here. */
  61. export function agentEnvs(agent: Pick<WorkspaceAgent,'computer'|'envs'> & {execution?:'profile'|'computer'}): AgentEnvs {
  62. if(agent.envs)return {vm:agent.envs.vm===true,cloud:agent.envs.cloud===true,desktop:agent.envs.desktop===true,browser:false}
  63. if(agent.computer===undefined&&agent.execution==='computer')return {vm:true,cloud:false,desktop:false,browser:false}
  64. switch(agent.computer){
  65. case 'vm':return {vm:true,cloud:false,desktop:false,browser:false}
  66. case 'cloud':return {vm:false,cloud:true,desktop:false,browser:false}
  67. case 'local':return {vm:false,cloud:false,desktop:true,browser:false}
  68. case 'browser':return {vm:false,cloud:false,desktop:false,browser:false}
  69. case 'auto':return {vm:true,cloud:true,desktop:true,browser:false}
  70. default:return {vm:false,cloud:false,desktop:false,browser:false}
  71. }
  72. }
  73. /** Single-choice projection kept for older clients reading agent.computer. */
  74. export function deriveComputer(envs: Pick<AgentEnvs,'vm'|'cloud'|'desktop'|'browser'>): 'vm'|'cloud'|'local'|'browser'|'off' {
  75. return envs.vm?'vm':envs.cloud?'cloud':envs.desktop?'local':'off'
  76. }
  77. const VOICE_TEXT:Record<WorkspaceVoice,string>={concise:'简洁专业:直击要点,不用客套与废话。',casual:'轻松随和:像朋友一样自然交流,可以适度幽默。',rigorous:'严谨细致:条理清晰,重要结论给出依据,主动指出风险与前提。',custom:''}
  78. const ACT_BIAS_TEXT:Record<WorkspaceActBias,string>={ask_first:'先问再做:任务不明确时先向用户澄清,确认后再执行。',ask_key_then_act:'先问关键问题即行动:最多问 2–3 个关键问题,职责清楚后立即开始,边做边汇报。',act_now:'直接行动:合理默认即可开工,只在重要分叉点询问。'}
  79. /** Structured persona spec injected before free-form instructions. */
  80. export function personaSection(agent:Pick<WorkspaceAgent,'job'|'antiJobs'|'voice'|'voiceCustom'|'actBias'>):string{
  81. const lines:string[]=[]
  82. if(agent.job)lines.push(`你的唯一职责:${agent.job}`)
  83. if(agent.antiJobs?.length)lines.push(`明确不做(反任务,任何情况下都不要做):\n${agent.antiJobs.map(item=>`- ${item}`).join('\n')}`)
  84. const voice=agent.voice?(agent.voice==='custom'?(agent.voiceCustom?`按以下要求把握语气:${agent.voiceCustom}`:''):VOICE_TEXT[agent.voice]):''
  85. if(voice)lines.push(`语气:${voice}`)
  86. if(agent.actBias)lines.push(`行动策略:${ACT_BIAS_TEXT[agent.actBias]}`)
  87. return lines.join('\n')
  88. }
  89. /** Hermes toolsets a profile chat must not have. Checked environments use their own tools. */
  90. export const PROFILE_DENIED_TOOLSETS = ['terminal', 'file'] as const
  91. export function supportsHostEnvironment(agent: Pick<WorkspaceAgent,'computer'|'execution'>):boolean {
  92. return agent.computer==='vm'||agent.computer==='cloud'||(!agent.computer&&agent.execution==='computer')
  93. }
  94. export function allowsHostEnvironment(agent: Pick<WorkspaceAgent,'computer'|'execution'|'allowHostEnvironment'|'archived'|'remoteAgentId'|'temporaryGoalId'>):boolean {
  95. return agent.allowHostEnvironment===true&&supportsHostEnvironment(agent)&&!agent.archived&&!agent.remoteAgentId&&!agent.temporaryGoalId
  96. }
  97. export interface WorkspaceMemberRole {
  98. name: string
  99. description: string
  100. }
  101. export interface WorkspaceConversation {
  102. collaborationMode?: 'discussion' | 'host' | 'free'
  103. projectId?: string
  104. collaborationWaiting?: number
  105. id: string
  106. kind: 'direct' | 'group'
  107. name: string
  108. avatar: string
  109. memberIds: string[]
  110. memberRoles?: Record<string, WorkspaceMemberRole>
  111. instructions: string
  112. administratorId: string
  113. mode: 'host' | 'free'
  114. autoReplyIds: string[]
  115. maxReplyRounds: number
  116. archived: boolean
  117. pinned: boolean
  118. readSeq: number
  119. lastSeq: number
  120. lastMessageAt?: number
  121. preview: string
  122. previewAgentId?: string
  123. activeRunId?: string
  124. activeAgentId?: string
  125. activeRunStatus?: WorkspaceRun['status']
  126. activeAgentStates?: Record<string, 'running' | 'waiting' | 'uncertain' | 'queued'>
  127. avatarSignals?: Record<string, { id: string; state: 'success' | 'failure'; at: number }>
  128. queuedMessageCount?: number
  129. unread?: boolean
  130. /** Changes when new attention arrives, so an older read cannot clear it. */
  131. unreadVersion?: number
  132. /** Compatibility signal for older clients: always 0 or 1. */
  133. unreadCount?: number
  134. createdAt: number
  135. updatedAt: number
  136. }
  137. /** Shared by the HTTP lists, snapshots and Web/desktop incremental state. */
  138. export function workspaceConversationTimestamp(value: Pick<WorkspaceConversation, 'lastMessageAt' | 'createdAt'>): number {
  139. return value.lastMessageAt ?? value.createdAt
  140. }
  141. export function compareWorkspaceConversations(a: WorkspaceConversation, b: WorkspaceConversation): number {
  142. return Number(b.pinned) - Number(a.pinned)
  143. || workspaceConversationTimestamp(b) - workspaceConversationTimestamp(a)
  144. || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
  145. }
  146. export interface WorkspaceTask {
  147. id: string
  148. conversationId: string
  149. title: string
  150. titleSource: 'automatic' | 'user'
  151. messageCount: number
  152. readSeq: number
  153. lastSeq: number
  154. unread?: boolean
  155. unreadVersion?: number
  156. /** Compatibility signal for older clients: always 0 or 1. */
  157. unreadCount: number
  158. activeRunId?: string
  159. activeRunStatus?: WorkspaceRun['status']
  160. lastMessageAt?: number
  161. createdAt: number
  162. updatedAt: number
  163. goal?: import('./agentTasks.js').AgentGoal
  164. }
  165. export function workspaceHasUnread(value: { unread?: boolean; unreadCount?: number; lastSeq: number; readSeq: number }): boolean {
  166. return value.unread ?? (value.unreadCount !== undefined ? value.unreadCount > 0 : value.lastSeq > value.readSeq)
  167. }
  168. export interface WorkspaceFile {
  169. id: string
  170. name: string
  171. mimeType: string
  172. size: number
  173. createdAt: number
  174. sourcePath?: string
  175. conversationId?: string
  176. messageId?: string
  177. profile?: string
  178. sender: 'user' | 'agent'
  179. }
  180. export interface WorkspaceMessage {
  181. /** Completion version assigned once to the stable user-facing reply ID. */
  182. chatUnreadVersion?: number
  183. browserCard?: import('./managedBrowser.js').ManagedBrowserCard
  184. /** Server-owned, nonfatal availability notices; never model-authored markup. */
  185. serviceWarnings?: Array<{code:string;service:string;message:string}>
  186. communication?: WorkspaceCommunication
  187. peerMessageId?: string
  188. revision?: number
  189. execution?:'profile'|'computer'
  190. /** Computer the user was on when sending: 'local' (YaoYao server) or paired computer uuid. */
  191. deviceHost?: string
  192. id: string
  193. conversationId: string
  194. /** User-visible task scope. `taskId` below remains the scheduler turn ID. */
  195. conversationTaskId?: string
  196. seq: number
  197. role: 'user' | 'assistant' | 'system'
  198. taskReference?: { conversationId: string; taskId: string }
  199. agentId?: string
  200. agentName?: string
  201. content: string
  202. reasoning: string
  203. runId?: string
  204. taskId?: string
  205. visible?: boolean
  206. error?: string
  207. status: 'queued' | 'streaming' | 'complete' | 'failed' | 'interrupted' | 'uncertain'
  208. attachments: WorkspaceFile[]
  209. tools: Array<Record<string, unknown>>
  210. createdAt: number
  211. }
  212. export function workspaceHasUnfinishedOutput(messages: WorkspaceMessage[]): boolean {
  213. // Legacy transcripts may retain tool.generating after the turn has settled.
  214. // A terminal message status is authoritative over those stale tool events.
  215. return messages.some(message => message.visible !== false && message.role === 'assistant'
  216. && ['queued', 'streaming', 'uncertain'].includes(message.status))
  217. }
  218. export interface WorkspaceMessagePatch {
  219. id: string
  220. conversationId: string
  221. conversationTaskId?: string
  222. baseRevision: number
  223. revision: number
  224. contentAppend: string
  225. reasoningAppend: string
  226. }
  227. /** Presentation-only provenance for a real Bot-to-Bot delivery. */
  228. export interface WorkspaceCommunication {
  229. content?: string
  230. direction: 'outgoing' | 'incoming'
  231. peerId: string
  232. peerName: string
  233. peerAvatar: string
  234. peerKind: 'agent' | 'group'
  235. }
  236. export interface WorkspaceRun {
  237. projectId?: string
  238. peerMessageId?: string
  239. collaborationChainId?: string
  240. priority?: boolean
  241. discussion?: { memberIds: string[]; rounds: number }
  242. /** Copied from the triggering user message when present. */
  243. deviceHost?: string
  244. id: string
  245. conversationId: string
  246. conversationTaskId?: string
  247. messageId: string
  248. mentionIds: string[]
  249. activeAgentId?: string
  250. status: 'queued' | 'running' | 'waiting' | 'complete' | 'failed' | 'interrupted' | 'uncertain'
  251. round: number
  252. error?: string
  253. stopRequested?: boolean
  254. assignmentId?: string
  255. /** Structured delivery run; ordinary chat does not carry a goal. */
  256. goalId?: string
  257. targetAgentId?: string
  258. triggerKind?: 'assignment' | 'task_review' | 'task_result' | 'peer'
  259. internalInstruction?: string
  260. authorizationVersion?: number
  261. createdAt: number
  262. updatedAt: number
  263. }
  264. export interface WorkspaceInteraction {
  265. id: string
  266. conversationId: string
  267. conversationTaskId?: string
  268. runId: string
  269. agentId: string
  270. kind: 'approval' | 'clarification'
  271. message: string
  272. choices: string[]
  273. resolved: boolean
  274. }
  275. export interface WorkspaceEvent {
  276. seq: number
  277. type: string
  278. conversationId?: string
  279. data: unknown
  280. }
  281. /** Additional fields are optional while clients can still connect to older servers. */
  282. export interface WorkspaceSendReceipt {
  283. requestId?: string
  284. run: WorkspaceRun
  285. message?: WorkspaceMessage
  286. conversation?: WorkspaceConversation
  287. task?: WorkspaceTask | null
  288. cursor?: number
  289. }
  290. export interface WorkspaceSource {
  291. nodeId: string
  292. profile: string
  293. name: string
  294. }
  295. /** Per-agent token accounting derived from Hermes session usage deltas. */
  296. export interface WorkspaceAgentUsageSummary {
  297. input: number
  298. output: number
  299. total: number
  300. }
  301. export interface WorkspaceAgentUsage {
  302. agentId: string
  303. today: string
  304. month: string
  305. todayUsage: WorkspaceAgentUsageSummary
  306. monthUsage: WorkspaceAgentUsageSummary
  307. totalUsage: WorkspaceAgentUsageSummary
  308. daily: Array<{ date: string } & WorkspaceAgentUsageSummary>
  309. }