pi-mega-compact 0.7.7 → 0.7.9
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 +11 -12
- package/dist/extensions/dashboard-server/helpers.js +37 -0
- package/dist/extensions/dashboard-server/html/all-repos-tab.js +26 -0
- package/dist/extensions/dashboard-server/html/body-open.js +23 -0
- package/dist/extensions/dashboard-server/html/current-repo-tab.js +130 -0
- package/dist/extensions/dashboard-server/html/head-open.js +16 -0
- package/dist/extensions/dashboard-server/html/high-score-tab.js +25 -0
- package/dist/extensions/dashboard-server/html/repo-detail-modal.js +26 -0
- package/dist/extensions/dashboard-server/html/script.js +259 -0
- package/dist/extensions/dashboard-server/html/styles.js +103 -0
- package/dist/extensions/dashboard-server/html/summary-tab.js +19 -0
- package/dist/extensions/dashboard-server/html-template.js +41 -0
- package/dist/extensions/dashboard-server/html.js +756 -0
- package/dist/extensions/dashboard-server/index-reader.js +133 -0
- package/dist/extensions/dashboard-server/server.js +370 -0
- package/dist/extensions/dashboard-server/snapshot.js +43 -0
- package/dist/extensions/dashboard-server/state.js +30 -0
- package/dist/extensions/dashboard-server/types.js +5 -0
- package/dist/extensions/dashboard-server.js +7 -1315
- package/dist/extensions/mega-commands.js +162 -134
- package/dist/extensions/mega-compact.test.js +292 -24
- package/dist/extensions/mega-config.js +10 -0
- package/dist/extensions/mega-conflict-cmds.js +5 -1
- package/dist/extensions/mega-dashboard-cmds.js +29 -22
- package/dist/extensions/mega-db-cmds.js +11 -2
- package/dist/extensions/mega-events/agent-handlers.js +173 -0
- package/dist/extensions/mega-events/compact-handlers.js +133 -0
- package/dist/extensions/mega-events/context-handler.js +249 -0
- package/dist/extensions/mega-events/register.js +21 -0
- package/dist/extensions/mega-events/session-handlers.js +142 -0
- package/dist/extensions/mega-events.js +15 -652
- package/dist/extensions/mega-pipeline/compact.js +324 -0
- package/dist/extensions/mega-pipeline/memory-review.js +38 -0
- package/dist/extensions/mega-pipeline/recall.js +147 -0
- package/dist/extensions/mega-pipeline.js +9 -480
- package/dist/extensions/mega-runtime/helpers.js +40 -0
- package/dist/extensions/mega-runtime/query.js +29 -0
- package/dist/extensions/mega-runtime/state.js +711 -0
- package/dist/extensions/mega-runtime/widget.js +197 -0
- package/dist/extensions/mega-runtime.js +15 -932
- package/dist/src/store/sqlite/checkpoints.js +145 -0
- package/dist/src/store/sqlite/connection.js +35 -0
- package/dist/src/store/sqlite/dedup-mirror.js +64 -0
- package/dist/src/store/sqlite/foundation.js +38 -0
- package/dist/src/store/sqlite/global-index.js +224 -0
- package/dist/src/store/sqlite/index-store.js +167 -0
- package/dist/src/store/sqlite/maintenance.js +235 -0
- package/dist/src/store/sqlite/memories.js +164 -0
- package/dist/src/store/sqlite/memory.js +54 -0
- package/dist/src/store/sqlite/meta.js +82 -0
- package/dist/src/store/sqlite/minhash-lsh.js +47 -0
- package/dist/src/store/sqlite/model-snapshots.js +47 -0
- package/dist/src/store/sqlite/raptor.js +57 -0
- package/dist/src/store/sqlite/raw-transcript.js +134 -0
- package/dist/src/store/sqlite/schema.js +250 -0
- package/dist/src/store/sqlite/session-state.js +28 -0
- package/dist/src/store/sqlite/sessions.js +39 -0
- package/dist/src/store/sqlite/stats.js +66 -0
- package/dist/src/store/sqlite/transaction.js +19 -0
- package/dist/src/store/sqlite/utils.js +120 -0
- package/dist/src/store/sqlite.js +20 -1607
- package/dist/src/vectorStore/add.js +260 -0
- package/dist/src/vectorStore/dedup.js +52 -0
- package/dist/src/vectorStore/index.js +10 -0
- package/dist/src/vectorStore/queries.js +83 -0
- package/dist/src/vectorStore/search.js +95 -0
- package/dist/src/vectorStore/session.js +19 -0
- package/dist/src/vectorStore/store.js +105 -0
- package/dist/src/vectorStore/types.js +6 -0
- package/dist/src/vectorStore/utils.js +23 -0
- package/extensions/dashboard-server/html.ts +758 -0
- package/extensions/dashboard-server/index-reader.ts +130 -0
- package/extensions/dashboard-server/server.ts +358 -0
- package/extensions/dashboard-server/snapshot.ts +44 -0
- package/extensions/dashboard-server/state.ts +33 -0
- package/extensions/dashboard-server/types.ts +134 -0
- package/extensions/dashboard-server.ts +7 -1431
- package/extensions/mega-commands.ts +33 -10
- package/extensions/mega-compact.test.ts +453 -37
- package/extensions/mega-config.ts +22 -0
- package/extensions/mega-conflict-cmds.ts +6 -2
- package/extensions/mega-dashboard-cmds.ts +30 -23
- package/extensions/mega-db-cmds.ts +11 -3
- package/extensions/mega-events/agent-handlers.ts +214 -0
- package/extensions/mega-events/compact-handlers.ts +164 -0
- package/extensions/mega-events/context-handler.ts +290 -0
- package/extensions/mega-events/register.ts +37 -0
- package/extensions/mega-events/session-handlers.ts +165 -0
- package/extensions/mega-events.ts +15 -732
- package/extensions/mega-pipeline/compact.ts +366 -0
- package/extensions/mega-pipeline/memory-review.ts +46 -0
- package/extensions/mega-pipeline/recall.ts +165 -0
- package/extensions/mega-pipeline.ts +9 -537
- package/extensions/mega-runtime/helpers.ts +68 -0
- package/extensions/mega-runtime/query.ts +29 -0
- package/extensions/mega-runtime/state.ts +797 -0
- package/extensions/mega-runtime/widget.ts +258 -0
- package/extensions/mega-runtime.ts +15 -1076
- package/package.json +4 -3
- package/src/store/sqlite/checkpoints.ts +204 -0
- package/src/store/sqlite/dedup-mirror.ts +114 -0
- package/src/store/sqlite/foundation.ts +63 -0
- package/src/store/sqlite/global-index.ts +305 -0
- package/src/store/sqlite/maintenance.ts +294 -0
- package/src/store/sqlite/memories.ts +217 -0
- package/src/store/sqlite/meta.ts +108 -0
- package/src/store/sqlite/model-snapshots.ts +83 -0
- package/src/store/sqlite/raptor.ts +107 -0
- package/src/store/sqlite/raw-transcript.ts +221 -0
- package/src/store/sqlite/schema.ts +258 -0
- package/src/store/sqlite/session-state.ts +38 -0
- package/src/store/sqlite/stats.ts +127 -0
- package/src/store/sqlite/utils.ts +125 -0
- package/src/store/sqlite.ts +20 -2204
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* mega-pipeline.ts — the compaction + recall pipelines.
|
|
2
|
+
* mega-pipeline.ts — barrel re-export of the compaction + recall pipelines.
|
|
3
|
+
*
|
|
4
|
+
* Split into focused submodules under `./mega-pipeline/`:
|
|
5
|
+
* - memory-review.ts — `runMemoryReview`
|
|
6
|
+
* - compact.ts — `runCompact`, `piCompactWouldNoop`, `RunCompactResult`
|
|
7
|
+
* - recall.ts — `doRecall`, `doRecallAsync`
|
|
3
8
|
*
|
|
4
9
|
* `runCompact` runs the full Trident pipeline (fast-gate aside) and persists a
|
|
5
10
|
* checkpoint. `doRecall` is the unified Layer-5 recall entry point. Both mutate
|
|
@@ -7,539 +12,6 @@
|
|
|
7
12
|
* driven by the event + command handlers in mega-events.ts / mega-commands.ts.
|
|
8
13
|
*/
|
|
9
14
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
import { compactSession } from "../src/engine.js";
|
|
14
|
-
import type { EngineMessage } from "../src/types.js";
|
|
15
|
-
import { recallAndInline, recallAndInlineAsync, formatRecallBlock, type RecallInjectResult } from "../src/recall.js";
|
|
16
|
-
import { normalizeSessionId } from "../src/store.js";
|
|
17
|
-
import { estimateBlockTokens } from "../src/tokens.js";
|
|
18
|
-
import { touchSession, logDaily, incCompactCount, incRecallInjected, incCacheHitTokens } from "../src/store/sqlite.js";
|
|
19
|
-
import { consolidateMemories } from "../src/memory.js";
|
|
20
|
-
import {
|
|
21
|
-
type MegaRuntime,
|
|
22
|
-
C,
|
|
23
|
-
MARKER_TYPE,
|
|
24
|
-
} from "./mega-runtime.js";
|
|
25
|
-
import { resolveRepoRoot, preserveRecentForPressure, type MegaConfig } from "./mega-config.js";
|
|
26
|
-
import { runRaptor } from "../src/dedup/raptor/index.js";
|
|
27
|
-
import { loadDedupConfig } from "../src/config/dedup.js";
|
|
28
|
-
import { upsertEmbedding as indexUpsertEmbedding } from "../src/store/vectorIndex.js";
|
|
29
|
-
|
|
30
|
-
export type RunCompactResult =
|
|
31
|
-
| { skipped: true }
|
|
32
|
-
| { skipped: false; result: ReturnType<typeof compactSession>; keepFrom: number; saved: number };
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* Review the live conversation and persist durable memories (S20+S24). Shared by
|
|
36
|
-
* the pressure-scaled turn-end cadence (mega-events.ts) AND review-on-compact
|
|
37
|
-
* (below) so both paths run the identical review body. Best-effort + non-fatal:
|
|
38
|
-
* a review failure is swallowed and never breaks the caller. On success, the
|
|
39
|
-
* number of applied ops is returned so callers can feed the consolidation gate.
|
|
40
|
-
*
|
|
41
|
-
* @param view the engine message view to review (caller builds it)
|
|
42
|
-
* @param label a short source tag for the ticker line (e.g. "pressure" / "turn")
|
|
43
|
-
*/
|
|
44
|
-
export async function runMemoryReview(
|
|
45
|
-
runtime: MegaRuntime,
|
|
46
|
-
view: ReturnType<MegaRuntime["engineView"]>,
|
|
47
|
-
label: string,
|
|
48
|
-
): Promise<number> {
|
|
49
|
-
try {
|
|
50
|
-
const { reviewConversation } = await import("../src/memory.js");
|
|
51
|
-
const { applyMemoryOps } = await import("../src/memoryOps.js");
|
|
52
|
-
const ops = reviewConversation(view, []);
|
|
53
|
-
if (ops.length) {
|
|
54
|
-
await applyMemoryOps(ops, runtime.currentStateDir);
|
|
55
|
-
// S21.2: ops landed — the compaction path reads this counter and fires
|
|
56
|
-
// `consolidateMemories` only when > 0.
|
|
57
|
-
runtime.memoriesTouchedThisCompaction += ops.length;
|
|
58
|
-
runtime.pushTicker(`${C.green}🧠${C.reset} reviewed ${ops.length} memory op${ops.length === 1 ? "" : "s"} (${label})`);
|
|
59
|
-
}
|
|
60
|
-
return ops.length;
|
|
61
|
-
} catch {
|
|
62
|
-
/* non-fatal — auto-review must never break the turn loop / compaction */
|
|
63
|
-
return 0;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Run the full compaction pipeline and persist a checkpoint. Returns the result. */
|
|
68
|
-
export function runCompact(
|
|
69
|
-
pi: ExtensionAPI,
|
|
70
|
-
runtime: MegaRuntime,
|
|
71
|
-
config: MegaConfig,
|
|
72
|
-
ctx: ExtensionContext,
|
|
73
|
-
messages: AgentMessage[],
|
|
74
|
-
opts: { keepFrom?: number; summary?: string; compressionPressure?: number } = {},
|
|
75
|
-
): RunCompactResult {
|
|
76
|
-
runtime.bindRepo(ctx.cwd);
|
|
77
|
-
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
78
|
-
runtime.resetRuntime(sid);
|
|
79
|
-
runtime.rt.sessionId = sid;
|
|
80
|
-
|
|
81
|
-
const view = runtime.engineView(messages);
|
|
82
|
-
// keepFrom deepens with context pressure (Fix E): under high pressure we
|
|
83
|
-
// compact more of the session, down to the preserveRecentMin floor.
|
|
84
|
-
const preserve = preserveRecentForPressure(
|
|
85
|
-
opts.compressionPressure ?? 0,
|
|
86
|
-
config.preserveRecent,
|
|
87
|
-
config.preserveRecentMin,
|
|
88
|
-
);
|
|
89
|
-
const keepFrom = opts.keepFrom ?? Math.max(0, view.length - preserve);
|
|
90
|
-
// For very small sessions (fewer messages than preserveRecent), allow
|
|
91
|
-
// compacting everything except the last message — the user explicitly
|
|
92
|
-
// requested compaction, so don't refuse it just because the session is short.
|
|
93
|
-
if (keepFrom <= 0) {
|
|
94
|
-
if (view.length <= 1) return { skipped: true };
|
|
95
|
-
// Use the fallback: compact everything except the last message
|
|
96
|
-
const fallbackKeepFrom = view.length - 1;
|
|
97
|
-
return doCompact(view, fallbackKeepFrom, opts, sid, config, pi, ctx, runtime);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return doCompact(view, keepFrom, opts, sid, config, pi, ctx, runtime);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function doCompact(
|
|
104
|
-
view: EngineMessage[],
|
|
105
|
-
keepFrom: number,
|
|
106
|
-
opts: { keepFrom?: number; summary?: string; compressionPressure?: number },
|
|
107
|
-
sid: string,
|
|
108
|
-
config: MegaConfig,
|
|
109
|
-
pi: ExtensionAPI,
|
|
110
|
-
ctx: ExtensionContext,
|
|
111
|
-
runtime: MegaRuntime,
|
|
112
|
-
): RunCompactResult {
|
|
113
|
-
runtime.pulsing = true; // animate the status line while the (sync) pipeline runs
|
|
114
|
-
// S21.2: reset the per-compaction memory-op counter so the post-compact
|
|
115
|
-
// consolidate pass only fires when memory rows actually changed during the
|
|
116
|
-
// compaction window (turn_end → auto-review may have written some).
|
|
117
|
-
runtime.memoriesTouchedThisCompaction = 0;
|
|
118
|
-
const result = compactSession(
|
|
119
|
-
{
|
|
120
|
-
sessionId: sid,
|
|
121
|
-
messages: view,
|
|
122
|
-
keepFrom,
|
|
123
|
-
summary: opts.summary,
|
|
124
|
-
timestamp: Date.now(),
|
|
125
|
-
onTier: runtime.makeTierCallback(ctx),
|
|
126
|
-
compressionPressure: opts.compressionPressure,
|
|
127
|
-
},
|
|
128
|
-
runtime.store,
|
|
129
|
-
);
|
|
130
|
-
runtime.pulsing = false;
|
|
131
|
-
|
|
132
|
-
if (result.skipped) return { skipped: true };
|
|
133
|
-
if (!result.deduped) {
|
|
134
|
-
runtime.rt.persistedThisSession = true;
|
|
135
|
-
runtime.rt.lastCheckpointId = result.checkpointId;
|
|
136
|
-
}
|
|
137
|
-
runtime.rt.lastCompactedFrom = result.compactedFrom;
|
|
138
|
-
runtime.rt.lastCompactedTokens = result.tokenEstimate;
|
|
139
|
-
runtime.rt.dedupAttempts++;
|
|
140
|
-
// Honest "tokens saved" for this session-instance only:
|
|
141
|
-
// new checkpoint → original − stored
|
|
142
|
-
// deduped onto existing → whole original region (nothing new stored)
|
|
143
|
-
// Resets to 0 on session_start (rt is rebuilt) — so a fresh session shows 0
|
|
144
|
-
// while the repo's cumulative saved (SQLite meta) keeps the running total.
|
|
145
|
-
const saved = result.deduped
|
|
146
|
-
? result.originalTokenEstimate
|
|
147
|
-
: Math.max(0, result.originalTokenEstimate - result.tokenEstimate);
|
|
148
|
-
runtime.rt.tokensSaved += saved;
|
|
149
|
-
runtime.rt.compactCount += 1;
|
|
150
|
-
incCompactCount(runtime.currentStateDir);
|
|
151
|
-
if (result.deduped) { runtime.rt.cacheHitTokens += saved; incCacheHitTokens(saved, runtime.currentStateDir); }
|
|
152
|
-
runtime.rt.lastCompactAt = Date.now();
|
|
153
|
-
if (result.deduped) runtime.rt.dedupSkips++;
|
|
154
|
-
// Grow the rolling "saved" goal so the progress bar always has a fresh
|
|
155
|
-
// denominator (we don't want it pinned at 100% once we pass an old target).
|
|
156
|
-
if (runtime.rt.tokensSaved > runtime.savedGoal) runtime.savedGoal = Math.ceil((runtime.rt.tokensSaved * 1.25) / 10_000) * 10_000;
|
|
157
|
-
|
|
158
|
-
// Live toolbar activity: what file/region just got compacted or deduped.
|
|
159
|
-
// Rendered via the rotating ticker line (see snapshot); the ring buffer is
|
|
160
|
-
// cycled one-per-repaint so the single line scrolls through recent files.
|
|
161
|
-
const files = result.filesModified ?? [];
|
|
162
|
-
const fileLabel = files.length
|
|
163
|
-
? files.map((f) => f.split("/").pop() ?? f).slice(0, 2).join(", ")
|
|
164
|
-
: result.regionHash.slice(0, 8);
|
|
165
|
-
runtime.lastActivityAt = Date.now();
|
|
166
|
-
// Explain-why line: surfaced while fresh. Pulls the dedup reason (which for
|
|
167
|
-
// L2 includes the cosine sim) so the user sees WHY a region was kept/dropped.
|
|
168
|
-
runtime.lastWhy = result.deduped
|
|
169
|
-
? `why: deduped@${result.dedupReason ?? "tier"}`
|
|
170
|
-
: `why: compacted → ${result.checkpointId}`;
|
|
171
|
-
// Recall/activity ticker: record this event in the ring buffer.
|
|
172
|
-
const savedK = (saved / 1000).toFixed(1);
|
|
173
|
-
runtime.pushTicker(
|
|
174
|
-
result.deduped
|
|
175
|
-
? `${C.green}♻${C.reset} deduped ${fileLabel} · ${savedK}k saved`
|
|
176
|
-
: `${C.cyan}🗜${C.reset} ${result.checkpointId} · +${savedK}k · ${fileLabel}`,
|
|
177
|
-
);
|
|
178
|
-
// The per-tier trace has settled into the final outcome — fold it back into
|
|
179
|
-
// the activity line and stop showing the live trace.
|
|
180
|
-
runtime.tierTrace = undefined;
|
|
181
|
-
|
|
182
|
-
// Record session activity + a daily-log entry in the per-repo SQLite store
|
|
183
|
-
// (foundation for resume-sessions / daily-log features). Best-effort — never
|
|
184
|
-
// block a compaction on bookkeeping.
|
|
185
|
-
try {
|
|
186
|
-
const root = resolveRepoRoot(ctx.cwd);
|
|
187
|
-
touchSession(sid, root, runtime.currentStateDir);
|
|
188
|
-
logDaily(sid, "compact", result.checkpointId, saved, runtime.currentStateDir);
|
|
189
|
-
} catch {
|
|
190
|
-
/* non-fatal: stats bookkeeping only */
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
// S21.2: best-effort consolidation of near-duplicate memories for this repo.
|
|
194
|
-
// Runs after the per-repo stats touch so `consolidateMemories` can use the
|
|
195
|
-
// same stateDir. Non-fatal — a failed consolidate never blocks a compaction.
|
|
196
|
-
// Only runs when new memory ops landed in this pass (otherwise the prior
|
|
197
|
-
// compaction's consolidate already had its shot — re-running would just
|
|
198
|
-
// touch every row again with no merges).
|
|
199
|
-
if (!result.deduped && runtime.memoriesTouchedThisCompaction > 0) {
|
|
200
|
-
try {
|
|
201
|
-
const root = resolveRepoRoot(ctx.cwd);
|
|
202
|
-
void consolidateMemories(runtime.currentStateDir, root).then(
|
|
203
|
-
(n) => {
|
|
204
|
-
if (n > 0) runtime.pushTicker(`${C.green}∫${C.reset} consolidated ${n} memory dup${n === 1 ? "" : "s"}`);
|
|
205
|
-
},
|
|
206
|
-
() => {
|
|
207
|
-
/* swallow: consolidate failures must never surface to the user */
|
|
208
|
-
},
|
|
209
|
-
);
|
|
210
|
-
} catch {
|
|
211
|
-
/* non-fatal */
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
// S24 review-on-compact: when pressure is high, the just-compacted region is
|
|
216
|
-
// exactly the context worth remembering, so review it immediately rather than
|
|
217
|
-
// waiting for the next turn-cadence tick. Uses the shared runMemoryReview
|
|
218
|
-
// helper (fire-and-forget; doCompact is sync). Best-effort + non-fatal. Only
|
|
219
|
-
// fires above the `high` band so low-pressure compactions don't pay the cost.
|
|
220
|
-
if (!result.deduped && config.memoryAutoReview && runtime.pressureBand !== "low" && runtime.pressureBand !== "medium") {
|
|
221
|
-
void runMemoryReview(runtime, view, "pressure");
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// Sentinel marker: a non-LLM bookkeeping entry so subsequent triggers can
|
|
225
|
-
// skip re-vectorizing an already-compacted region (zero token cost).
|
|
226
|
-
pi.appendEntry(MARKER_TYPE, {
|
|
227
|
-
checkpointId: result.checkpointId,
|
|
228
|
-
regionHash: result.regionHash,
|
|
229
|
-
tokenEstimate: result.tokenEstimate,
|
|
230
|
-
deduped: result.deduped,
|
|
231
|
-
});
|
|
232
|
-
|
|
233
|
-
// Fix D: refresh the RAPTOR tree for this session so live recall (search) can
|
|
234
|
-
// serve high-level summaries. Best-effort + non-fatal: never block compaction.
|
|
235
|
-
// Budget-guarded (RAPTOR_BUDGET_MS) so it can't hang a large session.
|
|
236
|
-
if (config.raptorEnabled && !result.deduped) {
|
|
237
|
-
try {
|
|
238
|
-
const dd = loadDedupConfig();
|
|
239
|
-
const all = runtime.store.list(sid);
|
|
240
|
-
const leaves = all.map((cp) => ({
|
|
241
|
-
id: cp.checkpointId,
|
|
242
|
-
messages: [],
|
|
243
|
-
sourceText: cp.normalizedText ?? cp.summary ?? cp.regionHash,
|
|
244
|
-
embedding: cp.embedding,
|
|
245
|
-
}));
|
|
246
|
-
if (leaves.length >= 2) {
|
|
247
|
-
// S25: stamp the tree with the newest checkpoint epoch so the
|
|
248
|
-
// freshness guard in raptorSearchHits can reject stale trees after a
|
|
249
|
-
// later compaction adds newer checkpoints.
|
|
250
|
-
const builtAt = all.length > 0 ? Math.max(...all.map((c) => c.timestamp)) : Date.now();
|
|
251
|
-
runRaptor(
|
|
252
|
-
leaves,
|
|
253
|
-
{
|
|
254
|
-
stateDir: runtime.currentStateDir,
|
|
255
|
-
sessionId: sid,
|
|
256
|
-
budgetMs: dd.RAPTOR_BUDGET_MS,
|
|
257
|
-
clustersPerLevel: dd.RAPTOR_CLUSTERS_PER_LEVEL,
|
|
258
|
-
consistencyThreshold: dd.RAPTOR_CONSISTENCY,
|
|
259
|
-
logger: runtime.logger,
|
|
260
|
-
builtAt: Number.isFinite(builtAt) ? builtAt : Date.now(),
|
|
261
|
-
},
|
|
262
|
-
);
|
|
263
|
-
}
|
|
264
|
-
} catch {
|
|
265
|
-
/* non-fatal: tree refresh never blocks a compaction */
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
// Slice 2: best-effort mirror of the new checkpoint into the async global
|
|
270
|
-
// PGlite/HNSW vector index. Fires once per compaction (not per-add), so the
|
|
271
|
-
// shared global dir is never hammered by concurrent test workers.
|
|
272
|
-
// Non-fatal: a WASM init failure degrades to the sync scan silently.
|
|
273
|
-
if (!result.deduped) {
|
|
274
|
-
try {
|
|
275
|
-
const all = runtime.store.list(sid);
|
|
276
|
-
const latest = all.find((cp) => cp.checkpointId === result.checkpointId);
|
|
277
|
-
if (latest?.embedding) {
|
|
278
|
-
void indexUpsertEmbedding(
|
|
279
|
-
runtime.currentStateDir,
|
|
280
|
-
sid,
|
|
281
|
-
latest.checkpointId,
|
|
282
|
-
latest.embedding,
|
|
283
|
-
).catch(() => {
|
|
284
|
-
/* non-fatal: index refresh never blocks a compaction */
|
|
285
|
-
});
|
|
286
|
-
}
|
|
287
|
-
} catch {
|
|
288
|
-
/* non-fatal: index refresh never blocks a compaction */
|
|
289
|
-
}
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
runtime.setStatus(
|
|
293
|
-
ctx,
|
|
294
|
-
runtime.rt.persistedThisSession
|
|
295
|
-
? `mega-compact: ${result.checkpointId} · ${saved} tok saved`
|
|
296
|
-
: `mega-compact: ready`,
|
|
297
|
-
);
|
|
298
|
-
runtime.logger.info("compact", {
|
|
299
|
-
sessionId: sid,
|
|
300
|
-
checkpointId: result.checkpointId ?? "(deduped)",
|
|
301
|
-
deduped: result.deduped,
|
|
302
|
-
tokenEstimate: saved,
|
|
303
|
-
compactedFrom: result.compactedFrom,
|
|
304
|
-
});
|
|
305
|
-
runtime.dashboard.event("compact", {
|
|
306
|
-
sessionId: sid,
|
|
307
|
-
checkpointId: result.checkpointId ?? "(deduped)",
|
|
308
|
-
deduped: result.deduped,
|
|
309
|
-
tokenEstimate: saved,
|
|
310
|
-
compactedFrom: result.compactedFrom,
|
|
311
|
-
});
|
|
312
|
-
runtime.snapshot(ctx);
|
|
313
|
-
return { skipped: false, result, keepFrom, saved };
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* Predict whether pi's `ctx.compact()` would throw a no-op error — "Already
|
|
318
|
-
* compacted" or "Nothing to compact (session too small)" — so the auto-trigger
|
|
319
|
-
* can SKIP the call instead of surfacing a hard, user-facing error.
|
|
320
|
-
*
|
|
321
|
-
* Why we can't intercept or suppress it: pi's public `compact()` computes
|
|
322
|
-
* `prepareCompaction()` and throws *before* it emits `session_before_compact`,
|
|
323
|
-
* so our handler there never runs on the no-op path. And `ctx.compact()`'s
|
|
324
|
-
* `onError` callback fires only AFTER pi has already emitted a `compaction_end`
|
|
325
|
-
* event carrying the error message (which the interactive UI renders) — so
|
|
326
|
-
* `onError` cannot mute it either. The only robust fix is to not call
|
|
327
|
-
* `ctx.compact()` when pi would no-op. (pi's own `_runAutoCompaction` path is
|
|
328
|
-
* silent on this same condition; the public path we're forced through is the
|
|
329
|
-
* one that throws.)
|
|
330
|
-
*
|
|
331
|
-
* Skipping is correct, not a compromise: by the time this runs, `runCompact()`
|
|
332
|
-
* has already persisted the recall checkpoint (Path A). The durable on-disk
|
|
333
|
-
* trim is only useful when pi can actually summarize a region; a transcript
|
|
334
|
-
* under pi's `keepRecentTokens` budget is small enough that reloading it on
|
|
335
|
-
* resume isn't a token-growth problem, so the durable trim is unnecessary
|
|
336
|
-
* there anyway.
|
|
337
|
-
*
|
|
338
|
-
* Mirrors pi's `prepareCompaction()` return-undefined conditions (compaction.js):
|
|
339
|
-
* (1) last entry is a compaction → "Already compacted"
|
|
340
|
-
* (2) <2 cut-point messages since the last compaction → nothing to summarize
|
|
341
|
-
* (a cut point = any non-toolResult message — user/assistant/bash/custom/
|
|
342
|
-
* branchSummary/compactionSummary — matching pi's isCutPointMessage)
|
|
343
|
-
* (3) transcript tokens since the last compaction < keepRecentTokens → pi
|
|
344
|
-
* keeps everything → nothing to summarize
|
|
345
|
-
* `keepRecentTokens` isn't readable from the extension API, so (3) uses the pi
|
|
346
|
-
* default (20000) as a conservative floor; raise it via
|
|
347
|
-
* `MEGACOMPACT_DURABLE_TRIM_FLOOR` if you raise pi's `compact.keepRecentTokens`.
|
|
348
|
-
*
|
|
349
|
-
* Best-effort: on any read error returns true (skip) — skipping a durable trim
|
|
350
|
-
* is always safe; calling `ctx.compact()` on a no-op throws to the user.
|
|
351
|
-
*/
|
|
352
|
-
export function piCompactWouldNoop(ctx: ExtensionContext): boolean {
|
|
353
|
-
try {
|
|
354
|
-
const branch = ctx.sessionManager.getBranch();
|
|
355
|
-
if (branch.length === 0) return true;
|
|
356
|
-
// (1) already compacted — pi throws "Already compacted"
|
|
357
|
-
if (branch[branch.length - 1].type === "compaction") return true;
|
|
358
|
-
// boundaryStart = index just after the most recent compaction entry (or 0)
|
|
359
|
-
let boundaryStart = 0;
|
|
360
|
-
for (let i = branch.length - 1; i >= 0; i--) {
|
|
361
|
-
if (branch[i].type === "compaction") { boundaryStart = i + 1; break; }
|
|
362
|
-
}
|
|
363
|
-
let cutPoints = 0;
|
|
364
|
-
let tokens = 0;
|
|
365
|
-
for (let i = boundaryStart; i < branch.length; i++) {
|
|
366
|
-
const e = branch[i];
|
|
367
|
-
if (e.type === "compaction") continue;
|
|
368
|
-
let isCut = false;
|
|
369
|
-
for (const m of sessionEntryToContextMessages(e)) {
|
|
370
|
-
// pi's isCutPointMessage: every role except toolResult
|
|
371
|
-
if ((m as { role?: string }).role !== "toolResult") isCut = true;
|
|
372
|
-
const c = (m as { content?: unknown }).content;
|
|
373
|
-
const text =
|
|
374
|
-
typeof c === "string" ? c
|
|
375
|
-
: Array.isArray(c)
|
|
376
|
-
? (c as { text?: string }[]).map((b) => b?.text ?? "").join(" ")
|
|
377
|
-
: "";
|
|
378
|
-
if (text) tokens += estimateBlockTokens(text);
|
|
379
|
-
}
|
|
380
|
-
if (isCut) cutPoints++;
|
|
381
|
-
}
|
|
382
|
-
// (2) need >=2 cut points so the kept cut isn't the first message
|
|
383
|
-
if (cutPoints < 2) return true;
|
|
384
|
-
// (3) transcript under pi's keepRecentTokens budget → pi keeps everything
|
|
385
|
-
if (tokens < durableTrimFloorTokens()) return true;
|
|
386
|
-
return false;
|
|
387
|
-
} catch {
|
|
388
|
-
return true; // safe: skip the durable trim rather than risk a user-facing throw
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
/** pi's default keepRecentTokens (compaction settings). Override with
|
|
393
|
-
* MEGACOMPACT_DURABLE_TRIM_FLOOR if you raise pi's compact.keepRecentTokens. */
|
|
394
|
-
function durableTrimFloorTokens(): number {
|
|
395
|
-
const raw = process.env.MEGACOMPACT_DURABLE_TRIM_FLOOR;
|
|
396
|
-
if (raw !== undefined && Number.isFinite(Number(raw))) return Number(raw);
|
|
397
|
-
return 20_000;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
/**
|
|
401
|
-
* Unified recall (Layer 5). The ONE path that injects. Returns the recall
|
|
402
|
-
* result; callers decide whether to stage it for before_agent_start (resume)
|
|
403
|
-
* or report it (command).
|
|
404
|
-
*/
|
|
405
|
-
export function doRecall(
|
|
406
|
-
runtime: MegaRuntime,
|
|
407
|
-
config: MegaConfig,
|
|
408
|
-
ctx: ExtensionContext,
|
|
409
|
-
query: string,
|
|
410
|
-
source: "resume" | "command",
|
|
411
|
-
) {
|
|
412
|
-
runtime.bindRepo(ctx.cwd);
|
|
413
|
-
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
414
|
-
// Live window text for inline dedupe (Fix C): drop recalled checkpoints that
|
|
415
|
-
// are already resident in the session, so recall never re-injects context the
|
|
416
|
-
// model can already see. Best-effort — an empty window just skips dedupe.
|
|
417
|
-
const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
|
|
418
|
-
const result = recallAndInline(
|
|
419
|
-
{
|
|
420
|
-
sessionId: sid,
|
|
421
|
-
query,
|
|
422
|
-
limit: config.autoInlineK,
|
|
423
|
-
source,
|
|
424
|
-
skipInjected: true,
|
|
425
|
-
recallMaxTokens: config.recallMaxTokens,
|
|
426
|
-
windowDedupe: config.windowDedupe,
|
|
427
|
-
liveWindow,
|
|
428
|
-
dedupSim: config.dedupSim,
|
|
429
|
-
},
|
|
430
|
-
runtime.store,
|
|
431
|
-
);
|
|
432
|
-
runtime.dashboard.event("recall", { source, query: query.slice(0, 120), injected: result.toInject.length, empty: result.empty });
|
|
433
|
-
if (!result.empty && result.toInject.length > 0) {
|
|
434
|
-
const top = result.toInject[0];
|
|
435
|
-
const scorePct = Math.round((top.score ?? 0) * 100);
|
|
436
|
-
const files = top.checkpoint.filesModified ?? [];
|
|
437
|
-
const label = files.length ? files.map((f) => f.split("/").pop() ?? f).slice(0, 2).join(", ") : top.checkpoint.checkpointId;
|
|
438
|
-
runtime.pushTicker(`${C.amber}↩${C.reset} recalled ${top.checkpoint.checkpointId} · ${scorePct}% · ${label}`);
|
|
439
|
-
runtime.lastWhy = `why: recalled@${scorePct}% (${result.toInject.length} chkpt)`;
|
|
440
|
-
}
|
|
441
|
-
if (result.toInject.length > 0) {
|
|
442
|
-
let sumTokens = 0; for (const h of result.toInject) sumTokens += h.checkpoint.tokenEstimate;
|
|
443
|
-
runtime.rt.recallInjections += result.toInject.length;
|
|
444
|
-
runtime.rt.cacheHitTokens += sumTokens;
|
|
445
|
-
incRecallInjected(result.toInject.length, runtime.currentStateDir);
|
|
446
|
-
incCacheHitTokens(sumTokens, runtime.currentStateDir);
|
|
447
|
-
}
|
|
448
|
-
return result;
|
|
449
|
-
}
|
|
450
|
-
|
|
451
|
-
/**
|
|
452
|
-
* S17: async recall with optional cross-repo augmentation. Used on resume
|
|
453
|
-
* (session_start) and /mega-recall --cross-repo — NEVER from the mid-turn
|
|
454
|
-
* context handler (that stays sync). Runs the sync same-repo scan first; if it
|
|
455
|
-
* returns < config.autoInlineK hits AND crossRepo is enabled, awaits the PGlite
|
|
456
|
-
* HNSW cross-repo path and merges (source-labeled, deduped by checkpointId). The
|
|
457
|
-
* recallMaxTokens cap + windowDedupe apply to the merged set so cross-repo can
|
|
458
|
-
* never net-inflate the window. Cross-repo uses a stricter cosine floor
|
|
459
|
-
* (config.crossRepoCosine) than same-repo. Non-fatal: any async failure returns
|
|
460
|
-
* the same-repo result unchanged.
|
|
461
|
-
*/
|
|
462
|
-
export async function doRecallAsync(
|
|
463
|
-
runtime: MegaRuntime,
|
|
464
|
-
config: MegaConfig,
|
|
465
|
-
ctx: ExtensionContext,
|
|
466
|
-
query: string,
|
|
467
|
-
source: "resume" | "command",
|
|
468
|
-
opts: { crossRepo?: boolean } = {},
|
|
469
|
-
): Promise<RecallInjectResult> {
|
|
470
|
-
runtime.bindRepo(ctx.cwd);
|
|
471
|
-
const sid = normalizeSessionId(ctx.sessionManager.getSessionId());
|
|
472
|
-
const liveWindow = config.windowDedupe ? extractLiveWindow(ctx) : undefined;
|
|
473
|
-
// Sync same-repo first (fast, never blocks).
|
|
474
|
-
const sameRepo = recallAndInline(
|
|
475
|
-
{
|
|
476
|
-
sessionId: sid, query, limit: config.autoInlineK, source, skipInjected: true,
|
|
477
|
-
recallMaxTokens: config.recallMaxTokens, windowDedupe: config.windowDedupe,
|
|
478
|
-
liveWindow, dedupSim: config.dedupSim,
|
|
479
|
-
},
|
|
480
|
-
runtime.store,
|
|
481
|
-
);
|
|
482
|
-
if (!config.crossRepoEnabled || !opts.crossRepo) return sameRepo;
|
|
483
|
-
if (sameRepo.toInject.length >= config.autoInlineK) return sameRepo; // same-repo satisfied
|
|
484
|
-
// Augment: cross-repo HNSW (async) with the stricter floor. Non-fatal.
|
|
485
|
-
try {
|
|
486
|
-
const x = await recallAndInlineAsync(
|
|
487
|
-
{
|
|
488
|
-
sessionId: sid, query, limit: config.autoInlineK, source, skipInjected: true,
|
|
489
|
-
recallMaxTokens: config.recallMaxTokens, windowDedupe: config.windowDedupe,
|
|
490
|
-
liveWindow, dedupSim: config.crossRepoCosine, crossRepo: true,
|
|
491
|
-
globalIndexDir: process.env.MEGACOMPACT_INDEX_DIR,
|
|
492
|
-
},
|
|
493
|
-
runtime.store,
|
|
494
|
-
);
|
|
495
|
-
runtime.dashboard.event("recall-crossrepo", {
|
|
496
|
-
source, query: query.slice(0, 120), injected: x.toInject.length,
|
|
497
|
-
sourceRepos: x.toInject.map((h) => h.repoId).filter(Boolean),
|
|
498
|
-
});
|
|
499
|
-
// Merge, dedup by checkpointId, respect the same token cap by reformatting.
|
|
500
|
-
const seen = new Set(sameRepo.toInject.map((h) => h.checkpoint.checkpointId));
|
|
501
|
-
const merged = [...sameRepo.toInject];
|
|
502
|
-
for (const h of x.toInject) {
|
|
503
|
-
if (!seen.has(h.checkpoint.checkpointId)) { merged.push(h); seen.add(h.checkpoint.checkpointId); }
|
|
504
|
-
}
|
|
505
|
-
const block = merged.length ? formatRecallBlock(merged) : "";
|
|
506
|
-
if (merged.length > 0) {
|
|
507
|
-
let sumTokens = 0; for (const h of merged) sumTokens += h.checkpoint.tokenEstimate;
|
|
508
|
-
runtime.rt.recallInjections += merged.length;
|
|
509
|
-
runtime.rt.cacheHitTokens += sumTokens;
|
|
510
|
-
incRecallInjected(merged.length, runtime.currentStateDir);
|
|
511
|
-
incCacheHitTokens(sumTokens, runtime.currentStateDir);
|
|
512
|
-
}
|
|
513
|
-
return {
|
|
514
|
-
toInject: merged,
|
|
515
|
-
report: merged.map((h) => ` • ${h.checkpoint.checkpointId}${h.repoId ? ` (from ${h.repoId.split("/").filter(Boolean).pop()})` : ""}`),
|
|
516
|
-
block,
|
|
517
|
-
empty: merged.length === 0,
|
|
518
|
-
};
|
|
519
|
-
} catch {
|
|
520
|
-
return sameRepo; // cross-repo failure → same-repo only (non-fatal)
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
/**
|
|
525
|
-
* Extract the live-window message texts from the session manager (Fix C),
|
|
526
|
-
* for inline-dedupe of recalled checkpoints. Best-effort: returns [] on any
|
|
527
|
-
* error so recall falls back to unbounded (still correct, just no dedupe).
|
|
528
|
-
* Mirrors recentUserQuery's use of sessionEntryToContextMessages.
|
|
529
|
-
*/
|
|
530
|
-
function extractLiveWindow(ctx: ExtensionContext): string[] {
|
|
531
|
-
try {
|
|
532
|
-
const entries = ctx.sessionManager.getEntries();
|
|
533
|
-
const texts: string[] = [];
|
|
534
|
-
for (const e of entries) {
|
|
535
|
-
for (const m of sessionEntryToContextMessages(e)) {
|
|
536
|
-
const c = (m as { content?: unknown }).content;
|
|
537
|
-
if (typeof c === "string") texts.push(c);
|
|
538
|
-
else if (Array.isArray(c)) texts.push(c.map((b: any) => b.text).join(" "));
|
|
539
|
-
}
|
|
540
|
-
}
|
|
541
|
-
return texts;
|
|
542
|
-
} catch {
|
|
543
|
-
return [];
|
|
544
|
-
}
|
|
545
|
-
}
|
|
15
|
+
export * from "./mega-pipeline/memory-review.js";
|
|
16
|
+
export * from "./mega-pipeline/compact.js";
|
|
17
|
+
export * from "./mega-pipeline/recall.js";
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* helpers.ts — shared constants, the SessionRuntime interface, and the
|
|
3
|
+
* ownVersion() package-version reader extracted from the original
|
|
4
|
+
* mega-runtime.ts monolith.
|
|
5
|
+
*
|
|
6
|
+
* These are pure constants/helpers with no class-state dependencies.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { join, dirname } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
|
|
13
|
+
// ── Public string constants ────────────────────────────────────────────────
|
|
14
|
+
// Exported via the barrel — consumers (mega-events.ts, mega-pipeline.ts) use
|
|
15
|
+
// these keys to register widgets/markers with pi.
|
|
16
|
+
export const STATUS_KEY = "mega-compact";
|
|
17
|
+
export const WIDGET_KEY = "mega-compact-stats";
|
|
18
|
+
export const MARKER_TYPE = "mega-compact-marker";
|
|
19
|
+
|
|
20
|
+
// ── Internal shared constants ──────────────────────────────────────────────
|
|
21
|
+
|
|
22
|
+
// Rough tokens-processed-per-second heuristic for the dashboard's "time saved"
|
|
23
|
+
// estimate. Throughput varies by model/hardware; this is order-of-magnitude so
|
|
24
|
+
// the dashboard can show a human-readable figure, not a precise measurement.
|
|
25
|
+
export const TOKENS_PER_SEC_ESTIMATE = 2000;
|
|
26
|
+
|
|
27
|
+
// ── SessionRuntime interface ───────────────────────────────────────────────
|
|
28
|
+
|
|
29
|
+
/** Per-session runtime state kept in the closure (mirrors neuralwatt-mcr). */
|
|
30
|
+
export interface SessionRuntime {
|
|
31
|
+
sessionId: string;
|
|
32
|
+
persistedThisSession: boolean;
|
|
33
|
+
lastCheckpointId: string | undefined;
|
|
34
|
+
lastCompactedFrom: number;
|
|
35
|
+
lastCompactedTokens: number;
|
|
36
|
+
dedupSkips: number; // compactions skipped because regionHash already stored
|
|
37
|
+
dedupAttempts: number; // total compaction attempts (for hit-rate denominator)
|
|
38
|
+
tokensSaved: number; // this session-instance only: reset on session_start
|
|
39
|
+
lastCompactAt: number | null; // wall-clock ms of the last compaction this session
|
|
40
|
+
lastNativeCompactAt: number | null; // COMPACT-DEDUP FIX: wall-clock ms of the last NATIVE pi compaction (session_compact event) — used by the agent_end/legacy race guard to skip a redundant ctx.compact() that would throw "Already compacted".
|
|
41
|
+
// S25: live dashboard counters (reset on session_start, mirrored to SQLite).
|
|
42
|
+
compactCount: number; // compactions performed this session-instance
|
|
43
|
+
recallInjections: number; // recall blocks injected this session-instance
|
|
44
|
+
cacheHitTokens: number; // tokens saved via cache hits (dedup + recall) this session
|
|
45
|
+
lengthStopPending: boolean; // S28: set on turn_end when stopReason==='length'
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ── ownVersion ─────────────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
/** Cached npm version, read once from this extension's own package.json. */
|
|
51
|
+
let CACHED_VERSION: string | null = null;
|
|
52
|
+
|
|
53
|
+
/** Read this extension's own version from its package.json (cached). */
|
|
54
|
+
export function ownVersion(): string {
|
|
55
|
+
if (CACHED_VERSION !== null) return CACHED_VERSION;
|
|
56
|
+
let v = "?";
|
|
57
|
+
try {
|
|
58
|
+
const here = dirname(fileURLToPath(import.meta.url)); // .../extensions/mega-runtime
|
|
59
|
+
const pkg = JSON.parse(
|
|
60
|
+
readFileSync(join(here, "..", "..", "package.json"), "utf-8"),
|
|
61
|
+
);
|
|
62
|
+
v = pkg.version ?? "?";
|
|
63
|
+
} catch {
|
|
64
|
+
v = "?";
|
|
65
|
+
}
|
|
66
|
+
CACHED_VERSION = v;
|
|
67
|
+
return v;
|
|
68
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* query.ts — the `recentUserQuery` free function, extracted from the original
|
|
3
|
+
* mega-runtime.ts monolith.
|
|
4
|
+
*
|
|
5
|
+
* Latest user message text — used as the auto-inline recall query.
|
|
6
|
+
* Kept as a free function (not instance state) since it only reads ctx.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { sessionEntryToContextMessages } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
|
|
12
|
+
export function recentUserQuery(ctx: ExtensionContext): string {
|
|
13
|
+
try {
|
|
14
|
+
const entries = ctx.sessionManager.getEntries();
|
|
15
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
16
|
+
const msgs = sessionEntryToContextMessages(entries[i]);
|
|
17
|
+
for (let j = msgs.length - 1; j >= 0; j--) {
|
|
18
|
+
if (msgs[j].role === "user") {
|
|
19
|
+
const c = (msgs[j] as { content: unknown }).content;
|
|
20
|
+
if (typeof c === "string") return c;
|
|
21
|
+
if (Array.isArray(c)) return c.map((b: { text?: string }) => b.text ?? "").join(" ");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
} catch {
|
|
26
|
+
/* best-effort */
|
|
27
|
+
}
|
|
28
|
+
return "";
|
|
29
|
+
}
|