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
package/dist/claude-llm.js
CHANGED
|
@@ -16,14 +16,14 @@ import { phoneToolPolicy } from './data-sender-auth.js';
|
|
|
16
16
|
import { openStore, recall, storeExists, updateSessionStore, getStorePath } from './session-store.js';
|
|
17
17
|
import { appendCompactionRecord, countTranscriptRows } from './compaction-log.js';
|
|
18
18
|
import { getEmbedder } from './embedder.js';
|
|
19
|
-
import {
|
|
19
|
+
import { launchCompactionLensWithRetry } from './content/lens-launch.js';
|
|
20
20
|
import { isSafeArtifactPath } from './lib/safe-artifact-path.js';
|
|
21
21
|
import { existsSync, readdirSync, readFileSync, writeFileSync, mkdirSync, statSync } from 'node:fs';
|
|
22
22
|
import { join, dirname, resolve, basename } from 'node:path';
|
|
23
23
|
import { fileURLToPath } from 'node:url';
|
|
24
24
|
import { homedir, loadavg, totalmem, freemem, cpus } from 'node:os';
|
|
25
25
|
import { stewardGate } from './steward-gate.js';
|
|
26
|
-
import { parseStewardVerdict,
|
|
26
|
+
import { parseStewardVerdict, appendStewardRecord } from './steward-verdict.js';
|
|
27
27
|
import { ROLES, EDIT_TOOLS, roleOf, coreRole, installsSkillsSilently, parseFrontMatter } from './agent-store.js';
|
|
28
28
|
// Directory of this module — used to locate co-located prompt files (e.g., turn-shape reminder).
|
|
29
29
|
const __claudeLlmDir = dirname(fileURLToPath(import.meta.url));
|
|
@@ -1242,6 +1242,7 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1242
1242
|
// the FULL source set — main JSONL + every sub-agent JSONL — exactly like the flat
|
|
1243
1243
|
// index. Incremental (byte-offset resume) + fire-and-forget, so it never blocks a turn.
|
|
1244
1244
|
#storeUpdating = false;
|
|
1245
|
+
#storeUpdateAgain = null;
|
|
1245
1246
|
// Turbo mode — when true, every spawned agent (main + sub-agents) runs on
|
|
1246
1247
|
// FAST_MODEL regardless of individual model config. Default off = no-op.
|
|
1247
1248
|
#turbo = false;
|
|
@@ -1303,7 +1304,10 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1303
1304
|
* Respond to a pending permission request
|
|
1304
1305
|
* Call this after receiving 'permission_request' event
|
|
1305
1306
|
*/
|
|
1306
|
-
respondToPermission(allow, message) {
|
|
1307
|
+
respondToPermission(allow, message, requestId) {
|
|
1308
|
+
// An answer meant for another request (a late click, a parked brain) never settles this one.
|
|
1309
|
+
if (requestId !== undefined && this.#pendingPermission?.requestId !== requestId)
|
|
1310
|
+
return false;
|
|
1307
1311
|
if (this.#pendingPermission) {
|
|
1308
1312
|
const input = this.#pendingPermission.input;
|
|
1309
1313
|
if (allow) {
|
|
@@ -1319,7 +1323,9 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1319
1323
|
});
|
|
1320
1324
|
}
|
|
1321
1325
|
this.#pendingPermission = null;
|
|
1326
|
+
return true;
|
|
1322
1327
|
}
|
|
1328
|
+
return false;
|
|
1323
1329
|
}
|
|
1324
1330
|
/**
|
|
1325
1331
|
* Check if there's a pending permission request
|
|
@@ -1332,7 +1338,8 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1332
1338
|
*/
|
|
1333
1339
|
getPendingPermission() {
|
|
1334
1340
|
if (this.#pendingPermission) {
|
|
1335
|
-
|
|
1341
|
+
const { toolName, input, requestId } = this.#pendingPermission;
|
|
1342
|
+
return { toolName, input, requestId };
|
|
1336
1343
|
}
|
|
1337
1344
|
return null;
|
|
1338
1345
|
}
|
|
@@ -1346,16 +1353,22 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1346
1353
|
* The guard lives here (on the long-lived ClaudeLLM, not the per-turn stream) so a slow
|
|
1347
1354
|
* write can't overlap the next turn's write. Never throws; never blocks the caller.
|
|
1348
1355
|
*/
|
|
1349
|
-
triggerStoreUpdate(sessionId, workingDir) {
|
|
1350
|
-
if (
|
|
1356
|
+
triggerStoreUpdate(sessionId, workingDir, mainOnly = false) {
|
|
1357
|
+
if (!sessionId || sessionId === 'pending' || !workingDir)
|
|
1351
1358
|
return;
|
|
1352
1359
|
if (process.env.OSBORN_STORE === '0')
|
|
1353
1360
|
return;
|
|
1361
|
+
// A request during a sweep runs once after it (a full sweep if any request was full),
|
|
1362
|
+
// so the turn-end sweep is never lost.
|
|
1363
|
+
if (this.#storeUpdating) {
|
|
1364
|
+
this.#storeUpdateAgain = { sessionId, workingDir, mainOnly: mainOnly && (this.#storeUpdateAgain?.mainOnly ?? true) };
|
|
1365
|
+
return;
|
|
1366
|
+
}
|
|
1354
1367
|
this.#storeUpdating = true;
|
|
1355
1368
|
(async () => {
|
|
1356
1369
|
try {
|
|
1357
1370
|
const embed = process.env.OSBORN_EMBED === '0' ? undefined : (await getEmbedder()) ?? undefined;
|
|
1358
|
-
const stats = await updateSessionStore(sessionId, workingDir, { embed });
|
|
1371
|
+
const stats = await updateSessionStore(sessionId, workingDir, { embed, mainOnly });
|
|
1359
1372
|
if (stats.newRows > 0)
|
|
1360
1373
|
console.log(`🗄️ [store] +${stats.newRows} rows (${stats.totalRows} total, embedded=${stats.embeddedRows}) across main+subagents`);
|
|
1361
1374
|
}
|
|
@@ -1364,6 +1377,10 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
1364
1377
|
}
|
|
1365
1378
|
finally {
|
|
1366
1379
|
this.#storeUpdating = false;
|
|
1380
|
+
const again = this.#storeUpdateAgain;
|
|
1381
|
+
this.#storeUpdateAgain = null;
|
|
1382
|
+
if (again)
|
|
1383
|
+
this.triggerStoreUpdate(again.sessionId, again.workingDir, again.mainOnly);
|
|
1367
1384
|
}
|
|
1368
1385
|
})();
|
|
1369
1386
|
}
|
|
@@ -2236,6 +2253,12 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
2236
2253
|
// errored, or its turn aborted) — drop it so it can't poison the next
|
|
2237
2254
|
// agent_id pairing of the same type.
|
|
2238
2255
|
this.#pendingToolUseByType.clear();
|
|
2256
|
+
// Ingest the finished reply now: the submit-time sweep ran before it was
|
|
2257
|
+
// written, so /session-messages would lack it until the next turn (#153).
|
|
2258
|
+
// Main JSONL only; the next submit-time sweep picks up sub-agents.
|
|
2259
|
+
const sid = msg.session_id || this.#sessionId;
|
|
2260
|
+
if (sid && this.#opts.workingDirectory)
|
|
2261
|
+
this.triggerStoreUpdate(sid, this.#opts.workingDirectory, true);
|
|
2239
2262
|
console.log('✅ Claude turn complete (persistent session stays alive)');
|
|
2240
2263
|
}
|
|
2241
2264
|
}
|
|
@@ -2298,9 +2321,10 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
2298
2321
|
// Pass permission handler for canUseTool callback
|
|
2299
2322
|
onPermissionRequest: (toolName, input) => {
|
|
2300
2323
|
return new Promise((resolve) => {
|
|
2301
|
-
|
|
2302
|
-
|
|
2303
|
-
|
|
2324
|
+
const requestId = crypto.randomUUID();
|
|
2325
|
+
this.#pendingPermission = { toolName, input, requestId, resolve };
|
|
2326
|
+
console.log(`⚠️ Permission request: ${toolName} (${requestId.slice(0, 8)})`);
|
|
2327
|
+
this.#eventEmitter.emit('permission_request', { toolName, input, requestId });
|
|
2304
2328
|
});
|
|
2305
2329
|
},
|
|
2306
2330
|
});
|
|
@@ -2331,6 +2355,16 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2331
2355
|
// SubagentStart can label the Running row with WHAT the sub-agent is doing even if the
|
|
2332
2356
|
// SDK hook input omits the prompt. Cleared when consumed by the matching start.
|
|
2333
2357
|
#pendingTaskByType = new Map();
|
|
2358
|
+
// Steward verdicts and gate events go to the session's sidecar (steward.jsonl) so a reload rebuilds them.
|
|
2359
|
+
#recordSteward(rec) {
|
|
2360
|
+
try {
|
|
2361
|
+
if (this.#sessionId && this.#opts.workingDirectory)
|
|
2362
|
+
appendStewardRecord(this.#sessionId, this.#opts.workingDirectory, rec);
|
|
2363
|
+
}
|
|
2364
|
+
catch (e) {
|
|
2365
|
+
console.warn('steward record persist failed:', e instanceof Error ? e.message : e);
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2334
2368
|
constructor(llmInstance, { chatCtx, toolCtx, connOptions, opts, sessionId, onSessionId, eventEmitter, onCheckpoint, onPermissionRequest, abortController, primeOnly, }) {
|
|
2335
2369
|
super(llmInstance, { chatCtx, toolCtx, connOptions });
|
|
2336
2370
|
this.#llmRef = llmInstance;
|
|
@@ -2561,8 +2595,10 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2561
2595
|
let stewardNote = null; // advise mode: rides the allow tail below
|
|
2562
2596
|
if (toolName === 'Bash') {
|
|
2563
2597
|
const gate = await stewardGate(String(toolInput.command || ''), this.#opts.workingDirectory || process.cwd());
|
|
2564
|
-
if (gate.decision !== 'allow')
|
|
2598
|
+
if (gate.decision !== 'allow') {
|
|
2599
|
+
this.#recordSteward({ gate: gate.decision, message: gate.message ?? '', at: new Date().toISOString() });
|
|
2565
2600
|
this.#eventEmitter.emit('steward_gate', { decision: gate.decision, message: gate.message });
|
|
2601
|
+
}
|
|
2566
2602
|
if (gate.decision === 'deny') {
|
|
2567
2603
|
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny' }, reason: gate.message };
|
|
2568
2604
|
}
|
|
@@ -2998,7 +3034,7 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2998
3034
|
// ON by default; OSBORN_CONTENT_LENS=0|off|false|no disables. Spawn is sync + unref'd: never awaited.
|
|
2999
3035
|
try {
|
|
3000
3036
|
if (!['0', 'off', 'false', 'no'].includes((process.env.OSBORN_CONTENT_LENS || '').trim().toLowerCase())) {
|
|
3001
|
-
const cl =
|
|
3037
|
+
const cl = launchCompactionLensWithRetry({ sessionId: input?.session_id || sessionId, transcriptPath: input?.transcript_path, cwd: this.#opts.workingDirectory });
|
|
3002
3038
|
progress('Content lens', cl.status === 'spawned' ? 'background worker started' : cl.status);
|
|
3003
3039
|
}
|
|
3004
3040
|
}
|
|
@@ -3087,13 +3123,7 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
3087
3123
|
const atRole = roleOf(at, this.#opts.agentRoles, NAMED_AGENTS);
|
|
3088
3124
|
const verdict = atRole && ROLES[atRole].verdict ? parseStewardVerdict(msg) : null;
|
|
3089
3125
|
if (verdict) {
|
|
3090
|
-
|
|
3091
|
-
if (this.#sessionId && this.#opts.workingDirectory)
|
|
3092
|
-
appendStewardVerdict(this.#sessionId, this.#opts.workingDirectory, verdict);
|
|
3093
|
-
}
|
|
3094
|
-
catch (e) {
|
|
3095
|
-
console.warn('steward verdict persist failed:', e instanceof Error ? e.message : e);
|
|
3096
|
-
}
|
|
3126
|
+
this.#recordSteward(verdict);
|
|
3097
3127
|
this.#eventEmitter.emit('steward_verdict', verdict);
|
|
3098
3128
|
}
|
|
3099
3129
|
// Pattern #1 verifier chaining — CORRECT timing (moved here from PostToolUse).
|
package/dist/config.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { McpServerConfig } from './claude-handler.js';
|
|
2
|
+
import { type ApprovalMode } from './approval-policy.js';
|
|
2
3
|
export type VoiceMode = 'pipeline';
|
|
3
4
|
export type EditMode = 'read-only' | 'edit';
|
|
4
5
|
export type AgentMode = 'plan' | 'execute' | 'research';
|
|
@@ -26,7 +27,18 @@ export interface OsbornConfig {
|
|
|
26
27
|
voiceMode?: VoiceMode;
|
|
27
28
|
direct?: DirectConfig;
|
|
28
29
|
inference?: InferenceConfig;
|
|
30
|
+
approvalMode?: ApprovalMode;
|
|
29
31
|
}
|
|
32
|
+
/** The saved approval mode (config.yaml `approvalMode`); 'ask' when unset or unreadable. */
|
|
33
|
+
export declare function readApprovalMode(file?: string): ApprovalMode;
|
|
34
|
+
/**
|
|
35
|
+
* Saves the approval mode into config.yaml. The YAML document is edited in
|
|
36
|
+
* place, so every other key and its comments survive, and the file keeps its
|
|
37
|
+
* permissions. Written to a temp file and renamed, so a crash never leaves a
|
|
38
|
+
* half-written config. Refuses (false) when the existing file cannot be
|
|
39
|
+
* parsed or is not a mapping, rather than overwrite it.
|
|
40
|
+
*/
|
|
41
|
+
export declare function writeApprovalMode(mode: ApprovalMode, configFile?: string): boolean;
|
|
30
42
|
interface McpServerConfigYaml {
|
|
31
43
|
enabled?: boolean;
|
|
32
44
|
command?: string;
|
|
@@ -180,22 +192,6 @@ export interface ClaudeSessionEntry {
|
|
|
180
192
|
* the JSONL file. This function is only reached when that fails.
|
|
181
193
|
*/
|
|
182
194
|
export declare function slugToPath(slug: string): string;
|
|
183
|
-
/**
|
|
184
|
-
* Extract cwd from the first JSONL entry that carries a `cwd` field.
|
|
185
|
-
*
|
|
186
|
-
* Previously: read only the first 8KB and only accepted `type === 'user'`. That
|
|
187
|
-
* broke for sessions whose first JSONL entry was larger than 8KB — e.g. a
|
|
188
|
-
* `queue-operation` containing pasted email/page text. readline never emits the
|
|
189
|
-
* `line` event for an incomplete final chunk, so the scan finds nothing,
|
|
190
|
-
* `listAllClaudeSessions` falls through to the lossy `slugToPath` reverse, and
|
|
191
|
-
* the mangled path ends up as a `cwd` passed to `child_process.spawn`, producing
|
|
192
|
-
* the misleading "Claude Code executable not found" error (see MEMORY bug #11).
|
|
193
|
-
*
|
|
194
|
-
* Now: stream line-by-line with no byte cap, short-circuit on the first entry
|
|
195
|
-
* with a `cwd` field regardless of `type` (every `user` / `attachment` /
|
|
196
|
-
* `assistant` / `system` entry in a Claude JSONL session carries `cwd`, so the
|
|
197
|
-
* scan finishes in the first few KB of any normal session).
|
|
198
|
-
*/
|
|
199
195
|
export declare function extractCwd(filePath: string): Promise<string>;
|
|
200
196
|
export declare function invalidateSessionListCache(): void;
|
|
201
197
|
/**
|
package/dist/config.js
CHANGED
|
@@ -1,11 +1,67 @@
|
|
|
1
|
-
import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync } from 'fs';
|
|
1
|
+
import { readFileSync, existsSync, mkdirSync, writeFileSync, renameSync, chmodSync, realpathSync, lstatSync, readlinkSync } from 'fs';
|
|
2
2
|
import { homedir } from 'os';
|
|
3
|
-
import { join } from 'path';
|
|
4
|
-
import { parse, stringify } from 'yaml';
|
|
3
|
+
import { dirname, join, resolve } from 'path';
|
|
4
|
+
import { Document, isMap, parse, parseDocument, stringify } from 'yaml';
|
|
5
5
|
import { cleanTurnText } from './content/transcript-sanitizer.js';
|
|
6
|
+
import { projectPathToSlug } from './session-access.js';
|
|
7
|
+
import { DEFAULT_APPROVAL_MODE, isApprovalMode } from './approval-policy.js';
|
|
6
8
|
// Config file paths
|
|
7
9
|
const CONFIG_DIR = join(homedir(), '.osborn');
|
|
8
10
|
const CONFIG_FILE = join(CONFIG_DIR, 'config.yaml');
|
|
11
|
+
/** The saved approval mode (config.yaml `approvalMode`); 'ask' when unset or unreadable. */
|
|
12
|
+
export function readApprovalMode(file = CONFIG_FILE) {
|
|
13
|
+
try {
|
|
14
|
+
const mode = parse(readFileSync(file, 'utf-8'))?.approvalMode;
|
|
15
|
+
return isApprovalMode(mode) ? mode : DEFAULT_APPROVAL_MODE;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return DEFAULT_APPROVAL_MODE;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Saves the approval mode into config.yaml. The YAML document is edited in
|
|
23
|
+
* place, so every other key and its comments survive, and the file keeps its
|
|
24
|
+
* permissions. Written to a temp file and renamed, so a crash never leaves a
|
|
25
|
+
* half-written config. Refuses (false) when the existing file cannot be
|
|
26
|
+
* parsed or is not a mapping, rather than overwrite it.
|
|
27
|
+
*/
|
|
28
|
+
export function writeApprovalMode(mode, configFile = CONFIG_FILE) {
|
|
29
|
+
try {
|
|
30
|
+
// A symlinked config (dotfiles repo) is written through to its target; the link stays.
|
|
31
|
+
let file = configFile;
|
|
32
|
+
try {
|
|
33
|
+
if (lstatSync(configFile).isSymbolicLink()) {
|
|
34
|
+
file = existsSync(configFile) ? realpathSync(configFile) : resolve(dirname(configFile), readlinkSync(configFile));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch { /* no file yet */ }
|
|
38
|
+
let doc = new Document({});
|
|
39
|
+
let fileMode = 0o600;
|
|
40
|
+
if (existsSync(file)) {
|
|
41
|
+
doc = parseDocument(readFileSync(file, 'utf-8'));
|
|
42
|
+
if (doc.errors.length)
|
|
43
|
+
return false;
|
|
44
|
+
if (doc.contents !== null && !isMap(doc.contents))
|
|
45
|
+
return false;
|
|
46
|
+
if (doc.contents === null)
|
|
47
|
+
doc.contents = doc.createNode({});
|
|
48
|
+
fileMode = statSync(file).mode & 0o777;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
52
|
+
}
|
|
53
|
+
doc.set('approvalMode', mode);
|
|
54
|
+
const tmp = `${file}.tmp-${process.pid}`;
|
|
55
|
+
writeFileSync(tmp, String(doc), { encoding: 'utf-8', mode: fileMode });
|
|
56
|
+
chmodSync(tmp, fileMode);
|
|
57
|
+
renameSync(tmp, file);
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
console.error(`❌ Failed to save approval mode: ${err.message}`);
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
9
65
|
export const MCP_CATALOG = [
|
|
10
66
|
// ── Cloud-hosted via Smithery Connect (no local install) ──────
|
|
11
67
|
// URLs are Smithery proxy endpoints: api.smithery.ai/connect/{namespace}/{connectionId}/mcp
|
|
@@ -411,18 +467,11 @@ import { createReadStream, statSync, readdirSync, openSync, readSync, closeSync
|
|
|
411
467
|
export function getClaudeProjectsDir() {
|
|
412
468
|
return join(homedir(), '.claude', 'projects');
|
|
413
469
|
}
|
|
414
|
-
/**
|
|
415
|
-
* Convert a project path to the .claude folder naming format
|
|
416
|
-
* e.g., /Users/foo/bar -> -Users-foo-bar
|
|
417
|
-
*/
|
|
418
|
-
function projectPathToClaudeFolderName(projectPath) {
|
|
419
|
-
return projectPath.replace(/\//g, '-');
|
|
420
|
-
}
|
|
421
470
|
/**
|
|
422
471
|
* Get the session storage directory for a specific project
|
|
423
472
|
*/
|
|
424
473
|
export function getSessionDir(projectPath) {
|
|
425
|
-
const claudeFolderName =
|
|
474
|
+
const claudeFolderName = projectPathToSlug(projectPath);
|
|
426
475
|
return join(getClaudeProjectsDir(), claudeFolderName);
|
|
427
476
|
}
|
|
428
477
|
/**
|
|
@@ -494,6 +543,8 @@ function accumulatePreviewEntry(acc, entry) {
|
|
|
494
543
|
return;
|
|
495
544
|
if (!acc.firstTs && typeof entry.timestamp === 'string' && entry.timestamp)
|
|
496
545
|
acc.firstTs = entry.timestamp;
|
|
546
|
+
if (typeof entry.timestamp === 'string' && entry.timestamp)
|
|
547
|
+
acc.anyTs = entry.timestamp;
|
|
497
548
|
if (entry.type === 'ai-title' && typeof entry.aiTitle === 'string') {
|
|
498
549
|
const t = cleanTurnText(entry.aiTitle, 'assistant');
|
|
499
550
|
if (t)
|
|
@@ -561,9 +612,9 @@ function scanPreviewLines(text, skipFirstPartial) {
|
|
|
561
612
|
* gate and (b) the LAST user message. So: small files are read whole (exact);
|
|
562
613
|
* large files read a bounded HEAD (gate + density sample + first turn/title) +
|
|
563
614
|
* TAIL (last user message, last activity), turning a hundreds-of-MB parse into
|
|
564
|
-
* ~192KB. messageCount becomes
|
|
565
|
-
*
|
|
566
|
-
* countable turn in the head at all.
|
|
615
|
+
* ~192KB. messageCount becomes a lower bound for large files (the turns in
|
|
616
|
+
* both samples) — it's display-only, and counts BOTH samples because a
|
|
617
|
+
* compacted transcript can have no countable turn in the head at all.
|
|
567
618
|
*/
|
|
568
619
|
async function getSessionPreview(filePath, fileSize) {
|
|
569
620
|
const HEAD = 64 * 1024;
|
|
@@ -604,16 +655,16 @@ async function getSessionPreview(filePath, fileSize) {
|
|
|
604
655
|
const head = scanPreviewLines(headBuf.toString('utf8', 0, hn), false);
|
|
605
656
|
const tail = scanPreviewLines(tailBuf.toString('utf8', 0, tn), true);
|
|
606
657
|
const lastMessage = tail.lastUser ?? head.lastUser;
|
|
607
|
-
//
|
|
608
|
-
|
|
609
|
-
const sampled = head.count + tail.count;
|
|
610
|
-
const messageCount = sampled > 0 ? Math.max(3, Math.round(size * sampled / (hn + tn))) : 3;
|
|
658
|
+
// A lower bound: the turns in both samples, floored at 3 to clear the list gate.
|
|
659
|
+
const messageCount = Math.max(3, head.count + tail.count);
|
|
611
660
|
return {
|
|
612
661
|
lastMessage,
|
|
613
662
|
title: tail.aiTitle ?? head.aiTitle ?? head.firstUser,
|
|
614
663
|
messageCount,
|
|
615
664
|
firstTs: head.firstTs,
|
|
616
|
-
|
|
665
|
+
// No dated turn in the tail sample: any dated record there (a tool result), else unset
|
|
666
|
+
// so callers use the file's mtime — never the head sample's turn.
|
|
667
|
+
lastActivityAt: tail.lastTs ?? tail.anyTs,
|
|
617
668
|
};
|
|
618
669
|
}
|
|
619
670
|
finally {
|
|
@@ -684,11 +735,13 @@ const UUID_JSONL_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]
|
|
|
684
735
|
* `assistant` / `system` entry in a Claude JSONL session carries `cwd`, so the
|
|
685
736
|
* scan finishes in the first few KB of any normal session).
|
|
686
737
|
*/
|
|
738
|
+
const EXTRACT_CWD_MAX_LINES = 50;
|
|
687
739
|
export async function extractCwd(filePath) {
|
|
688
740
|
return new Promise((resolve) => {
|
|
689
741
|
const fileStream = createReadStream(filePath);
|
|
690
742
|
const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
|
|
691
743
|
let resolved = false;
|
|
744
|
+
let lines = 0;
|
|
692
745
|
const done = (value) => {
|
|
693
746
|
if (resolved)
|
|
694
747
|
return;
|
|
@@ -706,6 +759,9 @@ export async function extractCwd(filePath) {
|
|
|
706
759
|
rl.on('line', (line) => {
|
|
707
760
|
if (resolved)
|
|
708
761
|
return;
|
|
762
|
+
// Capped: an old JSONL with no cwd must not stream whole on connect.
|
|
763
|
+
if (++lines > EXTRACT_CWD_MAX_LINES)
|
|
764
|
+
return done('');
|
|
709
765
|
if (!line.trim())
|
|
710
766
|
return;
|
|
711
767
|
try {
|
|
@@ -729,7 +785,8 @@ export function invalidateSessionListCache() {
|
|
|
729
785
|
}
|
|
730
786
|
// Older manifests are discarded on load. v2: sanitized preview fields. v3: the
|
|
731
787
|
// large-file messageCount estimate changed, and unchanged files are never re-read.
|
|
732
|
-
|
|
788
|
+
// v4: the large-file count is the sampled lower bound. v5: no head fallback for last activity.
|
|
789
|
+
const SESSION_MANIFEST_VERSION = 5;
|
|
733
790
|
function sessionManifestPath() {
|
|
734
791
|
return join(homedir(), '.claude', 'session-manifest.json');
|
|
735
792
|
}
|
|
@@ -902,7 +959,8 @@ export async function listAllClaudeSessions(limit = 1000, includeSubagents = fal
|
|
|
902
959
|
sessionId: c.sessionId,
|
|
903
960
|
projectSlug: c.slug,
|
|
904
961
|
projectPath: cwd || slugPath, // display / group key (original cwd)
|
|
905
|
-
cwd:
|
|
962
|
+
// The recorded cwd when it encodes to this slug: the lossy decode can name another project (#181).
|
|
963
|
+
cwd: (cwd && projectPathToSlug(cwd) === c.slug ? cwd : '') || slugPath || cwd, // resume routing (file location)
|
|
906
964
|
timestamp: c.mtime,
|
|
907
965
|
lastMessage: preview.lastMessage,
|
|
908
966
|
title: preview.title,
|
|
@@ -1147,7 +1205,7 @@ export async function cleanupOrphanedMetadata(projectPath) {
|
|
|
1147
1205
|
*/
|
|
1148
1206
|
export function getSessionWorkspace(workingDir, sessionId) {
|
|
1149
1207
|
const claudeDir = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
|
|
1150
|
-
const slug =
|
|
1208
|
+
const slug = projectPathToSlug(workingDir);
|
|
1151
1209
|
return join(claudeDir, 'projects', slug, 'osb', sessionId);
|
|
1152
1210
|
}
|
|
1153
1211
|
export function ensureSessionWorkspace(workingDir, sessionId) {
|
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
* copy to <path> instead of content-profile.md and leaves the HWM alone.
|
|
14
14
|
* node compaction-lens-worker.js --library <sessionId> [--cwd <dir>] [--dry] [--out-dir <dir>]
|
|
15
15
|
* LIBRARY step only (manual / dry run). Takes the per-project lock itself.
|
|
16
|
+
* node compaction-lens-worker.js --sweep [--exclude <id,id>] [--dry] [--max N]
|
|
17
|
+
* CATCH-UP SWEEP only (lens-library-sweep.ts): the Library backlog of every session on the
|
|
18
|
+
* machine plus the daily digests, newest first, capped. Takes the machine-wide sweep lock.
|
|
19
|
+
* The agent also launches it shortly after start (argfile { sweep }) and after each
|
|
20
|
+
* session-end run (the session-end argfile carries { sweep }; it runs after the steps).
|
|
16
21
|
* node compaction-lens-worker.js --content <sessionId> [--cwd <dir>] [--dry] [--research-refresh]
|
|
17
22
|
* CONTENT step (Stage A) only: manual / the per-project "Refresh research"
|
|
18
23
|
* backend. --dry = no ingest (still spends, capped). Takes the per-project lock.
|
|
@@ -13,6 +13,11 @@
|
|
|
13
13
|
* copy to <path> instead of content-profile.md and leaves the HWM alone.
|
|
14
14
|
* node compaction-lens-worker.js --library <sessionId> [--cwd <dir>] [--dry] [--out-dir <dir>]
|
|
15
15
|
* LIBRARY step only (manual / dry run). Takes the per-project lock itself.
|
|
16
|
+
* node compaction-lens-worker.js --sweep [--exclude <id,id>] [--dry] [--max N]
|
|
17
|
+
* CATCH-UP SWEEP only (lens-library-sweep.ts): the Library backlog of every session on the
|
|
18
|
+
* machine plus the daily digests, newest first, capped. Takes the machine-wide sweep lock.
|
|
19
|
+
* The agent also launches it shortly after start (argfile { sweep }) and after each
|
|
20
|
+
* session-end run (the session-end argfile carries { sweep }; it runs after the steps).
|
|
16
21
|
* node compaction-lens-worker.js --content <sessionId> [--cwd <dir>] [--dry] [--research-refresh]
|
|
17
22
|
* CONTENT step (Stage A) only: manual / the per-project "Refresh research"
|
|
18
23
|
* backend. --dry = no ingest (still spends, capped). Takes the per-project lock.
|
|
@@ -25,13 +30,14 @@
|
|
|
25
30
|
* Fully self-contained: top-level try/catch, redacted log in the project dir,
|
|
26
31
|
* refreshes + releases the per-project lock, always exits.
|
|
27
32
|
*/
|
|
28
|
-
import { readFileSync, rmSync } from 'node:fs';
|
|
33
|
+
import { mkdirSync, readFileSync, rmSync } from 'node:fs';
|
|
29
34
|
import { dirname } from 'node:path';
|
|
30
35
|
import { runCompactionLens } from './compaction-lens.js';
|
|
31
36
|
import { resolveSessionDb } from './lens-db.js';
|
|
32
|
-
import { acquireLock, refuseOutPath, releaseLock, resolveProjectDir, touchLock } from './lens-paths.js';
|
|
37
|
+
import { acquireLock, libraryHomeDir, readSweepStatus, refuseOutPath, releaseLock, resolveProjectDir, touchLock, writeSweepStatus } from './lens-paths.js';
|
|
33
38
|
import { logLine } from './lens-profile.js';
|
|
34
39
|
import { runLibraryStep } from './lens-library.js';
|
|
40
|
+
import { errorLine, runLibrarySweep } from './lens-library-sweep.js';
|
|
35
41
|
import { runContentStep } from './content-run.js';
|
|
36
42
|
// ≤2 big windows + reduce at ≤6 min/call, then the library step (1 call ≤6 min + model meta),
|
|
37
43
|
// then the content step (Stage A: ~10-18 small calls, ≤4 min each, capped in $).
|
|
@@ -39,11 +45,25 @@ const INCREMENTAL_TIMEOUT_MS = 45 * 60_000;
|
|
|
39
45
|
const BACKFILL_TIMEOUT_MS = 3 * 60 * 60_000;
|
|
40
46
|
const LIBRARY_TIMEOUT_MS = 15 * 60_000;
|
|
41
47
|
const CONTENT_TIMEOUT_MS = 20 * 60_000;
|
|
48
|
+
// The sweep stops starting pages after SWEEP_BUDGET_MS (60 min); one page call is ≤6 min.
|
|
49
|
+
const SWEEP_TIMEOUT_MS = 80 * 60_000;
|
|
42
50
|
function argVal(argv, flag) {
|
|
43
51
|
const i = argv.indexOf(flag);
|
|
44
52
|
return i >= 0 ? argv[i + 1] : undefined;
|
|
45
53
|
}
|
|
46
54
|
function parseJob(argv) {
|
|
55
|
+
if (argv[0] === '--sweep') {
|
|
56
|
+
const max = Number(argVal(argv, '--max'));
|
|
57
|
+
const exclude = (argVal(argv, '--exclude') ?? '').split(',').map(s => s.trim()).filter(Boolean);
|
|
58
|
+
return {
|
|
59
|
+
opts: { sessionId: '', mode: 'incremental' },
|
|
60
|
+
kind: 'sweep',
|
|
61
|
+
sweep: { exclude, trigger: 'manual', dry: argv.includes('--dry'), max: Number.isFinite(max) && max > 0 ? max : undefined, print: true },
|
|
62
|
+
lockDir: null,
|
|
63
|
+
logDir: libraryHomeDir(),
|
|
64
|
+
timeoutMs: SWEEP_TIMEOUT_MS,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
47
67
|
if (argv[0] === '--content') {
|
|
48
68
|
const sessionId = argv[1];
|
|
49
69
|
if (!sessionId || sessionId.startsWith('--'))
|
|
@@ -124,6 +144,11 @@ function parseJob(argv) {
|
|
|
124
144
|
/* ignore */
|
|
125
145
|
}
|
|
126
146
|
}
|
|
147
|
+
const sweep = payload.sweep && Array.isArray(payload.sweep.exclude) ? { exclude: payload.sweep.exclude.map(String), trigger: String(payload.sweep.trigger ?? 'launch') } : undefined;
|
|
148
|
+
if (sweep && !payload.sessionId) {
|
|
149
|
+
// Standalone sweep (agent start, or a session end whose project was busy).
|
|
150
|
+
return { opts: { sessionId: '', mode: 'incremental' }, kind: 'sweep', sweep, sweepLockHeld: payload.sweepLockHeld === true, lockDir: null, logDir: libraryHomeDir(), timeoutMs: SWEEP_TIMEOUT_MS };
|
|
151
|
+
}
|
|
127
152
|
const lockDir = payload.lockDir || null;
|
|
128
153
|
const logDir = lockDir || resolveProjectDir(payload.transcriptPath, payload.cwd);
|
|
129
154
|
if (!payload.sessionId)
|
|
@@ -131,11 +156,14 @@ function parseJob(argv) {
|
|
|
131
156
|
return {
|
|
132
157
|
opts: { sessionId: payload.sessionId, transcriptPath: payload.transcriptPath, cwd: payload.cwd, mode: 'incremental' },
|
|
133
158
|
skipLens: payload.skipLens === true,
|
|
159
|
+
sweep,
|
|
134
160
|
lockDir,
|
|
135
161
|
logDir,
|
|
136
|
-
timeoutMs: INCREMENTAL_TIMEOUT_MS,
|
|
162
|
+
timeoutMs: INCREMENTAL_TIMEOUT_MS + (sweep ? SWEEP_TIMEOUT_MS : 0),
|
|
137
163
|
};
|
|
138
164
|
}
|
|
165
|
+
/** Set while this worker holds the machine-wide sweep lock. */
|
|
166
|
+
let sweepHome = null;
|
|
139
167
|
async function main() {
|
|
140
168
|
let job = null;
|
|
141
169
|
let logDir = null;
|
|
@@ -151,18 +179,23 @@ async function main() {
|
|
|
151
179
|
}
|
|
152
180
|
lockDir = job.lockDir;
|
|
153
181
|
logDir = job.logDir;
|
|
154
|
-
const sid = job.opts.sessionId.substring(0, 8);
|
|
182
|
+
const sid = job.opts.sessionId.substring(0, 8) || 'sweep';
|
|
183
|
+
const steps = job.kind !== 'sweep';
|
|
155
184
|
const killer = setTimeout(() => {
|
|
156
185
|
logLine(logDir, `session ${sid}: hard timeout — exiting`);
|
|
157
186
|
if (lockDir)
|
|
158
187
|
releaseLock(lockDir);
|
|
188
|
+
if (sweepHome) {
|
|
189
|
+
writeSweepStatus({ status: 'timeout', finishedAt: new Date().toISOString(), errors: [...(readSweepStatus(sweepHome)?.errors ?? []), { kind: 'timeout' }] }, sweepHome);
|
|
190
|
+
releaseLock(sweepHome);
|
|
191
|
+
}
|
|
159
192
|
process.exit(2);
|
|
160
193
|
}, job.timeoutMs);
|
|
161
194
|
killer.unref();
|
|
162
195
|
const t0 = Date.now();
|
|
163
196
|
let lensErr = null;
|
|
164
197
|
// Step 1 — content lens (skipped by the --library entry).
|
|
165
|
-
if (job.kind !== 'library' && job.kind !== 'content' && !job.skipLens) {
|
|
198
|
+
if (steps && job.kind !== 'library' && job.kind !== 'content' && !job.skipLens) {
|
|
166
199
|
try {
|
|
167
200
|
const r = await runCompactionLens({
|
|
168
201
|
...job.opts,
|
|
@@ -183,7 +216,7 @@ async function main() {
|
|
|
183
216
|
// Step 2 — library page for the period that just ended (per-compaction + --library only; never backfill).
|
|
184
217
|
// runLibraryStep never throws; any failure is logged and the worker still exits cleanly.
|
|
185
218
|
let libPeriod = null;
|
|
186
|
-
if (job.opts.mode === 'incremental' && job.kind !== 'content') {
|
|
219
|
+
if (steps && job.opts.mode === 'incremental' && job.kind !== 'content') {
|
|
187
220
|
if (lockDir)
|
|
188
221
|
touchLock(lockDir);
|
|
189
222
|
const lib = await runLibraryStep({
|
|
@@ -199,10 +232,17 @@ async function main() {
|
|
|
199
232
|
process.stdout.write(`${JSON.stringify({ status: lib.status, page: lib.page, index: lib.index, period: lib.period, cost: lib.costUsd, errors: lib.errors })}\n`);
|
|
200
233
|
if (lib.status === 'written')
|
|
201
234
|
libPeriod = lib.period;
|
|
235
|
+
// The step's real outcome, on /health (the worker's own output goes nowhere).
|
|
236
|
+
if (job.kind !== 'library') {
|
|
237
|
+
writeSweepStatus({ lastStep: { at: new Date().toISOString(), session: sid, status: lib.status, ...(lib.period ? { period: lib.period.index } : {}), costUsd: lib.costUsd } });
|
|
238
|
+
}
|
|
239
|
+
if (lib.status === 'failed' || lib.status === 'model-error') {
|
|
240
|
+
writeSweepStatus({ workerError: { at: new Date().toISOString(), kind: `library-${lib.status}`, ref: sid, message: errorLine(lib.errors.join('; ')) } });
|
|
241
|
+
}
|
|
202
242
|
}
|
|
203
243
|
// Step 3 — content plan (Stage A) for the period (per-compaction + --content; never backfill / --library).
|
|
204
244
|
// runContentStep never throws; the try is belt and braces so nothing here can fail the worker.
|
|
205
|
-
if (job.opts.mode === 'incremental' && job.kind !== 'library') {
|
|
245
|
+
if (steps && job.opts.mode === 'incremental' && job.kind !== 'library') {
|
|
206
246
|
try {
|
|
207
247
|
if (lockDir)
|
|
208
248
|
touchLock(lockDir);
|
|
@@ -224,17 +264,48 @@ async function main() {
|
|
|
224
264
|
logLine(logDir, `content step error (ignored): ${err instanceof Error ? err.message : String(err)}`);
|
|
225
265
|
}
|
|
226
266
|
}
|
|
267
|
+
// Step 4 — catch-up sweep (agent start, after a session end, or --sweep). Never two at once:
|
|
268
|
+
// the machine-wide sweep lock is either handed over by the launcher or taken here.
|
|
269
|
+
if (job.sweep) {
|
|
270
|
+
const home = libraryHomeDir();
|
|
271
|
+
mkdirSync(home, { recursive: true });
|
|
272
|
+
// This session's steps are done: free its project for the next compaction run; the sweep
|
|
273
|
+
// takes each project's lock only while it writes a page there.
|
|
274
|
+
if (lockDir)
|
|
275
|
+
releaseLock(lockDir);
|
|
276
|
+
lockDir = null;
|
|
277
|
+
if (job.sweepLockHeld || acquireLock(home)) {
|
|
278
|
+
sweepHome = home;
|
|
279
|
+
// A manual --sweep (print) is never held back by the cooldown.
|
|
280
|
+
const s = await runLibrarySweep({ exclude: job.sweep.exclude, trigger: job.sweep.trigger, dry: job.sweep.dry, maxPages: job.sweep.max, ...(job.sweep.print ? { cooldownMs: 0 } : {}) });
|
|
281
|
+
logLine(logDir, `session ${sid}: sweep status=${s.status} pages=${s.pagesWritten} digests=${s.digestsWritten} calls=${s.modelCalls} cost=$${s.costUsd.toFixed(4)} errors=${s.errors.length}`);
|
|
282
|
+
if (job.sweep.print)
|
|
283
|
+
process.stdout.write(`${JSON.stringify(s)}\n`);
|
|
284
|
+
}
|
|
285
|
+
else {
|
|
286
|
+
logLine(logDir, `session ${sid}: sweep skipped (another sweep is running)`);
|
|
287
|
+
if (job.sweep.print)
|
|
288
|
+
process.stderr.write('sweep: another sweep is running\n');
|
|
289
|
+
}
|
|
290
|
+
}
|
|
227
291
|
return lensErr ? 1 : 0;
|
|
228
292
|
}
|
|
229
293
|
catch (err) {
|
|
230
294
|
logLine(logDir, `worker error: ${err instanceof Error ? err.stack || err.message : String(err)}`);
|
|
231
295
|
if (err instanceof Error && /^(backfill|library|content):/.test(err.message))
|
|
232
296
|
process.stderr.write(`${err.message}\n`);
|
|
297
|
+
// Visible on /health: a crashed worker no longer disappears into stdio 'ignore'.
|
|
298
|
+
writeSweepStatus({
|
|
299
|
+
...(sweepHome ? { status: 'error', finishedAt: new Date().toISOString() } : {}),
|
|
300
|
+
workerError: { at: new Date().toISOString(), kind: job?.kind ?? 'worker', message: errorLine(err) },
|
|
301
|
+
});
|
|
233
302
|
return 1;
|
|
234
303
|
}
|
|
235
304
|
finally {
|
|
236
305
|
if (lockDir)
|
|
237
306
|
releaseLock(lockDir);
|
|
307
|
+
if (sweepHome)
|
|
308
|
+
releaseLock(sweepHome);
|
|
238
309
|
}
|
|
239
310
|
}
|
|
240
311
|
main()
|
|
@@ -9,10 +9,14 @@
|
|
|
9
9
|
* OSBORN_CONTENT_DAILY_USD default 2.00 (UTC day, per MACHINE: $OSBORN_HOME or ~/.osborn/content-spend-ledger.json,
|
|
10
10
|
* locked read-modify-write so concurrent workers across projects share one cap)
|
|
11
11
|
* OSBORN_CONTENT_MAX_PIECES default 4 (1 highlight + up to 3 how-tos)
|
|
12
|
+
* OSBORN_LIBRARY_DAILY_USD default 1.00 (UTC day, per MACHINE): the Library catch-up sweep's own cap
|
|
13
|
+
* (period pages + daily digests), kept in the same ledger file under its
|
|
14
|
+
* own key ("<day>:library"), so the sweep never uses the content step's cap
|
|
12
15
|
* Every call reserves its WORST case (prompt + max output) against both caps up
|
|
13
16
|
* front and writes it to the ledger before the fetch; it is reconciled to the
|
|
14
17
|
* actual cost after. A failed call is charged the worst case, and a hard exit
|
|
15
|
-
* mid-call leaves the worst case in the ledger, so the caps stay hard
|
|
18
|
+
* mid-call leaves the worst case in the ledger, so the caps stay hard; such an
|
|
19
|
+
* unsettled reservation expires with its UTC day (the ledger is keyed by day).
|
|
16
20
|
* All outbound prompt text goes through the caller's scrub() first.
|
|
17
21
|
*/
|
|
18
22
|
export declare const LEDGER_FILE = "content-spend-ledger.json";
|
|
@@ -50,7 +54,10 @@ interface Ledger {
|
|
|
50
54
|
/** The machine ledger (UTC day → USD). */
|
|
51
55
|
export declare function readLedger(): Ledger;
|
|
52
56
|
/** Spend recorded (incl. open reservations) on this machine today, across every project. */
|
|
53
|
-
export declare function daySpent(now?: number): number;
|
|
57
|
+
export declare function daySpent(now?: number, scope?: string): number;
|
|
58
|
+
/** The Library sweep's own daily cap (OSBORN_LIBRARY_DAILY_USD, default $1), on ledger scope LIBRARY_LEDGER_SCOPE. */
|
|
59
|
+
export declare const LIBRARY_LEDGER_SCOPE = "library";
|
|
60
|
+
export declare const libraryDailyUsd: () => number;
|
|
54
61
|
export type CapKind = 'period' | 'day' | 'time';
|
|
55
62
|
export declare class CapError extends Error {
|
|
56
63
|
readonly cap: CapKind;
|
|
@@ -77,6 +84,8 @@ export declare class SpendGuard {
|
|
|
77
84
|
periodUsd: number;
|
|
78
85
|
/** Epoch ms after which reserve() refuses new calls (CapError 'time'). */
|
|
79
86
|
readonly deadline: number | null;
|
|
87
|
+
/** Ledger key scope: none = the content step's daily cap; e.g. LIBRARY_LEDGER_SCOPE for the sweep. */
|
|
88
|
+
readonly scope?: string;
|
|
80
89
|
runUsd: number;
|
|
81
90
|
calls: number;
|
|
82
91
|
capHit: CapKind | null;
|
|
@@ -86,7 +95,9 @@ export declare class SpendGuard {
|
|
|
86
95
|
/** Spend already recorded for this period by earlier runs. */
|
|
87
96
|
periodUsd?: number,
|
|
88
97
|
/** Epoch ms after which reserve() refuses new calls (CapError 'time'). */
|
|
89
|
-
deadline?: number | null
|
|
98
|
+
deadline?: number | null,
|
|
99
|
+
/** Ledger key scope: none = the content step's daily cap; e.g. LIBRARY_LEDGER_SCOPE for the sweep. */
|
|
100
|
+
scope?: string);
|
|
90
101
|
/**
|
|
91
102
|
* Reserve a worst-case spend of `usd`: throws CapError if it would cross a cap
|
|
92
103
|
* (or the deadline passed); otherwise writes it to the machine ledger BEFORE the
|