@johpaz/hive-agents 1.1.2 → 1.1.3

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 (55) hide show
  1. package/dist/hive.js +3741 -3150
  2. package/dist/tool-worker.js +25 -2
  3. package/dist/ui/assets/{A2UIPage-BOR7GzYi.js → A2UIPage-EDS7lN-K.js} +4 -4
  4. package/dist/ui/assets/{AgentCreateForm-Btza1Kiv.js → AgentCreateForm-KvhVhAFP.js} +1 -1
  5. package/dist/ui/assets/AgentDetailPage-B2dCpO92.js +1 -0
  6. package/dist/ui/assets/{AgentNewPage-DvP05Ap5.js → AgentNewPage-CF2B4dbu.js} +1 -1
  7. package/dist/ui/assets/AgentsPage-CMvz-CtA.js +10 -0
  8. package/dist/ui/assets/{ApiClientPage-Cmo0XBwk.js → ApiClientPage-tzzL3rZC.js} +1 -1
  9. package/dist/ui/assets/{ChannelsPage-C53NCtXi.js → ChannelsPage-fE2vRwup.js} +2 -2
  10. package/dist/ui/assets/DashboardPage-57SaHnBL.js +6 -0
  11. package/dist/ui/assets/{LoginPage-CTc-MbtG.js → LoginPage-Fag9Bp5h.js} +1 -1
  12. package/dist/ui/assets/{LogsPage-D-2DgTQh.js → LogsPage-GVJd_a65.js} +1 -1
  13. package/dist/ui/assets/{MeetingPage-B8Xb1z_0.js → MeetingPage-TKQu8Nr-.js} +1 -1
  14. package/dist/ui/assets/{ModelSelector-BcaASPWF.js → ModelSelector-DciHLo7R.js} +1 -1
  15. package/dist/ui/assets/{NotFound-PUg3gEO0.js → NotFound-D4ZlDVg9.js} +1 -1
  16. package/dist/ui/assets/{Office3DPage-6bDnybWI.js → Office3DPage-CQnO522l.js} +2 -2
  17. package/dist/ui/assets/ProvidersPage-BsWFvzqz.js +1 -0
  18. package/dist/ui/assets/{RecoverPage-UL782VIG.js → RecoverPage-BkdOyljs.js} +1 -1
  19. package/dist/ui/assets/SettingsPage-D_43Rc2I.js +9 -0
  20. package/dist/ui/assets/{SetupPage-B_fXVcuJ.js → SetupPage-D6Z3SYZu.js} +1 -1
  21. package/dist/ui/assets/VoicePage-CCE2EOE9.js +307 -0
  22. package/dist/ui/assets/{WebChatPage-D8KsJqMf.js → WebChatPage-Dzk3FhiR.js} +4 -4
  23. package/dist/ui/assets/{conversationsStore-8WwqUOpe.js → conversationsStore-5hf5grlP.js} +1 -1
  24. package/dist/ui/assets/{core-B_5cyOSV.js → core-p4c5dns5.js} +1 -1
  25. package/dist/ui/assets/{dialog-DcgGvP2g.js → dialog-DKnsGLwr.js} +1 -1
  26. package/dist/ui/assets/{dist-js-q7C_AB0j.js → dist-js-CkNhvsFc.js} +1 -1
  27. package/dist/ui/assets/dist-js-jWCEHSkB.js +1 -0
  28. package/dist/ui/assets/{index-C5Hhusqq.js → index-mBw9Tl7u.js} +44 -4
  29. package/dist/ui/assets/useAudioDevices-BYFaA0X-.js +1 -0
  30. package/dist/ui/assets/{useHiveAgentsModelLoad-IOqfYcrC.js → useHiveAgentsModelLoad-RRQ6-ANC.js} +1 -1
  31. package/dist/ui/assets/{useProviders-DsFqfiyM.js → useProviders-DXr4pJ57.js} +1 -1
  32. package/dist/ui/assets/{vendor-router-DP84b3LQ.js → vendor-router-DSMCk-Ka.js} +1 -1
  33. package/dist/ui/index.html +2 -2
  34. package/package.json +5 -3
  35. package/packages/core/src/agent/compaction.ts +162 -25
  36. package/packages/core/src/agent/context-compiler.ts +121 -8
  37. package/packages/core/src/agent/conversation-store.ts +43 -2
  38. package/packages/core/src/agent/handoff.ts +129 -0
  39. package/packages/core/src/agent/history-timeline.ts +133 -0
  40. package/packages/core/src/agent/message-memory.ts +148 -0
  41. package/packages/core/src/agent/summary-memory.ts +152 -0
  42. package/packages/core/src/agent/thread-store.ts +4 -0
  43. package/packages/core/src/config/loader.ts +37 -1
  44. package/packages/core/src/gateway/realtime/voice-session.ts +19 -0
  45. package/packages/core/src/storage/collections.ts +3 -0
  46. package/packages/core/src/tools/core/index.ts +19 -6
  47. package/packages/skills/src/bundled-data.generated.ts +756 -756
  48. package/dist/ui/assets/AgentDetailPage-D435IX8G.js +0 -1
  49. package/dist/ui/assets/AgentsPage-BT9CssIN.js +0 -10
  50. package/dist/ui/assets/DashboardPage-DpI54Ot0.js +0 -6
  51. package/dist/ui/assets/ProvidersPage-CVK-nKxE.js +0 -1
  52. package/dist/ui/assets/SettingsPage-CHJfutPk.js +0 -9
  53. package/dist/ui/assets/VoicePage-CdBZrLAm.js +0 -307
  54. package/dist/ui/assets/dist-js-Dh18rcg9.js +0 -1
  55. package/dist/ui/assets/useAudioDevices-BO-kUbtK.js +0 -41
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Historial recuperable — los mensajes compactados, indexados en HiveDB.
3
+ *
4
+ * La compactación pierde información por diseño. El paper "You don't need long
5
+ * context" (arXiv 2611.05306) lo resuelve guardando el historial completo y
6
+ * dándole al agente lectura selectiva: lo que no cabe en el contexto se recupera
7
+ * "bajo demanda". Esto es el índice de esa lectura: búsqueda híbrida (BM25 más
8
+ * vectores) sobre los mensajes de UN hilo, para `conversation_read`.
9
+ *
10
+ * El índice solo guarda ids y texto para buscar; el mensaje completo vive en la
11
+ * colección `conversations`, que sigue siendo la fuente de verdad.
12
+ *
13
+ * Convención (mismo índice que summary-memory y capability-search): id
14
+ * `message:<threadId>:<seq>`, filtros `type=message` y `mthread`.
15
+ * `searchCapabilities` siempre filtra por `type`, así que no los ve.
16
+ * Portado de hive-sdk sin la capa de inquilinos: hive es de un solo usuario.
17
+ */
18
+
19
+ import { getHiveDb } from "../storage/hivedb"
20
+ import { getMessagesByIds, type StoredMessage } from "./conversation-store"
21
+ import { logger } from "../utils/logger"
22
+
23
+ const log = logger.child("message-memory")
24
+
25
+ const TYPE = "message"
26
+ const BODY_MAX_CHARS = 2000
27
+ const TOOL_BODY_MAX_CHARS = 1000
28
+ const QUERY_MAX_CHARS = 500
29
+ const DEFAULT_K = 8
30
+
31
+ export interface MessageHit {
32
+ message: StoredMessage
33
+ score: number
34
+ }
35
+
36
+ function docId(threadId: string, seq: number): string {
37
+ return `${TYPE}:${threadId}:${seq}`
38
+ }
39
+
40
+ /** Lo que vale la pena buscar: texto de personas y del asistente, y resultados de herramientas (acotados). */
41
+ function searchableBody(row: StoredMessage): string {
42
+ const text = row.content?.trim() ?? ""
43
+ if (!text) return ""
44
+ return text.slice(0, row.role === "tool" ? TOOL_BODY_MAX_CHARS : BODY_MAX_CHARS)
45
+ }
46
+
47
+ /**
48
+ * Indexa (o reemplaza) los mensajes dados de un hilo. Idempotente por id. Nunca
49
+ * lanza: es memoria auxiliar y no debe romper la compactación.
50
+ */
51
+ export async function indexThreadMessages(threadId: string, rows: StoredMessage[]): Promise<void> {
52
+ try {
53
+ const docs = rows
54
+ .map((row) => ({ row, body: searchableBody(row) }))
55
+ .filter(({ body }) => body.length > 0)
56
+ .map(({ row, body }) => ({
57
+ id: docId(threadId, row.id),
58
+ body,
59
+ filters: [
60
+ { field: "type", value: TYPE },
61
+ { field: "mthread", value: threadId },
62
+ ],
63
+ }))
64
+ if (docs.length === 0) return
65
+ const db = await getHiveDb()
66
+ await db.upsertBatch(docs)
67
+ } catch (err) {
68
+ log.warn(`[message-memory] No se pudieron indexar los mensajes de ${threadId}: ${(err as Error).message}`)
69
+ }
70
+ }
71
+
72
+ /** Mensajes más cortos que esto no aportan nada que buscar («ok», «sigue»). */
73
+ const MIN_INDEXED_CHARS = 24
74
+
75
+ /**
76
+ * Indexa UN mensaje al guardarlo, en segundo plano. Así lo que sale de la ventana (los últimos 15 mensajes) ya
77
+ * es recuperable aunque nunca se compacte con un modelo: la recuperación no depende de la compactación.
78
+ * Idempotente por id; nunca lanza.
79
+ */
80
+ export async function indexMessage(threadId: string, seq: number, role: StoredMessage["role"], content: string): Promise<void> {
81
+ const body = searchableBody({ role, content } as StoredMessage)
82
+ if (body.length < MIN_INDEXED_CHARS) return
83
+ try {
84
+ const db = await getHiveDb()
85
+ await db.upsertDoc({
86
+ id: docId(threadId, seq),
87
+ body,
88
+ filters: [
89
+ { field: "type", value: TYPE },
90
+ { field: "mthread", value: threadId },
91
+ ],
92
+ })
93
+ } catch (err) {
94
+ log.warn(`[message-memory] No se pudo indexar el mensaje ${seq} de ${threadId}: ${(err as Error).message}`)
95
+ }
96
+ }
97
+
98
+ /** Quita del índice todos los mensajes de un hilo (al borrar la conversación). */
99
+ export async function removeThreadMessages(threadId: string): Promise<void> {
100
+ try {
101
+ const db = await getHiveDb()
102
+ await db.deleteByFilter({ field: "mthread", value: threadId })
103
+ } catch (err) {
104
+ log.warn(`[message-memory] No se pudieron quitar los mensajes de ${threadId}: ${(err as Error).message}`)
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Los mensajes de `threadId` más cercanos a `query`, del más relevante al
110
+ * menos. Vacío si el índice falla o no hay nada: quien llama cae a otra vía.
111
+ */
112
+ export async function searchThreadMessages(
113
+ threadId: string,
114
+ query: string,
115
+ k = DEFAULT_K,
116
+ ): Promise<MessageHit[]> {
117
+ const text = query.trim().slice(0, QUERY_MAX_CHARS)
118
+ if (!text || k <= 0) return []
119
+ try {
120
+ const db = await getHiveDb()
121
+ const hits = await db.queryHybrid({
122
+ text,
123
+ k,
124
+ filters: [
125
+ { field: "type", value: TYPE },
126
+ { field: "mthread", value: threadId },
127
+ ],
128
+ })
129
+ const prefix = `${TYPE}:${threadId}:`
130
+ const scored = new Map<number, number>()
131
+ for (const hit of hits) {
132
+ const id = hit.id
133
+ if (!id.startsWith(prefix)) continue
134
+ const seq = parseInt(id.slice(prefix.length), 10)
135
+ if (Number.isFinite(seq)) scored.set(seq, hit.score)
136
+ }
137
+ if (scored.size === 0) return []
138
+ // El índice solo devuelve ids: el texto vive en `conversations`. Un id cuyo
139
+ // mensaje ya no existe quedó huérfano y se descarta aquí.
140
+ const rows = await getMessagesByIds(threadId, [...scored.keys()])
141
+ return rows
142
+ .map((message) => ({ message, score: scored.get(message.id) ?? 0 }))
143
+ .sort((a, b) => b.score - a.score)
144
+ } catch (err) {
145
+ log.warn(`[message-memory] Búsqueda de mensajes de ${threadId} falló: ${(err as Error).message}`)
146
+ return []
147
+ }
148
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Memoria entre hilos — los resúmenes de compactación, indexados en HiveDB.
3
+ *
4
+ * Cada hilo tiene UN resumen acumulativo (cada compactación incorpora el
5
+ * anterior), así que no hay resúmenes viejos que recuperar dentro del mismo
6
+ * hilo. Lo que sí aporta el índice es encontrar, por relevancia, lo hablado en
7
+ * OTROS hilos.
8
+ *
9
+ * Convención (mismo índice que capability-search): id `summary:<threadId>`,
10
+ * filtros `type=summary` y `thread`. `searchCapabilities` siempre filtra por
11
+ * `type`, así que no ve estos documentos.
12
+ *
13
+ * Portado de hive-sdk sin la capa de inquilinos: hive es de un solo usuario.
14
+ */
15
+
16
+ import { getHiveDb } from "../storage/hivedb"
17
+ import { getSummary } from "./conversation-store"
18
+ import { loadConfig } from "../config/loader"
19
+ import { logger } from "../utils/logger"
20
+
21
+ const log = logger.child("summary-memory")
22
+
23
+ const TYPE = "summary"
24
+ const DEFAULT_K = 3
25
+ const QUERY_MAX_CHARS = 500
26
+ const BODY_MAX_CHARS = 4000
27
+
28
+ export interface RelatedSummary {
29
+ threadId: string
30
+ summary: string
31
+ score: number
32
+ }
33
+
34
+ export function crossThreadRecallEnabled(): boolean {
35
+ return !!loadConfig().memory?.crossThreadRecall?.enabled
36
+ }
37
+
38
+ function docId(threadId: string): string {
39
+ return `${TYPE}:${threadId}`
40
+ }
41
+
42
+ /** Indexa (o reemplaza) el resumen de un hilo. Nunca lanza: es memoria auxiliar. */
43
+ export async function indexThreadSummary(threadId: string, summary: string): Promise<void> {
44
+ try {
45
+ const db = await getHiveDb()
46
+ await db.upsertDoc({
47
+ id: docId(threadId),
48
+ body: summary.slice(0, BODY_MAX_CHARS),
49
+ filters: [
50
+ { field: "type", value: TYPE },
51
+ { field: "kind", value: "episode" },
52
+ { field: "thread", value: threadId },
53
+ ],
54
+ })
55
+ } catch (err) {
56
+ log.warn(`[summary-memory] No se pudo indexar el resumen de ${threadId}: ${(err as Error).message}`)
57
+ }
58
+ }
59
+
60
+ /** Quita el resumen de un hilo del índice (al borrar la conversación). */
61
+ export async function removeThreadSummary(threadId: string): Promise<void> {
62
+ try {
63
+ const db = await getHiveDb()
64
+ await db.deleteDoc(docId(threadId))
65
+ } catch (err) {
66
+ log.warn(`[summary-memory] No se pudo quitar el resumen de ${threadId}: ${(err as Error).message}`)
67
+ }
68
+ }
69
+
70
+ /** Resúmenes de otros hilos, por relevancia a `query`. */
71
+ export async function searchRelatedSummaries(
72
+ query: string,
73
+ excludeThreadId: string,
74
+ k = loadConfig().memory?.crossThreadRecall?.k ?? DEFAULT_K,
75
+ ): Promise<RelatedSummary[]> {
76
+ const text = query.trim().slice(0, QUERY_MAX_CHARS)
77
+ if (!text || k <= 0) return []
78
+ try {
79
+ const db = await getHiveDb()
80
+ // +1: el hilo actual puede ocupar un puesto y se descarta después.
81
+ const hits = await db.queryHybrid({
82
+ text,
83
+ k: k + 1,
84
+ filters: [{ field: "type", value: TYPE }],
85
+ })
86
+ const prefix = `${TYPE}:`
87
+ const out: RelatedSummary[] = []
88
+ for (const hit of hits) {
89
+ if (!hit.id.startsWith(prefix)) continue
90
+ const threadId = hit.id.slice(prefix.length)
91
+ if (threadId === excludeThreadId) continue
92
+ // El índice solo devuelve ids: el texto vive en la colección `summaries`.
93
+ // Si el hilo ya no tiene resumen, el documento del índice quedó huérfano.
94
+ const stored = await getSummary(threadId)
95
+ if (!stored) continue
96
+ out.push({ threadId, summary: stored.summary, score: hit.score })
97
+ if (out.length >= k) break
98
+ }
99
+ return out
100
+ } catch (err) {
101
+ log.warn(`[summary-memory] Búsqueda de resúmenes relacionados falló: ${(err as Error).message}`)
102
+ return []
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Episodios similares vía `buildAgentContext` (estrategia `episodicSimilarity`). El resumen de cada hilo
108
+ * se indexa como episodio (`kind=episode`). Solo existe si el HiveDB instalado trae `embedQuery` y el
109
+ * filtro del episodio: una versión anterior ignoraría el filtro y recorrería episodios ajenos, así que
110
+ * sin esa función no se activa.
111
+ */
112
+ export async function episodicStrategy(
113
+ objective: string,
114
+ k = loadConfig().memory?.crossThreadRecall?.k ?? DEFAULT_K,
115
+ ): Promise<{ vector: Float32Array; k: number; filters: Array<{ field: string; value: string }> } | undefined> {
116
+ const text = objective.trim().slice(0, QUERY_MAX_CHARS)
117
+ if (!text || k <= 0) return undefined
118
+ try {
119
+ const db = await getHiveDb()
120
+ // El HiveDB instalado puede ser anterior a embedQuery: se consulta por nombre.
121
+ const embed = (db as unknown as { embedQuery?: (t: string) => Promise<Float32Array | undefined> }).embedQuery
122
+ if (typeof embed !== "function") return undefined
123
+ const vector = await embed.call(db, text)
124
+ if (!vector) return undefined
125
+ return { vector, k: k + 1, filters: [] }
126
+ } catch (err) {
127
+ log.warn(`[summary-memory] No se pudo preparar la similitud episódica: ${(err as Error).message}`)
128
+ return undefined
129
+ }
130
+ }
131
+
132
+ /** Convierte los episodios que devuelve el motor en resúmenes legibles, sin el hilo actual ni los ya usados. */
133
+ export async function resolveEpisodes(
134
+ episodes: Array<{ taskId: string }>,
135
+ excludeThreadIds: Iterable<string>,
136
+ k = loadConfig().memory?.crossThreadRecall?.k ?? DEFAULT_K,
137
+ ): Promise<RelatedSummary[]> {
138
+ const exclude = new Set(excludeThreadIds)
139
+ const prefix = `${TYPE}:`
140
+ const out: RelatedSummary[] = []
141
+ for (const episode of episodes) {
142
+ const id = episode.taskId
143
+ if (!id.startsWith(prefix)) continue
144
+ const threadId = id.slice(prefix.length)
145
+ if (exclude.has(threadId)) continue
146
+ const stored = await getSummary(threadId)
147
+ if (!stored) continue
148
+ out.push({ threadId, summary: stored.summary, score: 0 })
149
+ if (out.length >= k) break
150
+ }
151
+ return out
152
+ }
@@ -14,6 +14,8 @@ import { col, updateDoc } from "../storage/hive"
14
14
  import { logger } from "../utils/logger"
15
15
  import type { ConversationThreadDoc, ConversationDoc, SummaryDoc } from "../storage/collections"
16
16
  import { makeThreadId, parseThreadId, newWebConversationId } from "./thread-id"
17
+ import { removeThreadSummary } from "./summary-memory"
18
+ import { removeThreadMessages } from "./message-memory"
17
19
 
18
20
  const log = logger.child("thread-store")
19
21
 
@@ -167,6 +169,8 @@ export async function deleteThread(threadId: string): Promise<void> {
167
169
 
168
170
  const summaries = await col<SummaryDoc>("summaries")
169
171
  await summaries.delete(threadId).catch(() => {})
172
+ await removeThreadSummary(threadId)
173
+ await removeThreadMessages(threadId)
170
174
 
171
175
  const scratchpad = await col<{ threadId: string }>("scratchpad")
172
176
  const notes = await scratchpad.scan({ prefix: `${threadId}:` })
@@ -256,6 +256,25 @@ const MemoryConfigSchema = z.object({
256
256
  dbPath: z.string().optional(),
257
257
  notesDir: z.string().optional(),
258
258
  episodic: EpisodicMemoryConfigSchema.optional(),
259
+ /** Memoria entre hilos (opt-in): recupera resúmenes de otras conversaciones por relevancia. */
260
+ crossThreadRecall: z.object({
261
+ enabled: z.boolean().optional(),
262
+ k: z.number().optional(),
263
+ }).optional(),
264
+ /**
265
+ * Línea de tiempo de la conversación fuera de ventana + recuperación que llena el presupuesto libre
266
+ * (agent/history-timeline.ts). Sin modelo. Apagado por defecto: HIVE_HISTORY_TIMELINE=true.
267
+ *
268
+ * `minWindow`: ventana de contexto mínima (tokens) para que tenga efecto; por debajo se ignora el flag.
269
+ * PROVISIONAL: 16 000 es una suposición: las pruebas con modelo no distinguen la mejora del ruido entre corridas (ver bench/history-timeline/README.md, «Ablación y ruido»).
270
+ * Se cambia con HIVE_HISTORY_TIMELINE_MIN_WINDOW (0 = sin compuerta, lo que usan los bancos).
271
+ */
272
+ historyTimeline: z.object({
273
+ enabled: z.boolean().optional(),
274
+ minWindow: z.number().optional(),
275
+ /** Ablación en los bancos: solo la línea de tiempo, solo la recuperación adaptativa, o ambas (por defecto). */
276
+ parts: z.enum(["both", "timeline", "recall"]).optional(),
277
+ }).optional(),
259
278
  });
260
279
 
261
280
  const CronConfigSchema = z.object({
@@ -403,6 +422,17 @@ export type AgentEntry = z.infer<typeof AgentEntrySchema>;
403
422
  export type Binding = z.infer<typeof BindingSchema>;
404
423
  export type UserConfig = z.infer<typeof UserConfigSchema>;
405
424
 
425
+ /** Entero >= 0 desde una variable de entorno; si falta o no es válido, `fallback`. */
426
+ function parseParts(raw: string | undefined): "both" | "timeline" | "recall" {
427
+ return raw === "timeline" || raw === "recall" ? raw : "both";
428
+ }
429
+
430
+ function parseNonNegativeInt(raw: string | undefined, fallback: number): number {
431
+ if (raw === undefined || raw.trim() === "") return fallback;
432
+ const n = Number(raw);
433
+ return Number.isInteger(n) && n >= 0 ? n : fallback;
434
+ }
435
+
406
436
  function buildDefaultConfig(): Config {
407
437
  const hiveDir = getHiveDir();
408
438
  return {
@@ -429,7 +459,8 @@ function buildDefaultConfig(): Config {
429
459
  baseDir: path.join(hiveDir, "agents"),
430
460
  context: {
431
461
  maxTokens: 0,
432
- compactionThreshold: 0.8,
462
+ // Proporción de la ventana del modelo (≤1) o tokens absolutos (>1).
463
+ compactionThreshold: 0.25,
433
464
  minMessagesAfterCompaction: 4,
434
465
  maxCompactionRetries: 3,
435
466
  },
@@ -522,6 +553,11 @@ function buildDefaultConfig(): Config {
522
553
  provider: "openai",
523
554
  maxEpisodesPerSession: 100,
524
555
  },
556
+ historyTimeline: {
557
+ enabled: process.env.HIVE_HISTORY_TIMELINE === "true",
558
+ minWindow: parseNonNegativeInt(process.env.HIVE_HISTORY_TIMELINE_MIN_WINDOW, 16_000),
559
+ parts: parseParts(process.env.HIVE_HISTORY_TIMELINE_PARTS),
560
+ },
525
561
  },
526
562
  cron: {
527
563
  enabled: true,
@@ -82,6 +82,15 @@ export class RealtimeVoiceSession {
82
82
  private usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
83
83
  private usageBase = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
84
84
 
85
+ /**
86
+ * Lo que llegó del navegador y lo que Gemini entendió, para diagnosticar
87
+ * "hablo y no me escucha": audio recibido sin transcripción es un modelo que
88
+ * no oye; ningún audio recibido es un micrófono que el navegador no abrió.
89
+ */
90
+ private readonly abiertaEn = Date.now();
91
+ private audioEntrada = { frames: 0, bytes: 0, primeroMs: -1 };
92
+ private transcripcionesUsuario = 0;
93
+
85
94
  /** Nº de conexión: los callbacks de generaciones viejas se descartan. */
86
95
  private generation = 0;
87
96
  /** Evita que goAway y onClose disparen dos reconexiones a la vez. */
@@ -143,6 +152,7 @@ export class RealtimeVoiceSession {
143
152
  if (!vigente()) return;
144
153
  this.lastActivityAt = Date.now();
145
154
  this.userTurnText += text;
155
+ this.transcripcionesUsuario++;
146
156
  this.send({ type: "transcript", role: "user", text });
147
157
  },
148
158
  onOutputTranscript: (text) => {
@@ -259,6 +269,9 @@ export class RealtimeVoiceSession {
259
269
  // ── Entrada desde el navegador ─────────────────────────────────────────────
260
270
 
261
271
  handleAudio(pcm: ArrayBufferLike): void {
272
+ if (this.audioEntrada.frames === 0) this.audioEntrada.primeroMs = Date.now() - this.abiertaEn;
273
+ this.audioEntrada.frames++;
274
+ this.audioEntrada.bytes += pcm.byteLength;
262
275
  if (!this.session || this.closed) return;
263
276
  this.session.sendAudio(pcm);
264
277
  }
@@ -426,6 +439,12 @@ export class RealtimeVoiceSession {
426
439
  close(): void {
427
440
  if (this.closed) return;
428
441
  this.closed = true;
442
+ const { frames, bytes, primeroMs } = this.audioEntrada;
443
+ log.info(
444
+ `llamada cerrada tras ${Math.round((Date.now() - this.abiertaEn) / 1000)} s: ` +
445
+ `audio del navegador=${frames} frames (${Math.round(bytes / 1024)} KB, primero a los ${primeroMs} ms), ` +
446
+ `transcripciones del usuario=${this.transcripcionesUsuario}`,
447
+ );
429
448
  if (this.idleTimer) clearInterval(this.idleTimer);
430
449
  this.idleTimer = null;
431
450
  if (this.flushTimer) clearTimeout(this.flushTimer);
@@ -302,9 +302,12 @@ export interface ConversationDoc {
302
302
 
303
303
  export interface SummaryDoc {
304
304
  thread_id: string
305
+ /** El traspaso renderizado como texto (o el resumen libre de hilos anteriores a `structured`). */
305
306
  summary: string
306
307
  messages_covered: number
307
308
  last_message_id: string | null
309
+ /** Traspaso en seis campos (ver agent/handoff.ts). Ausente en resúmenes anteriores. */
310
+ structured?: import("../agent/handoff").Handoff | null
308
311
  }
309
312
 
310
313
  /**
@@ -14,7 +14,8 @@ import {
14
14
  type CapabilityType,
15
15
  } from "../../agent/capability-search.ts";
16
16
  import { CORE_TOOL_CATALOG } from "../../agent/tool-selector.ts";
17
- import { saveScratchpadNote, getRecentMessages, getScratchpad } from "../../agent/conversation-store.ts";
17
+ import { saveScratchpadNote, getRecentMessages, getScratchpad, getMessagesByIds } from "../../agent/conversation-store.ts";
18
+ import { searchThreadMessages } from "../../agent/message-memory.ts";
18
19
 
19
20
  const log = logger.child("core");
20
21
 
@@ -459,16 +460,19 @@ export const reportProgressTool: Tool = {
459
460
  },
460
461
  };
461
462
 
463
+ /** Máximo de mensajes que devuelve conversation_read. */
464
+ const MESSAGE_LIMIT = 8;
465
+
462
466
  /** Recover a small, scoped slice of conversation omitted by Jev's context plan. */
463
467
  export const conversationReadTool: Tool = {
464
468
  name: "conversation_read",
465
- description: "Read earlier messages from the current conversation by message IDs or text query when selected context is insufficient.",
469
+ description: "Read earlier messages from the current conversation by message IDs or text query when selected context is insufficient. Searches by meaning across the whole history, including messages already compacted into the summary.",
466
470
  parameters: {
467
471
  type: "object",
468
472
  properties: {
469
473
  message_ids: { type: "array", description: "Message IDs shown in the context plan", items: { type: "number" } },
470
474
  note_keys: { type: "array", description: "Scratchpad note keys shown in the context plan", items: { type: "string" } },
471
- query: { type: "string", description: "Optional case-insensitive text to search in earlier messages" },
475
+ query: { type: "string", description: "Optional text to search in earlier messages, by meaning and keywords (includes compacted history)" },
472
476
  },
473
477
  },
474
478
  execute: async (params, config) => {
@@ -478,12 +482,21 @@ export const conversationReadTool: Tool = {
478
482
  const noteKeys = new Set(Array.isArray(params.note_keys) ? params.note_keys.map(String) : [])
479
483
  const query = String(params.query ?? "").trim().toLocaleLowerCase()
480
484
  if (!ids.size && !noteKeys.size && !query) return { ok: false, error: "Provide message_ids, note_keys or query" }
481
- const rows = await getRecentMessages(threadId, 200)
485
+ const recent = await getRecentMessages(threadId, 200)
482
486
  const notes = await getScratchpad(threadId)
487
+ // Por id: lectura directa, sin importar la antigüedad (antes solo los últimos 200).
488
+ const byId = ids.size ? await getMessagesByIds(threadId, [...ids]) : []
489
+ // Por texto: primero lo más cercano por significado en TODO el historial
490
+ // (índice híbrido); la subcadena sobre lo reciente cubre lo que aún no está indexado.
491
+ const byMeaning = query ? (await searchThreadMessages(threadId, query, MESSAGE_LIMIT)).map(hit => hit.message) : []
492
+ const bySubstring = query ? recent.filter(row => row.content.toLocaleLowerCase().includes(query)) : []
493
+ const seen = new Set<number>()
494
+ const messages = [...byId, ...byMeaning, ...bySubstring]
495
+ .filter(row => !seen.has(row.id) && seen.add(row.id))
496
+ .slice(0, MESSAGE_LIMIT)
483
497
  return {
484
498
  ok: true,
485
- messages: rows.filter(row => (ids.size && ids.has(row.id)) || (query && row.content.toLocaleLowerCase().includes(query)))
486
- .slice(-8).map(row => ({ id: row.id, role: row.role, source: row.source, content: row.content.slice(0, 2000) })),
499
+ messages: messages.map(row => ({ id: row.id, role: row.role, source: row.source, content: row.content.slice(0, 2000) })),
487
500
  notes: notes.filter(note => noteKeys.has(note.key) || (query && `${note.key} ${note.value}`.toLocaleLowerCase().includes(query)))
488
501
  .slice(0, 8).map(note => ({ key: note.key, value: note.value.slice(0, 2000) })),
489
502
  }