coucou-brain 0.0.0-stage → 0.7.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.
- package/README.md +156 -2
- package/brain.config.json +25 -0
- package/dist/archive.d.ts +20 -0
- package/dist/archive.js +131 -0
- package/dist/chunk.d.ts +14 -0
- package/dist/chunk.js +59 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1915 -0
- package/dist/collect.d.ts +84 -0
- package/dist/collect.js +592 -0
- package/dist/config.d.ts +41 -0
- package/dist/config.js +65 -0
- package/dist/coverage.d.ts +22 -0
- package/dist/coverage.js +120 -0
- package/dist/desktop-routing.d.ts +25 -0
- package/dist/desktop-routing.js +70 -0
- package/dist/digest.d.ts +183 -0
- package/dist/digest.js +458 -0
- package/dist/elements.d.ts +144 -0
- package/dist/elements.js +363 -0
- package/dist/fts.d.ts +46 -0
- package/dist/fts.js +364 -0
- package/dist/galaxy-layout.d.ts +45 -0
- package/dist/galaxy-layout.js +302 -0
- package/dist/graph.d.ts +25 -0
- package/dist/graph.js +341 -0
- package/dist/manifest.d.ts +65 -0
- package/dist/manifest.js +220 -0
- package/dist/mask.d.ts +21 -0
- package/dist/mask.js +164 -0
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +296 -0
- package/dist/mochis.d.ts +142 -0
- package/dist/mochis.js +662 -0
- package/dist/node-page.d.ts +29 -0
- package/dist/node-page.js +132 -0
- package/dist/patterns.d.ts +130 -0
- package/dist/patterns.js +553 -0
- package/dist/project-files.d.ts +27 -0
- package/dist/project-files.js +215 -0
- package/dist/rawindex.d.ts +108 -0
- package/dist/rawindex.js +454 -0
- package/dist/records.d.ts +24 -0
- package/dist/records.js +92 -0
- package/dist/recurrences.d.ts +24 -0
- package/dist/recurrences.js +139 -0
- package/dist/stats.d.ts +16 -0
- package/dist/stats.js +143 -0
- package/dist/suggest.d.ts +28 -0
- package/dist/suggest.js +59 -0
- package/dist/usage.d.ts +60 -0
- package/dist/usage.js +219 -0
- package/dist/utils.d.ts +23 -0
- package/dist/utils.js +88 -0
- package/dist/write.d.ts +43 -0
- package/dist/write.js +830 -0
- package/hooks/brain-prompt.js +472 -0
- package/hooks/brain-session-start.js +334 -0
- package/hooks/package.json +1 -0
- package/package.json +59 -4
- package/scripts/pin-node.cjs +17 -0
package/README.md
CHANGED
|
@@ -1,3 +1,157 @@
|
|
|
1
|
-
#
|
|
1
|
+
# coucou-brain
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The memory of [Coucou](https://github.com/Louis-CFM/coucou), the Mac app that lives in your notch. It indexes your
|
|
4
|
+
Claude Code sessions and your Claude conversations into a memory on your Mac that you can search, that Claude
|
|
5
|
+
Code can read (hooks and an MCP server), and that your **Mochis**, small agents, work from: a morning brief, a
|
|
6
|
+
draft reply to a mail, a task you keep asking Claude to do. Nothing leaves your Mac; secrets are masked before
|
|
7
|
+
anything goes to the model, which is your own Claude Code.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install -g coucou-brain
|
|
11
|
+
brain index
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Then open Coucou → **Memory** and **Mochis**. Needs Node 20 or later and [Claude Code](https://claude.com/claude-code).
|
|
15
|
+
Your settings live in `~/CoucouBrain/.state/config.json`, so an update keeps them. MIT license.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
# Coucou Brain (en français)
|
|
20
|
+
|
|
21
|
+
Transforme les sessions Claude Code et les repos git locaux en un second cerveau structuré — pages Markdown reliées entre elles, éléments extraits par type (décisions, faits, leçons, tâches, préférences, mesures), couverture vérifiable.
|
|
22
|
+
|
|
23
|
+
## Ce que ça fait
|
|
24
|
+
|
|
25
|
+
1. **Collecte** les sessions Claude Code (`~/.claude/projects/`) et les repos git locaux
|
|
26
|
+
2. **Masque** les secrets avant tout envoi au modèle (clés API, tokens, JWT, IBAN, numéros de carte…)
|
|
27
|
+
3. **Digère** chaque session via `claude -p` pour en extraire un `SessionDigest` : titre, résumé, éléments typés (kind : décision / fait / leçon / tâche / préférence / mesure), tâches, fichiers touchés, personnes, état du projet
|
|
28
|
+
4. **Sessions longues** : découpées en morceaux (~100k tokens chacun), chaque morceau digéré séparément puis fusionné avec déduplication
|
|
29
|
+
5. **Maintient un état par projet** dans `~/CoucouBrain/.state/proj/` — chaque élément a un ID stable, les nouveaux ingests ajoutent sans écraser
|
|
30
|
+
6. **Reconstruit** les pages Markdown depuis l'état (sans LLM) : `rebuild`
|
|
31
|
+
7. **Commite** automatiquement dans le git local de `~/CoucouBrain/`
|
|
32
|
+
|
|
33
|
+
Les données restent en local — aucun remote, aucune télémétrie.
|
|
34
|
+
|
|
35
|
+
## Structure de ~/CoucouBrain/
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
~/CoucouBrain/
|
|
39
|
+
records/ ← une fiche par session (AAAA-MM-JJ_projet_hash.md)
|
|
40
|
+
projects/ ← une page par projet, reconstruite depuis l'état
|
|
41
|
+
people/ ← une page par personne mentionnée
|
|
42
|
+
lessons.md ← leçons transverses (tous projets)
|
|
43
|
+
INDEX.md ← index court, première chose que Claude lira
|
|
44
|
+
.gitignore ← exclut .state/
|
|
45
|
+
.state/ ← manifest SQLite + états par projet (non suivi par git)
|
|
46
|
+
manifest.db ← sessions et repos traités (hash, status, prompt_hash)
|
|
47
|
+
proj/ ← JSON par page (éléments, project_states, files_touched)
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Installation
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
cd brain
|
|
54
|
+
npm install
|
|
55
|
+
npm run build
|
|
56
|
+
npm link # rend `brain` disponible en ligne de commande
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Usage
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
# Voir ce qui serait traité (aucun appel LLM)
|
|
63
|
+
brain ingest --dry-run
|
|
64
|
+
|
|
65
|
+
# 3 sessions de test
|
|
66
|
+
brain ingest --limit 3
|
|
67
|
+
|
|
68
|
+
# Seulement le projet coucou
|
|
69
|
+
brain ingest --project coucou
|
|
70
|
+
|
|
71
|
+
# Seulement depuis une date
|
|
72
|
+
brain ingest --since 2026-10-01
|
|
73
|
+
|
|
74
|
+
# Re-digérer malgré le cache (prompt changé)
|
|
75
|
+
brain ingest --force
|
|
76
|
+
|
|
77
|
+
# Reconstruire les pages sans LLM
|
|
78
|
+
brain rebuild
|
|
79
|
+
|
|
80
|
+
# Stats (JSON)
|
|
81
|
+
brain stats --pretty
|
|
82
|
+
|
|
83
|
+
# Quels souvenirs les agents utilisent (hooks + MCP, compté en local dans .state/usage.jsonl)
|
|
84
|
+
brain usage
|
|
85
|
+
|
|
86
|
+
# Vérifier la couverture des éléments attendus
|
|
87
|
+
brain coverage
|
|
88
|
+
|
|
89
|
+
# Ajouter une correction manuelle (jamais écrasée par l'ingestion)
|
|
90
|
+
brain correct "texte de la correction"
|
|
91
|
+
|
|
92
|
+
# Remettre tout en pending pour re-ingestion complète
|
|
93
|
+
brain reset
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Configuration
|
|
97
|
+
|
|
98
|
+
`brain.config.json` (commité, valeurs par défaut publiques) :
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
{
|
|
102
|
+
"brainPath": "~/CoucouBrain",
|
|
103
|
+
"claudeProjectsPath": "~/.claude/projects",
|
|
104
|
+
"repoPaths": ["~/Developer"],
|
|
105
|
+
"additionalRepoPaths": ["~/Documents/Projets"],
|
|
106
|
+
"mergeModel": "opus",
|
|
107
|
+
"maxChunkTokens": 100000,
|
|
108
|
+
"language": "fr",
|
|
109
|
+
"repoAliases": {}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
`brain.config.local.json` (gitignored, overrides personnels) :
|
|
114
|
+
|
|
115
|
+
```json
|
|
116
|
+
{
|
|
117
|
+
"mergeModel": "sonnet"
|
|
118
|
+
}
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Cache et re-ingestion
|
|
122
|
+
|
|
123
|
+
Le manifeste SQLite (`~/CoucouBrain/.state/manifest.db`) suit chaque session avec son `prompt_hash` — le SHA-256 du template de prompt au moment de la digestion. Une relance ne retraite que :
|
|
124
|
+
- les sessions nouvelles (pas encore dans le manifeste)
|
|
125
|
+
- les sessions modifiées (hash du fichier différent)
|
|
126
|
+
- les sessions en échec (status `failed`)
|
|
127
|
+
- les sessions dont le `prompt_hash` ne correspond plus au prompt actuel (si `--force`)
|
|
128
|
+
|
|
129
|
+
## PIÈGE : auto-ingestion
|
|
130
|
+
|
|
131
|
+
Les appels à `claude -p` créent eux-mêmes des sessions dans `~/.claude/projects/`. Ils tournent depuis `~/CoucouBrain/.state/digestion/`, dont le chemin Claude correspond à un dossier exclu de l'ingestion.
|
|
132
|
+
|
|
133
|
+
## Éléments et provenance
|
|
134
|
+
|
|
135
|
+
Chaque élément extrait a un `kind`, une `provenance` et un `statut` :
|
|
136
|
+
|
|
137
|
+
| kind | description |
|
|
138
|
+
|------|-------------|
|
|
139
|
+
| `décision` | Choix architectural, de workflow ou de style |
|
|
140
|
+
| `fait` | État actuel d'un projet (déploiement, format, config) |
|
|
141
|
+
| `leçon` | Erreur ou apprentissage réutilisable |
|
|
142
|
+
| `tâche` | Action demandée ou accomplie dans la session |
|
|
143
|
+
| `préférence` | Règle personnelle (workflow, style, communication) |
|
|
144
|
+
| `mesure` | Métrique nommée (MRR, abonnés…) |
|
|
145
|
+
|
|
146
|
+
Provenance : `décidé` (confirmé) · `proposé` (non validé) · `constaté` (fait observé, implémenté)
|
|
147
|
+
|
|
148
|
+
Statut : `✅` (en vigueur/faite) · `❌` (abandonné, raison obligatoire) · `⏳` (en attente) · `⚠️` (piège) · `null`
|
|
149
|
+
|
|
150
|
+
## Tests et couverture
|
|
151
|
+
|
|
152
|
+
```bash
|
|
153
|
+
npm test # tests unitaires (vitest)
|
|
154
|
+
brain coverage # compare les pages aux entrées du golden set
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Le golden set (`tests/golden-set.json`) liste les éléments critiques attendus après ingestion, avec une priorité `must` (bloquant) ou `should` (objectif).
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
{
|
|
2
|
+
"brainPath": "~/CoucouBrain",
|
|
3
|
+
"claudeProjectsPath": "~/.claude/projects",
|
|
4
|
+
"repoPaths": [
|
|
5
|
+
"~/Developer"
|
|
6
|
+
],
|
|
7
|
+
"additionalRepoPaths": [
|
|
8
|
+
"~/Documents/Projets"
|
|
9
|
+
],
|
|
10
|
+
"excludeProjectDirs": [],
|
|
11
|
+
"repoScanMaxDepth": 2,
|
|
12
|
+
"chunkModel": "sonnet",
|
|
13
|
+
"mergeModel": "opus",
|
|
14
|
+
"maxChunkTokens": 100000,
|
|
15
|
+
"repoAliases": {},
|
|
16
|
+
"activeSessionMinutes": 30,
|
|
17
|
+
|
|
18
|
+
"_depth_comment": "depth: search (Level 1, default) | live (Level 2: digest new on the fly) | full (Level 3: backfill all past)",
|
|
19
|
+
"depth": "search",
|
|
20
|
+
"claudeExportPath": "~/Downloads/conversations-000.zip",
|
|
21
|
+
|
|
22
|
+
"_level3_comment": "Level 3 backfill options (depth: full)",
|
|
23
|
+
"dailyLimit": 50,
|
|
24
|
+
"concurrency": 3
|
|
25
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { BrainConfig } from "./config.js";
|
|
2
|
+
import type { StoredElement } from "./elements.js";
|
|
3
|
+
export interface ArchivedEntry {
|
|
4
|
+
id: string;
|
|
5
|
+
/** The state file it came from: proj_<slug>, louis, lessons */
|
|
6
|
+
state: string;
|
|
7
|
+
element: StoredElement;
|
|
8
|
+
at: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function archivePath(config: BrainConfig): string;
|
|
11
|
+
export declare function readArchive(config: BrainConfig): Record<string, ArchivedEntry>;
|
|
12
|
+
export declare function archivedIds(config: BrainConfig): Set<string>;
|
|
13
|
+
/** Leave the archived memories out of a state about to be saved. */
|
|
14
|
+
export declare function withoutArchived<T extends {
|
|
15
|
+
elements: StoredElement[];
|
|
16
|
+
}>(state: T, config: BrainConfig): T;
|
|
17
|
+
/** Take these memories out of the memory. Returns how many were found and archived. */
|
|
18
|
+
export declare function archiveMemories(config: BrainConfig, ids: string[], now?: Date): number;
|
|
19
|
+
/** Put archived memories back where they were. Returns how many came back. */
|
|
20
|
+
export declare function restoreMemories(config: BrainConfig, ids: string[]): number;
|
package/dist/archive.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Archived memories: taken out of the memory the agents read (hooks, MCP, Search, Graph), kept
|
|
3
|
+
* aside in ~/CoucouBrain/.state/archived.json so they can come back with one click.
|
|
4
|
+
*
|
|
5
|
+
* Archiving never deletes: `brain restore` puts a memory back where it was. And an archived memory
|
|
6
|
+
* stays out even if a later ingestion finds it again (same text → same id): saving a project's
|
|
7
|
+
* state leaves out the archived ids.
|
|
8
|
+
*/
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { expandHome } from "./utils.js";
|
|
12
|
+
export function archivePath(config) {
|
|
13
|
+
return path.join(expandHome(config.brainPath), ".state", "archived.json");
|
|
14
|
+
}
|
|
15
|
+
function stateDir(config) {
|
|
16
|
+
return path.join(expandHome(config.brainPath), ".state", "proj");
|
|
17
|
+
}
|
|
18
|
+
export function readArchive(config) {
|
|
19
|
+
try {
|
|
20
|
+
const d = JSON.parse(fs.readFileSync(archivePath(config), "utf8"));
|
|
21
|
+
return d.entries ?? {};
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function writeArchive(config, entries) {
|
|
28
|
+
const file = archivePath(config);
|
|
29
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
30
|
+
fs.writeFileSync(file, JSON.stringify({ entries }, null, 2), "utf8");
|
|
31
|
+
}
|
|
32
|
+
export function archivedIds(config) {
|
|
33
|
+
return new Set(Object.keys(readArchive(config)));
|
|
34
|
+
}
|
|
35
|
+
/** Leave the archived memories out of a state about to be saved. */
|
|
36
|
+
export function withoutArchived(state, config) {
|
|
37
|
+
const gone = archivedIds(config);
|
|
38
|
+
if (gone.size)
|
|
39
|
+
state.elements = state.elements.filter(e => !gone.has(e.id));
|
|
40
|
+
return state;
|
|
41
|
+
}
|
|
42
|
+
function eachState(config, fn) {
|
|
43
|
+
const dir = stateDir(config);
|
|
44
|
+
let files = [];
|
|
45
|
+
try {
|
|
46
|
+
files = fs.readdirSync(dir).filter(f => f.endsWith(".json"));
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
for (const f of files) {
|
|
52
|
+
const file = path.join(dir, f);
|
|
53
|
+
let state;
|
|
54
|
+
try {
|
|
55
|
+
state = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (!Array.isArray(state.elements))
|
|
61
|
+
continue;
|
|
62
|
+
if (fn(file, state))
|
|
63
|
+
fs.writeFileSync(file, JSON.stringify(state, null, 2), "utf8");
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Take these memories out of the memory. Returns how many were found and archived. */
|
|
67
|
+
export function archiveMemories(config, ids, now = new Date()) {
|
|
68
|
+
const wanted = new Set(ids);
|
|
69
|
+
const entries = readArchive(config);
|
|
70
|
+
let n = 0;
|
|
71
|
+
eachState(config, (_file, state) => {
|
|
72
|
+
const keep = [];
|
|
73
|
+
for (const e of state.elements) {
|
|
74
|
+
if (wanted.has(e.id)) {
|
|
75
|
+
entries[e.id] = { id: e.id, state: state.id, element: e, at: now.toISOString() };
|
|
76
|
+
n++;
|
|
77
|
+
}
|
|
78
|
+
else
|
|
79
|
+
keep.push(e);
|
|
80
|
+
}
|
|
81
|
+
if (keep.length === state.elements.length)
|
|
82
|
+
return false;
|
|
83
|
+
state.elements = keep;
|
|
84
|
+
return true;
|
|
85
|
+
});
|
|
86
|
+
if (n)
|
|
87
|
+
writeArchive(config, entries);
|
|
88
|
+
return n;
|
|
89
|
+
}
|
|
90
|
+
/** Put archived memories back where they were. Returns how many came back. */
|
|
91
|
+
export function restoreMemories(config, ids) {
|
|
92
|
+
const entries = readArchive(config);
|
|
93
|
+
const back = ids.map(id => entries[id]).filter((e) => !!e);
|
|
94
|
+
if (!back.length)
|
|
95
|
+
return 0;
|
|
96
|
+
const byState = new Map();
|
|
97
|
+
for (const e of back)
|
|
98
|
+
byState.set(e.state, [...(byState.get(e.state) ?? []), e]);
|
|
99
|
+
const done = new Set();
|
|
100
|
+
eachState(config, (_file, state) => {
|
|
101
|
+
const list = byState.get(state.id);
|
|
102
|
+
if (!list)
|
|
103
|
+
return false;
|
|
104
|
+
const have = new Set(state.elements.map(e => e.id));
|
|
105
|
+
for (const e of list) {
|
|
106
|
+
if (!have.has(e.id))
|
|
107
|
+
state.elements.push(e.element);
|
|
108
|
+
done.add(e.id);
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
});
|
|
112
|
+
// a state file gone since: write it back with just these memories
|
|
113
|
+
for (const [id, list] of byState) {
|
|
114
|
+
const missing = list.filter(e => !done.has(e.id));
|
|
115
|
+
if (!missing.length)
|
|
116
|
+
continue;
|
|
117
|
+
fs.mkdirSync(stateDir(config), { recursive: true });
|
|
118
|
+
const elements = missing.map(e => e.element), day = new Date().toISOString().slice(0, 10);
|
|
119
|
+
const state = id.startsWith("proj_")
|
|
120
|
+
? { id, title: id.replace(/^proj_/, ""), goal: "", stack: "", remote: null, repoSources: [], recordSources: [],
|
|
121
|
+
etatActuel: "", linkedProjects: [], linkedPeople: [], elements, created: day, updated: day }
|
|
122
|
+
: { id, elements, updated: day };
|
|
123
|
+
fs.writeFileSync(path.join(stateDir(config), `${id}.json`), JSON.stringify(state, null, 2), "utf8");
|
|
124
|
+
for (const e of missing)
|
|
125
|
+
done.add(e.id);
|
|
126
|
+
}
|
|
127
|
+
for (const id of done)
|
|
128
|
+
delete entries[id];
|
|
129
|
+
writeArchive(config, entries);
|
|
130
|
+
return done.size;
|
|
131
|
+
}
|
package/dist/chunk.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CondensedMessage } from "./collect.js";
|
|
2
|
+
export interface Chunk {
|
|
3
|
+
index: number;
|
|
4
|
+
total: number;
|
|
5
|
+
text: string;
|
|
6
|
+
estimatedTokens: number;
|
|
7
|
+
}
|
|
8
|
+
/** Format messages as text for LLM input */
|
|
9
|
+
export declare function messagesToText(messages: CondensedMessage[]): string;
|
|
10
|
+
/**
|
|
11
|
+
* Split messages into chunks of at most maxTokens.
|
|
12
|
+
* Returns one chunk if the session fits; multiple otherwise.
|
|
13
|
+
*/
|
|
14
|
+
export declare function chunkMessages(messages: CondensedMessage[], maxTokens: number): Chunk[];
|
package/dist/chunk.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a session condensed text into token-bounded chunks.
|
|
3
|
+
* Chunks are split at message boundaries ("Human:" / "Claude:" lines in condensed text).
|
|
4
|
+
*/
|
|
5
|
+
import { estimateTokens } from "./utils.js";
|
|
6
|
+
/** Format messages as text for LLM input */
|
|
7
|
+
export function messagesToText(messages) {
|
|
8
|
+
return messages
|
|
9
|
+
.map((m) => `${m.role === "human" ? "Human" : "Claude"}: ${m.text}`)
|
|
10
|
+
.join("\n\n---\n\n");
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Split messages into chunks of at most maxTokens.
|
|
14
|
+
* Returns one chunk if the session fits; multiple otherwise.
|
|
15
|
+
*/
|
|
16
|
+
export function chunkMessages(messages, maxTokens) {
|
|
17
|
+
const fullText = messagesToText(messages);
|
|
18
|
+
const totalTokens = estimateTokens(fullText);
|
|
19
|
+
if (totalTokens <= maxTokens) {
|
|
20
|
+
return [{ index: 0, total: 1, text: fullText, estimatedTokens: totalTokens }];
|
|
21
|
+
}
|
|
22
|
+
// Split greedily at message boundaries
|
|
23
|
+
const chunks = [];
|
|
24
|
+
let current = [];
|
|
25
|
+
let currentTokens = 0;
|
|
26
|
+
for (const msg of messages) {
|
|
27
|
+
const msgText = `${msg.role === "human" ? "Human" : "Claude"}: ${msg.text}`;
|
|
28
|
+
const msgTokens = estimateTokens(msgText);
|
|
29
|
+
if (currentTokens + msgTokens > maxTokens && current.length > 0) {
|
|
30
|
+
const text = messagesToText(current);
|
|
31
|
+
chunks.push({
|
|
32
|
+
index: chunks.length,
|
|
33
|
+
total: 0, // will be filled after
|
|
34
|
+
text,
|
|
35
|
+
estimatedTokens: estimateTokens(text),
|
|
36
|
+
});
|
|
37
|
+
current = [msg];
|
|
38
|
+
currentTokens = msgTokens;
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
current.push(msg);
|
|
42
|
+
currentTokens += msgTokens;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (current.length > 0) {
|
|
46
|
+
const text = messagesToText(current);
|
|
47
|
+
chunks.push({
|
|
48
|
+
index: chunks.length,
|
|
49
|
+
total: 0,
|
|
50
|
+
text,
|
|
51
|
+
estimatedTokens: estimateTokens(text),
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
// Fill total
|
|
55
|
+
for (const chunk of chunks) {
|
|
56
|
+
chunk.total = chunks.length;
|
|
57
|
+
}
|
|
58
|
+
return chunks;
|
|
59
|
+
}
|
package/dist/cli.d.ts
ADDED