@swarmclawai/swarmclaw 0.3.1 → 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.
- package/README.md +33 -13
- package/bin/server-cmd.js +14 -7
- package/bin/swarmclaw.js +3 -1
- package/bin/update-cmd.js +120 -0
- package/next.config.ts +10 -0
- package/package.json +4 -1
- package/src/app/api/agents/[id]/route.ts +20 -18
- package/src/app/api/agents/[id]/thread/route.ts +4 -3
- package/src/app/api/agents/route.ts +8 -3
- package/src/app/api/auth/route.ts +3 -1
- package/src/app/api/claude-skills/route.ts +3 -1
- package/src/app/api/clawhub/install/route.ts +2 -2
- package/src/app/api/connectors/[id]/route.ts +14 -3
- package/src/app/api/connectors/[id]/webhook/route.ts +99 -0
- package/src/app/api/connectors/route.ts +12 -4
- package/src/app/api/credentials/[id]/route.ts +2 -1
- package/src/app/api/credentials/route.ts +5 -3
- package/src/app/api/daemon/route.ts +6 -1
- package/src/app/api/documents/route.ts +2 -2
- package/src/app/api/files/serve/route.ts +8 -0
- package/src/app/api/ip/route.ts +3 -1
- package/src/app/api/knowledge/[id]/route.ts +5 -4
- package/src/app/api/knowledge/upload/route.ts +2 -2
- package/src/app/api/mcp-servers/[id]/route.ts +11 -14
- package/src/app/api/mcp-servers/[id]/test/route.ts +2 -1
- package/src/app/api/mcp-servers/[id]/tools/route.ts +2 -1
- package/src/app/api/mcp-servers/route.ts +5 -3
- package/src/app/api/memory/[id]/route.ts +9 -8
- package/src/app/api/memory/route.ts +2 -2
- package/src/app/api/memory-images/[filename]/route.ts +2 -1
- package/src/app/api/openclaw/directory/route.ts +26 -0
- package/src/app/api/openclaw/discover/route.ts +61 -0
- package/src/app/api/openclaw/sync/route.ts +30 -0
- package/src/app/api/orchestrator/graph/route.ts +25 -0
- package/src/app/api/orchestrator/run/route.ts +2 -2
- package/src/app/api/plugins/marketplace/route.ts +3 -1
- package/src/app/api/plugins/route.ts +3 -1
- package/src/app/api/projects/[id]/route.ts +55 -0
- package/src/app/api/projects/route.ts +27 -0
- package/src/app/api/providers/[id]/models/route.ts +2 -1
- package/src/app/api/providers/[id]/route.ts +13 -12
- package/src/app/api/providers/configs/route.ts +3 -1
- package/src/app/api/providers/route.ts +7 -3
- package/src/app/api/schedules/[id]/route.ts +16 -15
- package/src/app/api/schedules/[id]/run/route.ts +4 -3
- package/src/app/api/schedules/route.ts +8 -3
- package/src/app/api/secrets/[id]/route.ts +16 -17
- package/src/app/api/secrets/route.ts +5 -3
- package/src/app/api/sessions/[id]/chat/route.ts +5 -2
- package/src/app/api/sessions/[id]/clear/route.ts +2 -1
- package/src/app/api/sessions/[id]/deploy/route.ts +2 -1
- package/src/app/api/sessions/[id]/devserver/route.ts +2 -1
- package/src/app/api/sessions/[id]/messages/route.ts +2 -1
- package/src/app/api/sessions/[id]/retry/route.ts +2 -1
- package/src/app/api/sessions/[id]/route.ts +2 -1
- package/src/app/api/sessions/route.ts +11 -4
- package/src/app/api/settings/route.ts +3 -1
- package/src/app/api/setup/doctor/route.ts +1 -0
- package/src/app/api/setup/openclaw-device/route.ts +3 -1
- package/src/app/api/skills/[id]/route.ts +23 -21
- package/src/app/api/skills/import/route.ts +2 -2
- package/src/app/api/skills/route.ts +5 -3
- package/src/app/api/tasks/[id]/approve/route.ts +74 -0
- package/src/app/api/tasks/[id]/route.ts +9 -5
- package/src/app/api/tasks/route.ts +5 -2
- package/src/app/api/tts/stream/route.ts +48 -0
- package/src/app/api/upload/route.ts +2 -2
- package/src/app/api/uploads/[filename]/route.ts +4 -1
- package/src/app/api/usage/route.ts +3 -1
- package/src/app/api/version/route.ts +3 -1
- package/src/app/api/webhooks/[id]/route.ts +31 -32
- package/src/app/api/webhooks/route.ts +5 -3
- package/src/app/icon.svg +58 -0
- package/src/app/page.tsx +11 -26
- package/src/cli/index.js +28 -9
- package/src/cli/index.ts +45 -2
- package/src/cli/spec.js +2 -8
- package/src/components/agents/agent-card.tsx +1 -1
- package/src/components/agents/agent-list.tsx +3 -1
- package/src/components/agents/agent-sheet.tsx +166 -81
- package/src/components/chat/chat-area.tsx +71 -34
- package/src/components/chat/chat-header.tsx +141 -29
- package/src/components/chat/chat-tool-toggles.tsx +12 -53
- package/src/components/chat/message-bubble.tsx +110 -42
- package/src/components/chat/tool-call-bubble.tsx +50 -6
- package/src/components/chat/tool-request-banner.tsx +1 -9
- package/src/components/chat/voice-overlay.tsx +80 -0
- package/src/components/connectors/connector-list.tsx +9 -10
- package/src/components/connectors/connector-sheet.tsx +55 -36
- package/src/components/input/chat-input.tsx +72 -56
- package/src/components/knowledge/knowledge-list.tsx +27 -31
- package/src/components/layout/app-layout.tsx +133 -90
- package/src/components/layout/daemon-indicator.tsx +3 -5
- package/src/components/logs/log-list.tsx +5 -9
- package/src/components/mcp-servers/mcp-server-list.tsx +24 -2
- package/src/components/memory/memory-detail.tsx +1 -1
- package/src/components/plugins/plugin-list.tsx +227 -27
- package/src/components/projects/project-list.tsx +122 -0
- package/src/components/projects/project-sheet.tsx +135 -0
- package/src/components/providers/provider-list.tsx +46 -13
- package/src/components/providers/provider-sheet.tsx +0 -45
- package/src/components/runs/run-list.tsx +6 -15
- package/src/components/schedules/schedule-card.tsx +54 -4
- package/src/components/schedules/schedule-list.tsx +9 -4
- package/src/components/schedules/schedule-sheet.tsx +0 -47
- package/src/components/secrets/secrets-list.tsx +20 -2
- package/src/components/sessions/new-session-sheet.tsx +14 -15
- package/src/components/sessions/session-card.tsx +1 -1
- package/src/components/sessions/session-list.tsx +7 -7
- package/src/components/shared/connector-platform-icon.tsx +26 -20
- package/src/components/shared/model-combobox.tsx +148 -0
- package/src/components/shared/settings/section-heartbeat.tsx +8 -40
- package/src/components/shared/settings/section-orchestrator.tsx +9 -11
- package/src/components/shared/settings/section-web-search.tsx +56 -0
- package/src/components/shared/settings/settings-page.tsx +73 -0
- package/src/components/skills/skill-list.tsx +262 -35
- package/src/components/skills/skill-sheet.tsx +0 -45
- package/src/components/tasks/task-board.tsx +3 -6
- package/src/components/tasks/task-card.tsx +43 -1
- package/src/components/tasks/task-list.tsx +8 -7
- package/src/components/tasks/task-sheet.tsx +0 -44
- package/src/components/usage/usage-list.tsx +12 -4
- package/src/hooks/use-continuous-speech.ts +144 -0
- package/src/hooks/use-view-router.ts +52 -0
- package/src/hooks/use-voice-conversation.ts +80 -0
- package/src/hooks/use-ws.ts +66 -0
- package/src/instrumentation.ts +2 -0
- package/src/lib/chat.ts +14 -2
- package/src/lib/id.ts +6 -0
- package/src/lib/projects.ts +13 -0
- package/src/lib/provider-sets.ts +5 -0
- package/src/lib/providers/anthropic.ts +15 -2
- package/src/lib/providers/index.ts +8 -0
- package/src/lib/providers/ollama.ts +10 -2
- package/src/lib/providers/openai.ts +42 -13
- package/src/lib/providers/openclaw.ts +11 -0
- package/src/lib/server/api-routes.test.ts +5 -6
- package/src/lib/server/build-llm.ts +17 -4
- package/src/lib/server/chat-execution.ts +57 -8
- package/src/lib/server/collection-helpers.ts +54 -0
- package/src/lib/server/connectors/bluebubbles.test.ts +208 -0
- package/src/lib/server/connectors/bluebubbles.ts +357 -0
- package/src/lib/server/connectors/connector-routing.test.ts +1 -1
- package/src/lib/server/connectors/googlechat.ts +46 -7
- package/src/lib/server/connectors/manager.ts +401 -6
- package/src/lib/server/connectors/media.ts +2 -2
- package/src/lib/server/connectors/openclaw.ts +64 -0
- package/src/lib/server/connectors/pairing.test.ts +99 -0
- package/src/lib/server/connectors/pairing.ts +256 -0
- package/src/lib/server/connectors/signal.ts +1 -0
- package/src/lib/server/connectors/teams.ts +5 -5
- package/src/lib/server/connectors/types.ts +10 -0
- package/src/lib/server/context-manager.ts +1 -1
- package/src/lib/server/daemon-state.ts +3 -0
- package/src/lib/server/data-dir.ts +1 -0
- package/src/lib/server/execution-log.ts +3 -3
- package/src/lib/server/heartbeat-service.ts +67 -3
- package/src/lib/server/knowledge-db.test.ts +2 -33
- package/src/lib/server/langgraph-checkpoint.ts +274 -0
- package/src/lib/server/main-agent-loop.ts +67 -8
- package/src/lib/server/memory-db.ts +6 -6
- package/src/lib/server/openclaw-approvals.ts +105 -0
- package/src/lib/server/openclaw-sync.ts +496 -0
- package/src/lib/server/orchestrator-lg.ts +422 -20
- package/src/lib/server/orchestrator.ts +29 -9
- package/src/lib/server/process-manager.ts +2 -2
- package/src/lib/server/queue.ts +39 -13
- package/src/lib/server/scheduler.ts +2 -2
- package/src/lib/server/session-mailbox.ts +2 -2
- package/src/lib/server/session-run-manager.ts +8 -3
- package/src/lib/server/session-tools/connector.ts +51 -4
- package/src/lib/server/session-tools/crud.ts +3 -3
- package/src/lib/server/session-tools/delegate.ts +5 -5
- package/src/lib/server/session-tools/file.ts +176 -3
- package/src/lib/server/session-tools/index.ts +4 -0
- package/src/lib/server/session-tools/memory.ts +2 -2
- package/src/lib/server/session-tools/openclaw-nodes.ts +112 -0
- package/src/lib/server/session-tools/sandbox.ts +197 -0
- package/src/lib/server/session-tools/search-providers.ts +270 -0
- package/src/lib/server/session-tools/session-info.ts +2 -2
- package/src/lib/server/session-tools/web.ts +47 -66
- package/src/lib/server/storage-mcp.test.ts +25 -2
- package/src/lib/server/storage.ts +36 -7
- package/src/lib/server/stream-agent-chat.ts +106 -22
- package/src/lib/server/task-result.test.ts +44 -0
- package/src/lib/server/task-result.ts +14 -0
- package/src/lib/server/task-validation.test.ts +23 -0
- package/src/lib/server/task-validation.ts +5 -3
- package/src/lib/server/ws-hub.ts +85 -0
- package/src/lib/tool-definitions.ts +44 -0
- package/src/lib/tts-stream.ts +130 -0
- package/src/lib/upload.ts +7 -1
- package/src/lib/view-routes.ts +28 -0
- package/src/lib/ws-client.ts +124 -0
- package/src/proxy.ts +3 -0
- package/src/stores/use-app-store.ts +28 -1
- package/src/stores/use-chat-store.ts +42 -14
- package/src/types/index.ts +34 -2
- package/src/app/api/agents/generate/route.ts +0 -42
- package/src/app/api/generate/info/route.ts +0 -12
- package/src/app/api/generate/route.ts +0 -106
- package/src/app/favicon.ico +0 -0
- package/src/components/shared/ai-gen-block.tsx +0 -77
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { test } from 'node:test'
|
|
6
|
+
import {
|
|
7
|
+
addAllowedSender,
|
|
8
|
+
approvePairingCode,
|
|
9
|
+
clearConnectorPairingState,
|
|
10
|
+
createOrTouchPairingRequest,
|
|
11
|
+
isSenderAllowed,
|
|
12
|
+
listPendingPairingRequests,
|
|
13
|
+
listStoredAllowedSenders,
|
|
14
|
+
parseAllowFromCsv,
|
|
15
|
+
parsePairingPolicy,
|
|
16
|
+
} from './pairing.ts'
|
|
17
|
+
|
|
18
|
+
function withTempDataDir<T>(fn: (dir: string) => T): T {
|
|
19
|
+
const original = process.env.DATA_DIR
|
|
20
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'swarmclaw-pairing-test-'))
|
|
21
|
+
process.env.DATA_DIR = tempDir
|
|
22
|
+
try {
|
|
23
|
+
return fn(tempDir)
|
|
24
|
+
} finally {
|
|
25
|
+
if (typeof original === 'string') process.env.DATA_DIR = original
|
|
26
|
+
else delete process.env.DATA_DIR
|
|
27
|
+
fs.rmSync(tempDir, { recursive: true, force: true })
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
test('pairing store creates request, approves code, and persists allowlist', () => {
|
|
32
|
+
withTempDataDir(() => {
|
|
33
|
+
const connectorId = 'pair-test-1'
|
|
34
|
+
|
|
35
|
+
const first = createOrTouchPairingRequest({
|
|
36
|
+
connectorId,
|
|
37
|
+
senderId: '+15551234567',
|
|
38
|
+
senderName: 'Alice',
|
|
39
|
+
channelId: 'chat:1',
|
|
40
|
+
})
|
|
41
|
+
assert.equal(first.created, true)
|
|
42
|
+
assert.equal(first.code.length, 8)
|
|
43
|
+
|
|
44
|
+
const second = createOrTouchPairingRequest({
|
|
45
|
+
connectorId,
|
|
46
|
+
senderId: '+15551234567',
|
|
47
|
+
senderName: 'Alice',
|
|
48
|
+
channelId: 'chat:1',
|
|
49
|
+
})
|
|
50
|
+
assert.equal(second.created, false)
|
|
51
|
+
assert.equal(second.code, first.code)
|
|
52
|
+
|
|
53
|
+
const pendingBefore = listPendingPairingRequests(connectorId)
|
|
54
|
+
assert.equal(pendingBefore.length, 1)
|
|
55
|
+
assert.equal(pendingBefore[0].senderId, '+15551234567')
|
|
56
|
+
|
|
57
|
+
const bad = approvePairingCode(connectorId, 'INVALID')
|
|
58
|
+
assert.equal(bad.ok, false)
|
|
59
|
+
|
|
60
|
+
const approved = approvePairingCode(connectorId, first.code)
|
|
61
|
+
assert.equal(approved.ok, true)
|
|
62
|
+
assert.equal(approved.senderId, '+15551234567')
|
|
63
|
+
|
|
64
|
+
const pendingAfter = listPendingPairingRequests(connectorId)
|
|
65
|
+
assert.equal(pendingAfter.length, 0)
|
|
66
|
+
|
|
67
|
+
const stored = listStoredAllowedSenders(connectorId)
|
|
68
|
+
assert.deepEqual(stored, ['+15551234567'])
|
|
69
|
+
|
|
70
|
+
assert.equal(isSenderAllowed({ connectorId, senderId: '+15551234567' }), true)
|
|
71
|
+
assert.equal(isSenderAllowed({ connectorId, senderId: '+16667778888' }), false)
|
|
72
|
+
|
|
73
|
+
clearConnectorPairingState(connectorId)
|
|
74
|
+
assert.deepEqual(listStoredAllowedSenders(connectorId), [])
|
|
75
|
+
})
|
|
76
|
+
})
|
|
77
|
+
|
|
78
|
+
test('pairing helpers normalize policy and allowFrom csv entries', () => {
|
|
79
|
+
assert.equal(parsePairingPolicy('PAIRING'), 'pairing')
|
|
80
|
+
assert.equal(parsePairingPolicy('allowlist'), 'allowlist')
|
|
81
|
+
assert.equal(parsePairingPolicy('unknown', 'open'), 'open')
|
|
82
|
+
|
|
83
|
+
const list = parseAllowFromCsv(' +1555,TEST@example.com,+1555 , ')
|
|
84
|
+
assert.deepEqual(list, ['+1555', 'test@example.com'])
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
test('addAllowedSender deduplicates and normalizes sender ids', () => {
|
|
88
|
+
withTempDataDir(() => {
|
|
89
|
+
const connectorId = 'pair-test-2'
|
|
90
|
+
const first = addAllowedSender(connectorId, ' TEST@Example.com ')
|
|
91
|
+
assert.equal(first.added, true)
|
|
92
|
+
assert.equal(first.normalized, 'test@example.com')
|
|
93
|
+
|
|
94
|
+
const second = addAllowedSender(connectorId, 'test@example.com')
|
|
95
|
+
assert.equal(second.added, false)
|
|
96
|
+
|
|
97
|
+
assert.deepEqual(listStoredAllowedSenders(connectorId), ['test@example.com'])
|
|
98
|
+
})
|
|
99
|
+
})
|
|
@@ -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
|
+
}
|
|
@@ -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
|
-
//
|
|
27
|
-
const processActivity = async (
|
|
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.
|
|
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,4 +1,5 @@
|
|
|
1
1
|
import { loadQueue, loadSchedules, loadSessions, saveSessions, loadConnectors } from './storage'
|
|
2
|
+
import { notify } from './ws-hub'
|
|
2
3
|
import { processNext, cleanupFinishedTaskSessions, validateCompletedTasksQueue, recoverStalledRunningTasks } from './queue'
|
|
3
4
|
import { startScheduler, stopScheduler } from './scheduler'
|
|
4
5
|
import { sweepOrphanedBrowsers, getActiveBrowserCount } from './session-tools'
|
|
@@ -114,6 +115,7 @@ export function startDaemon(options?: { source?: string; manualStart?: boolean }
|
|
|
114
115
|
return
|
|
115
116
|
}
|
|
116
117
|
ds.running = true
|
|
118
|
+
notify('daemon')
|
|
117
119
|
console.log(`[daemon] Starting daemon (source=${source}, scheduler + queue processor + heartbeat)`)
|
|
118
120
|
|
|
119
121
|
validateCompletedTasksQueue()
|
|
@@ -135,6 +137,7 @@ export function stopDaemon(options?: { source?: string; manualStop?: boolean })
|
|
|
135
137
|
if (options?.manualStop === true) ds.manualStopRequested = true
|
|
136
138
|
if (!ds.running) return
|
|
137
139
|
ds.running = false
|
|
140
|
+
notify('daemon')
|
|
138
141
|
console.log(`[daemon] Stopping daemon (source=${source})`)
|
|
139
142
|
|
|
140
143
|
stopScheduler()
|
|
@@ -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 =
|
|
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
|
-
|
|
136
|
+
genId(8),
|
|
137
137
|
e.sessionId,
|
|
138
138
|
e.runId ?? null,
|
|
139
139
|
e.agentId ?? null,
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import path from 'path'
|
|
1
3
|
import { loadAgents, loadSessions, loadSettings } from './storage'
|
|
2
4
|
import { enqueueSessionRun, getSessionRunState } from './session-run-manager'
|
|
3
5
|
import { log } from './logger'
|
|
4
6
|
import { buildMainLoopHeartbeatPrompt, getMainLoopStateForSession, isMainSession } from './main-agent-loop'
|
|
7
|
+
import { WORKSPACE_DIR } from './data-dir'
|
|
5
8
|
|
|
6
9
|
const HEARTBEAT_TICK_MS = 5_000
|
|
7
10
|
|
|
@@ -118,6 +121,56 @@ export interface HeartbeatConfig {
|
|
|
118
121
|
|
|
119
122
|
const DEFAULT_HEARTBEAT_PROMPT = 'Read HEARTBEAT.md if it exists (workspace context). Follow it strictly. Do not infer or repeat old tasks from prior chats. If nothing needs attention, reply HEARTBEAT_OK.'
|
|
120
123
|
|
|
124
|
+
function readHeartbeatFile(session: any): string {
|
|
125
|
+
try {
|
|
126
|
+
const filePath = path.join(session.cwd || WORKSPACE_DIR, 'HEARTBEAT.md')
|
|
127
|
+
if (fs.existsSync(filePath)) {
|
|
128
|
+
return fs.readFileSync(filePath, 'utf-8').trim()
|
|
129
|
+
}
|
|
130
|
+
} catch { /* ignore */ }
|
|
131
|
+
return ''
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function buildAgentHeartbeatPrompt(session: any, agent: any, fallbackPrompt: string, heartbeatFileContent: string): string {
|
|
135
|
+
if (!agent) return fallbackPrompt
|
|
136
|
+
|
|
137
|
+
// Dynamic goal (agent-set) takes priority over static system prompt
|
|
138
|
+
const dynamicGoal = agent.heartbeatGoal || ''
|
|
139
|
+
const dynamicNextAction = agent.heartbeatNextAction || ''
|
|
140
|
+
const description = agent.description || ''
|
|
141
|
+
const systemPrompt = agent.systemPrompt || ''
|
|
142
|
+
const soul = agent.soul || ''
|
|
143
|
+
const goalSummary = systemPrompt.slice(0, 500)
|
|
144
|
+
const recentMessages = (session.messages || []).slice(-5)
|
|
145
|
+
const recentContext = recentMessages
|
|
146
|
+
.map((m: any) => `[${m.role}]: ${(m.text || '').slice(0, 200)}`)
|
|
147
|
+
.join('\n')
|
|
148
|
+
|
|
149
|
+
return [
|
|
150
|
+
'AGENT_HEARTBEAT_TICK',
|
|
151
|
+
`Time: ${new Date().toISOString()}`,
|
|
152
|
+
`Agent: ${agent.name}`,
|
|
153
|
+
description ? `Description: ${description}` : '',
|
|
154
|
+
dynamicGoal
|
|
155
|
+
? `Current goal (self-set): ${dynamicGoal}`
|
|
156
|
+
: goalSummary ? `System prompt (initial goal):\n${goalSummary}` : '',
|
|
157
|
+
dynamicNextAction ? `Planned next action: ${dynamicNextAction}` : '',
|
|
158
|
+
soul ? `Persona: ${soul.slice(0, 300)}` : '',
|
|
159
|
+
heartbeatFileContent ? `\nHEARTBEAT.md contents:\n${heartbeatFileContent.slice(0, 2000)}` : '',
|
|
160
|
+
recentContext ? `Recent conversation:\n${recentContext}` : '',
|
|
161
|
+
fallbackPrompt !== DEFAULT_HEARTBEAT_PROMPT ? `\nAgent instructions:\n${fallbackPrompt}` : '',
|
|
162
|
+
'',
|
|
163
|
+
'You are running an autonomous heartbeat tick. Review your goal and recent context.',
|
|
164
|
+
'If there is meaningful work to do toward your goal, use your tools and take action.',
|
|
165
|
+
'If nothing needs attention right now, reply exactly HEARTBEAT_OK.',
|
|
166
|
+
'Do not ask clarifying questions. Take the most reasonable next action.',
|
|
167
|
+
'',
|
|
168
|
+
'To update your goal or plan, include this line in your response:',
|
|
169
|
+
'[AGENT_HEARTBEAT_META]{"goal": "your evolved goal", "status": "progress", "next_action": "what you plan to do next"}',
|
|
170
|
+
'You can evolve your goal as you learn more. Set status to "progress" while working, "ok" when done, "idle" when waiting.',
|
|
171
|
+
].filter(Boolean).join('\n')
|
|
172
|
+
}
|
|
173
|
+
|
|
121
174
|
function resolveInterval(obj: Record<string, any>, currentSec: number): number {
|
|
122
175
|
// Prefer heartbeatInterval (duration string) over heartbeatIntervalSec (raw number)
|
|
123
176
|
if (obj.heartbeatInterval !== undefined && obj.heartbeatInterval !== null) {
|
|
@@ -288,9 +341,20 @@ async function tickHeartbeats() {
|
|
|
288
341
|
const runState = getSessionRunState(session.id)
|
|
289
342
|
if (runState.runningRunId) continue
|
|
290
343
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
344
|
+
let heartbeatMessage: string
|
|
345
|
+
if (isMainSession(session)) {
|
|
346
|
+
heartbeatMessage = buildMainLoopHeartbeatPrompt(session, cfg.prompt)
|
|
347
|
+
} else {
|
|
348
|
+
const heartbeatFileContent = readHeartbeatFile(session)
|
|
349
|
+
const hasGoal = !!(agent?.heartbeatGoal || agent?.description || agent?.systemPrompt || agent?.soul)
|
|
350
|
+
const hasCustomPrompt = cfg.prompt !== DEFAULT_HEARTBEAT_PROMPT
|
|
351
|
+
// Skip heartbeat only if there's truly nothing to drive it:
|
|
352
|
+
// no agent goal, no HEARTBEAT.md content, AND no custom prompt configured
|
|
353
|
+
if (!hasGoal && !heartbeatFileContent && !hasCustomPrompt) {
|
|
354
|
+
continue
|
|
355
|
+
}
|
|
356
|
+
heartbeatMessage = buildAgentHeartbeatPrompt(session, agent, cfg.prompt, heartbeatFileContent)
|
|
357
|
+
}
|
|
294
358
|
|
|
295
359
|
const enqueue = enqueueSessionRun({
|
|
296
360
|
sessionId: session.id,
|
|
@@ -104,39 +104,8 @@ function rowToEntry(row: Record<string, unknown>): MemoryEntry {
|
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
|
|
107
|
-
// ---- Knowledge helpers (
|
|
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
|