@swarmclawai/swarmclaw 0.5.2 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +42 -7
  2. package/bin/swarmclaw.js +76 -16
  3. package/next.config.ts +11 -1
  4. package/package.json +4 -2
  5. package/public/screenshots/agents.png +0 -0
  6. package/public/screenshots/dashboard.png +0 -0
  7. package/public/screenshots/providers.png +0 -0
  8. package/public/screenshots/tasks.png +0 -0
  9. package/scripts/postinstall.mjs +18 -0
  10. package/src/app/api/chatrooms/[id]/chat/route.ts +410 -0
  11. package/src/app/api/chatrooms/[id]/members/route.ts +82 -0
  12. package/src/app/api/chatrooms/[id]/pins/route.ts +39 -0
  13. package/src/app/api/chatrooms/[id]/reactions/route.ts +42 -0
  14. package/src/app/api/chatrooms/[id]/route.ts +84 -0
  15. package/src/app/api/chatrooms/route.ts +50 -0
  16. package/src/app/api/credentials/route.ts +2 -3
  17. package/src/app/api/knowledge/[id]/route.ts +13 -2
  18. package/src/app/api/knowledge/route.ts +8 -1
  19. package/src/app/api/memory/route.ts +8 -0
  20. package/src/app/api/notifications/[id]/route.ts +27 -0
  21. package/src/app/api/notifications/route.ts +68 -0
  22. package/src/app/api/orchestrator/run/route.ts +1 -1
  23. package/src/app/api/plugins/install/route.ts +2 -2
  24. package/src/app/api/search/route.ts +155 -0
  25. package/src/app/api/sessions/[id]/chat/route.ts +2 -0
  26. package/src/app/api/sessions/[id]/edit-resend/route.ts +1 -1
  27. package/src/app/api/sessions/[id]/fork/route.ts +1 -1
  28. package/src/app/api/sessions/route.ts +3 -3
  29. package/src/app/api/settings/route.ts +9 -0
  30. package/src/app/api/setup/check-provider/route.ts +3 -16
  31. package/src/app/api/skills/[id]/route.ts +6 -0
  32. package/src/app/api/skills/route.ts +6 -0
  33. package/src/app/api/tasks/[id]/route.ts +20 -0
  34. package/src/app/api/tasks/bulk/route.ts +100 -0
  35. package/src/app/api/tasks/route.ts +1 -0
  36. package/src/app/api/usage/route.ts +45 -0
  37. package/src/app/api/webhooks/[id]/route.ts +15 -1
  38. package/src/app/globals.css +58 -15
  39. package/src/app/page.tsx +142 -13
  40. package/src/cli/index.js +42 -0
  41. package/src/cli/index.test.js +30 -0
  42. package/src/cli/spec.js +32 -0
  43. package/src/components/agents/agent-avatar.tsx +57 -10
  44. package/src/components/agents/agent-card.tsx +48 -15
  45. package/src/components/agents/agent-chat-list.tsx +123 -10
  46. package/src/components/agents/agent-list.tsx +50 -19
  47. package/src/components/agents/agent-sheet.tsx +56 -63
  48. package/src/components/auth/access-key-gate.tsx +10 -3
  49. package/src/components/auth/setup-wizard.tsx +2 -2
  50. package/src/components/auth/user-picker.tsx +31 -3
  51. package/src/components/chat/activity-moment.tsx +169 -0
  52. package/src/components/chat/chat-header.tsx +2 -0
  53. package/src/components/chat/chat-tool-toggles.tsx +1 -1
  54. package/src/components/chat/file-path-chip.tsx +125 -0
  55. package/src/components/chat/markdown-utils.ts +9 -0
  56. package/src/components/chat/message-bubble.tsx +46 -295
  57. package/src/components/chat/message-list.tsx +50 -1
  58. package/src/components/chat/streaming-bubble.tsx +36 -46
  59. package/src/components/chat/suggestions-bar.tsx +1 -1
  60. package/src/components/chat/thinking-indicator.tsx +72 -10
  61. package/src/components/chat/tool-call-bubble.tsx +66 -70
  62. package/src/components/chat/tool-request-banner.tsx +31 -7
  63. package/src/components/chat/transfer-agent-picker.tsx +63 -0
  64. package/src/components/chatrooms/agent-hover-card.tsx +124 -0
  65. package/src/components/chatrooms/chatroom-input.tsx +320 -0
  66. package/src/components/chatrooms/chatroom-list.tsx +123 -0
  67. package/src/components/chatrooms/chatroom-message.tsx +427 -0
  68. package/src/components/chatrooms/chatroom-sheet.tsx +215 -0
  69. package/src/components/chatrooms/chatroom-tool-request-banner.tsx +134 -0
  70. package/src/components/chatrooms/chatroom-typing-bar.tsx +88 -0
  71. package/src/components/chatrooms/chatroom-view.tsx +344 -0
  72. package/src/components/chatrooms/reaction-picker.tsx +273 -0
  73. package/src/components/connectors/connector-sheet.tsx +34 -47
  74. package/src/components/home/home-view.tsx +501 -0
  75. package/src/components/input/chat-input.tsx +79 -41
  76. package/src/components/knowledge/knowledge-list.tsx +31 -1
  77. package/src/components/knowledge/knowledge-sheet.tsx +83 -2
  78. package/src/components/layout/app-layout.tsx +209 -83
  79. package/src/components/layout/mobile-header.tsx +2 -0
  80. package/src/components/layout/update-banner.tsx +2 -2
  81. package/src/components/logs/log-list.tsx +2 -2
  82. package/src/components/mcp-servers/mcp-server-sheet.tsx +1 -1
  83. package/src/components/memory/memory-agent-list.tsx +143 -0
  84. package/src/components/memory/memory-browser.tsx +205 -0
  85. package/src/components/memory/memory-card.tsx +34 -7
  86. package/src/components/memory/memory-detail.tsx +359 -120
  87. package/src/components/memory/memory-sheet.tsx +157 -23
  88. package/src/components/plugins/plugin-list.tsx +1 -1
  89. package/src/components/plugins/plugin-sheet.tsx +1 -1
  90. package/src/components/projects/project-detail.tsx +509 -0
  91. package/src/components/projects/project-list.tsx +195 -59
  92. package/src/components/providers/provider-list.tsx +2 -2
  93. package/src/components/providers/provider-sheet.tsx +3 -3
  94. package/src/components/schedules/schedule-card.tsx +3 -2
  95. package/src/components/schedules/schedule-list.tsx +1 -1
  96. package/src/components/schedules/schedule-sheet.tsx +25 -25
  97. package/src/components/secrets/secret-sheet.tsx +47 -24
  98. package/src/components/secrets/secrets-list.tsx +18 -8
  99. package/src/components/sessions/new-session-sheet.tsx +33 -65
  100. package/src/components/sessions/session-card.tsx +45 -14
  101. package/src/components/sessions/session-list.tsx +35 -18
  102. package/src/components/shared/agent-picker-list.tsx +90 -0
  103. package/src/components/shared/agent-switch-dialog.tsx +156 -0
  104. package/src/components/shared/attachment-chip.tsx +165 -0
  105. package/src/components/shared/avatar.tsx +10 -1
  106. package/src/components/shared/check-icon.tsx +12 -0
  107. package/src/components/shared/confirm-dialog.tsx +1 -1
  108. package/src/components/shared/empty-state.tsx +32 -0
  109. package/src/components/shared/file-preview.tsx +34 -0
  110. package/src/components/shared/form-styles.ts +2 -0
  111. package/src/components/shared/keyboard-shortcuts-dialog.tsx +116 -0
  112. package/src/components/shared/notification-center.tsx +223 -0
  113. package/src/components/shared/profile-sheet.tsx +115 -0
  114. package/src/components/shared/reply-quote.tsx +26 -0
  115. package/src/components/shared/search-dialog.tsx +296 -0
  116. package/src/components/shared/section-label.tsx +12 -0
  117. package/src/components/shared/settings/plugin-manager.tsx +1 -1
  118. package/src/components/shared/settings/section-providers.tsx +1 -1
  119. package/src/components/shared/settings/section-secrets.tsx +1 -1
  120. package/src/components/shared/settings/section-theme.tsx +95 -0
  121. package/src/components/shared/settings/section-user-preferences.tsx +39 -0
  122. package/src/components/shared/settings/settings-page.tsx +180 -27
  123. package/src/components/shared/settings/settings-sheet.tsx +9 -73
  124. package/src/components/shared/sheet-footer.tsx +33 -0
  125. package/src/components/skills/skill-list.tsx +61 -30
  126. package/src/components/skills/skill-sheet.tsx +81 -2
  127. package/src/components/tasks/task-board.tsx +448 -26
  128. package/src/components/tasks/task-card.tsx +46 -9
  129. package/src/components/tasks/task-column.tsx +62 -3
  130. package/src/components/tasks/task-list.tsx +12 -4
  131. package/src/components/tasks/task-sheet.tsx +89 -72
  132. package/src/components/ui/hover-card.tsx +52 -0
  133. package/src/components/usage/metrics-dashboard.tsx +78 -0
  134. package/src/components/usage/usage-list.tsx +1 -1
  135. package/src/components/webhooks/webhook-sheet.tsx +1 -1
  136. package/src/hooks/use-view-router.ts +69 -19
  137. package/src/instrumentation.ts +15 -1
  138. package/src/lib/chat.ts +2 -0
  139. package/src/lib/cron-human.ts +114 -0
  140. package/src/lib/memory.ts +3 -0
  141. package/src/lib/server/chat-execution.ts +24 -4
  142. package/src/lib/server/connectors/manager.ts +11 -0
  143. package/src/lib/server/context-manager.ts +225 -13
  144. package/src/lib/server/create-notification.ts +42 -0
  145. package/src/lib/server/daemon-state.ts +165 -10
  146. package/src/lib/server/execution-log.ts +1 -0
  147. package/src/lib/server/heartbeat-service.ts +40 -5
  148. package/src/lib/server/heartbeat-wake.ts +110 -0
  149. package/src/lib/server/langgraph-checkpoint.ts +1 -0
  150. package/src/lib/server/memory-consolidation.ts +92 -0
  151. package/src/lib/server/memory-db.ts +51 -6
  152. package/src/lib/server/openclaw-gateway.ts +9 -1
  153. package/src/lib/server/provider-health.ts +125 -0
  154. package/src/lib/server/queue.ts +5 -4
  155. package/src/lib/server/scheduler.ts +8 -0
  156. package/src/lib/server/session-run-manager.ts +4 -0
  157. package/src/lib/server/session-tools/chatroom.ts +136 -0
  158. package/src/lib/server/session-tools/context-mgmt.ts +36 -18
  159. package/src/lib/server/session-tools/index.ts +2 -0
  160. package/src/lib/server/session-tools/memory.ts +6 -1
  161. package/src/lib/server/storage.ts +80 -29
  162. package/src/lib/server/stream-agent-chat.ts +153 -47
  163. package/src/lib/server/system-events.ts +49 -0
  164. package/src/lib/server/ws-hub.ts +11 -0
  165. package/src/lib/soul-suggestions.ts +109 -0
  166. package/src/lib/tasks.ts +4 -1
  167. package/src/lib/view-routes.ts +36 -1
  168. package/src/lib/ws-client.ts +14 -4
  169. package/src/proxy.ts +79 -2
  170. package/src/stores/use-app-store.ts +94 -3
  171. package/src/stores/use-chat-store.ts +48 -3
  172. package/src/stores/use-chatroom-store.ts +276 -0
  173. package/src/types/index.ts +69 -2
@@ -0,0 +1,50 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { genId } from '@/lib/id'
3
+ import { loadChatrooms, saveChatrooms, loadAgents } from '@/lib/server/storage'
4
+ import { notify } from '@/lib/server/ws-hub'
5
+ import type { Chatroom, ChatroomMessage } from '@/types'
6
+
7
+ export const dynamic = 'force-dynamic'
8
+
9
+ export async function GET() {
10
+ const chatrooms = loadChatrooms()
11
+ return NextResponse.json(chatrooms)
12
+ }
13
+
14
+ export async function POST(req: Request) {
15
+ const body = await req.json()
16
+ const chatrooms = loadChatrooms()
17
+ const id = genId()
18
+
19
+ const agentIds: string[] = Array.isArray(body.agentIds) ? body.agentIds : []
20
+ const now = Date.now()
21
+
22
+ // Generate join messages for initial agents
23
+ const agents = agentIds.length > 0 ? loadAgents() : {}
24
+ const joinMessages: ChatroomMessage[] = agentIds.map((agentId: string, i: number) => ({
25
+ id: genId(),
26
+ senderId: 'system',
27
+ senderName: 'System',
28
+ role: 'assistant',
29
+ text: `${agents[agentId]?.name || 'Unknown agent'} has joined the chat`,
30
+ mentions: [],
31
+ reactions: [],
32
+ time: now + i, // offset by 1ms so they sort in order
33
+ }))
34
+
35
+ const chatroom: Chatroom = {
36
+ id,
37
+ name: body.name || 'New Chatroom',
38
+ description: body.description || '',
39
+ agentIds,
40
+ messages: joinMessages,
41
+ createdAt: now,
42
+ updatedAt: now,
43
+ }
44
+
45
+ chatrooms[id] = chatroom
46
+ saveChatrooms(chatrooms)
47
+ notify('chatrooms')
48
+
49
+ return NextResponse.json(chatroom)
50
+ }
@@ -6,8 +6,8 @@ export const dynamic = 'force-dynamic'
6
6
 
7
7
  export async function GET(_req: Request) {
8
8
  const creds = loadCredentials()
9
- const safe: Record<string, any> = {}
10
- for (const [id, c] of Object.entries(creds) as [string, any][]) {
9
+ const safe: Record<string, Record<string, unknown>> = {}
10
+ for (const [id, c] of Object.entries(creds) as [string, Record<string, unknown>][]) {
11
11
  safe[id] = { id: c.id, provider: c.provider, name: c.name, createdAt: c.createdAt }
12
12
  }
13
13
  return NextResponse.json(safe)
@@ -28,6 +28,5 @@ export async function POST(req: Request) {
28
28
  createdAt: Date.now(),
29
29
  }
30
30
  saveCredentials(creds)
31
- console.log(`[credentials] stored ${id} for ${provider}`)
32
31
  return NextResponse.json({ id, provider, name: creds[id].name, createdAt: creds[id].createdAt })
33
32
  }
@@ -25,7 +25,7 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
25
25
  return NextResponse.json({ error: 'Invalid JSON body.' }, { status: 400 })
26
26
  }
27
27
 
28
- const { title, content, tags } = body as Record<string, unknown>
28
+ const { title, content, tags, scope, agentIds } = body as Record<string, unknown>
29
29
 
30
30
  const updates: Record<string, unknown> = {}
31
31
  if (typeof title === 'string' && title.trim()) {
@@ -36,13 +36,24 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
36
36
  }
37
37
 
38
38
  const existingMeta = (existing.metadata || {}) as Record<string, unknown>
39
+ const metaUpdates: Record<string, unknown> = { ...existingMeta }
40
+
39
41
  if (Array.isArray(tags)) {
40
42
  const normalizedTags = (tags as unknown[]).filter(
41
43
  (t): t is string => typeof t === 'string' && t.trim().length > 0,
42
44
  )
43
- updates.metadata = { ...existingMeta, tags: normalizedTags }
45
+ metaUpdates.tags = normalizedTags
46
+ }
47
+
48
+ if (scope === 'global' || scope === 'agent') {
49
+ metaUpdates.scope = scope
50
+ metaUpdates.agentIds = scope === 'agent' && Array.isArray(agentIds)
51
+ ? (agentIds as unknown[]).filter((id): id is string => typeof id === 'string')
52
+ : []
44
53
  }
45
54
 
55
+ updates.metadata = metaUpdates
56
+
46
57
  const updated = db.update(id, updates)
47
58
  if (!updated) {
48
59
  return notFound()
@@ -25,7 +25,7 @@ export async function POST(req: Request) {
25
25
  return NextResponse.json({ error: 'Invalid JSON body.' }, { status: 400 })
26
26
  }
27
27
 
28
- const { title, content, tags } = body as Record<string, unknown>
28
+ const { title, content, tags, scope, agentIds } = body as Record<string, unknown>
29
29
 
30
30
  if (typeof title !== 'string' || !title.trim()) {
31
31
  return NextResponse.json({ error: 'title is required.' }, { status: 400 })
@@ -38,10 +38,17 @@ export async function POST(req: Request) {
38
38
  ? (tags as unknown[]).filter((t): t is string => typeof t === 'string' && t.trim().length > 0)
39
39
  : undefined
40
40
 
41
+ const normalizedScope = scope === 'agent' ? 'agent' as const : 'global' as const
42
+ const normalizedAgentIds = Array.isArray(agentIds)
43
+ ? (agentIds as unknown[]).filter((id): id is string => typeof id === 'string')
44
+ : []
45
+
41
46
  const entry = addKnowledge({
42
47
  title: title.trim(),
43
48
  content,
44
49
  tags: normalizedTags,
50
+ scope: normalizedScope,
51
+ agentIds: normalizedAgentIds,
45
52
  })
46
53
 
47
54
  return NextResponse.json(entry)
@@ -26,7 +26,13 @@ export async function GET(req: Request) {
26
26
  const requestedLimit = parseOptionalInt(searchParams.get('limit'))
27
27
  const requestedLinkedLimit = parseOptionalInt(searchParams.get('linkedLimit'))
28
28
 
29
+ const counts = searchParams.get('counts') === 'true'
29
30
  const db = getMemoryDb()
31
+
32
+ if (counts) {
33
+ return NextResponse.json(db.countsByAgent())
34
+ }
35
+
30
36
  const defaults = getMemoryLookupLimits()
31
37
  const limits = resolveLookupRequest(defaults, {
32
38
  depth: requestedDepth,
@@ -106,6 +112,8 @@ export async function POST(req: Request) {
106
112
  image: image as MemoryImage | null | undefined,
107
113
  imagePath: image && typeof image === 'object' && 'path' in image ? String((image as { path: string }).path) : null,
108
114
  linkedMemoryIds: body.linkedMemoryIds as string[] | undefined,
115
+ pinned: body.pinned === true,
116
+ sharedWith: Array.isArray(body.sharedWith) ? body.sharedWith as string[] : undefined,
109
117
  })
110
118
  return NextResponse.json(entry)
111
119
  }
@@ -0,0 +1,27 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { loadNotifications, markNotificationRead, deleteNotification } from '@/lib/server/storage'
3
+ import { notify } from '@/lib/server/ws-hub'
4
+
5
+ export async function PUT(_req: Request, { params }: { params: Promise<{ id: string }> }) {
6
+ const { id } = await params
7
+ const all = loadNotifications()
8
+ if (!all[id]) {
9
+ return NextResponse.json({ error: 'Not found' }, { status: 404 })
10
+ }
11
+
12
+ markNotificationRead(id)
13
+ notify('notifications')
14
+ return NextResponse.json({ ok: true })
15
+ }
16
+
17
+ export async function DELETE(_req: Request, { params }: { params: Promise<{ id: string }> }) {
18
+ const { id } = await params
19
+ const all = loadNotifications()
20
+ if (!all[id]) {
21
+ return NextResponse.json({ error: 'Not found' }, { status: 404 })
22
+ }
23
+
24
+ deleteNotification(id)
25
+ notify('notifications')
26
+ return NextResponse.json({ ok: true })
27
+ }
@@ -0,0 +1,68 @@
1
+ import { NextResponse } from 'next/server'
2
+ import { genId } from '@/lib/id'
3
+ import { loadNotifications, saveNotification, deleteNotification } from '@/lib/server/storage'
4
+ import { notify } from '@/lib/server/ws-hub'
5
+ import type { AppNotification } from '@/types'
6
+ export const dynamic = 'force-dynamic'
7
+
8
+ export async function GET(req: Request) {
9
+ const { searchParams } = new URL(req.url)
10
+ const unreadOnly = searchParams.get('unreadOnly') === 'true'
11
+ const limit = Math.min(200, Math.max(1, Number(searchParams.get('limit')) || 100))
12
+
13
+ const all = loadNotifications()
14
+ let entries = Object.values(all) as AppNotification[]
15
+
16
+ if (unreadOnly) {
17
+ entries = entries.filter((e) => !e.read)
18
+ }
19
+
20
+ entries.sort((a, b) => b.createdAt - a.createdAt)
21
+ entries = entries.slice(0, limit)
22
+
23
+ return NextResponse.json(entries)
24
+ }
25
+
26
+ export async function POST(req: Request) {
27
+ const body = (await req.json()) as Record<string, unknown>
28
+ const actionLabel = typeof body.actionLabel === 'string' ? body.actionLabel : undefined
29
+ const actionUrl = typeof body.actionUrl === 'string' ? body.actionUrl : undefined
30
+ const id = genId()
31
+ const notification: AppNotification = {
32
+ id,
33
+ type: (['info', 'success', 'warning', 'error'].includes(body.type as string) ? body.type : 'info') as AppNotification['type'],
34
+ title: typeof body.title === 'string' ? body.title : 'Notification',
35
+ message: typeof body.message === 'string' ? body.message : undefined,
36
+ actionLabel,
37
+ actionUrl,
38
+ entityType: typeof body.entityType === 'string' ? body.entityType : undefined,
39
+ entityId: typeof body.entityId === 'string' ? body.entityId : undefined,
40
+ read: false,
41
+ createdAt: Date.now(),
42
+ }
43
+
44
+ saveNotification(id, notification)
45
+ notify('notifications')
46
+ return NextResponse.json(notification, { status: 201 })
47
+ }
48
+
49
+ export async function DELETE(req: Request) {
50
+ const { searchParams } = new URL(req.url)
51
+ const specificId = searchParams.get('id')
52
+
53
+ if (specificId) {
54
+ deleteNotification(specificId)
55
+ } else {
56
+ // Clear all read notifications
57
+ const all = loadNotifications()
58
+ for (const raw of Object.values(all)) {
59
+ const entry = raw as AppNotification
60
+ if (entry.read) {
61
+ deleteNotification(entry.id)
62
+ }
63
+ }
64
+ }
65
+
66
+ notify('notifications')
67
+ return NextResponse.json({ ok: true })
68
+ }
@@ -4,7 +4,7 @@ import { loadAgents, loadTasks, saveTasks } from '@/lib/server/storage'
4
4
  import { enqueueTask } from '@/lib/server/queue'
5
5
 
6
6
  export async function POST(req: Request) {
7
- const { agentId, task } = await req.json()
7
+ const { agentId, task } = await req.json().catch(() => ({}))
8
8
  if (!agentId || !task) {
9
9
  return NextResponse.json({ error: 'agentId and task are required' }, { status: 400 })
10
10
  }
@@ -49,9 +49,9 @@ export async function POST(req: Request) {
49
49
  fs.writeFileSync(dest, code, 'utf8')
50
50
 
51
51
  return NextResponse.json({ ok: true, filename: sanitized })
52
- } catch (err: any) {
52
+ } catch (err: unknown) {
53
53
  return NextResponse.json(
54
- { error: 'Failed to install plugin', message: err.message },
54
+ { error: 'Failed to install plugin', message: err instanceof Error ? err.message : String(err) },
55
55
  { status: 500 },
56
56
  )
57
57
  }
@@ -0,0 +1,155 @@
1
+ import { NextResponse } from 'next/server'
2
+ import {
3
+ loadTasks,
4
+ loadAgents,
5
+ loadSessions,
6
+ loadSchedules,
7
+ loadWebhooks,
8
+ loadSkills,
9
+ } from '@/lib/server/storage'
10
+
11
+ interface SearchResult {
12
+ type: 'task' | 'agent' | 'session' | 'schedule' | 'webhook' | 'skill' | 'message'
13
+ id: string
14
+ title: string
15
+ description?: string
16
+ status?: string
17
+ messageIndex?: number
18
+ }
19
+
20
+ const MAX_RESULTS = 20
21
+
22
+ function matches(haystack: string | undefined | null, needle: string): boolean {
23
+ if (!haystack) return false
24
+ return haystack.toLowerCase().includes(needle)
25
+ }
26
+
27
+ function searchCollection(
28
+ collection: Record<string, Record<string, unknown>>,
29
+ type: SearchResult['type'],
30
+ needle: string,
31
+ titleKey: string,
32
+ descKey: string,
33
+ statusKey?: string,
34
+ ): SearchResult[] {
35
+ const results: SearchResult[] = []
36
+ for (const [id, item] of Object.entries(collection)) {
37
+ const title = item[titleKey] as string | undefined
38
+ const desc = item[descKey] as string | undefined
39
+ const idStr = typeof item.id === 'string' ? item.id : id
40
+ if (matches(title, needle) || matches(desc, needle) || matches(idStr, needle)) {
41
+ results.push({
42
+ type,
43
+ id,
44
+ title: title || idStr || id,
45
+ description: desc ? desc.slice(0, 120) : undefined,
46
+ status: statusKey ? (item[statusKey] as string | undefined) : undefined,
47
+ })
48
+ }
49
+ }
50
+ return results
51
+ }
52
+
53
+ function searchMessages(
54
+ sessions: Record<string, Record<string, unknown>>,
55
+ agents: Record<string, Record<string, unknown>>,
56
+ needle: string,
57
+ ): SearchResult[] {
58
+ const results: SearchResult[] = []
59
+ const MAX_MSG_RESULTS = 10
60
+ for (const [sessionId, session] of Object.entries(sessions)) {
61
+ if (results.length >= MAX_MSG_RESULTS) break
62
+ const messages = session.messages as Array<{ role: string; text: string; time?: number }> | undefined
63
+ if (!messages?.length) continue
64
+ const agentId = session.agentId as string | undefined
65
+ const agentName = agentId && agents[agentId] ? (agents[agentId].name as string) : undefined
66
+ const sessionName = (session.name as string) || 'Untitled'
67
+ for (let i = 0; i < messages.length; i++) {
68
+ if (results.length >= MAX_MSG_RESULTS) break
69
+ const msg = messages[i]
70
+ if (!msg?.text) continue
71
+ const idx = msg.text.toLowerCase().indexOf(needle)
72
+ if (idx === -1) continue
73
+ // Build snippet with context around match
74
+ const start = Math.max(0, idx - 30)
75
+ const end = Math.min(msg.text.length, idx + needle.length + 50)
76
+ const snippet = (start > 0 ? '...' : '') + msg.text.slice(start, end).replace(/\n/g, ' ') + (end < msg.text.length ? '...' : '')
77
+ const timeAgo = msg.time ? formatTimeAgo(msg.time) : ''
78
+ results.push({
79
+ type: 'message',
80
+ id: sessionId,
81
+ title: snippet,
82
+ description: [agentName || sessionName, timeAgo].filter(Boolean).join(' · '),
83
+ messageIndex: i,
84
+ })
85
+ }
86
+ }
87
+ return results
88
+ }
89
+
90
+ function formatTimeAgo(ts: number): string {
91
+ const diff = Date.now() - ts
92
+ const mins = Math.floor(diff / 60000)
93
+ if (mins < 1) return 'just now'
94
+ if (mins < 60) return `${mins}m ago`
95
+ const hours = Math.floor(mins / 60)
96
+ if (hours < 24) return `${hours}h ago`
97
+ const days = Math.floor(hours / 24)
98
+ return `${days}d ago`
99
+ }
100
+
101
+ export async function GET(req: Request) {
102
+ const { searchParams } = new URL(req.url)
103
+ const q = (searchParams.get('q') || '').trim().toLowerCase()
104
+
105
+ if (q.length < 2) {
106
+ return NextResponse.json({ results: [] })
107
+ }
108
+
109
+ const tasks = loadTasks() as Record<string, Record<string, unknown>>
110
+ const agents = loadAgents() as Record<string, Record<string, unknown>>
111
+ const sessions = loadSessions() as Record<string, Record<string, unknown>>
112
+ const schedules = loadSchedules() as Record<string, Record<string, unknown>>
113
+ const webhooks = loadWebhooks() as Record<string, Record<string, unknown>>
114
+ const skills = loadSkills() as Record<string, Record<string, unknown>>
115
+
116
+ const buckets: SearchResult[][] = [
117
+ searchCollection(agents, 'agent', q, 'name', 'description'),
118
+ searchCollection(tasks, 'task', q, 'title', 'description', 'status'),
119
+ searchCollection(sessions, 'session', q, 'name', 'cwd'),
120
+ searchCollection(schedules, 'schedule', q, 'name', 'taskPrompt', 'status'),
121
+ searchCollection(webhooks, 'webhook', q, 'name', 'source'),
122
+ searchCollection(skills, 'skill', q, 'name', 'description'),
123
+ searchMessages(sessions, agents, q),
124
+ ]
125
+
126
+ // Proportional allocation across types
127
+ const totalRaw = buckets.reduce((s, b) => s + b.length, 0)
128
+ if (totalRaw === 0) {
129
+ return NextResponse.json({ results: [] })
130
+ }
131
+
132
+ const results: SearchResult[] = []
133
+ if (totalRaw <= MAX_RESULTS) {
134
+ for (const bucket of buckets) results.push(...bucket)
135
+ } else {
136
+ // Give each bucket a fair share, round-robin leftover slots
137
+ const perBucket = Math.floor(MAX_RESULTS / buckets.length)
138
+ let remaining = MAX_RESULTS
139
+ for (const bucket of buckets) {
140
+ const take = Math.min(bucket.length, perBucket)
141
+ results.push(...bucket.slice(0, take))
142
+ remaining -= take
143
+ }
144
+ // Fill remaining slots from buckets that had more
145
+ for (const bucket of buckets) {
146
+ if (remaining <= 0) break
147
+ const alreadyTaken = Math.min(bucket.length, perBucket)
148
+ const extra = bucket.slice(alreadyTaken, alreadyTaken + remaining)
149
+ results.push(...extra)
150
+ remaining -= extra.length
151
+ }
152
+ }
153
+
154
+ return NextResponse.json({ results })
155
+ }
@@ -17,6 +17,7 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
17
17
  const attachedFiles = Array.isArray(body.attachedFiles) ? body.attachedFiles.filter((f: unknown) => typeof f === 'string') as string[] : undefined
18
18
  const internal = body.internal === true
19
19
  const queueMode = normalizeQueueMode(body.queueMode, internal)
20
+ const replyToId = typeof body.replyToId === 'string' ? body.replyToId : undefined
20
21
 
21
22
  const hasFiles = !!(imagePath || imageUrl || (attachedFiles && attachedFiles.length > 0))
22
23
  if (!message.trim() && !hasFiles) {
@@ -46,6 +47,7 @@ export async function POST(req: Request, { params }: { params: Promise<{ id: str
46
47
  source: internal ? 'heartbeat' : 'chat',
47
48
  mode: queueMode,
48
49
  onEvent: (ev) => writeEvent(ev as unknown as Record<string, unknown>),
50
+ replyToId,
49
51
  })
50
52
 
51
53
  log.info('chat', `Enqueued session run ${run.runId}`, {
@@ -4,7 +4,7 @@ import { notFound } from '@/lib/server/collection-helpers'
4
4
 
5
5
  export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
6
6
  const { id } = await params
7
- const body = await req.json() as { messageIndex: number; newText: string }
7
+ const body = await req.json().catch(() => ({})) as { messageIndex: number; newText: string }
8
8
  const sessions = loadSessions()
9
9
  const session = sessions[id]
10
10
  if (!session) return notFound()
@@ -5,7 +5,7 @@ import { notFound } from '@/lib/server/collection-helpers'
5
5
 
6
6
  export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
7
7
  const { id } = await params
8
- const body = await req.json() as { messageIndex: number }
8
+ const body = await req.json().catch(() => ({})) as { messageIndex: number }
9
9
  const sessions = loadSessions()
10
10
  const source = sessions[id]
11
11
  if (!source) return notFound()
@@ -23,7 +23,7 @@ export async function GET(_req: Request) {
23
23
  }
24
24
 
25
25
  export async function DELETE(req: Request) {
26
- const { ids } = await req.json() as { ids: string[] }
26
+ const { ids } = await req.json().catch(() => ({ ids: [] })) as { ids: string[] }
27
27
  if (!Array.isArray(ids) || !ids.length) {
28
28
  return new NextResponse('Missing ids', { status: 400 })
29
29
  }
@@ -43,7 +43,7 @@ export async function DELETE(req: Request) {
43
43
  }
44
44
 
45
45
  export async function POST(req: Request) {
46
- const body = await req.json()
46
+ const body = await req.json().catch(() => ({}))
47
47
  let cwd = (body.cwd || '').trim()
48
48
  if (cwd.startsWith('~/')) cwd = path.join(os.homedir(), cwd.slice(2))
49
49
  else if (cwd === '~') cwd = os.homedir()
@@ -64,7 +64,7 @@ export async function POST(req: Request) {
64
64
 
65
65
  sessions[id] = {
66
66
  id, name: sessionName, cwd,
67
- user: body.user || 'wayde',
67
+ user: body.user || 'user',
68
68
  provider: body.provider || agent?.provider || 'claude-cli',
69
69
  model: body.model || agent?.model || '',
70
70
  credentialId: body.credentialId || agent?.credentialId || null,
@@ -56,5 +56,14 @@ export async function PUT(req: Request) {
56
56
  settings.maxLinkedMemoriesExpanded = nextLinked
57
57
 
58
58
  saveSettings(settings)
59
+
60
+ // Restart heartbeat service when heartbeat-related settings change
61
+ const heartbeatKeys = ['heartbeatIntervalSec', 'heartbeatInterval', 'heartbeatPrompt', 'heartbeatEnabled', 'heartbeatActiveStart', 'heartbeatActiveEnd']
62
+ if (heartbeatKeys.some((k) => k in body)) {
63
+ import('@/lib/server/heartbeat-service').then(({ restartHeartbeatService }) => {
64
+ restartHeartbeatService()
65
+ }).catch(() => { /* heartbeat service may not be initialized yet */ })
66
+ }
67
+
59
68
  return NextResponse.json(settings)
60
69
  }
@@ -1,6 +1,7 @@
1
1
  import { NextResponse } from 'next/server'
2
2
  import { loadCredentials, decryptKey } from '@/lib/server/storage'
3
3
  import { getDeviceId, wsConnect } from '@/lib/providers/openclaw'
4
+ import { OPENAI_COMPATIBLE_DEFAULTS } from '@/lib/server/provider-health'
4
5
 
5
6
  type SetupProvider =
6
7
  | 'openai'
@@ -15,20 +16,6 @@ type SetupProvider =
15
16
  | 'ollama'
16
17
  | 'openclaw'
17
18
 
18
- const OPENAI_COMPATIBLE_PROVIDER_INFO: Record<
19
- 'openai' | 'google' | 'deepseek' | 'groq' | 'together' | 'mistral' | 'xai' | 'fireworks',
20
- { name: string; defaultEndpoint: string }
21
- > = {
22
- openai: { name: 'OpenAI', defaultEndpoint: 'https://api.openai.com/v1' },
23
- google: { name: 'Google Gemini', defaultEndpoint: 'https://generativelanguage.googleapis.com/v1beta/openai' },
24
- deepseek: { name: 'DeepSeek', defaultEndpoint: 'https://api.deepseek.com/v1' },
25
- groq: { name: 'Groq', defaultEndpoint: 'https://api.groq.com/openai/v1' },
26
- together: { name: 'Together AI', defaultEndpoint: 'https://api.together.xyz/v1' },
27
- mistral: { name: 'Mistral AI', defaultEndpoint: 'https://api.mistral.ai/v1' },
28
- xai: { name: 'xAI (Grok)', defaultEndpoint: 'https://api.x.ai/v1' },
29
- fireworks: { name: 'Fireworks AI', defaultEndpoint: 'https://api.fireworks.ai/inference/v1' },
30
- }
31
-
32
19
  interface SetupCheckBody {
33
20
  provider?: string
34
21
  apiKey?: string
@@ -196,7 +183,7 @@ export async function POST(req: Request) {
196
183
  switch (provider) {
197
184
  case 'openai': {
198
185
  if (!apiKey) return NextResponse.json({ ok: false, message: 'OpenAI API key is required.' })
199
- const info = OPENAI_COMPATIBLE_PROVIDER_INFO.openai
186
+ const info = OPENAI_COMPATIBLE_DEFAULTS.openai
200
187
  const result = await checkOpenAiCompatible(info.name, apiKey, endpoint, info.defaultEndpoint)
201
188
  return NextResponse.json(result)
202
189
  }
@@ -212,7 +199,7 @@ export async function POST(req: Request) {
212
199
  case 'mistral':
213
200
  case 'xai':
214
201
  case 'fireworks': {
215
- const info = OPENAI_COMPATIBLE_PROVIDER_INFO[provider]
202
+ const info = OPENAI_COMPATIBLE_DEFAULTS[provider]
216
203
  if (!apiKey) return NextResponse.json({ ok: false, message: `${info.name} API key is required.` })
217
204
  const result = await checkOpenAiCompatible(info.name, apiKey, endpoint, info.defaultEndpoint)
218
205
  return NextResponse.json(result)
@@ -18,6 +18,10 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
18
18
  const body = await req.json()
19
19
  const result = mutateItem(ops, id, (skill) => {
20
20
  const normalized = normalizeSkillPayload({ ...skill, ...body })
21
+ const updatedScope = body.scope === 'agent' ? 'agent' as const : body.scope === 'global' ? 'global' as const : skill.scope
22
+ const updatedAgentIds = updatedScope === 'agent' && Array.isArray(body.agentIds)
23
+ ? (body.agentIds as unknown[]).filter((aid): aid is string => typeof aid === 'string')
24
+ : updatedScope === 'agent' ? (skill.agentIds || []) : []
21
25
  return {
22
26
  ...skill,
23
27
  ...body,
@@ -27,6 +31,8 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
27
31
  content: normalized.content,
28
32
  sourceUrl: normalized.sourceUrl,
29
33
  sourceFormat: normalized.sourceFormat,
34
+ scope: updatedScope,
35
+ agentIds: updatedAgentIds,
30
36
  id,
31
37
  updatedAt: Date.now(),
32
38
  }
@@ -14,6 +14,10 @@ export async function POST(req: Request) {
14
14
  const skills = loadSkills()
15
15
  const id = genId()
16
16
  const normalized = normalizeSkillPayload(body)
17
+ const scope = body.scope === 'agent' ? 'agent' as const : 'global' as const
18
+ const agentIds = scope === 'agent' && Array.isArray(body.agentIds)
19
+ ? (body.agentIds as unknown[]).filter((id): id is string => typeof id === 'string')
20
+ : []
17
21
  skills[id] = {
18
22
  id,
19
23
  name: normalized.name,
@@ -22,6 +26,8 @@ export async function POST(req: Request) {
22
26
  description: normalized.description || '',
23
27
  sourceUrl: normalized.sourceUrl,
24
28
  sourceFormat: normalized.sourceFormat,
29
+ scope,
30
+ agentIds,
25
31
  createdAt: Date.now(),
26
32
  updatedAt: Date.now(),
27
33
  }
@@ -7,6 +7,9 @@ import { ensureTaskCompletionReport } from '@/lib/server/task-reports'
7
7
  import { formatValidationFailure, validateTaskCompletion } from '@/lib/server/task-validation'
8
8
  import { pushMainLoopEventToMainSessions } from '@/lib/server/main-agent-loop'
9
9
  import { notify } from '@/lib/server/ws-hub'
10
+ import { createNotification } from '@/lib/server/create-notification'
11
+ import { enqueueSystemEvent } from '@/lib/server/system-events'
12
+ import { requestHeartbeatNow } from '@/lib/server/heartbeat-wake'
10
13
 
11
14
  export async function GET(_req: Request, { params }: { params: Promise<{ id: string }> }) {
12
15
  // Keep completed queue integrity even if daemon is not running.
@@ -33,6 +36,8 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
33
36
  tasks[id].updatedAt = Date.now()
34
37
  } else {
35
38
  Object.assign(tasks[id], body, { updatedAt: Date.now() })
39
+ // Explicitly clear nullable fields when sent as null (Object.assign copies null but not undefined)
40
+ if (body.projectId === null) delete tasks[id].projectId
36
41
  }
37
42
  tasks[id].id = id // prevent id overwrite
38
43
 
@@ -76,6 +81,21 @@ export async function PUT(req: Request, { params }: { params: Promise<{ id: stri
76
81
  // If task is manually transitioned to a terminal status, disable session heartbeat.
77
82
  if (prevStatus !== tasks[id].status && (tasks[id].status === 'completed' || tasks[id].status === 'failed')) {
78
83
  disableSessionHeartbeat(tasks[id].sessionId)
84
+ createNotification({
85
+ type: tasks[id].status === 'completed' ? 'success' : 'error',
86
+ title: `Task ${tasks[id].status}: "${tasks[id].title}"`,
87
+ message: tasks[id].status === 'failed' ? tasks[id].error?.slice(0, 200) : undefined,
88
+ entityType: 'task',
89
+ entityId: id,
90
+ })
91
+
92
+ // Enqueue system event + heartbeat wake
93
+ if (tasks[id].sessionId) {
94
+ enqueueSystemEvent(tasks[id].sessionId, `Task ${tasks[id].status}: ${tasks[id].title}`)
95
+ }
96
+ if (tasks[id].agentId) {
97
+ requestHeartbeatNow({ agentId: tasks[id].agentId, reason: 'task-completed' })
98
+ }
79
99
  }
80
100
 
81
101
  // Dependency check: cannot queue a task if any blocker is incomplete