@johpaz/hive-agents 1.1.2 → 1.1.4
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/dist/hive.js +3801 -3154
- package/dist/tool-worker.js +25 -2
- package/dist/ui/assets/{A2UIPage-BOR7GzYi.js → A2UIPage-EDS7lN-K.js} +4 -4
- package/dist/ui/assets/{AgentCreateForm-Btza1Kiv.js → AgentCreateForm-KvhVhAFP.js} +1 -1
- package/dist/ui/assets/AgentDetailPage-B2dCpO92.js +1 -0
- package/dist/ui/assets/{AgentNewPage-DvP05Ap5.js → AgentNewPage-CF2B4dbu.js} +1 -1
- package/dist/ui/assets/AgentsPage-CMvz-CtA.js +10 -0
- package/dist/ui/assets/{ApiClientPage-Cmo0XBwk.js → ApiClientPage-tzzL3rZC.js} +1 -1
- package/dist/ui/assets/{ChannelsPage-C53NCtXi.js → ChannelsPage-fE2vRwup.js} +2 -2
- package/dist/ui/assets/DashboardPage-57SaHnBL.js +6 -0
- package/dist/ui/assets/{LoginPage-CTc-MbtG.js → LoginPage-Fag9Bp5h.js} +1 -1
- package/dist/ui/assets/{LogsPage-D-2DgTQh.js → LogsPage-GVJd_a65.js} +1 -1
- package/dist/ui/assets/{MeetingPage-B8Xb1z_0.js → MeetingPage-TKQu8Nr-.js} +1 -1
- package/dist/ui/assets/{ModelSelector-BcaASPWF.js → ModelSelector-DciHLo7R.js} +1 -1
- package/dist/ui/assets/{NotFound-PUg3gEO0.js → NotFound-D4ZlDVg9.js} +1 -1
- package/dist/ui/assets/{Office3DPage-6bDnybWI.js → Office3DPage-CQnO522l.js} +2 -2
- package/dist/ui/assets/ProvidersPage-BsWFvzqz.js +1 -0
- package/dist/ui/assets/{RecoverPage-UL782VIG.js → RecoverPage-BkdOyljs.js} +1 -1
- package/dist/ui/assets/SettingsPage-D_43Rc2I.js +9 -0
- package/dist/ui/assets/{SetupPage-B_fXVcuJ.js → SetupPage-D6Z3SYZu.js} +1 -1
- package/dist/ui/assets/VoicePage-CCE2EOE9.js +307 -0
- package/dist/ui/assets/{WebChatPage-D8KsJqMf.js → WebChatPage-Dzk3FhiR.js} +4 -4
- package/dist/ui/assets/{conversationsStore-8WwqUOpe.js → conversationsStore-5hf5grlP.js} +1 -1
- package/dist/ui/assets/{core-B_5cyOSV.js → core-p4c5dns5.js} +1 -1
- package/dist/ui/assets/{dialog-DcgGvP2g.js → dialog-DKnsGLwr.js} +1 -1
- package/dist/ui/assets/{dist-js-q7C_AB0j.js → dist-js-CkNhvsFc.js} +1 -1
- package/dist/ui/assets/dist-js-jWCEHSkB.js +1 -0
- package/dist/ui/assets/{index-C5Hhusqq.js → index-mBw9Tl7u.js} +44 -4
- package/dist/ui/assets/useAudioDevices-BYFaA0X-.js +1 -0
- package/dist/ui/assets/{useHiveAgentsModelLoad-IOqfYcrC.js → useHiveAgentsModelLoad-RRQ6-ANC.js} +1 -1
- package/dist/ui/assets/{useProviders-DsFqfiyM.js → useProviders-DXr4pJ57.js} +1 -1
- package/dist/ui/assets/{vendor-router-DP84b3LQ.js → vendor-router-DSMCk-Ka.js} +1 -1
- package/dist/ui/index.html +2 -2
- package/package.json +5 -3
- package/packages/core/src/agent/agent-catalog.ts +2 -2
- package/packages/core/src/agent/compaction.ts +162 -25
- package/packages/core/src/agent/context-compiler.ts +121 -8
- package/packages/core/src/agent/conversation-store.ts +43 -2
- package/packages/core/src/agent/handoff.ts +129 -0
- package/packages/core/src/agent/history-timeline.ts +133 -0
- package/packages/core/src/agent/message-memory.ts +148 -0
- package/packages/core/src/agent/summary-memory.ts +152 -0
- package/packages/core/src/agent/thread-store.ts +4 -0
- package/packages/core/src/config/loader.ts +37 -1
- package/packages/core/src/gateway/realtime/voice-session.ts +19 -0
- package/packages/core/src/storage/collections.ts +3 -0
- package/packages/core/src/tools/a2ui/index.ts +76 -0
- package/packages/core/src/tools/core/index.ts +19 -6
- package/packages/skills/src/bundled-data.generated.ts +756 -756
- package/dist/ui/assets/AgentDetailPage-D435IX8G.js +0 -1
- package/dist/ui/assets/AgentsPage-BT9CssIN.js +0 -10
- package/dist/ui/assets/DashboardPage-DpI54Ot0.js +0 -6
- package/dist/ui/assets/ProvidersPage-CVK-nKxE.js +0 -1
- package/dist/ui/assets/SettingsPage-CHJfutPk.js +0 -9
- package/dist/ui/assets/VoicePage-CdBZrLAm.js +0 -307
- package/dist/ui/assets/dist-js-Dh18rcg9.js +0 -1
- package/dist/ui/assets/useAudioDevices-BO-kUbtK.js +0 -41
|
@@ -29,7 +29,11 @@ import type { MCPClientManager } from "@johpaz/hive-agents-mcp"
|
|
|
29
29
|
import { syncToolCatalogToIndex, mcpToolFullName } from "./tool-selector"
|
|
30
30
|
import { syncSkillsToIndex, getMinimalSkills, selectSkills, getSkillByName, type SkillDescriptor } from "./skill-selector"
|
|
31
31
|
import { syncPlaybookToIndex, selectPlaybookRules } from "./playbook-selector"
|
|
32
|
-
import { getRecentMessages, getSummary, getScratchpad, toAPIMessages } from "./conversation-store"
|
|
32
|
+
import { getRecentMessages, getMessagesBefore, getSummary, getScratchpad, toAPIMessages } from "./conversation-store"
|
|
33
|
+
import { renderHistoryTimeline, packRecall, renderRecall, clampTokens } from "./history-timeline"
|
|
34
|
+
import { searchThreadMessages } from "./message-memory"
|
|
35
|
+
import { noteFixedTokens } from "./compaction"
|
|
36
|
+
import { crossThreadRecallEnabled, searchRelatedSummaries, episodicStrategy, resolveEpisodes } from "./summary-memory"
|
|
33
37
|
import { formatContext, estimateTokens } from "../utils/toon"
|
|
34
38
|
import { buildSystemPromptWithProjects } from "./prompt-builder"
|
|
35
39
|
import { createAllTools } from "../tools/index.ts"
|
|
@@ -53,7 +57,15 @@ const DEFAULT_CONTEXT_WINDOW = 250000 // Default context window when model is un
|
|
|
53
57
|
const COMPACT_RATIO = 0.80 // Reserve budget: truncate system prompt when it would exceed 80% of context window
|
|
54
58
|
const MAX_SYSTEM_PROMPT_CHARS_CAP = 128000 // Hard cap for pathological prompts; normal budget is model-aware
|
|
55
59
|
const MCP_LAZY_CONNECT_TIMEOUT_MS = 8000 // Bound for on-demand connect of a dormant MCP server
|
|
60
|
+
// Recuperación por turno de mensajes que salieron de la ventana (ver `recalledSection`).
|
|
61
|
+
const RECALL_MIN_QUERY_CHARS = 12 // una pregunta más corta («sí», «sigue») no dice qué buscar
|
|
62
|
+
const RECALL_CANDIDATES = 8 // candidatos que se piden al índice antes de descartar los que ya están en la ventana
|
|
63
|
+
const RECALL_MESSAGES = 3 // mensajes que se inyectan como máximo
|
|
64
|
+
const RECALL_CHARS = 500 // caracteres por mensaje inyectado
|
|
65
|
+
const RECALL_CANDIDATES_ADAPTIVE = 20 // con historyTimeline: más candidatos, se empaquetan por presupuesto
|
|
66
|
+
const RECALL_CHARS_ADAPTIVE = 1200 // con historyTimeline: tope por mensaje
|
|
56
67
|
const SUMMARY_MAX_CHARS = 4000 // Cap the compacted summary so it can't itself blow the system-prompt budget
|
|
68
|
+
const RELATED_SUMMARY_MAX_CHARS = 1200 // Cap per related-thread summary injected from other conversations
|
|
57
69
|
|
|
58
70
|
|
|
59
71
|
|
|
@@ -121,7 +133,8 @@ function formatCausalContextItem(item: AgentContextItemShape): string | null {
|
|
|
121
133
|
case "anomaly":
|
|
122
134
|
return item.text ? `- ⚠ ${item.text}` : null
|
|
123
135
|
case "episode":
|
|
124
|
-
|
|
136
|
+
// Se muestra aparte, con el resumen real del hilo (el motor solo conoce el id).
|
|
137
|
+
return null
|
|
125
138
|
default:
|
|
126
139
|
return null
|
|
127
140
|
}
|
|
@@ -537,9 +550,81 @@ export async function compileContext(opts: {
|
|
|
537
550
|
(recentMessages.length === 0 || recentMessages[0].id > summary.last_message_id)
|
|
538
551
|
)
|
|
539
552
|
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
553
|
+
// Parte del hilo queda fuera de la ventana cuando los mensajes cargados no empiezan por el primero del hilo.
|
|
554
|
+
// Recuperarlo no necesita un modelo: el historial está guardado e indexado en HiveDB, y el resumen, si lo hay,
|
|
555
|
+
// es una pieza más y no la única.
|
|
556
|
+
const outOfWindow = summaryApplies || (recentMessages.length > 0 && recentMessages[0].id > 1)
|
|
557
|
+
|
|
558
|
+
// Mensajes anteriores relevantes para lo que el usuario acaba de decir, hallados por búsqueda (BM25 y vectores
|
|
559
|
+
// si están activos). Solo lectura: sin llamadas al modelo.
|
|
560
|
+
//
|
|
561
|
+
// Con `memory.historyTimeline` (HIVE_HISTORY_TIMELINE=true, apagado por defecto) se añade además una línea de
|
|
562
|
+
// tiempo de todo lo que quedó fuera de la ventana y la recuperación llena un presupuesto en vez de 3 × 500.
|
|
563
|
+
const historyTimelineCfg = loadConfig().memory?.historyTimeline
|
|
564
|
+
const historyTimelineWanted = !!historyTimelineCfg?.enabled
|
|
565
|
+
// Compuerta provisional por tamaño de ventana (ver `minWindow` en config/loader.ts): en ventanas pequeñas el
|
|
566
|
+
// presupuesto de la línea de tiempo es de unos 300 tokens y las pruebas no muestran mejora.
|
|
567
|
+
const historyTimelineMinWindow = historyTimelineCfg?.minWindow ?? 0
|
|
568
|
+
const historyTimelineOn = historyTimelineWanted && modelContextWindow >= historyTimelineMinWindow
|
|
569
|
+
const historyParts = historyTimelineCfg?.parts ?? "both"
|
|
570
|
+
const historyTimelineBlock = historyTimelineOn && historyParts !== "recall"
|
|
571
|
+
const historyAdaptiveRecall = historyTimelineOn && historyParts !== "timeline"
|
|
572
|
+
if (historyTimelineWanted && !historyTimelineOn && outOfWindow && !isolated) {
|
|
573
|
+
log.info(`[context-compiler] historyTimeline ignorado: ventana ${modelContextWindow} < mínimo ${historyTimelineMinWindow}`)
|
|
574
|
+
}
|
|
575
|
+
let recalledSection = ""
|
|
576
|
+
if (outOfWindow && !isolated) {
|
|
577
|
+
try {
|
|
578
|
+
const query = typeof userMessage === "string"
|
|
579
|
+
? userMessage
|
|
580
|
+
: userMessage.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join(" ")
|
|
581
|
+
const windowStart = recentMessages.length > 0 ? recentMessages[0].id : 0
|
|
582
|
+
if (historyTimelineBlock && windowStart > 1) {
|
|
583
|
+
const older = await getMessagesBefore(threadId, windowStart)
|
|
584
|
+
const timeline = renderHistoryTimeline(older, {
|
|
585
|
+
budgetTokens: clampTokens(modelContextWindow * 0.03, 300, 2000),
|
|
586
|
+
})
|
|
587
|
+
if (timeline.text) {
|
|
588
|
+
recalledSection +=
|
|
589
|
+
"\n\n# LÍNEA DE TIEMPO DE LA CONVERSACIÓN (mensajes fuera de tu ventana, una línea cada uno; para el texto exacto usa `conversation_read`)\n" +
|
|
590
|
+
timeline.text + "\n"
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (query.trim().length >= RECALL_MIN_QUERY_CHARS && recentMessages.length > 0) {
|
|
594
|
+
if (historyAdaptiveRecall) {
|
|
595
|
+
const hits = (await searchThreadMessages(threadId, query, RECALL_CANDIDATES_ADAPTIVE))
|
|
596
|
+
.filter((h) => h.message.id < windowStart)
|
|
597
|
+
const packed = packRecall(hits, {
|
|
598
|
+
budgetTokens: clampTokens(modelContextWindow * 0.04, 300, 3000),
|
|
599
|
+
maxCharsPerMessage: RECALL_CHARS_ADAPTIVE,
|
|
600
|
+
})
|
|
601
|
+
if (packed.length > 0) {
|
|
602
|
+
recalledSection +=
|
|
603
|
+
"\n\n# MENSAJES ANTERIORES RELEVANTES (fuera de tu ventana; la conversación actual manda)\n" +
|
|
604
|
+
renderRecall(packed) + "\n"
|
|
605
|
+
}
|
|
606
|
+
} else {
|
|
607
|
+
const hits = (await searchThreadMessages(threadId, query, RECALL_CANDIDATES))
|
|
608
|
+
.filter((h) => h.message.id < windowStart)
|
|
609
|
+
.slice(0, RECALL_MESSAGES)
|
|
610
|
+
if (hits.length > 0) {
|
|
611
|
+
recalledSection +=
|
|
612
|
+
"\n\n# MENSAJES ANTERIORES RELEVANTES (fuera de tu ventana; la conversación actual manda)\n" +
|
|
613
|
+
hits.map((h) => `- #${h.message.id} [${h.message.role}] ${h.message.content.replace(/\s+/g, " ").slice(0, RECALL_CHARS)}`).join("\n") + "\n"
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
} catch (err) {
|
|
618
|
+
log.warn(`[context-compiler] message recall failed: ${(err as Error).message}`)
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const conversationSummarySection = (summaryApplies
|
|
623
|
+
? `\n\n# RESUMEN DE LA CONVERSACIÓN (turnos anteriores, compactados)\n${summary!.summary.slice(0, SUMMARY_MAX_CHARS)}\n` +
|
|
624
|
+
`Los mensajes hasta el #${summary!.last_message_id} están compactados en este resumen. Si necesitas un dato exacto que no aparece (una cifra, un nombre, una fecha), usa \`conversation_read\` con \`query\` antes de asumir que falta.\n`
|
|
625
|
+
: outOfWindow
|
|
626
|
+
? `\n\n# HISTORIAL FUERA DE VENTANA\nLos mensajes anteriores al #${recentMessages[0].id} siguen guardados e indexados. Si necesitas un dato exacto de ellos (una cifra, un nombre, una fecha), usa \`conversation_read\` con \`query\` antes de asumir que falta.\n`
|
|
627
|
+
: "") + recalledSection
|
|
543
628
|
|
|
544
629
|
if (summaryApplies) {
|
|
545
630
|
log.info(`[context-compiler] [STEP-9c] Summary applies (${summary!.messages_covered} messages compressed) — folded into system prompt`)
|
|
@@ -618,6 +703,19 @@ export async function compileContext(opts: {
|
|
|
618
703
|
// budget, so a summary appended last would be the first thing silently
|
|
619
704
|
// dropped on an oversized prompt.
|
|
620
705
|
systemPrompt += conversationSummarySection
|
|
706
|
+
|
|
707
|
+
// Memoria entre hilos (opt-in): lo más relevante de OTRAS conversaciones.
|
|
708
|
+
// El resumen del hilo actual ya va arriba y es acumulativo.
|
|
709
|
+
const recalledThreads = new Set<string>([threadId])
|
|
710
|
+
if (crossThreadRecallEnabled()) {
|
|
711
|
+
const related = await searchRelatedSummaries(objective, threadId)
|
|
712
|
+
for (const r of related) recalledThreads.add(r.threadId)
|
|
713
|
+
if (related.length > 0) {
|
|
714
|
+
const body = related.map((r) => `- ${r.summary.slice(0, RELATED_SUMMARY_MAX_CHARS)}`).join("\n")
|
|
715
|
+
systemPrompt += `\n\n# CONVERSACIONES RELACIONADAS (otros hilos; contexto de apoyo, la conversación actual manda)\n${body}\n`
|
|
716
|
+
log.info(`[context-compiler] Injected ${related.length} related thread summar${related.length === 1 ? "y" : "ies"}`)
|
|
717
|
+
}
|
|
718
|
+
}
|
|
621
719
|
if (omittedMessageIds.length > 0 || omittedScratchpadKeys.length > 0) {
|
|
622
720
|
const recoverable = `\n\n# CONTEXTO RECUPERABLE\nMensajes previos omitidos: ${omittedMessageIds.join(", ") || "ninguno"}. Notas omitidas: ${omittedScratchpadKeys.join(", ") || "ninguna"}. Si necesitas un dato de ellos, usa conversation_read con message_ids, note_keys o query antes de asumir que falta información.\n`
|
|
623
721
|
systemPrompt += recoverable
|
|
@@ -673,8 +771,11 @@ export async function compileContext(opts: {
|
|
|
673
771
|
|
|
674
772
|
// G9: causal context window (buildAgentContext) — only when the summary
|
|
675
773
|
// applies this turn (a real DB round-trip, not a per-turn cost) and
|
|
676
|
-
// there's a causal stream to build it from. episodicSimilarity is
|
|
677
|
-
//
|
|
774
|
+
// there's a causal stream to build it from. episodicSimilarity is on when memory.crossThreadRecall is enabled and the
|
|
775
|
+
// installed HiveDB has embedQuery (see episodicStrategy): thread summaries are
|
|
776
|
+
// indexed as kind=episode, scoped to the tenant. The TaskState is not injected
|
|
777
|
+
// here: single-action mode puts it in the conversation itself (single-action.ts),
|
|
778
|
+
// so a second copy would only cost tokens.
|
|
678
779
|
if (summaryApplies && opts.causalStreamId && loadConfig().causalLog?.enabled) {
|
|
679
780
|
try {
|
|
680
781
|
const causalDb = await getHiveDb()
|
|
@@ -686,12 +787,13 @@ export async function compileContext(opts: {
|
|
|
686
787
|
: String(objectiveSource)
|
|
687
788
|
const causalMaxTokens = Math.max(500, Math.min(4000, Math.floor(modelContextWindow * 0.05)))
|
|
688
789
|
|
|
790
|
+
const episodic = crossThreadRecallEnabled() ? await episodicStrategy(currentObjective) : undefined
|
|
689
791
|
const causalCtx = (await causalDb.buildAgentContext({
|
|
690
792
|
taskId: opts.causalStreamId,
|
|
691
793
|
currentPhase: "current",
|
|
692
794
|
currentObjective: currentObjective.slice(0, 2000),
|
|
693
795
|
maxTokens: causalMaxTokens,
|
|
694
|
-
strategy: { causalAnchors: true, compressCompletedPhases: true },
|
|
796
|
+
strategy: { causalAnchors: true, compressCompletedPhases: true, ...(episodic ? { episodicSimilarity: episodic } : {}) },
|
|
695
797
|
})) as AgentContextShape
|
|
696
798
|
|
|
697
799
|
const causalLines = [...(causalCtx.items ?? []), ...(causalCtx.anomalies ?? [])]
|
|
@@ -702,6 +804,15 @@ export async function compileContext(opts: {
|
|
|
702
804
|
systemPrompt += `\n\n# CAUSAL CONTEXT (decisiones y tool calls de este turno, previos a la compactación — prioriza la conversación actual; úsalo solo para no repetir algo que ya funcionó o ya falló)\n${causalLines.join("\n")}\n`
|
|
703
805
|
log.info(`[context-compiler] [STEP-9d] ✅ Injected ${causalLines.length} causal context item(s)`)
|
|
704
806
|
}
|
|
807
|
+
|
|
808
|
+
if (episodic) {
|
|
809
|
+
const episodes = await resolveEpisodes(causalCtx.similarEpisodes ?? [], recalledThreads)
|
|
810
|
+
if (episodes.length > 0) {
|
|
811
|
+
const body = episodes.map((e) => `- ${e.summary.slice(0, RELATED_SUMMARY_MAX_CHARS)}`).join("\n")
|
|
812
|
+
systemPrompt += `\n\n# EPISODIOS PREVIOS SIMILARES (trabajo parecido en otros hilos; apoyo, la conversación actual manda)\n${body}\n`
|
|
813
|
+
log.info(`[context-compiler] [STEP-9d] ✅ Injected ${episodes.length} similar episode(s)`)
|
|
814
|
+
}
|
|
815
|
+
}
|
|
705
816
|
} catch (err) {
|
|
706
817
|
log.warn(`[context-compiler] [STEP-9d] ⚠️ Causal context build failed: ${(err as Error).message}`)
|
|
707
818
|
}
|
|
@@ -796,6 +907,8 @@ export async function compileContext(opts: {
|
|
|
796
907
|
const estimatedMsgTokens = messages.reduce((sum, m) => sum + estimateTokens(typeof m.content === 'string' ? m.content : JSON.stringify(m.content)), 0)
|
|
797
908
|
const estimatedToolTokens = toolsForLLM.reduce((sum, t) => sum + estimateTokens(JSON.stringify(t)), 0)
|
|
798
909
|
const estimatedTotal = estimatedSystemTokens + estimatedMsgTokens + estimatedToolTokens
|
|
910
|
+
// La parte fija (no compactable) de este turno: la compactación del siguiente la usa para fijar su umbral.
|
|
911
|
+
noteFixedTokens(threadId, estimatedSystemTokens + estimatedToolTokens)
|
|
799
912
|
const budgetPct = modelContextWindow > 0 ? Math.round((estimatedTotal / modelContextWindow) * 100) : 0
|
|
800
913
|
|
|
801
914
|
log.info(
|
|
@@ -155,6 +155,10 @@ export async function addMessage(
|
|
|
155
155
|
updated_at: now,
|
|
156
156
|
}, { expectedVersion: 0 })
|
|
157
157
|
|
|
158
|
+
// Indexado para recuperar más tarde lo que salga de la ventana: segundo plano, sin bloquear el guardado.
|
|
159
|
+
// Import dinámico porque message-memory importa este módulo.
|
|
160
|
+
void import("./message-memory").then((m) => m.indexMessage(threadId, seq, role, textContent)).catch(() => {})
|
|
161
|
+
|
|
158
162
|
// Fire-and-forget — never block message persistence on the activity chart rollup.
|
|
159
163
|
const hour = new Date(now).toISOString().slice(0, 13)
|
|
160
164
|
bumpRollup("activityRollups", hour, { messageCount: 1 }).catch(() => {})
|
|
@@ -239,6 +243,24 @@ export async function getTotalTokens(threadId: string): Promise<number> {
|
|
|
239
243
|
return entries.reduce((sum, e) => sum + e.doc.token_count, 0)
|
|
240
244
|
}
|
|
241
245
|
|
|
246
|
+
/**
|
|
247
|
+
* Mensajes concretos de un hilo por su id, en orden cronológico. Los ids que no
|
|
248
|
+
* existen (borrados, de otro hilo) se omiten. Es la lectura puntual que usa la
|
|
249
|
+
* búsqueda de historial: el índice devuelve ids y el texto sale de aquí.
|
|
250
|
+
*/
|
|
251
|
+
export async function getMessagesByIds(threadId: string, ids: number[]): Promise<StoredMessage[]> {
|
|
252
|
+
if (ids.length === 0) return []
|
|
253
|
+
const conversationsCol = await col<ConversationDoc>("conversations")
|
|
254
|
+
const found = await Promise.all(
|
|
255
|
+
[...new Set(ids)].map(async (seq) => {
|
|
256
|
+
const id = storageId(threadId, seq)
|
|
257
|
+
const entry = await conversationsCol.get(id)
|
|
258
|
+
return entry ? toStoredMessage(id, entry.doc) : null
|
|
259
|
+
}),
|
|
260
|
+
)
|
|
261
|
+
return found.filter((m): m is StoredMessage => m !== null).sort((a, b) => a.id - b.id)
|
|
262
|
+
}
|
|
263
|
+
|
|
242
264
|
/**
|
|
243
265
|
* Messages after a given message ID (for incremental summary updates).
|
|
244
266
|
*/
|
|
@@ -250,6 +272,20 @@ export async function getMessagesAfter(threadId: string, afterId: number): Promi
|
|
|
250
272
|
.filter(m => m.id > afterId)
|
|
251
273
|
}
|
|
252
274
|
|
|
275
|
+
/**
|
|
276
|
+
* Los últimos `limit` mensajes de texto (user/assistant) con id menor que `beforeId`, en orden cronológico.
|
|
277
|
+
* Es lo que queda fuera de la ventana: alimenta la línea de tiempo del historial. Los `tool` se omiten a
|
|
278
|
+
* propósito (pueden llevar credenciales y no aportan a una línea de tiempo).
|
|
279
|
+
*/
|
|
280
|
+
export async function getMessagesBefore(threadId: string, beforeId: number, limit = 400): Promise<StoredMessage[]> {
|
|
281
|
+
const conversationsCol = await col<ConversationDoc>("conversations")
|
|
282
|
+
const entries = await conversationsCol.scan({ prefix: `${threadId}:` })
|
|
283
|
+
const rows = entries
|
|
284
|
+
.map(e => toStoredMessage(e.id, e.doc))
|
|
285
|
+
.filter(m => m.id < beforeId && m.role !== "tool")
|
|
286
|
+
return rows.length > limit ? rows.slice(rows.length - limit) : rows
|
|
287
|
+
}
|
|
288
|
+
|
|
253
289
|
// ─── Convert stored messages → LLMMessage array ───────────────────────────────
|
|
254
290
|
|
|
255
291
|
export function toAPIMessages(rows: StoredMessage[]): LLMMessage[] {
|
|
@@ -280,6 +316,8 @@ export interface Summary {
|
|
|
280
316
|
summary: string
|
|
281
317
|
last_message_id: number
|
|
282
318
|
messages_covered: number
|
|
319
|
+
/** Traspaso en seis campos; null en resúmenes libres anteriores. */
|
|
320
|
+
structured: import("./handoff").Handoff | null
|
|
283
321
|
}
|
|
284
322
|
|
|
285
323
|
export async function getSummary(threadId: string): Promise<Summary | null> {
|
|
@@ -290,6 +328,7 @@ export async function getSummary(threadId: string): Promise<Summary | null> {
|
|
|
290
328
|
summary: entry.doc.summary,
|
|
291
329
|
last_message_id: entry.doc.last_message_id ? parseInt(entry.doc.last_message_id, 10) : 0,
|
|
292
330
|
messages_covered: entry.doc.messages_covered,
|
|
331
|
+
structured: entry.doc.structured ?? null,
|
|
293
332
|
}
|
|
294
333
|
}
|
|
295
334
|
|
|
@@ -297,7 +336,8 @@ export async function saveSummary(
|
|
|
297
336
|
threadId: string,
|
|
298
337
|
summary: string,
|
|
299
338
|
messagesCovered: number,
|
|
300
|
-
lastMessageId: number
|
|
339
|
+
lastMessageId: number,
|
|
340
|
+
structured: import("./handoff").Handoff | null = null,
|
|
301
341
|
): Promise<void> {
|
|
302
342
|
const summariesCol = await col<SummaryDoc>("summaries")
|
|
303
343
|
const existing = await summariesCol.get(threadId)
|
|
@@ -306,7 +346,8 @@ export async function saveSummary(
|
|
|
306
346
|
summary,
|
|
307
347
|
messages_covered: messagesCovered,
|
|
308
348
|
last_message_id: String(lastMessageId),
|
|
309
|
-
|
|
349
|
+
structured,
|
|
350
|
+
},existing ? { expectedVersion: existing.version } : { expectedVersion: 0 })
|
|
310
351
|
}
|
|
311
352
|
|
|
312
353
|
// ─── Scratchpad (HiveDB collection) ────────────────────────────────────────────
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Handoff — el estado de una conversación compactada, en seis campos.
|
|
3
|
+
*
|
|
4
|
+
* Reemplaza al resumen de "3–5 oraciones": ese formato pierde justo lo que
|
|
5
|
+
* hace falta para continuar (rutas, valores exactos, errores, qué ya falló).
|
|
6
|
+
* El traspaso estructurado sigue el de "You don't need long context"
|
|
7
|
+
* (arXiv 2611.05306, apéndice A): objetivo, hechos establecidos, cambios
|
|
8
|
+
* aplicados, verificación, callejones sin salida y plan restante.
|
|
9
|
+
*
|
|
10
|
+
* Todo aquí es puro (sin LLM ni base de datos) para poder probarlo aislado.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export interface Handoff {
|
|
14
|
+
/** Una línea: el resultado que se busca. */
|
|
15
|
+
objective: string
|
|
16
|
+
/** Hechos verificados: rutas, valores, ids, errores, preferencias del usuario. */
|
|
17
|
+
facts: string[]
|
|
18
|
+
/** Qué se cambió o creó, y si se verificó. */
|
|
19
|
+
changes: string[]
|
|
20
|
+
/** Comprobaciones hechas y su resultado. */
|
|
21
|
+
verification: string[]
|
|
22
|
+
/** Enfoques que fallaron y no deben repetirse. */
|
|
23
|
+
dead_ends: string[]
|
|
24
|
+
/** Subtareas pendientes en orden; la primera es el siguiente paso. */
|
|
25
|
+
plan: string[]
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const MAX_ITEMS = 30
|
|
29
|
+
const MAX_ITEM_CHARS = 500
|
|
30
|
+
const MAX_OBJECTIVE_CHARS = 400
|
|
31
|
+
|
|
32
|
+
export const HANDOFF_SYSTEM_PROMPT =
|
|
33
|
+
"You are a conversation state compactor. You write a handoff so that another instance of the " +
|
|
34
|
+
"assistant, seeing ONLY your handoff plus the latest messages, can continue the work without " +
|
|
35
|
+
"asking again or repeating what already failed. Answer with a single JSON object and nothing else."
|
|
36
|
+
|
|
37
|
+
/** El prompt de usuario: transcripción nueva y, si la hay, el traspaso anterior a incorporar. */
|
|
38
|
+
export function buildHandoffPrompt(input: {
|
|
39
|
+
transcript: string
|
|
40
|
+
messageCount: number
|
|
41
|
+
/** Traspaso (o resumen libre) de la compactación anterior del mismo hilo. */
|
|
42
|
+
previous?: string | null
|
|
43
|
+
}): string {
|
|
44
|
+
const previous = input.previous?.trim()
|
|
45
|
+
return [
|
|
46
|
+
previous
|
|
47
|
+
? `Previous handoff (carry forward what is still true; drop what is obsolete):\n${previous}\n`
|
|
48
|
+
: "",
|
|
49
|
+
`New conversation to fold in (${input.messageCount} messages):\n${input.transcript}\n`,
|
|
50
|
+
"Reply with ONLY this JSON object (same language as the conversation; one short line per item):",
|
|
51
|
+
"{",
|
|
52
|
+
' "objective": "one line: the result the user wants",',
|
|
53
|
+
' "facts": ["established facts, kept EXACT: paths, ids, values, names, errors, user preferences and decisions"],',
|
|
54
|
+
' "changes": ["what was changed or created, and whether it was verified"],',
|
|
55
|
+
' "verification": ["checks run and their outcome"],',
|
|
56
|
+
' "dead_ends": ["approaches that failed and must not be repeated, with why"],',
|
|
57
|
+
' "plan": ["remaining steps in order; the first is the immediate next step"]',
|
|
58
|
+
"}",
|
|
59
|
+
"Rules:",
|
|
60
|
+
"- facts: keep EXACT, character for character, every value the user or a tool DECLARED as configuration or requirement: " +
|
|
61
|
+
"limits, endpoints, URLs, tokens, ids, file paths, names, versions and preferences. If a similar value appears elsewhere " +
|
|
62
|
+
"(another environment, a free-tier limit, an example), keep both and say which is which.",
|
|
63
|
+
"- Do not spend facts on incidental output that does not matter for the next step: timings, test counts, commit hashes, unchanged-file reports.",
|
|
64
|
+
"- dead_ends: every approach that failed, with its error or reason, so nobody tries it again.",
|
|
65
|
+
"- Carry forward everything still true from the previous handoff; never drop a fact just to make room.",
|
|
66
|
+
"Use [] for a field with nothing to report. Never invent facts; separate what was observed from what is only an idea.",
|
|
67
|
+
].filter(Boolean).join("\n")
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function clean(value: unknown, max: number): string {
|
|
71
|
+
const text = typeof value === "string" ? value : value == null ? "" : JSON.stringify(value)
|
|
72
|
+
return text.replace(/\s+/g, " ").trim().slice(0, max)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function cleanList(value: unknown): string[] {
|
|
76
|
+
const items = Array.isArray(value) ? value : typeof value === "string" && value.trim() ? [value] : []
|
|
77
|
+
return items.map((item) => clean(item, MAX_ITEM_CHARS)).filter(Boolean).slice(0, MAX_ITEMS)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** El objeto JSON dentro de la respuesta del modelo (con o sin cercas de código). */
|
|
81
|
+
function extractJson(raw: string): unknown {
|
|
82
|
+
const text = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "")
|
|
83
|
+
const start = text.indexOf("{")
|
|
84
|
+
const end = text.lastIndexOf("}")
|
|
85
|
+
if (start < 0 || end <= start) return null
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(text.slice(start, end + 1))
|
|
88
|
+
} catch {
|
|
89
|
+
return null
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Lee la respuesta del modelo como traspaso. `null` si no es JSON o no trae
|
|
95
|
+
* nada útil (ni objetivo, ni hechos, ni plan): el llamador decide qué hacer.
|
|
96
|
+
*/
|
|
97
|
+
export function parseHandoff(raw: string): Handoff | null {
|
|
98
|
+
const data = extractJson(raw)
|
|
99
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return null
|
|
100
|
+
const o = data as Record<string, unknown>
|
|
101
|
+
const handoff: Handoff = {
|
|
102
|
+
objective: clean(o.objective, MAX_OBJECTIVE_CHARS),
|
|
103
|
+
facts: cleanList(o.facts),
|
|
104
|
+
changes: cleanList(o.changes),
|
|
105
|
+
verification: cleanList(o.verification),
|
|
106
|
+
dead_ends: cleanList(o.dead_ends),
|
|
107
|
+
plan: cleanList(o.plan),
|
|
108
|
+
}
|
|
109
|
+
if (!handoff.objective && handoff.facts.length === 0 && handoff.plan.length === 0) return null
|
|
110
|
+
return handoff
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* El traspaso como texto para el prompt. El orden es el de prioridad: quien
|
|
115
|
+
* recorte la cola (el compilador de contexto corta al llegar a su tope) pierde
|
|
116
|
+
* primero la verificación y los cambios, y último los hechos.
|
|
117
|
+
*/
|
|
118
|
+
export function renderHandoff(h: Handoff): string {
|
|
119
|
+
const list = (title: string, items: string[]) =>
|
|
120
|
+
items.length ? `${title}:\n${items.map((i) => `- ${i}`).join("\n")}` : ""
|
|
121
|
+
return [
|
|
122
|
+
h.objective ? `Objetivo: ${h.objective}` : "",
|
|
123
|
+
list("Hechos establecidos", h.facts),
|
|
124
|
+
list("Callejones sin salida (no repetir)", h.dead_ends),
|
|
125
|
+
list("Plan restante", h.plan),
|
|
126
|
+
list("Cambios aplicados", h.changes),
|
|
127
|
+
list("Verificación", h.verification),
|
|
128
|
+
].filter(Boolean).join("\n\n")
|
|
129
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Línea de tiempo del historial fuera de ventana + recuperación que llena el presupuesto.
|
|
3
|
+
*
|
|
4
|
+
* Idea tomada de FlexA-Mem (arXiv 2610.33274): el historial ya se guarda una sola vez (conversation-store)
|
|
5
|
+
* y se indexa (message-memory); lo que faltaba es RENDERIZARLO en cada llamada como una línea de tiempo
|
|
6
|
+
* compacta más el texto original de lo relevante, con una regla fija y sin modelo.
|
|
7
|
+
*
|
|
8
|
+
* Todo aquí es puro (sin I/O): recibe filas y presupuestos, devuelve texto. Así se prueba sin base de datos.
|
|
9
|
+
* El contenido de los mensajes `tool` nunca entra en la línea de tiempo: puede llevar credenciales.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type { StoredMessage } from "./conversation-store"
|
|
13
|
+
import { estimateTokens } from "../utils/toon"
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_LINE_CHARS = 80
|
|
16
|
+
|
|
17
|
+
export interface HistoryTimeline {
|
|
18
|
+
/** Una línea por mensaje, en orden cronológico. Vacío si no hay nada que mostrar o el presupuesto no da. */
|
|
19
|
+
text: string
|
|
20
|
+
/** Ids de los mensajes con línea, en orden. */
|
|
21
|
+
ids: number[]
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function oneLine(text: string, max: number): string {
|
|
25
|
+
const flat = text.replace(/\s+/g, " ").trim()
|
|
26
|
+
return flat.length <= max ? flat : `${flat.slice(0, Math.max(0, max - 1))}…`
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function toolNames(row: StoredMessage): string {
|
|
30
|
+
if (row.role !== "assistant" || !row.tool_calls_json) return ""
|
|
31
|
+
try {
|
|
32
|
+
const calls = JSON.parse(row.tool_calls_json) as Array<{ function?: { name?: string } }>
|
|
33
|
+
const names = calls.map((c) => c.function?.name).filter((n): n is string => !!n)
|
|
34
|
+
return names.length > 0 ? ` → tools: ${names.join(", ")}` : ""
|
|
35
|
+
} catch {
|
|
36
|
+
return ""
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function renderLine(row: StoredMessage, lineChars: number): string {
|
|
41
|
+
const text = oneLine(row.content ?? "", lineChars)
|
|
42
|
+
return `#${row.id} [${row.role}] ${text}${toolNames(row)}`
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Una línea por mensaje (user/assistant) con el texto recortado. Si no caben todas en `budgetTokens`,
|
|
47
|
+
* conserva la primera y la última y reparte el resto con paso fijo, para que se vea el arco completo en vez
|
|
48
|
+
* de solo el principio. Determinista: mismas filas y presupuesto, mismo resultado.
|
|
49
|
+
*/
|
|
50
|
+
export function renderHistoryTimeline(
|
|
51
|
+
rows: StoredMessage[],
|
|
52
|
+
opts: { budgetTokens: number; lineChars?: number },
|
|
53
|
+
): HistoryTimeline {
|
|
54
|
+
const lineChars = opts.lineChars ?? DEFAULT_LINE_CHARS
|
|
55
|
+
const usable = rows
|
|
56
|
+
.filter((r) => (r.role === "user" || r.role === "assistant") && (r.content ?? "").trim().length > 0)
|
|
57
|
+
.sort((a, b) => a.id - b.id)
|
|
58
|
+
if (usable.length === 0 || opts.budgetTokens <= 0) return { text: "", ids: [] }
|
|
59
|
+
|
|
60
|
+
const lines = usable.map((r) => renderLine(r, lineChars))
|
|
61
|
+
// +1 por el salto de línea.
|
|
62
|
+
const costs = lines.map((l) => estimateTokens(l) + 1)
|
|
63
|
+
const total = costs.reduce((a, b) => a + b, 0)
|
|
64
|
+
|
|
65
|
+
let picked: number[]
|
|
66
|
+
if (total <= opts.budgetTokens) {
|
|
67
|
+
picked = usable.map((_, i) => i)
|
|
68
|
+
} else {
|
|
69
|
+
// Primero y último, luego paso fijo, luego el resto: se toma lo que quepa en ese orden de prioridad.
|
|
70
|
+
const n = usable.length
|
|
71
|
+
const order: number[] = [0, n - 1]
|
|
72
|
+
const step = Math.max(1, Math.floor(n / 8))
|
|
73
|
+
for (let i = step; i < n - 1; i += step) order.push(i)
|
|
74
|
+
for (let i = 1; i < n - 1; i++) order.push(i)
|
|
75
|
+
const seen = new Set<number>()
|
|
76
|
+
const chosen: number[] = []
|
|
77
|
+
let used = 0
|
|
78
|
+
for (const i of order) {
|
|
79
|
+
if (seen.has(i)) continue
|
|
80
|
+
seen.add(i)
|
|
81
|
+
if (used + costs[i]! <= opts.budgetTokens) {
|
|
82
|
+
used += costs[i]!
|
|
83
|
+
chosen.push(i)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
picked = chosen.sort((a, b) => a - b)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
text: picked.map((i) => lines[i]!).join("\n"),
|
|
91
|
+
ids: picked.map((i) => usable[i]!.id),
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface RecallHit {
|
|
96
|
+
message: StoredMessage
|
|
97
|
+
score: number
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Mensajes recuperados por búsqueda, del más relevante al menos, hasta agotar `budgetTokens`. Lo que no cabe
|
|
102
|
+
* se SALTA (un mensaje largo no impide que entren los cortos que siguen). Excluye los ids de `excludeIds`
|
|
103
|
+
* (la ventana y la línea de tiempo) y los repetidos. Devuelve en orden cronológico.
|
|
104
|
+
*/
|
|
105
|
+
export function packRecall(
|
|
106
|
+
hits: RecallHit[],
|
|
107
|
+
opts: { budgetTokens: number; maxCharsPerMessage: number; excludeIds?: Iterable<number> },
|
|
108
|
+
): StoredMessage[] {
|
|
109
|
+
const exclude = new Set(opts.excludeIds ?? [])
|
|
110
|
+
const chosen: StoredMessage[] = []
|
|
111
|
+
let used = 0
|
|
112
|
+
for (const hit of [...hits].sort((a, b) => b.score - a.score)) {
|
|
113
|
+
const row = hit.message
|
|
114
|
+
if (exclude.has(row.id)) continue
|
|
115
|
+
if (row.role === "tool") continue
|
|
116
|
+
const body = oneLine(row.content ?? "", opts.maxCharsPerMessage)
|
|
117
|
+
if (!body) continue
|
|
118
|
+
const cost = estimateTokens(`#${row.id} [${row.role}] ${body}`) + 2
|
|
119
|
+
if (used + cost > opts.budgetTokens) continue
|
|
120
|
+
used += cost
|
|
121
|
+
exclude.add(row.id)
|
|
122
|
+
chosen.push({ ...row, content: body })
|
|
123
|
+
}
|
|
124
|
+
return chosen.sort((a, b) => a.id - b.id)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Texto del bloque de recuperación, en el mismo formato que el actual. */
|
|
128
|
+
export function renderRecall(rows: StoredMessage[]): string {
|
|
129
|
+
return rows.map((m) => `- #${m.id} [${m.role}] ${m.content}`).join("\n")
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export const clampTokens = (value: number, min: number, max: number): number =>
|
|
133
|
+
Math.max(min, Math.min(max, Math.floor(value)))
|