osborn 0.9.291 → 0.9.293
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/.claude/skills/browser-apply/SKILL.md +5 -4
- package/.claude/skills/browser-apply/candidate.example.env +4 -1
- package/.claude/skills/browser-apply/fill.mjs +13 -2
- package/.claude/skills/meetings/SKILL.md +26 -7
- package/.env.example +6 -0
- package/dist/agent-store.d.ts +6 -0
- package/dist/agent-store.js +36 -6
- package/dist/approval-policy.d.ts +99 -0
- package/dist/approval-policy.js +196 -0
- package/dist/claude-llm.d.ts +3 -2
- package/dist/claude-llm.js +49 -19
- package/dist/config.d.ts +12 -16
- package/dist/config.js +80 -22
- package/dist/content/compaction-lens-worker.d.ts +5 -0
- package/dist/content/compaction-lens-worker.js +78 -7
- package/dist/content/content-llm.d.ts +14 -3
- package/dist/content/content-llm.js +33 -142
- package/dist/content/lens-db.d.ts +16 -5
- package/dist/content/lens-db.js +58 -11
- package/dist/content/lens-ingest.d.ts +1 -0
- package/dist/content/lens-ingest.js +1 -1
- package/dist/content/lens-launch.d.ts +42 -1
- package/dist/content/lens-launch.js +202 -40
- package/dist/content/lens-library-digest.d.ts +85 -0
- package/dist/content/lens-library-digest.js +305 -0
- package/dist/content/lens-library-index.d.ts +14 -3
- package/dist/content/lens-library-index.js +35 -8
- package/dist/content/lens-library-select.d.ts +1 -1
- package/dist/content/lens-library-select.js +1 -1
- package/dist/content/lens-library-sweep.d.ts +36 -0
- package/dist/content/lens-library-sweep.js +331 -0
- package/dist/content/lens-library.d.ts +29 -0
- package/dist/content/lens-library.js +130 -20
- package/dist/content/lens-model.d.ts +4 -0
- package/dist/content/lens-model.js +5 -0
- package/dist/content/lens-paths.d.ts +72 -0
- package/dist/content/lens-paths.js +248 -5
- package/dist/content/period-run.js +2 -2
- package/dist/content/secret-rules.d.ts +51 -0
- package/dist/content/secret-rules.js +185 -0
- package/dist/content/transcript-sanitizer.d.ts +1 -41
- package/dist/content/transcript-sanitizer.js +4 -171
- package/dist/data-sender-auth.d.ts +43 -6
- package/dist/data-sender-auth.js +61 -45
- package/dist/env-keys.d.ts +10 -2
- package/dist/env-keys.js +26 -5
- package/dist/index.js +499 -106
- package/dist/phone-code.d.ts +76 -0
- package/dist/phone-code.js +124 -0
- package/dist/phone-voice-actions.d.ts +132 -0
- package/dist/phone-voice-actions.js +223 -0
- package/dist/pipeline-direct-llm.d.ts +7 -1
- package/dist/pipeline-direct-llm.js +12 -1
- package/dist/prompts/library-digest.md +11 -0
- package/dist/prompts.js +2 -2
- package/dist/pushover.d.ts +2 -1
- package/dist/pushover.js +7 -6
- package/dist/risk-tier.d.ts +14 -0
- package/dist/risk-tier.js +140 -0
- package/dist/session-store.d.ts +1 -0
- package/dist/session-store.js +3 -2
- package/dist/session-switch.d.ts +22 -7
- package/dist/session-switch.js +58 -24
- package/dist/steward-verdict.d.ts +16 -3
- package/dist/steward-verdict.js +37 -18
- package/dist/watch-gateway.js +3 -1
- package/package.json +1 -1
- package/dist/bridge-llm.d.ts +0 -22
- package/dist/bridge-llm.js +0 -39
- package/dist/codex-handler.d.ts +0 -38
- package/dist/codex-handler.js +0 -83
- package/dist/codex-llm.d.ts +0 -40
- package/dist/codex-llm.js +0 -144
- package/dist/fast-brain.d.ts +0 -176
- package/dist/fast-brain.js +0 -1887
- package/dist/index-3-2-26-legacy.d.ts +0 -1
- package/dist/index-3-2-26-legacy.js +0 -2233
- package/dist/leagcyprompts2.d.ts +0 -0
- package/dist/leagcyprompts2.js +0 -573
- package/dist/prompts-2-25-26.d.ts +0 -0
- package/dist/prompts-2-25-26.js +0 -518
- package/dist/prompts-3-2-26.d.ts +0 -78
- package/dist/prompts-3-2-26.js +0 -1319
- package/dist/summary-index.d.ts +0 -90
- package/dist/summary-index.js +0 -585
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lens-library-sweep.ts — the Library's CATCH-UP SWEEP (runs in the detached worker).
|
|
3
|
+
*
|
|
4
|
+
* The per-session step writes at most one page per run (the period that just ended). The sweep
|
|
5
|
+
* writes the rest of the backlog across every session on this machine except the live ones:
|
|
6
|
+
* - every unwritten period that spans >= the min span (libraryBacklog: older closed periods,
|
|
7
|
+
* gaps between written pages, tails of ended sessions), one page each via runLibraryStep;
|
|
8
|
+
* - one daily digest per past local day for the chats too short to become a period
|
|
9
|
+
* (lens-library-digest.ts).
|
|
10
|
+
* Newest work first, at most SWEEP_MAX_PAGES model-call pages a run (periods and digests
|
|
11
|
+
* together), so spend stays bounded and the backlog clears over several runs. Each period or
|
|
12
|
+
* day gets one attempt per run; repeat failures stop being retried (MAX_*_FAILURES).
|
|
13
|
+
* Idempotent through the manifests: a written period or digested day is never redone.
|
|
14
|
+
*
|
|
15
|
+
* Locking: the caller holds the machine-wide sweep lock (<claudeDir>/osb-library) and no project
|
|
16
|
+
* lock. Each period takes its project's lock for the length of its write (skipped when another
|
|
17
|
+
* worker has it), and periods in a project a live session uses wait for a later run, so the sweep
|
|
18
|
+
* never keeps a live session's compaction run out. A dry run writes only under <home>/dry. Result + backlog go to library-sweep-status.json there (read by /health), the log to
|
|
19
|
+
* content-lens.log there. Never throws.
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync, statSync } from 'node:fs';
|
|
22
|
+
import { join } from 'node:path';
|
|
23
|
+
import { isContentLensEnabled } from './lens-launch.js';
|
|
24
|
+
import { SWEEP_COOLDOWN_MS, readLiveSessions, acquireLock, libraryHomeDir, releaseLock, sweepCoolingDown, touchLock, writeSweepStatus } from './lens-paths.js';
|
|
25
|
+
import { logLine } from './lens-profile.js';
|
|
26
|
+
import { libraryBacklog, libraryDirFor, libraryMinSpanMs, readManifest, runLibraryStep } from './lens-library.js';
|
|
27
|
+
import { isTransportError } from './lens-model.js';
|
|
28
|
+
import { DIGEST_CAP_USD, digestDir, ingestPendingDigests, pendingDigestDays, readDigestManifest, removeDigestDay, runDigestDay, writeDigestManifest } from './lens-library-digest.js';
|
|
29
|
+
import { CapError, LIBRARY_LEDGER_SCOPE, SpendGuard, libraryDailyUsd } from './content-llm.js';
|
|
30
|
+
import { PERIOD_CAP_USD } from './period-run.js';
|
|
31
|
+
import { loadClientRedactor } from './lens-redact.js';
|
|
32
|
+
import { listSessionDbs } from './lens-db.js';
|
|
33
|
+
import { writeAtomic } from './content-manifest.js';
|
|
34
|
+
import { redactSecrets } from './transcript-sanitizer.js';
|
|
35
|
+
const SWEEP_MAX_PAGES = 10;
|
|
36
|
+
/** No new page is started after this long; the worker's hard timeout sits above it. */
|
|
37
|
+
const SWEEP_BUDGET_MS = 60 * 60_000;
|
|
38
|
+
const SCAN_CACHE_FILE = 'sweep-scan.json';
|
|
39
|
+
/** Changes whenever the store does (WAL included). */
|
|
40
|
+
function fingerprint(db) {
|
|
41
|
+
const f = (p) => {
|
|
42
|
+
try {
|
|
43
|
+
const s = statSync(p);
|
|
44
|
+
return `${s.mtimeMs}:${s.size}`;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return '-';
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
return `${f(db)}|${f(`${db}-wal`)}`;
|
|
51
|
+
}
|
|
52
|
+
function readScanCache(home) {
|
|
53
|
+
try {
|
|
54
|
+
const o = JSON.parse(readFileSync(join(home, SCAN_CACHE_FILE), 'utf-8'));
|
|
55
|
+
return o && typeof o === 'object' && !Array.isArray(o) ? o : {};
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function writeScanCache(home, c) {
|
|
62
|
+
try {
|
|
63
|
+
writeAtomic(join(home, SCAN_CACHE_FILE), JSON.stringify(c) + '\n');
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
/* a missing cache only costs a rescan */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** An error as one redacted line of at most 200 chars: what the status file keeps (SweepError, workerError). */
|
|
70
|
+
export const errorLine = (e) => redactSecrets(String(e instanceof Error ? e.message : e).replace(/\s+/g, ' '), { assistant: true }).slice(0, 200);
|
|
71
|
+
/** Run one sweep. Never throws; returns the status it wrote. */
|
|
72
|
+
export async function runLibrarySweep(o = {}) {
|
|
73
|
+
const home = libraryHomeDir();
|
|
74
|
+
const log = (m) => logLine(home, `sweep: ${m}`);
|
|
75
|
+
const maxPages = o.maxPages ?? SWEEP_MAX_PAGES;
|
|
76
|
+
const deadline = Date.now() + SWEEP_BUDGET_MS;
|
|
77
|
+
const now = o.now ?? Date.now();
|
|
78
|
+
const st = {
|
|
79
|
+
status: 'running', trigger: o.trigger ?? 'manual', at: new Date().toISOString(), finishedAt: null, pid: process.pid,
|
|
80
|
+
pagesWritten: 0, digestsWritten: 0, modelCalls: 0, costUsd: 0, capHit: false, errors: [], backlog: undefined,
|
|
81
|
+
};
|
|
82
|
+
const err = (e) => {
|
|
83
|
+
st.errors.push(e);
|
|
84
|
+
log(`${e.kind}${e.ref ? ` ${e.ref}` : ''}: ${e.message ?? ''}`);
|
|
85
|
+
};
|
|
86
|
+
// A dry run writes nothing real: no status file, scan cache, manifest or digest (pages go to <home>/dry).
|
|
87
|
+
const save = () => {
|
|
88
|
+
if (!o.dry)
|
|
89
|
+
writeSweepStatus(st, home);
|
|
90
|
+
};
|
|
91
|
+
const finish = (status) => {
|
|
92
|
+
st.status = status;
|
|
93
|
+
st.finishedAt = new Date().toISOString();
|
|
94
|
+
st.costUsd = +st.costUsd.toFixed(4);
|
|
95
|
+
save();
|
|
96
|
+
return st;
|
|
97
|
+
};
|
|
98
|
+
const alive = () => touchLock(home);
|
|
99
|
+
try {
|
|
100
|
+
if (!isContentLensEnabled())
|
|
101
|
+
return finish('disabled');
|
|
102
|
+
if (!o.dry && !(process.env.OPENROUTER_API_KEY || '').trim())
|
|
103
|
+
return finish('no-key');
|
|
104
|
+
if (sweepCoolingDown(o.cooldownMs ?? SWEEP_COOLDOWN_MS, home)) {
|
|
105
|
+
log(`${st.trigger}: skipped, the last sweep finished under ${Math.round((o.cooldownMs ?? SWEEP_COOLDOWN_MS) / 60_000)} min ago`);
|
|
106
|
+
return { ...st, status: 'cooldown', finishedAt: new Date().toISOString() }; // the last result stays on /health
|
|
107
|
+
}
|
|
108
|
+
save();
|
|
109
|
+
// Every page and digest call is charged to the Library's own daily cap (OSBORN_LIBRARY_DAILY_USD) in
|
|
110
|
+
// the machine ledger, apart from the content step's: the worst case is reserved before the call
|
|
111
|
+
// and settled to the actual cost (an unsettled one, from a killed sweep, expires with its day).
|
|
112
|
+
const guard = new SpendGuard(null, { periodUsd: Number.POSITIVE_INFINITY, dailyUsd: libraryDailyUsd(), maxPieces: 0 }, 0, deadline, LIBRARY_LEDGER_SCOPE);
|
|
113
|
+
const exclude = new Set((o.exclude ?? []).filter(Boolean));
|
|
114
|
+
const minSpan = libraryMinSpanMs();
|
|
115
|
+
// 1. Scan: every session's backlog (skipping live ones and those settled since the last scan).
|
|
116
|
+
const cache = readScanCache(home);
|
|
117
|
+
const nextCache = {};
|
|
118
|
+
const scanned = [];
|
|
119
|
+
const items = [];
|
|
120
|
+
const shortChats = [];
|
|
121
|
+
const stores = listSessionDbs();
|
|
122
|
+
// A live session's project is left alone: its compaction run must find the project lock free.
|
|
123
|
+
const liveProjects = new Set(stores.filter(s => exclude.has(s.sessionId)).map(s => s.projectDir));
|
|
124
|
+
let livePeriods = 0;
|
|
125
|
+
// Sessions whose short chats are known this run (scanned, or from the cache): a digest day is only
|
|
126
|
+
// rewritten when every chat it holds comes from one of them, so a rewrite never drops a chat.
|
|
127
|
+
const known = new Set();
|
|
128
|
+
for (const s of stores) {
|
|
129
|
+
if (Date.now() > deadline) {
|
|
130
|
+
st.capHit = true;
|
|
131
|
+
err({ kind: 'time', message: 'time budget reached while scanning; the rest waits for the next run' });
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
const hit = cache[s.sessionId];
|
|
135
|
+
if (exclude.has(s.sessionId)) {
|
|
136
|
+
// Live: never scanned, but its last settled short chats still belong to their days.
|
|
137
|
+
if (hit && Array.isArray(hit.short)) {
|
|
138
|
+
nextCache[s.sessionId] = hit;
|
|
139
|
+
for (const p of hit.short)
|
|
140
|
+
shortChats.push({ ...s, period: p });
|
|
141
|
+
known.add(s.sessionId);
|
|
142
|
+
}
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const fp = `${fingerprint(s.db)}|${minSpan}`;
|
|
146
|
+
if (hit?.fp === fp && Array.isArray(hit.short)) {
|
|
147
|
+
nextCache[s.sessionId] = hit;
|
|
148
|
+
for (const p of hit.short)
|
|
149
|
+
shortChats.push({ ...s, period: p });
|
|
150
|
+
known.add(s.sessionId);
|
|
151
|
+
continue;
|
|
152
|
+
}
|
|
153
|
+
try {
|
|
154
|
+
const manifest = readManifest(libraryDirFor(s.db, s.sessionId), s.sessionId);
|
|
155
|
+
const b = libraryBacklog(s.db, manifest, minSpan, m => log(`${s.sessionId.slice(0, 8)} ${m}`));
|
|
156
|
+
if (b.periods.length && liveProjects.has(s.projectDir)) {
|
|
157
|
+
livePeriods += b.periods.length;
|
|
158
|
+
log(`${s.sessionId.slice(0, 8)}: ${b.periods.length} period(s) wait — a live session uses this project`);
|
|
159
|
+
}
|
|
160
|
+
else
|
|
161
|
+
for (const p of b.periods)
|
|
162
|
+
items.push({ kind: 'period', s, p, at: Date.parse(p.toTs) || 0 });
|
|
163
|
+
for (const p of b.short)
|
|
164
|
+
shortChats.push({ ...s, period: p });
|
|
165
|
+
scanned.push({ s, fp, periods: b.periods.length, short: b.short, written: Object.values(manifest.periods).filter(e => e.status === 'ok') });
|
|
166
|
+
known.add(s.sessionId);
|
|
167
|
+
}
|
|
168
|
+
catch (e) {
|
|
169
|
+
err({ kind: 'scan', ref: s.sessionId.slice(0, 8), message: errorLine(e) });
|
|
170
|
+
}
|
|
171
|
+
alive();
|
|
172
|
+
}
|
|
173
|
+
const dDir = digestDir(home);
|
|
174
|
+
const dryDir = join(home, 'dry');
|
|
175
|
+
const dm = readDigestManifest(dDir);
|
|
176
|
+
// A digested chat is stale once a written ("ok") page of its session covers its start row: its
|
|
177
|
+
// day is rewritten without it, or emptied / removed when nothing is left.
|
|
178
|
+
const pages = new Map(scanned.map(x => [x.s.sessionId, x.written]));
|
|
179
|
+
const stale = new Set(Object.values(dm.days).flatMap(e => e.chats).filter(k => {
|
|
180
|
+
const cut = k.lastIndexOf(':');
|
|
181
|
+
const start = Number(k.slice(cut + 1).split('-')[0]);
|
|
182
|
+
return (pages.get(k.slice(0, cut)) ?? []).some(e => start >= e.startRowId && start <= e.endRowId);
|
|
183
|
+
}));
|
|
184
|
+
const { days, today, emptied } = pendingDigestDays(shortChats, dm, now, stale);
|
|
185
|
+
const scrubAll = (s) => redactSecrets(loadClientRedactor(null).redact(s), { assistant: true });
|
|
186
|
+
if (!o.dry)
|
|
187
|
+
for (const day of emptied)
|
|
188
|
+
await removeDigestDay(dDir, day, { scrub: scrubAll, log });
|
|
189
|
+
const onDisk = new Set(stores.map(s => s.sessionId));
|
|
190
|
+
const sessionOf = (k) => k.slice(0, k.lastIndexOf(':'));
|
|
191
|
+
for (const [day, chats] of days) {
|
|
192
|
+
const unknown = (dm.days[day]?.chats ?? []).filter(k => onDisk.has(sessionOf(k)) && !known.has(sessionOf(k)));
|
|
193
|
+
if (unknown.length) {
|
|
194
|
+
log(`digest ${day}: waits — ${unknown.length} of its chat(s) come from a session not read this run`);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
items.push({ kind: 'digest', day, chats, at: Math.max(...chats.map(c => Date.parse(c.period.toTs) || 0)) });
|
|
198
|
+
}
|
|
199
|
+
// Settled = nothing pending for it now; skipped by later scans until its store changes.
|
|
200
|
+
const waiting = new Set([...today, ...[...days.values()].flat()].map(c => c.sessionId));
|
|
201
|
+
for (const x of scanned)
|
|
202
|
+
if (!x.periods && !waiting.has(x.s.sessionId))
|
|
203
|
+
nextCache[x.s.sessionId] = { fp: x.fp, short: x.short };
|
|
204
|
+
if (!o.dry)
|
|
205
|
+
writeScanCache(home, nextCache);
|
|
206
|
+
items.sort((a, b) => b.at - a.at);
|
|
207
|
+
log(`${st.trigger}: ${items.filter(i => i.kind === 'period').length} period(s), ${days.size} digest day(s) pending, ${today.length} chat(s) today; cap ${maxPages}`);
|
|
208
|
+
// 2. Write, newest first, under the cap. One attempt per period/day per run.
|
|
209
|
+
let periodsDone = 0;
|
|
210
|
+
let emptyDays = 0;
|
|
211
|
+
let infraFails = 0;
|
|
212
|
+
let calls = 0;
|
|
213
|
+
const reserve = (usd) => {
|
|
214
|
+
if (o.dry)
|
|
215
|
+
return null;
|
|
216
|
+
try {
|
|
217
|
+
return guard.reserve(usd);
|
|
218
|
+
}
|
|
219
|
+
catch (e) {
|
|
220
|
+
if (e instanceof CapError)
|
|
221
|
+
return 'cap';
|
|
222
|
+
throw e;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
const timeStop = () => err({ kind: 'time', message: 'time budget reached; the rest waits for the next run' });
|
|
226
|
+
// The guard refuses for the Library's daily cap, or (its deadline) the sweep's time budget.
|
|
227
|
+
const capStop = () => (guard.capHit === 'time' ? timeStop() : err({ kind: 'cap', message: 'Library daily spend cap reached' }));
|
|
228
|
+
for (const it of items) {
|
|
229
|
+
if (calls >= maxPages || Date.now() > deadline) {
|
|
230
|
+
st.capHit = true;
|
|
231
|
+
if (Date.now() > deadline)
|
|
232
|
+
timeStop();
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
if (infraFails >= 2) {
|
|
236
|
+
// An outage (bad key, provider down): stop instead of spending the cap on failing calls.
|
|
237
|
+
err({ kind: it.kind, message: 'stopped: the model call failed twice in a row' });
|
|
238
|
+
break;
|
|
239
|
+
}
|
|
240
|
+
alive();
|
|
241
|
+
if (it.kind === 'period') {
|
|
242
|
+
const sid8 = it.s.sessionId.slice(0, 8);
|
|
243
|
+
const pd = it.s.projectDir;
|
|
244
|
+
// A session that went live since the scan (the agent rewrites the list as it changes) leaves its project alone.
|
|
245
|
+
const liveNow = readLiveSessions();
|
|
246
|
+
if (liveNow && stores.some(x => liveNow.includes(x.sessionId) && x.projectDir === pd)) {
|
|
247
|
+
livePeriods++;
|
|
248
|
+
log(`${sid8}: a session in this project went live — next run`);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (!acquireLock(pd)) {
|
|
252
|
+
log(`${sid8}: project busy (another worker holds its lock) — next run`);
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const held = reserve(PERIOD_CAP_USD);
|
|
256
|
+
if (held === 'cap') {
|
|
257
|
+
releaseLock(pd);
|
|
258
|
+
st.capHit = true;
|
|
259
|
+
capStop();
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
let spent = 0;
|
|
263
|
+
try {
|
|
264
|
+
const r = await runLibraryStep({
|
|
265
|
+
sessionId: it.s.sessionId, projectDir: pd, period: it.p, dry: o.dry,
|
|
266
|
+
...(o.dry ? { outDir: join(dryDir, it.s.sessionId.slice(0, 8)) } : {}),
|
|
267
|
+
keepAlive: () => {
|
|
268
|
+
alive();
|
|
269
|
+
touchLock(pd);
|
|
270
|
+
},
|
|
271
|
+
log: m => log(`${sid8} ${m}`),
|
|
272
|
+
});
|
|
273
|
+
spent = r.costUsd;
|
|
274
|
+
st.costUsd += r.costUsd;
|
|
275
|
+
if (r.status === 'written' || r.status === 'dry' || r.status === 'model-error')
|
|
276
|
+
calls++;
|
|
277
|
+
if (r.status === 'written')
|
|
278
|
+
st.pagesWritten++;
|
|
279
|
+
if (r.status === 'written' || r.status === 'already-written')
|
|
280
|
+
periodsDone++;
|
|
281
|
+
if (r.status === 'model-error' || r.status === 'failed')
|
|
282
|
+
err({ kind: 'period', ref: sid8, message: errorLine(r.errors.join('; ')) });
|
|
283
|
+
infraFails = r.status === 'failed' || isTransportError(r.errors) ? infraFails + 1 : 0;
|
|
284
|
+
}
|
|
285
|
+
finally {
|
|
286
|
+
if (held)
|
|
287
|
+
guard.settle(held, spent);
|
|
288
|
+
releaseLock(pd);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
else {
|
|
292
|
+
const held = reserve(DIGEST_CAP_USD);
|
|
293
|
+
if (held === 'cap') {
|
|
294
|
+
st.capHit = true;
|
|
295
|
+
capStop();
|
|
296
|
+
break;
|
|
297
|
+
}
|
|
298
|
+
const r = await runDigestDay({ day: it.day, chats: it.chats, dir: o.dry ? join(dryDir, 'digests') : dDir, dry: o.dry, log });
|
|
299
|
+
if (held)
|
|
300
|
+
guard.settle(held, r.costUsd);
|
|
301
|
+
st.costUsd += r.costUsd;
|
|
302
|
+
if (r.status === 'written' || r.status === 'dry' || r.status === 'model-error')
|
|
303
|
+
calls++;
|
|
304
|
+
if (r.status === 'empty')
|
|
305
|
+
emptyDays++;
|
|
306
|
+
if (r.status === 'written')
|
|
307
|
+
st.digestsWritten++;
|
|
308
|
+
if (r.status === 'model-error' || r.status === 'failed')
|
|
309
|
+
err({ kind: 'digest', ref: it.day, message: errorLine(r.errors.join('; ')) });
|
|
310
|
+
infraFails = r.status === 'failed' || isTransportError(r.errors) ? infraFails + 1 : 0;
|
|
311
|
+
}
|
|
312
|
+
st.modelCalls = calls;
|
|
313
|
+
save();
|
|
314
|
+
}
|
|
315
|
+
st.modelCalls = calls;
|
|
316
|
+
// 3. Digests whose cloud ingest never landed (no model call).
|
|
317
|
+
if (!o.dry) {
|
|
318
|
+
const m = readDigestManifest(dDir);
|
|
319
|
+
if (await ingestPendingDigests(dDir, m, { scrub: scrubAll, log }))
|
|
320
|
+
writeDigestManifest(dDir, m);
|
|
321
|
+
}
|
|
322
|
+
const pendingPeriods = items.filter(i => i.kind === 'period').length - periodsDone + livePeriods;
|
|
323
|
+
st.backlog = { periods: Math.max(0, pendingPeriods), digestDays: Math.max(0, days.size - st.digestsWritten - emptyDays), todayChats: today.length };
|
|
324
|
+
log(`done: ${st.pagesWritten} page(s), ${st.digestsWritten} digest(s), ${calls} call(s), $${st.costUsd.toFixed(4)}; left: ${st.backlog.periods} period(s), ${st.backlog.digestDays} digest day(s)${st.capHit ? ' — cap reached' : ''}`);
|
|
325
|
+
return finish('done');
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
err({ kind: 'worker', message: errorLine(e) });
|
|
329
|
+
return finish('error');
|
|
330
|
+
}
|
|
331
|
+
}
|
|
@@ -13,6 +13,10 @@
|
|
|
13
13
|
* model call. A failed run publishes nothing (the reply stays in .staging/) and
|
|
14
14
|
* is retried next time. Fail-open: never throws; the caller just logs the result.
|
|
15
15
|
* Opt-out: OSBORN_CONTENT_LENS=0 (same switch as the launcher).
|
|
16
|
+
*
|
|
17
|
+
* The step writes one page per run. libraryBacklog lists everything else that is unwritten
|
|
18
|
+
* (older periods, gaps between pages, short stretches) for the catch-up sweep
|
|
19
|
+
* (lens-library-sweep.ts), which writes each through runLibraryStep({ period }).
|
|
16
20
|
*/
|
|
17
21
|
import { type LibraryPeriod, type Segmentation } from './lens-library-select.js';
|
|
18
22
|
import { type IngestOptions, type IngestState } from './lens-ingest.js';
|
|
@@ -27,6 +31,8 @@ export interface ManifestEntry {
|
|
|
27
31
|
costUsd: number;
|
|
28
32
|
errors: string[];
|
|
29
33
|
updatedAt: string;
|
|
34
|
+
/** Consecutive model errors on this period; the sweep stops retrying it at MAX_PERIOD_FAILURES. */
|
|
35
|
+
failures?: number;
|
|
30
36
|
/** Cloud ingest outcome (content_ingest RPC). Anything but ok/oversize is retried next run. */
|
|
31
37
|
ingest?: IngestState;
|
|
32
38
|
}
|
|
@@ -35,6 +41,8 @@ export interface Manifest {
|
|
|
35
41
|
sessionId: string;
|
|
36
42
|
/** key = String(startRowId) */
|
|
37
43
|
periods: Record<string, ManifestEntry>;
|
|
44
|
+
/** Keys of malformed entries dropped on read (never written back). */
|
|
45
|
+
invalid?: string[];
|
|
38
46
|
}
|
|
39
47
|
export type LibraryStatus = 'disabled' | 'no-key' | 'no-db' | 'no-rows' | 'deferred' | 'already-written' | 'written' | 'dry' | 'model-error' | 'failed';
|
|
40
48
|
export interface LibraryStepResult {
|
|
@@ -55,6 +63,8 @@ export interface LibraryStepOptions {
|
|
|
55
63
|
/** Write here instead of the session's library dir (dry runs / review). */
|
|
56
64
|
outDir?: string;
|
|
57
65
|
minSpanMs?: number;
|
|
66
|
+
/** Write exactly this period (the catch-up sweep, from libraryBacklog) instead of picking one. */
|
|
67
|
+
period?: LibraryPeriod;
|
|
58
68
|
/** Called every 60s while the step runs (worker refreshes its lock). */
|
|
59
69
|
keepAlive?: () => void;
|
|
60
70
|
log?: (m: string) => void;
|
|
@@ -86,6 +96,10 @@ export declare function ingestPendingPages(dir: string, m: Manifest, o?: IngestO
|
|
|
86
96
|
skipKey?: string;
|
|
87
97
|
}): Promise<boolean>;
|
|
88
98
|
export declare function libraryDirFor(dbPath: string, sessionId: string): string;
|
|
99
|
+
/**
|
|
100
|
+
* Malformed entries (hand-edited, legacy, partly written) are dropped and their keys listed in
|
|
101
|
+
* `invalid`, so NaN never reaches segmentation or file names (#271). The next write leaves them out.
|
|
102
|
+
*/
|
|
89
103
|
export declare function readManifest(dir: string, sessionId: string): Manifest;
|
|
90
104
|
export declare function writeManifest(dir: string, m: Manifest): void;
|
|
91
105
|
/**
|
|
@@ -94,5 +108,20 @@ export declare function writeManifest(dir: string, m: Manifest): void;
|
|
|
94
108
|
* written page instead of keeping its start row forever.
|
|
95
109
|
*/
|
|
96
110
|
export declare function librarySegments(db: string, manifest: Manifest, minSpanMs?: number): Segmentation;
|
|
111
|
+
export declare function libraryMinSpanMs(): number;
|
|
112
|
+
export interface LibraryBacklog {
|
|
113
|
+
/** Every unwritten period that spans >= the min span, oldest first. */
|
|
114
|
+
periods: LibraryPeriod[];
|
|
115
|
+
/** Stretches that will never reach a page on their own (span < min span): daily-digest material. */
|
|
116
|
+
short: LibraryPeriod[];
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* ALL the work the one-per-run pick leaves behind: closed periods older than the last one, the
|
|
120
|
+
* gaps between written pages (rows a later page skipped past), and the tail. Same seams and
|
|
121
|
+
* numbering as librarySegments, so a period found here has the key, index and file the step
|
|
122
|
+
* would give it. Excludes written periods, periods that keep failing, and periods whose file
|
|
123
|
+
* name is already another page's.
|
|
124
|
+
*/
|
|
125
|
+
export declare function libraryBacklog(db: string, manifest: Manifest, minSpanMs?: number, log?: (m: string) => void): LibraryBacklog;
|
|
97
126
|
/** Run the library step once. Never throws. */
|
|
98
127
|
export declare function runLibraryStep(o: LibraryStepOptions): Promise<LibraryStepResult>;
|
|
@@ -13,15 +13,20 @@
|
|
|
13
13
|
* model call. A failed run publishes nothing (the reply stays in .staging/) and
|
|
14
14
|
* is retried next time. Fail-open: never throws; the caller just logs the result.
|
|
15
15
|
* Opt-out: OSBORN_CONTENT_LENS=0 (same switch as the launcher).
|
|
16
|
+
*
|
|
17
|
+
* The step writes one page per run. libraryBacklog lists everything else that is unwritten
|
|
18
|
+
* (older periods, gaps between pages, short stretches) for the catch-up sweep
|
|
19
|
+
* (lens-library-sweep.ts), which writes each through runLibraryStep({ period }).
|
|
16
20
|
*/
|
|
17
21
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
18
22
|
import { basename, dirname, join } from 'node:path';
|
|
19
|
-
import {
|
|
23
|
+
import { resolveSessionDb, loadRowStamps } from './lens-db.js';
|
|
20
24
|
import { isContentLensEnabled } from './lens-launch.js';
|
|
21
25
|
import { readCompactionBoundaries } from './lens-period-boundaries.js';
|
|
22
26
|
import { loadClientRedactor } from './lens-redact.js';
|
|
23
27
|
import { redactSecrets } from './transcript-sanitizer.js';
|
|
24
28
|
import { runPeriodMap } from './period-run.js';
|
|
29
|
+
import { isTransportError } from './lens-model.js';
|
|
25
30
|
import { DEFAULT_MIN_SPAN_MS, pageFileName, period, pickLibraryPeriod, segmentPeriods } from './lens-library-select.js';
|
|
26
31
|
import { rebuildIndex } from './lens-library-index.js';
|
|
27
32
|
import { contentHashFor, ingestPage, needsIngest, resolveIngestConfig } from './lens-ingest.js';
|
|
@@ -73,11 +78,30 @@ export async function ingestPendingPages(dir, m, o = {}) {
|
|
|
73
78
|
export function libraryDirFor(dbPath, sessionId) {
|
|
74
79
|
return join(dirname(dbPath), 'library', sessionId.slice(0, 8));
|
|
75
80
|
}
|
|
81
|
+
const posInt = (n) => Number.isInteger(n) && n > 0;
|
|
82
|
+
/** A manifest entry the segmentation can trust: finite row range and index, a page file, its own key. */
|
|
83
|
+
function isValidEntry(key, e) {
|
|
84
|
+
return !!e && typeof e === 'object' && ['ok', 'error', 'dry'].includes(e.status) && posInt(e.startRowId) && posInt(e.endRowId) &&
|
|
85
|
+
e.endRowId >= e.startRowId && posInt(e.index) && typeof e.file === 'string' && !!e.file && key === String(e.startRowId);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Malformed entries (hand-edited, legacy, partly written) are dropped and their keys listed in
|
|
89
|
+
* `invalid`, so NaN never reaches segmentation or file names (#271). The next write leaves them out.
|
|
90
|
+
*/
|
|
76
91
|
export function readManifest(dir, sessionId) {
|
|
77
92
|
try {
|
|
78
93
|
const o = JSON.parse(readFileSync(join(dir, MANIFEST_FILE), 'utf-8'));
|
|
79
|
-
if (o && typeof o.periods === 'object' && !Array.isArray(o.periods))
|
|
80
|
-
|
|
94
|
+
if (o && typeof o.periods === 'object' && o.periods && !Array.isArray(o.periods)) {
|
|
95
|
+
const periods = {};
|
|
96
|
+
const invalid = [];
|
|
97
|
+
for (const [k, e] of Object.entries(o.periods)) {
|
|
98
|
+
if (isValidEntry(k, e))
|
|
99
|
+
periods[k] = e;
|
|
100
|
+
else
|
|
101
|
+
invalid.push(k);
|
|
102
|
+
}
|
|
103
|
+
return { version: 1, sessionId, periods, ...(invalid.length ? { invalid } : {}) };
|
|
104
|
+
}
|
|
81
105
|
}
|
|
82
106
|
catch {
|
|
83
107
|
/* missing / unreadable → empty */
|
|
@@ -90,7 +114,8 @@ function writeAtomic(path, text) {
|
|
|
90
114
|
renameSync(tmp, path);
|
|
91
115
|
}
|
|
92
116
|
export function writeManifest(dir, m) {
|
|
93
|
-
|
|
117
|
+
const { invalid: _invalid, ...out } = m;
|
|
118
|
+
writeAtomic(join(dir, MANIFEST_FILE), JSON.stringify(out, null, 2) + '\n');
|
|
94
119
|
}
|
|
95
120
|
const envNum = (k) => {
|
|
96
121
|
const n = Number(process.env[k]);
|
|
@@ -102,21 +127,85 @@ const envNum = (k) => {
|
|
|
102
127
|
* written page instead of keeping its start row forever.
|
|
103
128
|
*/
|
|
104
129
|
export function librarySegments(db, manifest, minSpanMs = libraryMinSpanMs()) {
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
130
|
+
const s = segmentLibrary(db, manifest, minSpanMs);
|
|
131
|
+
const closed = [...s.frozen, ...s.gapPeriods, ...s.rest.closed].sort((a, b) => a.startRowId - b.startRowId);
|
|
132
|
+
return { closed, tail: s.rest.tail };
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Written pages are frozen: they keep their rows, index and file whatever the period length is
|
|
136
|
+
* now. Rows after the last written page are segmented and numbered on. Rows BEFORE a written
|
|
137
|
+
* page that no page covers (a tail written while an earlier closed period was not) are segmented
|
|
138
|
+
* too, numbered on from the page before them, so that period is never orphaned (#267). A gap's
|
|
139
|
+
* last stretch is closed by the next written page: a period if it spans the min span, else short.
|
|
140
|
+
*/
|
|
141
|
+
function segmentLibrary(db, manifest, minSpanMs) {
|
|
142
|
+
const rows = loadRowStamps(db); // ids + timestamps only: no blob is decompressed for segmentation
|
|
143
|
+
const seams = readCompactionBoundaries(db);
|
|
108
144
|
const written = Object.values(manifest.periods).filter(e => e.status === 'ok').sort((a, b) => a.startRowId - b.startRowId);
|
|
109
|
-
const lastEnd = written.length ? Math.max(...written.map(e => e.endRowId)) : 0;
|
|
110
|
-
const lastIndex = written.length ? Math.max(...written.map(e => e.index)) : 0;
|
|
111
145
|
const frozen = written.map(e => period(e.index, e.startRowId, e.endRowId, typeof e.closedBy === 'number' ? e.closedBy : null, rows.filter(r => r.id >= e.startRowId && r.id <= e.endRowId)));
|
|
112
|
-
const
|
|
113
|
-
const
|
|
114
|
-
|
|
146
|
+
const gapPeriods = [];
|
|
147
|
+
const gapShort = [];
|
|
148
|
+
let prevEnd = 0;
|
|
149
|
+
let prevIndex = 0;
|
|
150
|
+
for (const e of written) {
|
|
151
|
+
const gap = rows.filter(r => r.id > prevEnd && r.id < e.startRowId);
|
|
152
|
+
if (gap.length) {
|
|
153
|
+
const g = segmentPeriods(gap, seams, minSpanMs);
|
|
154
|
+
const at = (p) => ({ ...p, index: p.index + prevIndex });
|
|
155
|
+
gapPeriods.push(...g.closed.map(at));
|
|
156
|
+
if (g.tail) {
|
|
157
|
+
const t = { ...at(g.tail), closedBy: e.startRowId };
|
|
158
|
+
if (t.spanMs >= minSpanMs)
|
|
159
|
+
gapPeriods.push(t);
|
|
160
|
+
else
|
|
161
|
+
gapShort.push(t);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
prevEnd = Math.max(prevEnd, e.endRowId);
|
|
165
|
+
prevIndex = Math.max(prevIndex, e.index);
|
|
166
|
+
}
|
|
167
|
+
const after = segmentPeriods(rows.filter(r => r.id > prevEnd), seams, minSpanMs);
|
|
168
|
+
const renumber = (p) => ({ ...p, index: p.index + prevIndex });
|
|
169
|
+
return { frozen, gapPeriods, gapShort, rest: { closed: after.closed.map(renumber), tail: after.tail ? renumber(after.tail) : null } };
|
|
115
170
|
}
|
|
116
|
-
function libraryMinSpanMs() {
|
|
171
|
+
export function libraryMinSpanMs() {
|
|
117
172
|
const envH = envNum('OSBORN_LIBRARY_MIN_PERIOD_H');
|
|
118
173
|
return envH ? envH * 3_600_000 : DEFAULT_MIN_SPAN_MS;
|
|
119
174
|
}
|
|
175
|
+
/** A period whose reply was unusable this many times in a row is no longer retried by the sweep (manual run only). */
|
|
176
|
+
const MAX_PERIOD_FAILURES = 3;
|
|
177
|
+
/**
|
|
178
|
+
* ALL the work the one-per-run pick leaves behind: closed periods older than the last one, the
|
|
179
|
+
* gaps between written pages (rows a later page skipped past), and the tail. Same seams and
|
|
180
|
+
* numbering as librarySegments, so a period found here has the key, index and file the step
|
|
181
|
+
* would give it. Excludes written periods, periods that keep failing, and periods whose file
|
|
182
|
+
* name is already another page's.
|
|
183
|
+
*/
|
|
184
|
+
export function libraryBacklog(db, manifest, minSpanMs = libraryMinSpanMs(), log = () => { }) {
|
|
185
|
+
const s = segmentLibrary(db, manifest, minSpanMs);
|
|
186
|
+
const periods = [...s.gapPeriods, ...s.rest.closed];
|
|
187
|
+
const short = [...s.gapShort];
|
|
188
|
+
const tail = s.rest.tail;
|
|
189
|
+
if (tail && tail.spanMs >= minSpanMs)
|
|
190
|
+
periods.push(tail);
|
|
191
|
+
else if (tail)
|
|
192
|
+
short.push(tail);
|
|
193
|
+
const owner = new Map(Object.values(manifest.periods).filter(e => e.status === 'ok').map(e => [e.file, e.startRowId]));
|
|
194
|
+
return {
|
|
195
|
+
periods: periods.filter(p => {
|
|
196
|
+
const e = manifest.periods[String(p.startRowId)];
|
|
197
|
+
if (e?.status === 'ok' || (e?.status === 'error' && (e.failures ?? 0) >= MAX_PERIOD_FAILURES))
|
|
198
|
+
return false;
|
|
199
|
+
const file = pageFileName(p);
|
|
200
|
+
const o = owner.get(file);
|
|
201
|
+
if (o === undefined || o === p.startRowId)
|
|
202
|
+
return true;
|
|
203
|
+
log(`library: period #${p.startRowId}–#${p.endRowId} would be ${file}, which is period #${o}'s page — skipped (write it by hand)`);
|
|
204
|
+
return false;
|
|
205
|
+
}),
|
|
206
|
+
short,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
120
209
|
/** Run the library step once. Never throws. */
|
|
121
210
|
export async function runLibraryStep(o) {
|
|
122
211
|
const log = o.log ?? (() => { });
|
|
@@ -134,26 +223,45 @@ export async function runLibraryStep(o) {
|
|
|
134
223
|
const projectDir = dirname(dirname(dirname(db)));
|
|
135
224
|
const dir = (res.libraryDir = o.outDir ?? libraryDirFor(db, o.sessionId));
|
|
136
225
|
const manifest = readManifest(dir, o.sessionId);
|
|
226
|
+
if (manifest.invalid?.length)
|
|
227
|
+
log(`library: dropped ${manifest.invalid.length} malformed manifest entry(ies): ${manifest.invalid.slice(0, 5).join(', ')}`);
|
|
137
228
|
const minSpan = o.minSpanMs ?? libraryMinSpanMs();
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
229
|
+
const isDone = (start) => manifest.periods[String(start)]?.status === 'ok';
|
|
230
|
+
let target;
|
|
231
|
+
let skipped = 'already-written';
|
|
232
|
+
if (o.period) {
|
|
233
|
+
target = isDone(o.period.startRowId) ? null : o.period;
|
|
234
|
+
log(`library: backlog period ${o.period.index} rows #${o.period.startRowId}–#${o.period.endRowId} → ${target ? 'backlog' : skipped}`);
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
const seg = librarySegments(db, manifest, minSpan);
|
|
238
|
+
const pick = pickLibraryPeriod(seg, isDone, minSpan);
|
|
239
|
+
target = pick.period;
|
|
240
|
+
if (pick.reason !== 'tail' && pick.reason !== 'last-closed')
|
|
241
|
+
skipped = pick.reason;
|
|
242
|
+
log(`library: ${seg.closed.length} closed period(s), tail ${seg.tail ? `#${seg.tail.startRowId}–#${seg.tail.endRowId} (${(seg.tail.spanMs / 3_600_000).toFixed(1)}h)` : 'none'} → ${pick.reason}`);
|
|
243
|
+
}
|
|
141
244
|
const red = loadClientRedactor(projectDir);
|
|
142
245
|
const scrub = (s) => redactSecrets(red.redact(s), { assistant: true });
|
|
143
|
-
if (
|
|
246
|
+
if (!target) {
|
|
144
247
|
// Nothing new to write; still retry pages whose cloud ingest never landed (no model call).
|
|
145
248
|
if (!o.dry && !o.outDir && (await ingestPendingPages(dir, manifest, { scrub, log })))
|
|
146
249
|
writeManifest(dir, manifest);
|
|
147
|
-
return { ...res, status:
|
|
250
|
+
return { ...res, status: skipped };
|
|
148
251
|
}
|
|
149
|
-
const p = (res.period =
|
|
252
|
+
const p = (res.period = target);
|
|
150
253
|
const key = String(p.startRowId);
|
|
151
254
|
const file = pageFileName(p);
|
|
152
|
-
// Never overwrite a page this manifest did not write (e.g. a manual backfill page)
|
|
255
|
+
// Never overwrite a page this manifest did not write (e.g. a manual backfill page),
|
|
256
|
+
// nor another period's written page that happens to share the file name.
|
|
153
257
|
if (!o.outDir && existsSync(join(dir, file)) && !Object.values(manifest.periods).some(e => e.file === file)) {
|
|
154
258
|
log(`library: ${file} exists and is not ours — not overwritten`);
|
|
155
259
|
return { ...res, status: 'already-written' };
|
|
156
260
|
}
|
|
261
|
+
if (!o.outDir && Object.values(manifest.periods).some(e => e.file === file && e.status === 'ok' && e.startRowId !== p.startRowId)) {
|
|
262
|
+
log(`library: ${file} belongs to another written period — not overwritten`);
|
|
263
|
+
return { ...res, status: 'already-written' };
|
|
264
|
+
}
|
|
157
265
|
// Period map on exactly this row range, staged first; published only when a map came back.
|
|
158
266
|
mkdirSync(join(dir, STAGING_DIR), { recursive: true });
|
|
159
267
|
const staged = join(dir, STAGING_DIR, file);
|
|
@@ -164,6 +272,8 @@ export async function runLibraryStep(o) {
|
|
|
164
272
|
const entry = {
|
|
165
273
|
startRowId: p.startRowId, endRowId: p.endRowId, closedBy: p.closedBy ?? 'compaction', index: p.index, file,
|
|
166
274
|
status: o.dry ? 'dry' : r.map ? 'ok' : 'error', costUsd: r.costUsd, errors: r.errors, updatedAt: new Date().toISOString(),
|
|
275
|
+
// Only a reply the step could not use counts toward giving up; an outage (HTTP / network) does not.
|
|
276
|
+
...(!o.dry && !r.map ? { failures: (manifest.periods[key]?.failures ?? 0) + (isTransportError(r.errors) ? 0 : 1) } : {}),
|
|
167
277
|
};
|
|
168
278
|
if (ok) {
|
|
169
279
|
const marker = `<!-- osborn-library: key=${key} rows=${p.startRowId}-${p.endRowId} closed-by=${entry.closedBy} period=${p.index}${o.dry ? ' dry' : ''} -->\n`;
|
|
@@ -60,5 +60,9 @@ export interface ChatResult {
|
|
|
60
60
|
completionTokens: number;
|
|
61
61
|
costUsd: number;
|
|
62
62
|
}
|
|
63
|
+
/** How a thrown chat() (HTTP, timeout, network) is recorded in a run's errors; isTransportError reads it back. */
|
|
64
|
+
export declare const modelCallFailed: (e: any) => string;
|
|
65
|
+
/** The model call itself failed: an outage, not a bad reply. */
|
|
66
|
+
export declare const isTransportError: (errors: string[]) => boolean;
|
|
63
67
|
/** One chat call. Returns null when the budget refuses; throws on HTTP/timeout errors. */
|
|
64
68
|
export declare function chat(budget: Budget, user: string, apiKey: string, maxOut?: number): Promise<ChatResult | null>;
|
|
@@ -136,6 +136,11 @@ export function reducePrompt(candidatesJson, maxA, maxC) {
|
|
|
136
136
|
'</candidates>',
|
|
137
137
|
].join('\n\n');
|
|
138
138
|
}
|
|
139
|
+
const CALL_FAILED = 'model call failed';
|
|
140
|
+
/** How a thrown chat() (HTTP, timeout, network) is recorded in a run's errors; isTransportError reads it back. */
|
|
141
|
+
export const modelCallFailed = (e) => `${CALL_FAILED}: ${e?.message ?? e}`;
|
|
142
|
+
/** The model call itself failed: an outage, not a bad reply. */
|
|
143
|
+
export const isTransportError = (errors) => errors.some(e => e.startsWith(CALL_FAILED));
|
|
139
144
|
/** One chat call. Returns null when the budget refuses; throws on HTTP/timeout errors. */
|
|
140
145
|
export async function chat(budget, user, apiKey, maxOut = 16_000) {
|
|
141
146
|
const estPrompt = Math.ceil((SYSTEM.length + user.length) / 4);
|