workspace.ts 12 KB

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