@swarmclawai/swarmclaw 0.4.0 → 0.4.5

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 (144) hide show
  1. package/README.md +13 -2
  2. package/next.config.ts +8 -0
  3. package/package.json +2 -1
  4. package/src/app/api/agents/[id]/route.ts +20 -21
  5. package/src/app/api/agents/[id]/thread/route.ts +2 -2
  6. package/src/app/api/agents/route.ts +3 -2
  7. package/src/app/api/clawhub/install/route.ts +2 -2
  8. package/src/app/api/connectors/[id]/route.ts +10 -3
  9. package/src/app/api/connectors/[id]/webhook/route.ts +99 -0
  10. package/src/app/api/connectors/route.ts +6 -3
  11. package/src/app/api/credentials/[id]/route.ts +2 -1
  12. package/src/app/api/credentials/route.ts +2 -2
  13. package/src/app/api/documents/route.ts +2 -2
  14. package/src/app/api/files/serve/route.ts +8 -0
  15. package/src/app/api/knowledge/[id]/route.ts +5 -4
  16. package/src/app/api/knowledge/upload/route.ts +2 -2
  17. package/src/app/api/mcp-servers/[id]/route.ts +11 -14
  18. package/src/app/api/mcp-servers/[id]/test/route.ts +2 -1
  19. package/src/app/api/mcp-servers/[id]/tools/route.ts +2 -1
  20. package/src/app/api/mcp-servers/route.ts +2 -2
  21. package/src/app/api/memory/[id]/route.ts +9 -8
  22. package/src/app/api/memory/route.ts +2 -2
  23. package/src/app/api/memory-images/[filename]/route.ts +2 -1
  24. package/src/app/api/openclaw/directory/route.ts +26 -0
  25. package/src/app/api/openclaw/discover/route.ts +61 -0
  26. package/src/app/api/openclaw/sync/route.ts +30 -0
  27. package/src/app/api/orchestrator/run/route.ts +2 -2
  28. package/src/app/api/projects/[id]/route.ts +55 -0
  29. package/src/app/api/projects/route.ts +27 -0
  30. package/src/app/api/providers/[id]/models/route.ts +2 -1
  31. package/src/app/api/providers/[id]/route.ts +13 -15
  32. package/src/app/api/providers/route.ts +2 -2
  33. package/src/app/api/schedules/[id]/route.ts +16 -18
  34. package/src/app/api/schedules/[id]/run/route.ts +4 -3
  35. package/src/app/api/schedules/route.ts +2 -2
  36. package/src/app/api/secrets/[id]/route.ts +16 -17
  37. package/src/app/api/secrets/route.ts +2 -2
  38. package/src/app/api/sessions/[id]/clear/route.ts +2 -1
  39. package/src/app/api/sessions/[id]/deploy/route.ts +2 -1
  40. package/src/app/api/sessions/[id]/devserver/route.ts +2 -1
  41. package/src/app/api/sessions/[id]/messages/route.ts +2 -1
  42. package/src/app/api/sessions/[id]/retry/route.ts +2 -1
  43. package/src/app/api/sessions/[id]/route.ts +2 -1
  44. package/src/app/api/sessions/route.ts +2 -2
  45. package/src/app/api/skills/[id]/route.ts +23 -21
  46. package/src/app/api/skills/import/route.ts +2 -2
  47. package/src/app/api/skills/route.ts +2 -2
  48. package/src/app/api/tasks/[id]/approve/route.ts +2 -1
  49. package/src/app/api/tasks/[id]/route.ts +6 -5
  50. package/src/app/api/tasks/route.ts +2 -2
  51. package/src/app/api/tts/stream/route.ts +48 -0
  52. package/src/app/api/upload/route.ts +2 -2
  53. package/src/app/api/uploads/[filename]/route.ts +4 -1
  54. package/src/app/api/webhooks/[id]/route.ts +29 -31
  55. package/src/app/api/webhooks/route.ts +2 -2
  56. package/src/app/page.tsx +3 -24
  57. package/src/cli/index.js +28 -0
  58. package/src/cli/index.ts +1 -1
  59. package/src/cli/spec.js +2 -0
  60. package/src/components/agents/agent-list.tsx +3 -1
  61. package/src/components/agents/agent-sheet.tsx +116 -14
  62. package/src/components/chat/chat-area.tsx +27 -4
  63. package/src/components/chat/chat-header.tsx +141 -29
  64. package/src/components/chat/tool-call-bubble.tsx +9 -3
  65. package/src/components/chat/voice-overlay.tsx +80 -0
  66. package/src/components/connectors/connector-list.tsx +6 -2
  67. package/src/components/connectors/connector-sheet.tsx +31 -7
  68. package/src/components/layout/app-layout.tsx +47 -25
  69. package/src/components/projects/project-list.tsx +122 -0
  70. package/src/components/projects/project-sheet.tsx +135 -0
  71. package/src/components/schedules/schedule-list.tsx +3 -1
  72. package/src/components/sessions/new-session-sheet.tsx +6 -6
  73. package/src/components/sessions/session-card.tsx +1 -1
  74. package/src/components/sessions/session-list.tsx +7 -7
  75. package/src/components/shared/connector-platform-icon.tsx +4 -0
  76. package/src/components/shared/settings/section-heartbeat.tsx +1 -1
  77. package/src/components/shared/settings/section-orchestrator.tsx +1 -2
  78. package/src/components/shared/settings/section-web-search.tsx +56 -0
  79. package/src/components/shared/settings/settings-page.tsx +73 -0
  80. package/src/components/skills/skill-list.tsx +2 -1
  81. package/src/components/tasks/task-list.tsx +5 -2
  82. package/src/hooks/use-continuous-speech.ts +144 -0
  83. package/src/hooks/use-view-router.ts +52 -0
  84. package/src/hooks/use-voice-conversation.ts +80 -0
  85. package/src/lib/id.ts +6 -0
  86. package/src/lib/projects.ts +13 -0
  87. package/src/lib/provider-sets.ts +5 -0
  88. package/src/lib/providers/anthropic.ts +14 -1
  89. package/src/lib/providers/index.ts +6 -0
  90. package/src/lib/providers/ollama.ts +9 -1
  91. package/src/lib/providers/openai.ts +9 -1
  92. package/src/lib/providers/openclaw.ts +11 -0
  93. package/src/lib/server/api-routes.test.ts +5 -6
  94. package/src/lib/server/build-llm.ts +17 -4
  95. package/src/lib/server/chat-execution.ts +38 -4
  96. package/src/lib/server/collection-helpers.ts +54 -0
  97. package/src/lib/server/connectors/bluebubbles.test.ts +208 -0
  98. package/src/lib/server/connectors/bluebubbles.ts +357 -0
  99. package/src/lib/server/connectors/connector-routing.test.ts +1 -1
  100. package/src/lib/server/connectors/googlechat.ts +46 -7
  101. package/src/lib/server/connectors/manager.ts +392 -3
  102. package/src/lib/server/connectors/media.ts +2 -2
  103. package/src/lib/server/connectors/openclaw.ts +64 -0
  104. package/src/lib/server/connectors/pairing.test.ts +99 -0
  105. package/src/lib/server/connectors/pairing.ts +256 -0
  106. package/src/lib/server/connectors/signal.ts +1 -0
  107. package/src/lib/server/connectors/teams.ts +5 -5
  108. package/src/lib/server/connectors/types.ts +10 -0
  109. package/src/lib/server/execution-log.ts +3 -3
  110. package/src/lib/server/heartbeat-service.ts +1 -1
  111. package/src/lib/server/knowledge-db.test.ts +2 -33
  112. package/src/lib/server/main-agent-loop.ts +6 -6
  113. package/src/lib/server/memory-db.ts +6 -6
  114. package/src/lib/server/openclaw-approvals.ts +105 -0
  115. package/src/lib/server/openclaw-sync.ts +496 -0
  116. package/src/lib/server/orchestrator-lg.ts +30 -9
  117. package/src/lib/server/orchestrator.ts +4 -4
  118. package/src/lib/server/process-manager.ts +2 -2
  119. package/src/lib/server/queue.ts +22 -10
  120. package/src/lib/server/scheduler.ts +2 -2
  121. package/src/lib/server/session-mailbox.ts +2 -2
  122. package/src/lib/server/session-run-manager.ts +2 -2
  123. package/src/lib/server/session-tools/connector.ts +51 -4
  124. package/src/lib/server/session-tools/crud.ts +3 -3
  125. package/src/lib/server/session-tools/delegate.ts +3 -3
  126. package/src/lib/server/session-tools/file.ts +176 -3
  127. package/src/lib/server/session-tools/index.ts +2 -0
  128. package/src/lib/server/session-tools/memory.ts +2 -2
  129. package/src/lib/server/session-tools/openclaw-nodes.ts +112 -0
  130. package/src/lib/server/session-tools/sandbox.ts +33 -0
  131. package/src/lib/server/session-tools/search-providers.ts +270 -0
  132. package/src/lib/server/session-tools/session-info.ts +2 -2
  133. package/src/lib/server/session-tools/web.ts +47 -66
  134. package/src/lib/server/storage.ts +12 -0
  135. package/src/lib/server/stream-agent-chat.ts +29 -0
  136. package/src/lib/server/task-result.test.ts +44 -0
  137. package/src/lib/server/task-result.ts +14 -0
  138. package/src/lib/tool-definitions.ts +5 -3
  139. package/src/lib/tts-stream.ts +130 -0
  140. package/src/lib/view-routes.ts +28 -0
  141. package/src/proxy.ts +3 -0
  142. package/src/stores/use-app-store.ts +28 -1
  143. package/src/stores/use-chat-store.ts +9 -1
  144. package/src/types/index.ts +27 -2
@@ -0,0 +1,256 @@
1
+ import crypto from 'node:crypto'
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+
5
+ const DEFAULT_DATA_DIR = path.join(process.cwd(), 'data')
6
+ const STORE_VERSION = 1
7
+ const PENDING_TTL_MS = 24 * 60 * 60 * 1000
8
+ const MAX_PENDING_PER_CONNECTOR = 100
9
+ const PAIR_CODE_LENGTH = 8
10
+ const PAIR_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
11
+
12
+ function resolveStorePath(): string {
13
+ const dataDir = process.env.DATA_DIR || DEFAULT_DATA_DIR
14
+ return path.join(dataDir, 'connectors', 'pairing-store.json')
15
+ }
16
+
17
+ export type PairingPolicy = 'open' | 'allowlist' | 'pairing' | 'disabled'
18
+
19
+ export interface PairingRequest {
20
+ code: string
21
+ senderId: string
22
+ senderName?: string
23
+ channelId?: string
24
+ createdAt: number
25
+ updatedAt: number
26
+ }
27
+
28
+ interface ConnectorPairingState {
29
+ allowedSenderIds: string[]
30
+ pending: PairingRequest[]
31
+ }
32
+
33
+ interface PairingStore {
34
+ version: number
35
+ connectors: Record<string, ConnectorPairingState>
36
+ }
37
+
38
+ function normalizeSenderId(value: string): string {
39
+ return value.trim().toLowerCase()
40
+ }
41
+
42
+ function dedupe(items: string[]): string[] {
43
+ const seen = new Set<string>()
44
+ const out: string[] = []
45
+ for (const item of items) {
46
+ const normalized = normalizeSenderId(item)
47
+ if (!normalized || seen.has(normalized)) continue
48
+ seen.add(normalized)
49
+ out.push(normalized)
50
+ }
51
+ return out
52
+ }
53
+
54
+ function prunePending(entries: PairingRequest[]): PairingRequest[] {
55
+ const now = Date.now()
56
+ return entries.filter((entry) => {
57
+ if (!entry?.code || !entry?.senderId) return false
58
+ if (!Number.isFinite(entry.createdAt) || !Number.isFinite(entry.updatedAt)) return false
59
+ return (now - entry.updatedAt) <= PENDING_TTL_MS
60
+ }).slice(-MAX_PENDING_PER_CONNECTOR)
61
+ }
62
+
63
+ function emptyStore(): PairingStore {
64
+ return { version: STORE_VERSION, connectors: {} }
65
+ }
66
+
67
+ function loadStore(): PairingStore {
68
+ const storePath = resolveStorePath()
69
+ try {
70
+ if (!fs.existsSync(storePath)) return emptyStore()
71
+ const raw = fs.readFileSync(storePath, 'utf8')
72
+ const parsed = JSON.parse(raw) as PairingStore
73
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.connectors !== 'object') {
74
+ return emptyStore()
75
+ }
76
+
77
+ const normalized: PairingStore = emptyStore()
78
+ for (const [connectorId, value] of Object.entries(parsed.connectors || {})) {
79
+ const state = value as Partial<ConnectorPairingState>
80
+ const allowedSenderIds = dedupe(Array.isArray(state.allowedSenderIds) ? state.allowedSenderIds.map(String) : [])
81
+ const pending = prunePending(Array.isArray(state.pending) ? state.pending as PairingRequest[] : [])
82
+ normalized.connectors[connectorId] = { allowedSenderIds, pending }
83
+ }
84
+ return normalized
85
+ } catch {
86
+ return emptyStore()
87
+ }
88
+ }
89
+
90
+ function saveStore(store: PairingStore): void {
91
+ const storePath = resolveStorePath()
92
+ fs.mkdirSync(path.dirname(storePath), { recursive: true })
93
+ fs.writeFileSync(storePath, `${JSON.stringify(store, null, 2)}\n`)
94
+ }
95
+
96
+ function ensureConnectorState(store: PairingStore, connectorId: string): ConnectorPairingState {
97
+ const existing = store.connectors[connectorId]
98
+ if (existing) {
99
+ existing.allowedSenderIds = dedupe(existing.allowedSenderIds || [])
100
+ existing.pending = prunePending(existing.pending || [])
101
+ return existing
102
+ }
103
+ const created: ConnectorPairingState = {
104
+ allowedSenderIds: [],
105
+ pending: [],
106
+ }
107
+ store.connectors[connectorId] = created
108
+ return created
109
+ }
110
+
111
+ function randomPairCode(existing: Set<string>): string {
112
+ for (let i = 0; i < 256; i++) {
113
+ const bytes = crypto.randomBytes(PAIR_CODE_LENGTH)
114
+ let out = ''
115
+ for (let j = 0; j < PAIR_CODE_LENGTH; j++) {
116
+ out += PAIR_CODE_ALPHABET[bytes[j] % PAIR_CODE_ALPHABET.length]
117
+ }
118
+ if (!existing.has(out)) return out
119
+ }
120
+ throw new Error('Unable to generate unique pairing code')
121
+ }
122
+
123
+ export function parsePairingPolicy(value: unknown, fallback: PairingPolicy = 'open'): PairingPolicy {
124
+ if (typeof value !== 'string') return fallback
125
+ const normalized = value.trim().toLowerCase()
126
+ if (normalized === 'open' || normalized === 'allowlist' || normalized === 'pairing' || normalized === 'disabled') {
127
+ return normalized
128
+ }
129
+ return fallback
130
+ }
131
+
132
+ export function parseAllowFromCsv(value: unknown): string[] {
133
+ if (typeof value !== 'string') return []
134
+ return dedupe(value.split(',').map((item) => item.trim()).filter(Boolean))
135
+ }
136
+
137
+ export function listStoredAllowedSenders(connectorId: string): string[] {
138
+ const store = loadStore()
139
+ const state = ensureConnectorState(store, connectorId)
140
+ return state.allowedSenderIds.slice()
141
+ }
142
+
143
+ export function listPendingPairingRequests(connectorId: string): PairingRequest[] {
144
+ const store = loadStore()
145
+ const state = ensureConnectorState(store, connectorId)
146
+ return state.pending.slice().sort((a, b) => b.updatedAt - a.updatedAt)
147
+ }
148
+
149
+ export function addAllowedSender(connectorId: string, senderId: string): { added: boolean; normalized: string } {
150
+ const normalized = normalizeSenderId(senderId)
151
+ if (!normalized) return { added: false, normalized }
152
+
153
+ const store = loadStore()
154
+ const state = ensureConnectorState(store, connectorId)
155
+ const hasExisting = state.allowedSenderIds.includes(normalized)
156
+ if (!hasExisting) {
157
+ state.allowedSenderIds.push(normalized)
158
+ }
159
+
160
+ // Remove any pending requests for the same sender after approval.
161
+ state.pending = state.pending.filter((entry) => normalizeSenderId(entry.senderId) !== normalized)
162
+
163
+ saveStore(store)
164
+ return { added: !hasExisting, normalized }
165
+ }
166
+
167
+ export function createOrTouchPairingRequest(params: {
168
+ connectorId: string
169
+ senderId: string
170
+ senderName?: string
171
+ channelId?: string
172
+ }): { code: string; created: boolean } {
173
+ const normalized = normalizeSenderId(params.senderId)
174
+ if (!normalized) throw new Error('senderId is required')
175
+
176
+ const store = loadStore()
177
+ const state = ensureConnectorState(store, params.connectorId)
178
+ const now = Date.now()
179
+
180
+ const existing = state.pending.find((entry) => normalizeSenderId(entry.senderId) === normalized)
181
+ if (existing) {
182
+ existing.updatedAt = now
183
+ existing.senderName = params.senderName || existing.senderName
184
+ existing.channelId = params.channelId || existing.channelId
185
+ saveStore(store)
186
+ return { code: existing.code, created: false }
187
+ }
188
+
189
+ const existingCodes = new Set(state.pending.map((entry) => entry.code.toUpperCase()))
190
+ const code = randomPairCode(existingCodes)
191
+ state.pending.push({
192
+ code,
193
+ senderId: normalized,
194
+ senderName: params.senderName,
195
+ channelId: params.channelId,
196
+ createdAt: now,
197
+ updatedAt: now,
198
+ })
199
+ state.pending = prunePending(state.pending)
200
+ saveStore(store)
201
+ return { code, created: true }
202
+ }
203
+
204
+ export function approvePairingCode(connectorId: string, codeRaw: string): {
205
+ ok: boolean
206
+ senderId?: string
207
+ senderName?: string
208
+ reason?: string
209
+ } {
210
+ const code = codeRaw.trim().toUpperCase()
211
+ if (!code) return { ok: false, reason: 'Missing code' }
212
+
213
+ const store = loadStore()
214
+ const state = ensureConnectorState(store, connectorId)
215
+ const idx = state.pending.findIndex((entry) => entry.code.toUpperCase() === code)
216
+ if (idx < 0) return { ok: false, reason: 'Code not found or expired' }
217
+
218
+ const pending = state.pending[idx]
219
+ state.pending.splice(idx, 1)
220
+
221
+ const normalizedSender = normalizeSenderId(pending.senderId)
222
+ if (!state.allowedSenderIds.includes(normalizedSender)) {
223
+ state.allowedSenderIds.push(normalizedSender)
224
+ state.allowedSenderIds = dedupe(state.allowedSenderIds)
225
+ }
226
+
227
+ saveStore(store)
228
+ return {
229
+ ok: true,
230
+ senderId: normalizedSender,
231
+ senderName: pending.senderName,
232
+ }
233
+ }
234
+
235
+ export function isSenderAllowed(params: {
236
+ connectorId: string
237
+ senderId: string
238
+ configAllowFrom?: string[]
239
+ }): boolean {
240
+ const normalized = normalizeSenderId(params.senderId)
241
+ if (!normalized) return false
242
+
243
+ const configSet = new Set((params.configAllowFrom || []).map((item) => normalizeSenderId(item)).filter(Boolean))
244
+ if (configSet.has(normalized)) return true
245
+
246
+ const store = loadStore()
247
+ const state = ensureConnectorState(store, params.connectorId)
248
+ return state.allowedSenderIds.includes(normalized)
249
+ }
250
+
251
+ export function clearConnectorPairingState(connectorId: string): void {
252
+ const store = loadStore()
253
+ if (!store.connectors[connectorId]) return
254
+ delete store.connectors[connectorId]
255
+ saveStore(store)
256
+ }
@@ -147,6 +147,7 @@ export async function handleSignalEvent(
147
147
  senderId: sender,
148
148
  senderName: envelope.sourceName || sender,
149
149
  text,
150
+ isGroup: !!groupId,
150
151
  }
151
152
 
152
153
  try {
@@ -22,11 +22,11 @@ const teams: PlatformConnector = {
22
22
  const conversationReferences = new Map<string, any>()
23
23
  let stopped = false
24
24
 
25
- // Process incoming activities — called from the webhook endpoint
26
- // POST /api/connectors/[id]/webhook should pipe req/res through this
27
- const processActivity = async (req: any, res: any) => {
25
+ // Process incoming activities — called from the webhook endpoint.
26
+ // We use processActivityDirect so this works from Next.js route handlers.
27
+ const processActivity = async (activity: any) => {
28
28
  if (stopped) return
29
- await adapter.processActivity(req, res, async (context: any) => {
29
+ await adapter.processActivityDirect(activity, async (context: any) => {
30
30
  if (context.activity.type !== 'message') return
31
31
  if (!context.activity.text) return
32
32
 
@@ -57,7 +57,7 @@ const teams: PlatformConnector = {
57
57
  })
58
58
  }
59
59
 
60
- // Store processActivity on globalThis so the webhook route can access it
60
+ // Store processActivity on globalThis so the webhook route can access it.
61
61
  const handlerKey = `__swarmclaw_teams_handler_${connector.id}__`
62
62
  ;(globalThis as any)[handlerKey] = processActivity
63
63
 
@@ -21,9 +21,11 @@ export interface InboundMessage {
21
21
  senderId: string // platform-specific user ID
22
22
  senderName: string // display name
23
23
  text: string
24
+ isGroup?: boolean
24
25
  imageUrl?: string
25
26
  media?: InboundMedia[]
26
27
  replyToMessageId?: string
28
+ agentIdOverride?: string
27
29
  }
28
30
 
29
31
  /** A running connector instance */
@@ -50,6 +52,14 @@ export interface ConnectorInstance {
50
52
  authenticated?: boolean
51
53
  /** Whether the connector has existing saved credentials (WhatsApp only) */
52
54
  hasCredentials?: boolean
55
+ /** Rich messaging: send a reaction emoji to a message */
56
+ sendReaction?: (channelId: string, messageId: string, emoji: string) => Promise<void>
57
+ /** Rich messaging: edit a previously sent message */
58
+ editMessage?: (channelId: string, messageId: string, newText: string) => Promise<void>
59
+ /** Rich messaging: delete a message */
60
+ deleteMessage?: (channelId: string, messageId: string) => Promise<void>
61
+ /** Rich messaging: pin a message */
62
+ pinMessage?: (channelId: string, messageId: string) => Promise<void>
53
63
  }
54
64
 
55
65
  /** Platform-specific connector implementation */
@@ -1,7 +1,7 @@
1
1
  import fs from 'fs'
2
2
  import path from 'path'
3
- import crypto from 'crypto'
4
3
  import Database from 'better-sqlite3'
4
+ import { genId } from '@/lib/id'
5
5
 
6
6
  // ---------------------------------------------------------------------------
7
7
  // Types
@@ -94,7 +94,7 @@ export function logExecution(
94
94
  detail?: Record<string, unknown>
95
95
  },
96
96
  ): string {
97
- const id = crypto.randomBytes(8).toString('hex')
97
+ const id = genId(8)
98
98
  const ts = Date.now()
99
99
  try {
100
100
  insertStmt().run(
@@ -133,7 +133,7 @@ export function logExecutionBatch(
133
133
  const tx = db.transaction(() => {
134
134
  for (const e of entries) {
135
135
  stmt.run(
136
- crypto.randomBytes(8).toString('hex'),
136
+ genId(8),
137
137
  e.sessionId,
138
138
  e.runId ?? null,
139
139
  e.agentId ?? null,
@@ -158,6 +158,7 @@ function buildAgentHeartbeatPrompt(session: any, agent: any, fallbackPrompt: str
158
158
  soul ? `Persona: ${soul.slice(0, 300)}` : '',
159
159
  heartbeatFileContent ? `\nHEARTBEAT.md contents:\n${heartbeatFileContent.slice(0, 2000)}` : '',
160
160
  recentContext ? `Recent conversation:\n${recentContext}` : '',
161
+ fallbackPrompt !== DEFAULT_HEARTBEAT_PROMPT ? `\nAgent instructions:\n${fallbackPrompt}` : '',
161
162
  '',
162
163
  'You are running an autonomous heartbeat tick. Review your goal and recent context.',
163
164
  'If there is meaningful work to do toward your goal, use your tools and take action.',
@@ -167,7 +168,6 @@ function buildAgentHeartbeatPrompt(session: any, agent: any, fallbackPrompt: str
167
168
  'To update your goal or plan, include this line in your response:',
168
169
  '[AGENT_HEARTBEAT_META]{"goal": "your evolved goal", "status": "progress", "next_action": "what you plan to do next"}',
169
170
  'You can evolve your goal as you learn more. Set status to "progress" while working, "ok" when done, "idle" when waiting.',
170
- fallbackPrompt !== DEFAULT_HEARTBEAT_PROMPT ? `\nAdditional instructions: ${fallbackPrompt}` : '',
171
171
  ].filter(Boolean).join('\n')
172
172
  }
173
173
 
@@ -104,39 +104,8 @@ function rowToEntry(row: Record<string, unknown>): MemoryEntry {
104
104
  }
105
105
  }
106
106
 
107
- // ---- Knowledge helpers (mirrors memory-db.ts exported functions) ----
108
-
109
- const MEMORY_FTS_STOP_WORDS = new Set([
110
- 'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how',
111
- 'i', 'if', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this',
112
- 'to', 'was', 'we', 'were', 'what', 'when', 'where', 'which', 'who', 'with',
113
- 'you', 'your',
114
- ])
115
- const MAX_FTS_QUERY_TERMS = 6
116
- const MAX_FTS_TERM_LENGTH = 48
117
-
118
- function buildFtsQuery(input: string): string {
119
- const tokens = String(input || '')
120
- .toLowerCase()
121
- .match(/[a-z0-9][a-z0-9._:/-]*/g) || []
122
- if (!tokens.length) return ''
123
- const unique: string[] = []
124
- const seen = new Set<string>()
125
- for (const token of tokens) {
126
- const term = token.slice(0, MAX_FTS_TERM_LENGTH)
127
- if (term.length < 3) continue
128
- if (MEMORY_FTS_STOP_WORDS.has(term)) continue
129
- if (seen.has(term)) continue
130
- seen.add(term)
131
- unique.push(term)
132
- if (unique.length >= MAX_FTS_QUERY_TERMS) break
133
- }
134
- if (unique.length === 1) {
135
- return unique[0].length >= 5 ? `"${unique[0].replace(/"/g, '')}"` : ''
136
- }
137
- const selected = unique.slice(0, Math.min(4, MAX_FTS_QUERY_TERMS))
138
- return selected.map((term) => `"${term.replace(/"/g, '')}"`).join(' AND ')
139
- }
107
+ // ---- Knowledge helpers (re-exported from memory-db.ts) ----
108
+ import { buildFtsQuery } from './memory-db'
140
109
 
141
110
  function addRawMemory(data: {
142
111
  agentId?: string | null
@@ -1,4 +1,4 @@
1
- import crypto from 'crypto'
1
+ import { genId } from '@/lib/id'
2
2
  import { z } from 'zod'
3
3
  import type { GoalContract, MessageToolEvent } from '@/types'
4
4
  import { loadSessions, saveSessions, loadAgents, saveAgents, loadTasks, saveTasks } from './storage'
@@ -151,7 +151,7 @@ function appendTimeline(
151
151
  const recent = state.timeline.at(-1)
152
152
  if (recent && recent.source === source && recent.note === normalizedNote && now - recent.at < 45_000) return
153
153
  state.timeline.push({
154
- id: `tl_${crypto.randomBytes(4).toString('hex')}`,
154
+ id: `tl_${genId()}`,
155
155
  at: now,
156
156
  source,
157
157
  note: normalizedNote,
@@ -226,7 +226,7 @@ function normalizeState(raw: any, now = Date.now()): MainLoopState {
226
226
  const text = toOneLine(typeof e?.text === 'string' ? e.text : '')
227
227
  if (!text) return null
228
228
  return {
229
- id: typeof e?.id === 'string' && e.id.trim() ? e.id.trim() : `evt_${crypto.randomBytes(3).toString('hex')}`,
229
+ id: typeof e?.id === 'string' && e.id.trim() ? e.id.trim() : `evt_${genId(3)}`,
230
230
  type: typeof e?.type === 'string' && e.type.trim() ? e.type.trim() : 'event',
231
231
  text,
232
232
  createdAt: typeof e?.createdAt === 'number' ? e.createdAt : now,
@@ -246,7 +246,7 @@ function normalizeState(raw: any, now = Date.now()): MainLoopState {
246
246
  ? entry.status
247
247
  : undefined
248
248
  return {
249
- id: typeof entry?.id === 'string' && entry.id.trim() ? entry.id.trim() : `tl_${crypto.randomBytes(3).toString('hex')}`,
249
+ id: typeof entry?.id === 'string' && entry.id.trim() ? entry.id.trim() : `tl_${genId(3)}`,
250
250
  at: typeof entry?.at === 'number' ? entry.at : now,
251
251
  source: typeof entry?.source === 'string' && entry.source.trim() ? entry.source.trim() : 'event',
252
252
  note,
@@ -303,7 +303,7 @@ function appendEvent(state: MainLoopState, type: string, text: string, now = Dat
303
303
  return false
304
304
  }
305
305
  state.pendingEvents.push({
306
- id: `evt_${crypto.randomBytes(4).toString('hex')}`,
306
+ id: `evt_${genId()}`,
307
307
  type,
308
308
  text: normalizedText,
309
309
  createdAt: now,
@@ -517,7 +517,7 @@ function upsertMissionTask(session: any, state: MainLoopState, now: number): str
517
517
  ].filter(Boolean).join('\n')
518
518
 
519
519
  if (!task) {
520
- const id = crypto.randomBytes(4).toString('hex')
520
+ const id = genId()
521
521
  task = {
522
522
  id,
523
523
  title,
@@ -1,7 +1,7 @@
1
1
  import Database from 'better-sqlite3'
2
2
  import path from 'path'
3
- import crypto from 'crypto'
4
3
  import fs from 'fs'
4
+ import { genId } from '@/lib/id'
5
5
  import type { MemoryEntry, FileReference, MemoryImage, MemoryReference } from '@/types'
6
6
  import { getEmbedding, cosineSimilarity, serializeEmbedding, deserializeEmbedding } from './embeddings'
7
7
  import { loadSettings } from './storage'
@@ -20,12 +20,12 @@ const IMAGES_DIR = path.join(DATA_DIR, 'memory-images')
20
20
 
21
21
  const MAX_IMAGE_INPUT_BYTES = 10 * 1024 * 1024 // 10MB
22
22
  const IMAGE_EXT_WHITELIST = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp', '.tiff'])
23
- const MAX_FTS_QUERY_TERMS = 6
24
- const MAX_FTS_TERM_LENGTH = 48
23
+ export const MAX_FTS_QUERY_TERMS = 6
24
+ export const MAX_FTS_TERM_LENGTH = 48
25
25
  const MAX_FTS_RESULT_ROWS = 30
26
26
  const MAX_MERGED_RESULTS = 50
27
27
 
28
- const MEMORY_FTS_STOP_WORDS = new Set([
28
+ export const MEMORY_FTS_STOP_WORDS = new Set([
29
29
  'a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how',
30
30
  'i', 'if', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this',
31
31
  'to', 'was', 'we', 'were', 'what', 'when', 'where', 'which', 'who', 'with',
@@ -184,7 +184,7 @@ function canonicalText(value: unknown): string {
184
184
  .trim()
185
185
  }
186
186
 
187
- function buildFtsQuery(input: string): string {
187
+ export function buildFtsQuery(input: string): string {
188
188
  const tokens = String(input || '')
189
189
  .toLowerCase()
190
190
  .match(/[a-z0-9][a-z0-9._:/-]*/g) || []
@@ -546,7 +546,7 @@ function initDb() {
546
546
 
547
547
  return {
548
548
  add(data: Omit<MemoryEntry, 'id' | 'createdAt' | 'updatedAt'>): MemoryEntry {
549
- const id = crypto.randomBytes(6).toString('hex')
549
+ const id = genId(6)
550
550
  const now = Date.now()
551
551
  const references = normalizeReferences(data.references, data.filePaths)
552
552
  const legacyFilePaths = referencesToLegacyFilePaths(references)
@@ -0,0 +1,105 @@
1
+ import fs from 'node:fs'
2
+ import path from 'node:path'
3
+ import net from 'node:net'
4
+ import { resolveOpenClawWorkspace } from './openclaw-sync'
5
+
6
+ const APPROVAL_TIMEOUT_MS = 30_000
7
+
8
+ interface ApprovalRequest {
9
+ toolName: string
10
+ args: Record<string, unknown>
11
+ socketPath?: string
12
+ }
13
+
14
+ interface ApprovalResponse {
15
+ approved: boolean
16
+ reason?: string
17
+ }
18
+
19
+ function resolveSocketPath(): string | null {
20
+ try {
21
+ const workspace = resolveOpenClawWorkspace()
22
+ const socketPath = path.join(workspace, 'exec-approvals.sock')
23
+ if (fs.existsSync(socketPath)) return socketPath
24
+ } catch { /* workspace not found */ }
25
+ return null
26
+ }
27
+
28
+ function resolveApprovalToken(): string | null {
29
+ try {
30
+ const workspace = resolveOpenClawWorkspace()
31
+ const tokenPath = path.join(workspace, 'exec-approvals.json')
32
+ if (!fs.existsSync(tokenPath)) return null
33
+ const raw = JSON.parse(fs.readFileSync(tokenPath, 'utf8'))
34
+ return typeof raw?.token === 'string' ? raw.token : null
35
+ } catch {
36
+ return null
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Forward a tool approval request to OpenClaw's exec-approvals Unix socket.
42
+ * Returns the approval decision, or null if the socket is unavailable.
43
+ */
44
+ export async function forwardApprovalToOpenClaw(request: ApprovalRequest): Promise<ApprovalResponse | null> {
45
+ const socketPath = request.socketPath || resolveSocketPath()
46
+ if (!socketPath) return null
47
+
48
+ const token = resolveApprovalToken()
49
+
50
+ return new Promise<ApprovalResponse | null>((resolve) => {
51
+ const socket = net.createConnection({ path: socketPath }, () => {
52
+ const payload = JSON.stringify({
53
+ type: 'approval_request',
54
+ toolName: request.toolName,
55
+ args: request.args,
56
+ token,
57
+ timestamp: Date.now(),
58
+ })
59
+ socket.write(payload + '\n')
60
+ })
61
+
62
+ let data = ''
63
+ const timer = setTimeout(() => {
64
+ socket.destroy()
65
+ resolve(null) // Timeout — fall through to SwarmClaw UI
66
+ }, APPROVAL_TIMEOUT_MS)
67
+
68
+ socket.on('data', (chunk) => {
69
+ data += chunk.toString()
70
+ // Try to parse complete JSON response
71
+ try {
72
+ const response = JSON.parse(data.trim())
73
+ clearTimeout(timer)
74
+ socket.destroy()
75
+ resolve({
76
+ approved: response.approved === true,
77
+ reason: typeof response.reason === 'string' ? response.reason : undefined,
78
+ })
79
+ } catch {
80
+ // Incomplete data, wait for more
81
+ }
82
+ })
83
+
84
+ socket.on('error', () => {
85
+ clearTimeout(timer)
86
+ resolve(null) // Socket error — fall through
87
+ })
88
+
89
+ socket.on('close', () => {
90
+ clearTimeout(timer)
91
+ // If we haven't resolved yet, try to parse what we have
92
+ if (data.trim()) {
93
+ try {
94
+ const response = JSON.parse(data.trim())
95
+ resolve({
96
+ approved: response.approved === true,
97
+ reason: typeof response.reason === 'string' ? response.reason : undefined,
98
+ })
99
+ return
100
+ } catch { /* fall through */ }
101
+ }
102
+ resolve(null)
103
+ })
104
+ })
105
+ }