osborn 0.9.269 → 0.9.271
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/claude-llm.js +54 -1
- package/dist/index.js +1 -1
- package/dist/pipeline-fastbrain.js +40 -7
- package/package.json +1 -1
package/dist/claude-llm.js
CHANGED
|
@@ -79,6 +79,14 @@ async function buildRecallInjection(sessionId, workingDir, prompt) {
|
|
|
79
79
|
}
|
|
80
80
|
if (!hits.length)
|
|
81
81
|
return '';
|
|
82
|
+
// PREFIX-STABILITY: this block rides AFTER the whole stable conversation prefix
|
|
83
|
+
// (tools → system → history), so it never invalidates the cached head. Keep the
|
|
84
|
+
// body deterministic anyway: recall() orders top-K by score (deterministic given
|
|
85
|
+
// the same DB state) and V8's Array.sort is stable, so equal-score hits keep
|
|
86
|
+
// insertion order — same DB state ⇒ same injected bytes. No timestamps are
|
|
87
|
+
// rendered here (only source/line/msgType), so the block has no volatile head.
|
|
88
|
+
// The one genuinely volatile per-turn injection (the machine-load nudge) is
|
|
89
|
+
// placed LAST in additionalContext by the UserPromptSubmit hook below.
|
|
82
90
|
const lines = hits.map((h, i) => {
|
|
83
91
|
let body = h.text.replace(/\n{3,}/g, '\n\n').trim();
|
|
84
92
|
if (body.length > RECALL_PER_HIT_CHARS)
|
|
@@ -93,6 +101,20 @@ async function buildRecallInjection(sessionId, workingDir, prompt) {
|
|
|
93
101
|
return ''; // recall is best-effort — never break the turn
|
|
94
102
|
}
|
|
95
103
|
}
|
|
104
|
+
/** Per-turn cache observability: log Anthropic prompt-cache reads/writes from an SDK result's usage. */
|
|
105
|
+
function logCacheUsage(usage) {
|
|
106
|
+
try {
|
|
107
|
+
const read = usage?.cache_read_input_tokens;
|
|
108
|
+
const write = usage?.cache_creation_input_tokens;
|
|
109
|
+
if (typeof read !== 'number' && typeof write !== 'number')
|
|
110
|
+
return;
|
|
111
|
+
const r = read || 0;
|
|
112
|
+
const w = write || 0;
|
|
113
|
+
const hit = r + w > 0 ? Math.round((r / (r + w)) * 100) : 0;
|
|
114
|
+
console.log(`[cache] read=${r} write=${w} (hit${hit}%)`);
|
|
115
|
+
}
|
|
116
|
+
catch { /* observability only */ }
|
|
117
|
+
}
|
|
96
118
|
// ≤5 direct tool call budget per turn. Reset on every UserPromptSubmit (new user message).
|
|
97
119
|
// Enforced mechanically in PreToolUse — the model CANNOT exceed this regardless of JSONL history.
|
|
98
120
|
// Task/Agent delegations are exempt (delegation is what we WANT). Sub-agent tool calls
|
|
@@ -395,11 +417,34 @@ if (!process.env.ANTHROPIC_SMALL_FAST_MODEL) {
|
|
|
395
417
|
if (process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC === undefined) {
|
|
396
418
|
process.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1';
|
|
397
419
|
}
|
|
420
|
+
// ── PROMPT-CACHING POSTURE ───────────────────────────────────────────────────
|
|
421
|
+
// We pay Anthropic usage credits, so maximizing cache hits (reads are ~0.1x the
|
|
422
|
+
// input price vs. 1x uncached; writes ~1.25x) matters. What the cache needs: a
|
|
423
|
+
// byte-stable prompt PREFIX. The Claude Code CLI caches the Anthropic prefix
|
|
424
|
+
// (tools → system → conversation) automatically on every /v1/messages call —
|
|
425
|
+
// it is ON by default and nothing we set disables it. Audit of our env/config:
|
|
426
|
+
// • ENABLE_1M_CONTEXT / CLAUDE_AUTOCOMPACT_PCT_OVERRIDE — context-window only,
|
|
427
|
+
// cache-neutral (per-1m-model cache entry; invalidates only on model switch).
|
|
428
|
+
// • ANTHROPIC_SMALL_FAST_MODEL — internal non-main calls only.
|
|
429
|
+
// • CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC — strips the cache-miss *diagnostics*
|
|
430
|
+
// telemetry (previous_message_id); it does NOT disable caching itself.
|
|
431
|
+
// • No DISABLE_PROMPT_CACHING / PROMPT_CACHING=0 style flags are set anywhere.
|
|
432
|
+
// What WE are responsible for: keeping per-turn injections out of the stable
|
|
433
|
+
// prefix and deterministic (buildRecallInjection + the UserPromptSubmit hook
|
|
434
|
+
// below — static content first, volatile last), and static sub-agent system
|
|
435
|
+
// prompts (NAMED_AGENTS are module-level constants; applyGrounding interpolates
|
|
436
|
+
// only the per-session --db path ONCE at query() creation, stable for the
|
|
437
|
+
// session's lifetime). Per-turn cache reads/writes are logged by
|
|
438
|
+
// logCacheUsage() on each SDK result message: `[cache] read=X write=Y (hitZ%)`.
|
|
398
439
|
// Research mode tools — full research capabilities
|
|
399
440
|
// Named sub-agents — the orchestrator delegates to these specialists. Each has
|
|
400
441
|
// a specific role, model, and tool set. Module-level + exported so the HTTP
|
|
401
442
|
// API (/agents) and the frontend agents manager can list them without
|
|
402
443
|
// duplicating the definitions. The query options reference this same object.
|
|
444
|
+
// CACHE NOTE: keep these system prompts STATIC — no per-turn interpolation.
|
|
445
|
+
// Per-session values (the applyGrounding --db path) are injected exactly once
|
|
446
|
+
// at query() creation and never change for the session, so the sub-agent
|
|
447
|
+
// prompt prefix stays cacheable across the session's turns.
|
|
403
448
|
export const NAMED_AGENTS = {
|
|
404
449
|
researcher: {
|
|
405
450
|
description: [
|
|
@@ -2035,6 +2080,7 @@ export class ClaudeLLM extends llm.LLM {
|
|
|
2035
2080
|
}
|
|
2036
2081
|
// Result — marks end of a turn (but we keep consuming for next turn)
|
|
2037
2082
|
if (msg.type === 'result') {
|
|
2083
|
+
logCacheUsage(msg.usage); // per-turn cache reads/writes (main loop only)
|
|
2038
2084
|
const turnMessageId = this.#currentTurnMessageId;
|
|
2039
2085
|
const turnChunks = [...this.#currentTurnChunks];
|
|
2040
2086
|
if (msg.result) {
|
|
@@ -2453,7 +2499,13 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
2453
2499
|
// snapshot, prepended so it's present even when recall degrades under load.
|
|
2454
2500
|
// Advisory only — never caps/refuses a dispatch.
|
|
2455
2501
|
const machineNudge = fromSubagent ? '' : await buildMachineNudge();
|
|
2456
|
-
|
|
2502
|
+
// PREFIX-STABILITY order (cache-friendly): STATIC first (turn-shape
|
|
2503
|
+
// reminder — byte-stable across the session), then recall (deterministic
|
|
2504
|
+
// given the DB state), then the volatile machine-load nudge LAST. The
|
|
2505
|
+
// whole block already lands after the cached tools→system→history
|
|
2506
|
+
// prefix, but ordering volatile content last keeps any future
|
|
2507
|
+
// cache_control breakpoint inside this block useful too.
|
|
2508
|
+
const additionalContext = [reminder, recalled, machineNudge].filter(Boolean).join('\n\n');
|
|
2457
2509
|
console.log(`📌 UserPromptSubmit: injected turn-shape reminder (${reminder.length} chars)${recalled ? ` + recall (${recalled.length} chars)` : ''}${machineNudge ? ` + machine(${machineNudge.includes('⚠️') ? 'HOT' : 'ok'})` : ''} for prompt="${promptPreview}..." [tool budget reset to 0/${TOOL_CALL_BUDGET}]`);
|
|
2458
2510
|
return {
|
|
2459
2511
|
hookSpecificOutput: {
|
|
@@ -3015,6 +3067,7 @@ class ClaudeLLMStream extends llm.LLMStream {
|
|
|
3015
3067
|
}
|
|
3016
3068
|
// Final result — only speak if no text blocks were streamed already
|
|
3017
3069
|
if (message.type === 'result' && message.result) {
|
|
3070
|
+
logCacheUsage(message.usage); // per-turn cache reads/writes (cold-start path)
|
|
3018
3071
|
const rawResult = message.result;
|
|
3019
3072
|
// Emit RAW result to frontend
|
|
3020
3073
|
this.#eventEmitter.emit('assistant_result', { text: rawResult, messageId: streamTurnMessageId });
|
package/dist/index.js
CHANGED
|
@@ -5362,7 +5362,7 @@ async function main() {
|
|
|
5362
5362
|
// No sessions at all (or new session chosen) — greet as new user
|
|
5363
5363
|
try {
|
|
5364
5364
|
console.log('👋 Sending greeting...');
|
|
5365
|
-
await greetViaVoice("Hey! I'm Osborn, your AI
|
|
5365
|
+
await greetViaVoice("Hey! I'm Osborn, your AI engineer — I write, run, and ship code while you talk. What should we build today?");
|
|
5366
5366
|
console.log('✅ Greeting sent');
|
|
5367
5367
|
}
|
|
5368
5368
|
catch (err) {
|
|
@@ -279,7 +279,18 @@ async function getRecentEntries(sessionId, workingDir, _, count) {
|
|
|
279
279
|
// ============================================================
|
|
280
280
|
// SYSTEM PROMPT
|
|
281
281
|
// ============================================================
|
|
282
|
-
|
|
282
|
+
// ============================================================
|
|
283
|
+
// SYSTEM PROMPT
|
|
284
|
+
// ============================================================
|
|
285
|
+
//
|
|
286
|
+
// PROMPT-CACHING NOTE (Fireworks/z.ai auto-cache long prefixes): the system
|
|
287
|
+
// message is the START of the OpenAI prompt and those providers cache by
|
|
288
|
+
// prefix. buildSystemPrompt() is therefore fully STATIC — the volatile
|
|
289
|
+
// per-call inputs (chatHistory, researchContext) live in buildTurnContext()
|
|
290
|
+
// and are prepended to the CURRENT user message instead, so the system +
|
|
291
|
+
// persistent-messages prefix stays byte-identical across a session and every
|
|
292
|
+
// turn after the first is a cache hit.
|
|
293
|
+
function buildSystemPrompt() {
|
|
283
294
|
const parts = [
|
|
284
295
|
`You are a fast memory recall agent for a voice AI assistant called Osborn.`,
|
|
285
296
|
`You search the user's conversation history — their questions, the assistant's answers,`,
|
|
@@ -321,15 +332,26 @@ function buildSystemPrompt(chatHistory, researchContext) {
|
|
|
321
332
|
` Only say "didn't find" after 3+ failed rounds.`,
|
|
322
333
|
`⚠ Your own prior answers may have errors. Trust search results over your memory.`,
|
|
323
334
|
];
|
|
335
|
+
return parts.join('\n');
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* Volatile per-turn context (recent conversation, active research) that USED to be
|
|
339
|
+
* interpolated into the system prompt. Moved into the first user message so the
|
|
340
|
+
* system + persistent-messages PREFIX stays byte-stable across a session and the
|
|
341
|
+
* Fireworks/z.ai prefix cache hits on every turn after the first. Rendered LAST
|
|
342
|
+
* (just before the question) so the stable head hits cache. '' when empty.
|
|
343
|
+
*/
|
|
344
|
+
function buildTurnContext(chatHistory, researchContext) {
|
|
345
|
+
const parts = [];
|
|
324
346
|
if (chatHistory && chatHistory.length > 0) {
|
|
325
|
-
parts.push(
|
|
347
|
+
parts.push(`== RECENT CONVERSATION ==`);
|
|
326
348
|
for (const turn of chatHistory.slice(-6)) {
|
|
327
349
|
parts.push(`${turn.role}: ${turn.content.substring(0, 200)}`);
|
|
328
350
|
}
|
|
329
351
|
}
|
|
330
352
|
if (researchContext)
|
|
331
|
-
parts.push(
|
|
332
|
-
return parts.join('\n');
|
|
353
|
+
parts.push(`== ACTIVE RESEARCH ==`, researchContext);
|
|
354
|
+
return parts.length ? parts.join('\n') + '\n\n' : '';
|
|
333
355
|
}
|
|
334
356
|
// ============================================================
|
|
335
357
|
// OPENROUTER CALL
|
|
@@ -413,15 +435,18 @@ export async function askPipelineFastBrain(workingDir, sessionId, question, opts
|
|
|
413
435
|
if (persistentMessages.length > 24) {
|
|
414
436
|
persistentMessages = persistentMessages.slice(-24);
|
|
415
437
|
}
|
|
416
|
-
const systemPrompt = buildSystemPrompt(
|
|
438
|
+
const systemPrompt = buildSystemPrompt();
|
|
439
|
+
const turnContext = buildTurnContext(opts?.chatHistory, opts?.researchContext);
|
|
417
440
|
const sessionBaseDir = opts?.sessionBaseDir || workingDir;
|
|
418
441
|
const tools = buildTools(!!opts?.agentControl);
|
|
419
442
|
const toolsUsed = [];
|
|
420
|
-
// Build messages: system + persistent history + new user message
|
|
443
|
+
// Build messages: STATIC system + persistent history + new user message.
|
|
444
|
+
// The volatile per-turn context rides INSIDE the current user message (last)
|
|
445
|
+
// so the system+history prefix is a cache-stable head (see buildTurnContext).
|
|
421
446
|
const messages = [
|
|
422
447
|
{ role: 'system', content: systemPrompt },
|
|
423
448
|
...persistentMessages,
|
|
424
|
-
{ role: 'user', content: question },
|
|
449
|
+
{ role: 'user', content: turnContext ? `${turnContext}${question}` : question },
|
|
425
450
|
];
|
|
426
451
|
try {
|
|
427
452
|
let rounds = 0;
|
|
@@ -437,6 +462,14 @@ export async function askPipelineFastBrain(workingDir, sessionId, question, opts
|
|
|
437
462
|
}
|
|
438
463
|
rounds++;
|
|
439
464
|
const data = await callOpenRouter(messages, tools, apiKey);
|
|
465
|
+
// Cache observability: OpenAI-compatible providers report cached prefix
|
|
466
|
+
// tokens on usage.prompt_tokens_details.cached_tokens (Fireworks/z.ai both
|
|
467
|
+
// populate it when the prefix cache hits).
|
|
468
|
+
const cachedTokens = data?.usage?.prompt_tokens_details?.cached_tokens;
|
|
469
|
+
if (typeof cachedTokens === 'number' && cachedTokens > 0) {
|
|
470
|
+
const promptTokens = data?.usage?.prompt_tokens || 0;
|
|
471
|
+
console.log(`[cache] fast-brain cached=${cachedTokens} prompt=${promptTokens} (hit${promptTokens > 0 ? Math.round((cachedTokens / promptTokens) * 100) : 0}%)`);
|
|
472
|
+
}
|
|
440
473
|
const choice = data.choices?.[0];
|
|
441
474
|
const msg = choice?.message;
|
|
442
475
|
if (!msg)
|