-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
877 lines (775 loc) · 29.4 KB
/
index.js
File metadata and controls
877 lines (775 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
/** @typedef {import('pear-interface')} */ /* global Pear */
/**
* Oikos Companion — Pear Runtime P2P Client
*
* Lightweight companion app that connects to a running oikos-wallet
* over Hyperswarm. No sidecar, no Node.js, no Express.
*
* The Bare main process:
* 1. Loads/creates Ed25519 companion keypair
* 2. Derives companion topic (BLAKE2b, matches CompanionCoordinator)
* 3. Connects to agent's oikos-app via Hyperswarm Noise
* 4. Opens protomux oikos/companion channel
* 5. Caches incoming state, serves internal HTTP API for renderer
*
* Architecture:
* Agent (oikos-wallet) <== Hyperswarm Noise E2E ==> This (Bare main)
* |
* bare-http1 :13421
* |
* Electron Renderer
*/
import Runtime from 'pear-electron'
import Bridge from 'pear-bridge'
import http from 'bare-http1'
import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import env from 'bare-env'
import b4a from 'b4a'
import sodium from 'sodium-universal'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import c from 'compact-encoding'
const INTERNAL_PORT = parseInt(env.OIKOS_PORT || '13421', 10)
// Prevent uncaught Hyperswarm errors (ETIMEDOUT, etc.) from crashing the Pear app
if (typeof Bare !== 'undefined') {
Bare.on('uncaughtException', (err) => {
console.log('[companion] Uncaught error (recovered):', err.message || err)
console.log('[companion] Stack:', err.stack || 'no stack')
})
}
// Also catch on server errors
if (typeof globalThis.addEventListener === 'function') {
globalThis.addEventListener('error', (e) => {
console.log('[companion] Global error:', e.message || e)
})
}
// ── State cache (updated by companion channel messages) ──
const state = {
connected: false,
balances: [],
reasoning: { status: 'idle', reasoning: '', decision: '' },
policies: [],
swarm: { enabled: false, peersConnected: 0, activeRooms: 0, announcements: 0, economics: {} },
executions: [],
approvalRequests: [],
instructions: [],
chatMessages: [],
identity: {},
prices: [],
addresses: [],
strategies: [],
auditEntries: [],
lastUpdate: 0,
}
// Pending chat reply resolvers (instruction → wait for chat_reply)
let chatReplyResolve = null
// Pending protomux request/response correlators (requestId → resolve callback)
const pendingRequests = new Map()
let companionMessage = null
let swarm = null
// ── 1. Keypair management ──
function loadOrCreateKeypair (filepath) {
try {
const dir = path.dirname(filepath)
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
if (fs.existsSync(filepath)) {
const data = JSON.parse(fs.readFileSync(filepath, 'utf-8'))
return {
publicKey: b4a.from(data.publicKey, 'hex'),
secretKey: b4a.from(data.secretKey, 'hex')
}
}
} catch { /* create new */ }
const publicKey = b4a.alloc(sodium.crypto_sign_PUBLICKEYBYTES)
const secretKey = b4a.alloc(sodium.crypto_sign_SECRETKEYBYTES)
sodium.crypto_sign_keypair(publicKey, secretKey)
const dir = path.dirname(filepath)
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(filepath, JSON.stringify({
publicKey: b4a.toString(publicKey, 'hex'),
secretKey: b4a.toString(secretKey, 'hex')
}))
return { publicKey, secretKey }
}
// ── 2. Configuration ──
const oikosHome = env.OIKOS_HOME || path.join(os.homedir(), '.oikos')
const keypairPath = path.join(oikosHome, 'companion-keypair.json')
const keypair = loadOrCreateKeypair(keypairPath)
const companionPubkey = b4a.toString(keypair.publicKey, 'hex')
// Try env first, then auto-detect from agent-written file, then manual pairing file
let agentPubkey = env.OIKOS_AGENT_PUBKEY || null
if (!agentPubkey) {
// Priority 1: agent-swarm-pubkey.txt (written by agent on startup — always correct)
// Priority 2: agent-pubkey.txt (manual pairing / legacy)
const candidates = [
path.join(oikosHome, 'agent-swarm-pubkey.txt'),
path.join(oikosHome, 'agent-pubkey.txt')
]
for (const autoPath of candidates) {
try {
if (fs.existsSync(autoPath)) {
const pk = fs.readFileSync(autoPath, 'utf-8').trim()
if (/^[0-9a-fA-F]{64}$/.test(pk)) {
agentPubkey = pk
console.log('[companion] Auto-detected agent pubkey from ' + path.basename(autoPath))
break
}
}
} catch { /* try next */ }
}
}
const topicSeed = env.OIKOS_TOPIC_SEED || 'oikos-companion-default'
// Auth state cache (populated by auth_update protomux messages)
const authState = { enabled: false, authenticated: false, threshold: 100, pending: [] }
console.log('[companion] Pubkey:', companionPubkey.slice(0, 16) + '...')
console.log('[companion] Set this as COMPANION_OWNER_PUBKEY on your agent.')
if (!agentPubkey) {
console.log('[companion] No OIKOS_AGENT_PUBKEY set. Running in offline mode.')
console.log('[companion] Set OIKOS_AGENT_PUBKEY=<agent swarm pubkey> to connect.')
}
// ── 3. Hyperswarm companion client ──
function sendToAgent (msg) {
if (!state.connected || !companionMessage) return false
try {
const m = companionMessage
m.send(b4a.from(JSON.stringify(msg)))
return true
} catch {
return false
}
}
function handleAgentMessage (buf) {
try {
const text = b4a.toString(buf, 'utf-8')
const msg = JSON.parse(text)
state.lastUpdate = Date.now()
switch (msg.type) {
case 'balance_update':
state.balances = msg.balances || []
break
case 'agent_reasoning':
state.reasoning = {
status: msg.status || 'idle',
reasoning: msg.reasoning || '',
decision: msg.decision || ''
}
break
case 'policy_update':
state.policies = msg.policies || []
break
case 'swarm_status':
state.swarm = {
enabled: true,
peersConnected: msg.peersConnected || 0,
activeRooms: msg.activeRooms || 0,
announcements: msg.announcements || 0,
boardPeers: msg.boardPeers || [],
announcementList: msg.announcementList || [],
roomList: msg.roomList || [],
identity: msg.identity || null,
economics: msg.economics || {}
}
break
case 'execution_notify':
state.executions.push(msg.result)
if (state.executions.length > 50) state.executions.shift()
break
case 'audit_update':
state.auditEntries = msg.entries || []
break
case 'approval_request':
state.approvalRequests.push(msg)
break
case 'address_update':
state.addresses = msg.addresses || []
break
case 'price_update':
state.prices = msg.prices || []
break
case 'identity_update':
state.identity = msg.identity || {}
break
case 'chat_reply': {
// Agent brain replied to our instruction via protomux
const agentMsg = {
id: 'msg-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8),
text: msg.text || '',
from: 'agent',
brainName: msg.brainName || 'unknown',
timestamp: msg.timestamp || Date.now()
}
state.chatMessages.push(agentMsg)
if (state.chatMessages.length > 100) state.chatMessages.shift()
console.log('[companion] Chat reply from ' + agentMsg.brainName + ': ' + agentMsg.text.slice(0, 60) + '...')
// Resolve any pending chat request
if (chatReplyResolve) {
chatReplyResolve(agentMsg)
chatReplyResolve = null
}
break
}
case 'strategy_update':
state.strategies = (msg.strategies || []).map(s => ({
id: (s.filename || '').replace('.md', ''),
name: ((s.content || '').match(/^#\s+(.+)$/m) || [])[1] || (s.filename || '').replace('.md', ''),
filename: s.filename,
source: s.source || 'human',
enabled: s.enabled,
content: s.content,
createdAt: '',
}))
break
case 'strategy_result': {
const cb = pendingRequests.get(msg.requestId)
if (cb) { pendingRequests.delete(msg.requestId); cb(msg) }
break
}
case 'policy_result': {
const cb = pendingRequests.get(msg.requestId)
if (cb) { pendingRequests.delete(msg.requestId); cb(msg) }
break
}
case 'auth_update':
authState.status = msg.status || {}
authState.pending = msg.pending || []
break
case 'auth_response': {
const cb = pendingRequests.get(msg.requestId)
if (cb) { pendingRequests.delete(msg.requestId); cb(msg) }
break
}
default:
console.log('[companion] Unknown message:', msg.type)
}
} catch {
console.log('[companion] Failed to parse agent message')
}
}
async function connectToAgent () {
if (!agentPubkey) return
// Derive COMPANION topic — matches companion/coordinator.ts lines 103-109.
// The agent uses COMPANION_OWNER_PUBKEY (our pubkey) as the BLAKE2b key.
// A dedicated topic prevents swarm socket cycling from killing the companion channel.
const companionTopic = b4a.alloc(32)
sodium.crypto_generichash(
companionTopic,
b4a.from('oikos-companion-v0:' + topicSeed),
keypair.publicKey // our own Ed25519 pubkey = the owner key
)
console.log('[companion] Companion topic:', b4a.toString(companionTopic, 'hex').slice(0, 16) + '...')
console.log('[companion] Looking for agent:', agentPubkey.slice(0, 16) + '...')
const swarmOpts = { keyPair: keypair }
const relayHex = env.SWARM_RELAY_PUBKEY || 'e7ab6adb1a18e7d22649691dc65f5789f6fdd25422b0770ab068ee9bbe0a3003'
if (relayHex) {
try {
const relayBuf = b4a.from(relayHex, 'hex')
swarmOpts.relayThrough = () => relayBuf
} catch { /* skip */ }
}
swarm = new Hyperswarm(swarmOpts)
// Maintain persistent connection to relay for NAT traversal
if (relayHex) {
try {
swarm.joinPeer(b4a.from(relayHex, 'hex'))
console.log('[companion] Joined relay peer:', relayHex.slice(0, 16) + '...')
} catch { /* non-fatal */ }
}
// Catch uncaught errors on swarm to prevent crashes
swarm.on('error', (err) => {
console.log('[companion] Swarm error (non-fatal):', err.message || err)
})
// Rate-limit noisy peer logs (relay connects/disconnects/timeouts loop)
const seenPeers = new Map()
const PEER_LOG_INTERVAL = 60000 // log each non-agent peer at most once per minute
swarm.on('connection', (socket) => {
const remotePubkey = socket.remotePublicKey
if (!remotePubkey) return
const remoteHex = b4a.toString(remotePubkey, 'hex')
// Catch socket errors to prevent uncaught ETIMEDOUT crashes
socket.on('error', () => { /* non-fatal, suppressed */ })
// Only open companion channel with the expected agent, not relay or other peers
if (remoteHex !== agentPubkey) {
const now = Date.now()
const lastLog = seenPeers.get(remoteHex) || 0
if (now - lastLog > PEER_LOG_INTERVAL) {
console.log('[companion] Ignoring non-agent peer:', remoteHex.slice(0, 16) + '...')
seenPeers.set(remoteHex, now)
}
return
}
console.log('[companion] Agent connected:', remoteHex.slice(0, 16) + '...')
const mux = Protomux.from(socket)
const channel = mux.createChannel({
protocol: 'oikos/companion',
id: null,
unique: true,
messages: [{
encoding: c.raw,
onmessage: (buf) => handleAgentMessage(buf)
}],
onclose: () => {
console.log('[companion] Channel closed.')
state.connected = false
companionMessage = null
}
})
companionMessage = channel.messages[0]
channel.open()
state.connected = true
socket.on('close', () => {
state.connected = false
companionMessage = null
console.log('[companion] Disconnected. Will reconnect via DHT...')
})
// Ping to trigger immediate state push from agent
sendToAgent({ type: 'ping', timestamp: Date.now() })
console.log('[companion] Channel open. Receiving state updates.')
})
const discovery = swarm.join(companionTopic, { server: false, client: true })
await discovery.flushed()
console.log('[companion] Joined topic. Searching for agent...')
}
// ── 4. Internal HTTP API (bare-http1) ──
function readBody (req) {
return new Promise((resolve) => {
const chunks = []
req.on('data', (chunk) => chunks.push(chunk))
req.on('end', () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()))
} catch {
resolve({})
}
})
})
}
// Send a message over protomux and wait for a correlated response by requestId
function sendProtomuxRequest (msg, timeoutMs) {
timeoutMs = timeoutMs || 10000
return new Promise((resolve) => {
if (!companionMessage) {
resolve({ error: 'Companion channel not connected' })
return
}
const timer = setTimeout(() => {
pendingRequests.delete(msg.requestId)
resolve({ error: 'Timeout waiting for wallet response' })
}, timeoutMs)
pendingRequests.set(msg.requestId, (result) => {
clearTimeout(timer)
resolve(result)
})
try {
companionMessage.send(Buffer.from(JSON.stringify(msg)))
} catch (err) {
clearTimeout(timer)
pendingRequests.delete(msg.requestId)
resolve({ error: 'Failed to send: ' + (err.message || String(err)) })
}
})
}
function json (res, data, status) {
res.statusCode = status || 200
res.setHeader('Content-Type', 'application/json')
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
res.end(JSON.stringify(data))
}
const server = http.createServer(async (req, res) => {
// CORS preflight
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
res.statusCode = 204
res.end()
return
}
const url = req.url || '/'
// ── GET endpoints ──
// ── Companion pairing endpoints ──
if (url === '/api/companion/pubkey') {
return json(res, { pubkey: companionPubkey })
}
if (url === '/api/companion/status') {
return json(res, {
connected: state.connected,
companionPubkey: companionPubkey,
agentPubkey: agentPubkey ? agentPubkey : null,
agentPubkeyShort: agentPubkey ? agentPubkey.slice(0, 16) + '...' : null
})
}
if (url === '/api/companion/pair' && req.method === 'POST') {
try {
const body = await readBody(req)
const pk = (body.agentPubkey || '').trim()
if (!pk || !/^[0-9a-fA-F]{64}$/.test(pk)) {
return json(res, { error: 'Invalid pubkey. Must be 64 hex chars.' }, 400)
}
// Write to persistent file
const agentPubkeyPath = path.join(oikosHome, 'agent-pubkey.txt')
const dir = path.dirname(agentPubkeyPath)
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(agentPubkeyPath, pk)
agentPubkey = pk
console.log('[companion] Paired with agent:', pk.slice(0, 16) + '...')
// Trigger connection (non-blocking)
connectToAgent().catch((err) => console.log('[companion] Connect error:', err.message || err))
return json(res, { success: true, agentPubkey: pk })
} catch (e) {
return json(res, { error: 'Failed to pair: ' + (e.message || String(e)) }, 500)
}
}
if (url === '/api/companion/unpair' && req.method === 'POST') {
try {
const agentPubkeyPath = path.join(oikosHome, 'agent-pubkey.txt')
if (fs.existsSync(agentPubkeyPath)) fs.unlinkSync(agentPubkeyPath)
agentPubkey = null
if (swarm) { swarm.destroy(); swarm = null }
state.connected = false
companionMessage = null
console.log('[companion] Unpaired. Running in offline mode.')
return json(res, { success: true })
} catch (e) {
return json(res, { error: 'Failed to unpair: ' + (e.message || String(e)) }, 500)
}
}
if (url === '/api/config') {
return json(res, { port: INTERNAL_PORT })
}
if (url === '/api/health') {
return json(res, {
status: 'ok',
walletConnected: state.connected,
swarmEnabled: state.swarm.enabled,
companionConnected: state.connected,
eventsBuffered: state.executions.length
})
}
if (url === '/api/state') {
return json(res, {
status: state.connected ? 'running' : 'disconnected',
balances: state.balances,
recentResults: state.executions.slice(-10),
swarmEvents: [],
eventsSeen: state.executions.length,
proposalsSent: state.executions.length,
proposalsApproved: state.executions.filter(e => e && e.status === 'executed').length,
proposalsRejected: state.executions.filter(e => e && e.status === 'rejected').length,
defiOps: 0,
lastReasoning: state.reasoning.reasoning || (state.connected ? 'Connected to agent.' : 'Not connected.'),
lastDecision: state.reasoning.decision || '--'
})
}
if (url === '/api/balances') {
return json(res, { balances: state.balances })
}
if (url === '/api/addresses') {
return json(res, { addresses: state.addresses || [] })
}
if (url === '/api/policies' && req.method === 'GET') {
return json(res, { policies: state.policies })
}
if (url === '/api/policies' && req.method === 'POST') {
if (!companionMessage) return json(res, { error: 'Not connected to agent' }, 503)
const body = await readBody(req)
const requestId = 'pr-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6)
const result = await sendProtomuxRequest({
type: 'policy_save', rules: body.rules, name: body.name,
requestId, timestamp: Date.now()
}, 15000) // longer timeout — includes wallet restart
return json(res, result)
}
if (url === '/api/strategies' && req.method === 'GET') {
return json(res, { strategies: state.strategies, modules: [] })
}
if (url === '/api/strategies' && req.method === 'POST') {
const body = await readBody(req)
// Protomux first when connected — modify remote agent's strategies
if (companionMessage) {
const requestId = 'sr-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6)
const result = await sendProtomuxRequest({
type: 'strategy_save', filename: body.filename, content: body.content,
requestId, timestamp: Date.now()
})
return json(res, result)
}
return json(res, { error: 'Wallet not connected' }, 503)
}
if (url === '/api/strategies/toggle' && req.method === 'POST') {
const body = await readBody(req)
// Protomux first when connected — toggle remote agent's strategies
if (companionMessage) {
const requestId = 'st-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6)
const result = await sendProtomuxRequest({
type: 'strategy_toggle', filename: body.filename, enabled: body.enabled,
requestId, timestamp: Date.now()
})
return json(res, result)
}
return json(res, { error: 'Wallet not connected' }, 503)
}
if (url === '/api/strategies/delete' && req.method === 'POST') {
if (!companionMessage) return json(res, { error: 'Not connected to agent' }, 503)
const body = await readBody(req)
const requestId = 'sd-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6)
const result = await sendProtomuxRequest({
type: 'strategy_delete', filename: body.filename,
requestId, timestamp: Date.now()
})
return json(res, result)
}
if (url.startsWith('/api/audit')) {
const entries = state.auditEntries.length > 0 ? state.auditEntries : state.executions
return json(res, { entries })
}
// ── Auth API — via protomux companion channel ──
if (url === '/api/auth/status' && req.method === 'GET') {
return json(res, authState.status || { enabled: false })
}
if (url === '/api/auth/pending' && req.method === 'GET') {
return json(res, { pending: authState.pending || [] })
}
if (url.startsWith('/api/auth/') && req.method === 'POST') {
if (!companionMessage) return json(res, { error: 'Not connected to agent' }, 503)
const body = await readBody(req)
// Determine action from URL path
const pathParts = url.replace('/api/auth/', '').split('/')
let action = pathParts[0] // setup, verify, disable, change, settings
let payload = body
// Handle /api/auth/pending/:id/resolve
if (pathParts[0] === 'pending' && pathParts[2] === 'resolve') {
action = 'resolve'
payload = { proposalId: pathParts[1], passphrase: body.passphrase }
}
const requestId = 'au-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6)
const result = await sendProtomuxRequest({
type: 'auth_request', action, requestId, payload, timestamp: Date.now()
})
return json(res, result.data || result)
}
if (url === '/api/swarm') {
return json(res, {
enabled: state.swarm.enabled,
peersConnected: state.swarm.peersConnected || 0,
boardPeers: state.swarm.boardPeers || [],
announcements: state.swarm.announcementList || [],
activeRooms: state.swarm.roomList || [],
identity: state.swarm.identity || null,
economics: state.swarm.economics || {},
recentEvents: []
})
}
if (url === '/api/economics') {
return json(res, { enabled: state.swarm.enabled, economics: state.swarm.economics })
}
if (url === '/api/valuation') {
// Use live prices from state cache (populated by companion or wallet-direct)
const fallback = { USDT: 1, USAT: 1, XAUT: 4975, BTC: 73900, ETH: 2300 }
const livePrices = {}
if (state.prices && state.prices.length > 0) {
state.prices.forEach(p => { livePrices[p.symbol] = p.priceUsd })
}
const prices = Object.assign({}, fallback, livePrices)
const decimals = { USDT: 6, USAT: 6, XAUT: 6, BTC: 8, ETH: 18 }
let totalUsd = 0
const assets = (state.balances || []).map(b => {
const sym = (b.symbol || '').toUpperCase()
const price = prices[sym] || 0
const dec = decimals[sym] || 18
const human = Number(b.balance || 0) / Math.pow(10, dec)
const usd = human * price
totalUsd += usd
return { symbol: sym, chain: b.chain, balance: b.balance, humanBalance: human, usdValue: usd, price }
})
return json(res, { totalUsd, assets, updatedAt: state.lastUpdate })
}
if (url === '/api/prices') {
if (state.prices && state.prices.length > 0) {
return json(res, { source: 'agent-live', prices: state.prices })
}
return json(res, {
source: 'fallback',
prices: [
{ symbol: 'USDT', priceUsd: 1, source: 'fallback', updatedAt: Date.now() },
{ symbol: 'USAT', priceUsd: 1, source: 'fallback', updatedAt: Date.now() },
{ symbol: 'XAUT', priceUsd: 4975, source: 'fallback', updatedAt: Date.now() },
{ symbol: 'BTC', priceUsd: 73900, source: 'fallback', updatedAt: Date.now() },
{ symbol: 'ETH', priceUsd: 2300, source: 'fallback', updatedAt: Date.now() }
]
})
}
// Historical prices — deferred to protomux (returns empty for now)
if (url.startsWith('/api/prices/history/')) {
return json(res, { symbol: url.split('/').pop(), history: [] })
}
if (url === '/api/identity') {
return json(res, state.identity || {})
}
if (url === '/api/companion/state') {
return json(res, {
balances: state.balances,
policies: state.policies,
swarm: state.swarm,
events: [],
instructions: state.instructions.slice(-20),
companionConnected: state.connected,
identity: state.identity,
walletConnected: state.connected
})
}
if (url === '/api/events') {
return json(res, { events: state.executions })
}
if (url === '/api/companion/instructions') {
return json(res, { instructions: state.instructions.slice(-50) })
}
// ── Chat endpoints (agent-agnostic bridge) ──
if (url.startsWith('/api/agent/chat/history')) {
return json(res, { messages: state.chatMessages })
}
// ── POST endpoints ──
if (req.method === 'POST' && url === '/api/agent/chat') {
const body = await readBody(req)
const message = String(body.message || '').trim()
if (!message) return json(res, { error: 'message required' }, 400)
const from = body.from || 'companion'
// Store human message
const humanMsg = {
id: 'msg-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8),
text: message,
from: 'human',
timestamp: Date.now()
}
state.chatMessages.push(humanMsg)
if (state.chatMessages.length > 100) state.chatMessages.shift()
// Send instruction via protomux and wait for chat_reply
const sent = sendToAgent({ type: 'instruction', text: message, timestamp: Date.now() })
if (!sent) {
const errMsg = {
id: 'msg-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8),
text: 'Agent not connected. Message queued as instruction.',
from: 'agent',
timestamp: Date.now()
}
state.chatMessages.push(errMsg)
state.instructions.push({ text: message, timestamp: Date.now() })
return json(res, { reply: errMsg.text, from: 'agent', brainName: 'offline' })
}
// Wait for chat_reply (timeout 120s — Ollama 8B can take 30-60s for complex queries)
try {
const reply = await new Promise((resolve, reject) => {
chatReplyResolve = resolve
setTimeout(() => {
if (chatReplyResolve === resolve) {
chatReplyResolve = null
reject(new Error('timeout'))
}
}, 120000)
})
return json(res, {
reply: reply.text,
from: 'agent',
brainName: reply.brainName || 'unknown',
messageId: reply.id
})
} catch {
return json(res, {
reply: 'Agent did not respond in time. The instruction was sent.',
from: 'agent',
brainName: 'timeout'
})
}
}
if (req.method === 'POST' && url === '/api/companion/instruct') {
const body = await readBody(req)
const text = String(body.text || '').trim()
if (!text) return json(res, { error: 'text required' }, 400)
const instruction = { text, timestamp: Date.now() }
state.instructions.push(instruction)
if (state.instructions.length > 50) state.instructions.shift()
const sent = sendToAgent({ type: 'instruction', text, timestamp: Date.now() })
return json(res, { ok: true, sent, queued: state.instructions.length })
}
if (req.method === 'POST' && url === '/api/companion/propose') {
const body = await readBody(req)
// Translate proposal into an instruction for the agent
const type = body.type || 'payment'
let text = ''
if (type === 'swap') {
text = `Swap ${body.amount} ${body.symbol} to ${body.toSymbol}. Reason: ${body.reason || 'companion'}`
} else {
text = `Send ${body.amount} ${body.symbol} to ${body.to}. Reason: ${body.reason || 'companion'}`
}
const sent = sendToAgent({ type: 'instruction', text, timestamp: Date.now() })
return json(res, { ok: true, sent, instruction: text })
}
if (req.method === 'POST' && url === '/api/simulate') {
// Simulate not available over companion channel
return json(res, { error: 'Simulate not available in companion mode. Use Chat to instruct the agent.' }, 501)
}
// ── Logo ──
if (url === '/logo.png') {
try {
// Try multiple paths — Bare CWD and import.meta may differ
const dir = typeof import.meta.dirname === 'string' ? import.meta.dirname : '.'
const candidates = [
path.join(dir, 'assets', 'logo.png'),
path.resolve('assets', 'logo.png'),
path.join(home, 'sovclaw', 'assets', 'logo.png')
]
for (const candidate of candidates) {
if (fs.existsSync(candidate)) {
const data = fs.readFileSync(candidate)
res.setHeader('Content-Type', 'image/png')
res.end(data)
return
}
}
res.statusCode = 404
res.end()
return
} catch {
res.statusCode = 404
res.end()
return
}
}
// 404
json(res, { error: 'not found' }, 404)
})
server.on('error', (err) => {
console.log('[companion] HTTP server error:', err.message || err)
})
server.listen(INTERNAL_PORT, '127.0.0.1', () => {
console.log('[companion] Internal API: http://127.0.0.1:' + INTERNAL_PORT)
})
// ── 5. Write port config + Start Electron renderer ──
// Write port config for app.js (Pear app dir is read-only, write to oikosHome)
if (!fs.existsSync(oikosHome)) fs.mkdirSync(oikosHome, { recursive: true })
fs.writeFileSync(path.join(oikosHome, 'port.json'), JSON.stringify({ port: INTERNAL_PORT }))
const bridge = new Bridge()
await bridge.ready()
const runtime = new Runtime()
const pipe = await runtime.start({ bridge })
pipe.on('close', () => {
if (swarm) swarm.destroy()
Pear.exit()
})
// ── 6. Connect to agent (non-blocking — after Runtime is up) ──
connectToAgent().catch((err) => {
console.log('[companion] Swarm connect error:', err.message)
})
console.log('[companion] Oikos Companion ready.')
if (agentPubkey) {
console.log('[companion] Connecting to agent over Hyperswarm...')
} else {
console.log('[companion] Offline mode. Set OIKOS_AGENT_PUBKEY to connect.')
}
Pear.teardown(async () => {
console.log('[companion] Shutting down.')
if (swarm) await swarm.destroy()
})