luca 3.0.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,493 @@
1
+ import { z } from 'zod'
2
+ import { Feature, FeatureStateSchema, FeatureOptionsSchema, FeatureEventsSchema } from 'luca'
3
+ import type { ContainerContext } from 'luca'
4
+ import { x25519 } from '@noble/curves/ed25519.js'
5
+ import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'
6
+ import { blake3 } from '@noble/hashes/blake3.js'
7
+ import { randomBytes } from '@noble/hashes/utils.js'
8
+ import { Iroh, SetTagOption, BlobDownloadOptions } from '@number0/iroh'
9
+ import type { NodeAddr } from '@number0/iroh'
10
+
11
+ export interface BlobMeta {
12
+ hash: string
13
+ format: string
14
+ size: number
15
+ filename: string
16
+ nodeAddr: NodeAddr
17
+ }
18
+
19
+ // Default topic — matches Cipher's public topic_to_id() Rust implementation
20
+ const DEFAULT_TOPIC_BYTES = Array.from(blake3(new TextEncoder().encode('cipher/content/v1')))
21
+
22
+ declare module 'luca' {
23
+ interface AvailableFeatures {
24
+ cipherSocial: typeof CipherSocialFeature
25
+ }
26
+ }
27
+
28
+ export const CipherOptionsSchema = FeatureOptionsSchema.extend({
29
+ /** Name for this agent — used as display name and to namespace stored identity */
30
+ name: z.string().default('luca-agent').describe('Agent display name'),
31
+ /** Override directory for Iroh node data and identity. Defaults to ~/.luca/cipher/<name> */
32
+ dataDir: z.string().optional().describe('Data directory override'),
33
+ /**
34
+ * Full Iroh NodeAddr JSON objects for bootstrap peers.
35
+ * Each entry: { nodeId: string, relayUrl?: string, addresses?: string[] }
36
+ * Get this from another agent's `nodeAddr` state field.
37
+ */
38
+ bootstrapAddrs: z.array(z.string()).default([]).describe('JSON-encoded Iroh NodeAddr objects for bootstrap'),
39
+ /**
40
+ * Private mesh identifier. All agents sharing this value subscribe to the same
41
+ * derived gossip topic and are invisible to agents on different meshes.
42
+ * Defaults to the public Cipher topic — omit only if you want interop with
43
+ * the Cipher desktop app.
44
+ */
45
+ meshId: z.string().optional().describe('Private mesh ID — derives a closed gossip topic'),
46
+ })
47
+ export type CipherOptions = z.infer<typeof CipherOptionsSchema>
48
+
49
+ export const CipherStateSchema = FeatureStateSchema.extend({
50
+ connected: z.boolean().default(false).describe('Whether connected to the Cipher gossip mesh'),
51
+ nodeId: z.string().optional().describe('Iroh transport node ID'),
52
+ nodeAddr: z.string().optional().describe('Full Iroh NodeAddr as JSON — share with peers for bootstrapping'),
53
+ publicKey: z.string().optional().describe('Agent X25519 public key (base64) — share this with peers'),
54
+ peers: z.number().default(0).describe('Known peers seen via presence announcements'),
55
+ })
56
+ export type CipherState = z.infer<typeof CipherStateSchema>
57
+
58
+ export const CipherEventsSchema = FeatureEventsSchema.extend({
59
+ connected: z.tuple([z.object({
60
+ nodeId: z.string(),
61
+ publicKey: z.string(),
62
+ })]).describe('Connected to mesh'),
63
+ message: z.tuple([z.object({
64
+ from: z.string(),
65
+ payload: z.any(),
66
+ timestamp: z.number(),
67
+ })]).describe('Decrypted message received'),
68
+ presence: z.tuple([z.object({
69
+ publicKey: z.string(),
70
+ name: z.string(),
71
+ nodeId: z.string().optional(),
72
+ })]).describe('Peer announced presence'),
73
+ error: z.tuple([z.string()]).describe('Error occurred'),
74
+ })
75
+
76
+ /**
77
+ * Cipher P2P feature — connects a Luca agent to the Cipher encrypted social network.
78
+ *
79
+ * Each agent gets a persistent X25519 identity. Messages are encrypted using
80
+ * Cipher's GossipEnvelope/SealedBox format (ephemeral X25519 ECDH + XChaCha20-Poly1305),
81
+ * fully compatible with the Cipher desktop app.
82
+ *
83
+ * @example
84
+ * ```typescript
85
+ * const cipher = container.feature('cipher', { name: 'planner-agent' })
86
+ * await cipher.connect()
87
+ * console.log('My public key:', cipher.publicKey)
88
+ *
89
+ * cipher.on('message', ({ from, payload }) => {
90
+ * console.log('Message from', from.slice(0, 8), payload)
91
+ * })
92
+ *
93
+ * await cipher.send(recipientPublicKey, { type: 'task', data: { ... } })
94
+ * ```
95
+ */
96
+ export class CipherSocialFeature extends Feature<CipherState, CipherOptions> {
97
+ static override shortcut = 'features.cipherSocial' as const
98
+ static override stateSchema = CipherStateSchema
99
+ static override optionsSchema = CipherOptionsSchema
100
+ static override eventsSchema = CipherEventsSchema
101
+ static { Feature.register(this, 'cipherSocial') }
102
+
103
+ private _iroh: Awaited<ReturnType<typeof Iroh.persistent>> | null = null
104
+ private _sender: any = null
105
+ private _privateKey: Uint8Array | null = null
106
+ private _publicKey: Uint8Array | null = null
107
+ private _knownPeers: Map<string, { name: string; nodeId?: string }> = new Map()
108
+
109
+ private get fs() { return this.container.feature('fs') }
110
+ private get os() { return this.container.feature('os') as any }
111
+
112
+ private get topicBytes(): number[] {
113
+ if (this.options.meshId) {
114
+ return Array.from(blake3(new TextEncoder().encode(`luca/mesh/v1/${this.options.meshId}`)))
115
+ }
116
+ return DEFAULT_TOPIC_BYTES
117
+ }
118
+
119
+ private get identityPath(): string {
120
+ return this.container.paths.resolve(this.dataDir, 'identity.json')
121
+ }
122
+
123
+ private get irohDataDir(): string {
124
+ return this.container.paths.resolve(this.dataDir, 'iroh')
125
+ }
126
+
127
+ /** Connect to the Cipher gossip mesh. Generates identity on first run. */
128
+ async connect(): Promise<void> {
129
+ await this.loadOrGenerateKeypair()
130
+
131
+ this.fs.ensureFolder(this.irohDataDir)
132
+ this._iroh = await Iroh.persistent(this.irohDataDir)
133
+ const nodeId = await this._iroh.net.nodeId()
134
+ const nodeAddr = await this._iroh.net.nodeAddr()
135
+
136
+ // Add bootstrap peer addresses so Iroh knows how to reach them
137
+ const bootstrapNodeIds: string[] = []
138
+ for (const addrJson of this.options.bootstrapAddrs) {
139
+ try {
140
+ const addr = JSON.parse(addrJson)
141
+ await this._iroh.net.addNodeAddr(addr)
142
+ bootstrapNodeIds.push(addr.nodeId)
143
+ } catch (e) {
144
+ // ignore malformed bootstrap entries
145
+ }
146
+ }
147
+
148
+ // When bootstrapping, wait for the joined event before considering the mesh ready.
149
+ // Without this, broadcast() fires before the gossip connection is established.
150
+ let meshReady: (() => void) | null = null
151
+ const meshJoined = bootstrapNodeIds.length > 0
152
+ ? new Promise<void>(resolve => { meshReady = resolve })
153
+ : Promise.resolve()
154
+
155
+ this._sender = await this._iroh.gossip.subscribe(
156
+ this.topicBytes,
157
+ bootstrapNodeIds,
158
+ (error: Error | null, event: any) => {
159
+ if (error) {
160
+ this.emit('error', error.message)
161
+ return
162
+ }
163
+ if (event.joined && meshReady) {
164
+ meshReady()
165
+ meshReady = null
166
+ }
167
+ if (event.received) {
168
+ this.handleIncoming(event.received)
169
+ }
170
+ }
171
+ )
172
+
173
+ // Wait for mesh to be ready (or 8s timeout to avoid hanging forever)
174
+ await Promise.race([
175
+ meshJoined,
176
+ new Promise<void>(resolve => setTimeout(resolve, 8000)),
177
+ ])
178
+
179
+ const publicKey = Buffer.from(this._publicKey!).toString('base64')
180
+ this.setState({ connected: true, nodeId, nodeAddr: JSON.stringify(nodeAddr), publicKey })
181
+ this.emit('connected', { nodeId, publicKey })
182
+
183
+ await this.announcePresence()
184
+ }
185
+
186
+ /**
187
+ * Send an encrypted message to a specific agent by their X25519 public key.
188
+ * The payload can be any JSON-serializable value.
189
+ */
190
+ async send(recipientPublicKey: string, payload: any): Promise<void> {
191
+ if (!this._sender || !this._publicKey) throw new Error('Not connected — call connect() first')
192
+
193
+ const contentPayload = {
194
+ DirectMessage: {
195
+ content: JSON.stringify({ 'luca:v1': payload }),
196
+ thread_id: null,
197
+ }
198
+ }
199
+
200
+ const envelope = this.buildEnvelope([recipientPublicKey], contentPayload)
201
+ const p2pMessage = { SealedEnvelope: { envelope_json: JSON.stringify(envelope) } }
202
+ await this._sender.broadcast(Array.from(Buffer.from(JSON.stringify(p2pMessage))))
203
+ }
204
+
205
+ /** Broadcast presence so other agents learn your public key and name. */
206
+ async announcePresence(): Promise<void> {
207
+ if (!this._sender || !this._publicKey) return
208
+ const presence = {
209
+ Presence: {
210
+ public_key: Buffer.from(this._publicKey).toString('base64'),
211
+ display_name: this.options.name,
212
+ node_id: this.state.get('nodeId') ?? '',
213
+ timestamp: Date.now(),
214
+ // Required fields for Cipher protocol compat
215
+ user_id: this.agentUserId,
216
+ encryption_public_key: Buffer.from(this._publicKey).toString('base64'),
217
+ device_id: this.agentUserId,
218
+ bio: 'Luca agent',
219
+ profile_picture: '',
220
+ profile_signature: null,
221
+ node_addr: { node_id: this.state.get('nodeId') ?? '', relay_url: null, direct_addresses: [] },
222
+ }
223
+ }
224
+ await this._sender.broadcast(Array.from(Buffer.from(JSON.stringify(presence))))
225
+ }
226
+
227
+ async disconnect(): Promise<void> {
228
+ await this._sender?.close()
229
+ await this._iroh?.node.shutdown()
230
+ this._iroh = null
231
+ this._sender = null
232
+ this.setState({ connected: false })
233
+ }
234
+
235
+ get publicKey(): string | undefined {
236
+ return this.state.get('publicKey')
237
+ }
238
+
239
+ get nodeId(): string | undefined {
240
+ return this.state.get('nodeId')
241
+ }
242
+
243
+ /** Full NodeAddr JSON — pass this to other agents via --bootstrap-addr for immediate connectivity */
244
+ get nodeAddrJson(): string | undefined {
245
+ return this.state.get('nodeAddr')
246
+ }
247
+
248
+ get knownPeers(): Map<string, { name: string; nodeId?: string }> {
249
+ return this._knownPeers
250
+ }
251
+
252
+ /**
253
+ * Store a file as an Iroh blob. Returns a BlobMeta object that you can
254
+ * include in a message so the recipient can fetch the file.
255
+ * @param filePath Path to the file (relative to container.cwd)
256
+ */
257
+ async storeFile(filePath: string): Promise<BlobMeta> {
258
+ if (!this._iroh) throw new Error('Not connected — call connect() first')
259
+ const absolutePath = this.container.paths.resolve(filePath)
260
+ const filename = absolutePath.split('/').pop() ?? filePath
261
+
262
+ const hash = await new Promise<string>((resolve, reject) => {
263
+ this._iroh!.blobs.addFromPath(
264
+ absolutePath,
265
+ true,
266
+ SetTagOption.auto(),
267
+ { wrap: false },
268
+ (err: Error | null, progress: any) => {
269
+ if (err) return reject(err)
270
+ if (progress.allDone) resolve(progress.allDone.hash)
271
+ }
272
+ )
273
+ })
274
+
275
+ const size = Number(await this._iroh.blobs.size(hash))
276
+ const nodeAddr = await this._iroh.net.nodeAddr()
277
+
278
+ return { hash, format: 'Raw', size, filename, nodeAddr }
279
+ }
280
+
281
+ /**
282
+ * Store raw bytes as an Iroh blob. Useful for in-memory data like
283
+ * generated images, JSON exports, etc.
284
+ * @param data Buffer or Uint8Array to store
285
+ * @param filename Optional logical filename to include in the metadata
286
+ */
287
+ async storeBytes(data: Buffer | Uint8Array, filename = 'blob'): Promise<BlobMeta> {
288
+ if (!this._iroh) throw new Error('Not connected — call connect() first')
289
+ const outcome = await this._iroh.blobs.addBytes(Array.from(data))
290
+ const size = Number(await this._iroh.blobs.size(outcome.hash))
291
+ const nodeAddr = await this._iroh.net.nodeAddr()
292
+ return { hash: outcome.hash, format: outcome.format, size, filename, nodeAddr }
293
+ }
294
+
295
+ /**
296
+ * Fetch a blob from a peer and return its contents as a Buffer.
297
+ * @param hash Blob hash from the message payload
298
+ * @param senderNodeAddr NodeAddr of the sender (from the message payload)
299
+ */
300
+ async fetchBlob(hash: string, senderNodeAddr: NodeAddr): Promise<Buffer> {
301
+ if (!this._iroh) throw new Error('Not connected — call connect() first')
302
+ await this._iroh.net.addNodeAddr(senderNodeAddr)
303
+ const opts = new BlobDownloadOptions('Raw', [senderNodeAddr], SetTagOption.auto())
304
+
305
+ await new Promise<void>((resolve, reject) => {
306
+ this._iroh!.blobs.download(hash, opts, (err: Error | null, progress: any) => {
307
+ if (err) return reject(err)
308
+ if (progress.allDone) resolve()
309
+ })
310
+ })
311
+
312
+ return Buffer.from(await this._iroh.blobs.readToBytes(hash))
313
+ }
314
+
315
+ /**
316
+ * Fetch a blob from a peer and save it to disk.
317
+ * @param hash Blob hash from the message payload
318
+ * @param senderNodeAddr NodeAddr of the sender
319
+ * @param outputPath Where to save the file (relative to container.cwd)
320
+ */
321
+ async fetchBlobToFile(hash: string, senderNodeAddr: NodeAddr, outputPath: string): Promise<void> {
322
+ if (!this._iroh) throw new Error('Not connected — call connect() first')
323
+ const absolutePath = this.container.paths.resolve(outputPath)
324
+ const dir = absolutePath.split('/').slice(0, -1).join('/')
325
+ this.fs.ensureFolder(dir)
326
+
327
+ await this._iroh.net.addNodeAddr(senderNodeAddr)
328
+ const opts = new BlobDownloadOptions('Raw', [senderNodeAddr], SetTagOption.auto())
329
+
330
+ await new Promise<void>((resolve, reject) => {
331
+ this._iroh!.blobs.download(hash, opts, (err: Error | null, progress: any) => {
332
+ if (err) return reject(err)
333
+ if (progress.allDone) resolve()
334
+ })
335
+ })
336
+
337
+ await this._iroh.blobs.writeToPath(hash, absolutePath)
338
+ }
339
+
340
+ /**
341
+ * Send a file to a recipient. Stores the file as a blob then sends
342
+ * the hash and node address so they can fetch it directly.
343
+ * @param recipientPublicKey Recipient's X25519 public key (base64)
344
+ * @param filePath Path to the file (relative to container.cwd)
345
+ * @param caption Optional text caption
346
+ */
347
+ async sendFile(recipientPublicKey: string, filePath: string, caption?: string): Promise<void> {
348
+ const blob = await this.storeFile(filePath)
349
+ await this.send(recipientPublicKey, {
350
+ type: 'file',
351
+ filename: blob.filename,
352
+ blobHash: blob.hash,
353
+ blobFormat: blob.format,
354
+ blobNodeAddr: blob.nodeAddr,
355
+ size: blob.size,
356
+ caption: caption ?? null,
357
+ })
358
+ }
359
+
360
+ /**
361
+ * Load or generate the keypair without starting the Iroh node.
362
+ * Useful for printing identity without joining the network.
363
+ */
364
+ async loadIdentity(): Promise<void> {
365
+ await this.loadOrGenerateKeypair()
366
+ this.setState({ publicKey: Buffer.from(this._publicKey!).toString('base64') })
367
+ }
368
+
369
+ get dataDir(): string {
370
+ if (this.options.dataDir) return this.options.dataDir
371
+ const home = (this.os as any).homedir
372
+ return this.container.paths.resolve(home, '.luca', 'cipher', this.options.name)
373
+ }
374
+
375
+ // Deterministic agent user ID derived from public key (hex prefix)
376
+ private get agentUserId(): string {
377
+ if (!this._publicKey) return 'unknown'
378
+ return Buffer.from(this._publicKey.slice(0, 16)).toString('hex')
379
+ }
380
+
381
+ private async loadOrGenerateKeypair(): Promise<void> {
382
+ this.fs.ensureFolder(this.dataDir)
383
+
384
+ if (this.fs.exists(this.identityPath)) {
385
+ const identity = this.fs.readJson(this.identityPath)
386
+ this._privateKey = new Uint8Array(Buffer.from(identity.privateKey, 'base64'))
387
+ this._publicKey = new Uint8Array(Buffer.from(identity.publicKey, 'base64'))
388
+ } else {
389
+ this._privateKey = x25519.utils.randomSecretKey()
390
+ this._publicKey = new Uint8Array(x25519.getPublicKey(this._privateKey))
391
+ this.fs.writeJson(this.identityPath, {
392
+ name: this.options.name,
393
+ publicKey: Buffer.from(this._publicKey).toString('base64'),
394
+ privateKey: Buffer.from(this._privateKey).toString('base64'),
395
+ createdAt: new Date().toISOString(),
396
+ })
397
+ }
398
+ }
399
+
400
+ private handleIncoming(received: { content: number[]; deliveredFrom: string }): void {
401
+ try {
402
+ const text = Buffer.from(received.content).toString('utf8')
403
+ const msg = JSON.parse(text)
404
+
405
+ if (msg.Presence) {
406
+ const p = msg.Presence
407
+ if (!p.public_key) return
408
+ this._knownPeers.set(p.public_key, { name: p.display_name ?? 'unknown', nodeId: p.node_id })
409
+ this.setState({ peers: this._knownPeers.size })
410
+ this.emit('presence', { publicKey: p.public_key, name: p.display_name ?? 'unknown', nodeId: p.node_id })
411
+ return
412
+ }
413
+
414
+ if (msg.SealedEnvelope) {
415
+ const envelope = JSON.parse(msg.SealedEnvelope.envelope_json)
416
+ const contentPayload = this.tryDecryptEnvelope(envelope)
417
+ if (!contentPayload) return
418
+
419
+ let payload = contentPayload
420
+ if (contentPayload.DirectMessage?.content) {
421
+ try {
422
+ const parsed = JSON.parse(contentPayload.DirectMessage.content)
423
+ payload = parsed['luca:v1'] ?? parsed
424
+ } catch {
425
+ payload = { type: 'text', text: contentPayload.DirectMessage.content }
426
+ }
427
+ }
428
+
429
+ this.emit('message', {
430
+ from: envelope.sender_public_key,
431
+ payload,
432
+ timestamp: envelope.timestamp,
433
+ })
434
+ }
435
+ } catch {
436
+ // ignore malformed messages
437
+ }
438
+ }
439
+
440
+ private buildEnvelope(recipientKeys: string[], contentPayload: any): object {
441
+ const sealedBoxes = recipientKeys.map(k => this.sealFor(k, contentPayload))
442
+ return {
443
+ message_id: Buffer.from(randomBytes(32)).toString('hex'),
444
+ timestamp: Math.floor(Date.now() / 1000),
445
+ content_type: 'DirectMessage',
446
+ sender_public_key: Buffer.from(this._publicKey!).toString('base64'),
447
+ sealed_boxes: sealedBoxes,
448
+ }
449
+ }
450
+
451
+ private sealFor(recipientPubKeyB64: string, payload: any): object {
452
+ const recipientPub = new Uint8Array(Buffer.from(recipientPubKeyB64, 'base64'))
453
+ const ephPriv = x25519.utils.randomSecretKey()
454
+ const ephPub = new Uint8Array(x25519.getPublicKey(ephPriv))
455
+ const shared = x25519.getSharedSecret(ephPriv, recipientPub)
456
+ const nonce = randomBytes(24)
457
+ const ct = xchacha20poly1305(shared, nonce).encrypt(
458
+ new TextEncoder().encode(JSON.stringify(payload))
459
+ )
460
+ return {
461
+ ephemeral_pubkey: Buffer.from(ephPub).toString('base64'),
462
+ recipient_hint: Buffer.from(recipientPub.slice(0, 8)).toString('hex'),
463
+ nonce: Buffer.from(nonce).toString('base64'),
464
+ ciphertext: Buffer.from(ct).toString('base64'),
465
+ }
466
+ }
467
+
468
+ private tryDecryptEnvelope(envelope: any): any | null {
469
+ if (!this._privateKey || !this._publicKey) return null
470
+ const myHint = Buffer.from(this._publicKey.slice(0, 8)).toString('hex')
471
+ for (const box of envelope.sealed_boxes ?? []) {
472
+ if (box.recipient_hint !== myHint) continue
473
+ const result = this.tryDecryptBox(box)
474
+ if (result !== null) return result
475
+ }
476
+ return null
477
+ }
478
+
479
+ private tryDecryptBox(box: any): any | null {
480
+ try {
481
+ const ephPub = new Uint8Array(Buffer.from(box.ephemeral_pubkey, 'base64'))
482
+ const shared = x25519.getSharedSecret(this._privateKey!, ephPub)
483
+ const nonce = new Uint8Array(Buffer.from(box.nonce, 'base64'))
484
+ const ct = new Uint8Array(Buffer.from(box.ciphertext, 'base64'))
485
+ const pt = xchacha20poly1305(shared, nonce).decrypt(ct)
486
+ return JSON.parse(new TextDecoder().decode(pt))
487
+ } catch {
488
+ return null
489
+ }
490
+ }
491
+ }
492
+
493
+ export default CipherSocialFeature
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "luca",
3
3
  "website": "https://luca-js.soederpop.com",
4
- "version": "3.0.2",
4
+ "version": "3.1.0",
5
5
  "description": "lightweight universal conversational architecture AKA Le Ultimate Component Architecture AKA Last Universal Common Ancestor, part AI part Human",
6
6
  "author": "jon soeder aka the people's champ <jon@soederpop.com>",
7
7
  "type": "module",
@@ -145,6 +145,10 @@
145
145
  },
146
146
  "dependencies": {
147
147
  "@modelcontextprotocol/sdk": "1.12.1",
148
+ "@noble/ciphers": "^2.2.0",
149
+ "@noble/curves": "^2.2.0",
150
+ "@noble/hashes": "^2.2.0",
151
+ "@number0/iroh": "^0.35.0",
148
152
  "@openai/codex": "0.99.0",
149
153
  "@resvg/resvg-js": "2.6.2",
150
154
  "@supabase/supabase-js": "2.95.3",
@@ -203,6 +207,7 @@
203
207
  "wink-eng-lite-web-model": "1.8.1",
204
208
  "wink-nlp": "2.4.0",
205
209
  "ws": "8.18.2",
210
+ "telnyx": "6.41.1",
206
211
  "zod": "4.3.6"
207
212
  },
208
213
  "optionalDependencies": {