osborn 0.9.268 → 0.9.270

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.
@@ -177,7 +177,33 @@ export function applyAuthFallback() {
177
177
  if (process.env.ANTHROPIC_API_KEY && process.env.ANTHROPIC_API_KEY.trim() !== '') {
178
178
  return;
179
179
  }
180
- // Tier 3: central OpenRouter key.
180
+ // Tier 3: HOUSE DEMO PASS - z.ai GLM coding subscription (flat/shared, not
181
+ // pay-per-use). Cline/opencode-style: unauthenticated demo users ride the
182
+ // house pass instead of raw API billing. The z.ai Anthropic-compatible
183
+ // endpoint (api.z.ai/api/anthropic) speaks native Messages - verified live
184
+ // 2026-10-24 (glm-4.7 returned a real response). Precedence: Z_AI_PERSONAL_API_KEY
185
+ // (verified working; ZAI_STANDARD_API_KEY in .env is expired).
186
+ const zaiKey = process.env.Z_AI_PERSONAL_API_KEY || process.env.ZAI_API_KEY;
187
+ if (zaiKey && zaiKey.trim() !== '') {
188
+ // Native Anthropic-Messages endpoint - no local translation proxy needed.
189
+ process.env.ANTHROPIC_BASE_URL = process.env.OSBORN_DEMO_BASE_URL || 'https://api.z.ai/api/anthropic';
190
+ process.env.ANTHROPIC_AUTH_TOKEN = zaiKey;
191
+ process.env.ANTHROPIC_API_KEY = ''; // required - a set key bypasses AUTH_TOKEN
192
+ const demoModel = process.env.OSBORN_DEMO_MODEL || 'glm-4.7';
193
+ process.env.ANTHROPIC_MODEL = demoModel;
194
+ process.env.ANTHROPIC_SMALL_FAST_MODEL = demoModel;
195
+ process.env.CLAUDE_CODE_SUBAGENT_MODEL = demoModel;
196
+ process.env.CLAUDE_CODE_SUBAGENT_MODEL_FORCE = demoModel;
197
+ // GLM-4.7 exposes a 200K window; pins the CLI's context-cap handling.
198
+ process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = process.env.OSBORN_DEMO_MAX_CONTEXT || '200000';
199
+ // Signal for the fast brain (pipeline-fastbrain reads this per call) so the
200
+ // WHOLE model layer - main agent AND fast brain - rides the same pass.
201
+ process.env.OSBORN_DEMO_PASS = 'zai';
202
+ fallbackTierActive = true;
203
+ console.log(`[auth-fallback] using house demo pass (z.ai), model=${demoModel}`);
204
+ return;
205
+ }
206
+ // Tier 4: central OpenRouter key (pay-per-use fallback of the fallback).
181
207
  const openRouterKey = process.env.OPENROUTER_API_KEY;
182
208
  if (openRouterKey && openRouterKey.trim() !== '') {
183
209
  // Native Anthropic-Messages endpoint — no local translation proxy needed.
@@ -207,8 +233,8 @@ export function applyAuthFallback() {
207
233
  console.log(`[auth-fallback] using central OpenRouter tier, model=${FALLBACK_MODEL}`);
208
234
  return;
209
235
  }
210
- // Tier 3 fail: no OpenRouter key — do NOT throw.
211
- console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, and no OPENROUTER_API_KEY — agent may be unauthenticated');
236
+ // Tier 4 fail: no fallback key at all — do NOT throw.
237
+ console.warn('[auth-fallback] no Claude login, no ANTHROPIC_API_KEY, no Z_AI key, and no OPENROUTER_API_KEY — agent may be unauthenticated');
212
238
  }
213
239
  /**
214
240
  * Clear the OpenRouter fallback redirect — but ONLY if applyAuthFallback() set
@@ -229,8 +255,11 @@ function clearAuthFallbackIfActive() {
229
255
  // must be unset so the per-agent sonnet/opus fields take effect again.
230
256
  delete process.env.CLAUDE_CODE_SUBAGENT_MODEL;
231
257
  delete process.env.CLAUDE_CODE_SUBAGENT_MODEL_FORCE;
258
+ // Demo-pass signal - without this a post-login fast brain would keep routing
259
+ // to the house z.ai pass instead of the user's own pay-per-use providers.
260
+ delete process.env.OSBORN_DEMO_PASS;
232
261
  fallbackTierActive = false;
233
- console.log('[auth-fallback] real Claude login completed — cleared OpenRouter redirect');
262
+ console.log('[auth-fallback] real Claude login completed — cleared fallback redirect');
234
263
  }
235
264
  /**
236
265
  * Check auth via `claude auth status` (most reliable).
@@ -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
- const additionalContext = [machineNudge, reminder, recalled].filter(Boolean).join('\n\n');
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 });
@@ -32,6 +32,27 @@ const OPENROUTER_URL = FIREWORKS
32
32
  : 'https://openrouter.ai/api/v1/chat/completions';
33
33
  const TIMEOUT_MS = 20_000;
34
34
  const MAX_TOOL_ROUNDS = 4;
35
+ /**
36
+ * Per-call provider resolution for the HOUSE DEMO PASS. When the user has no
37
+ * Claude auth, applyAuthFallback() sets OSBORN_DEMO_PASS='zai' - the whole
38
+ * model layer (main agent AND this fast brain) then rides the shared z.ai GLM
39
+ * subscription instead of pay-per-use Fireworks/OpenRouter. Checked per call
40
+ * (not module-load) because applyAuthFallback runs after this module loads, and
41
+ * because a mid-session real-Claude login clears the flag via clearAuthFallback.
42
+ * Returns null on the normal (user pays their own providers) path.
43
+ */
44
+ function resolveFastBrainProvider() {
45
+ if (process.env.OSBORN_DEMO_PASS !== 'zai')
46
+ return null;
47
+ const zaiKey = process.env.Z_AI_PERSONAL_API_KEY || process.env.ZAI_API_KEY;
48
+ if (!zaiKey)
49
+ return null;
50
+ return {
51
+ url: 'https://api.z.ai/api/paas/v4/chat/completions',
52
+ model: process.env.OSBORN_DEMO_FAST_MODEL || 'glm-4.5-air', // fast/cheap tier of the pass
53
+ name: 'z.ai (demo pass)',
54
+ };
55
+ }
35
56
  // ============================================================
36
57
  // PERSISTENT STATE (OpenAI message format)
37
58
  // ============================================================
@@ -258,7 +279,18 @@ async function getRecentEntries(sessionId, workingDir, _, count) {
258
279
  // ============================================================
259
280
  // SYSTEM PROMPT
260
281
  // ============================================================
261
- function buildSystemPrompt(chatHistory, researchContext) {
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() {
262
294
  const parts = [
263
295
  `You are a fast memory recall agent for a voice AI assistant called Osborn.`,
264
296
  `You search the user's conversation history — their questions, the assistant's answers,`,
@@ -300,21 +332,37 @@ function buildSystemPrompt(chatHistory, researchContext) {
300
332
  ` Only say "didn't find" after 3+ failed rounds.`,
301
333
  `⚠ Your own prior answers may have errors. Trust search results over your memory.`,
302
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 = [];
303
346
  if (chatHistory && chatHistory.length > 0) {
304
- parts.push(``, `== RECENT CONVERSATION ==`);
347
+ parts.push(`== RECENT CONVERSATION ==`);
305
348
  for (const turn of chatHistory.slice(-6)) {
306
349
  parts.push(`${turn.role}: ${turn.content.substring(0, 200)}`);
307
350
  }
308
351
  }
309
352
  if (researchContext)
310
- parts.push(``, `== ACTIVE RESEARCH ==`, researchContext);
311
- return parts.join('\n');
353
+ parts.push(`== ACTIVE RESEARCH ==`, researchContext);
354
+ return parts.length ? parts.join('\n') + '\n\n' : '';
312
355
  }
313
356
  // ============================================================
314
357
  // OPENROUTER CALL
315
358
  // ============================================================
316
359
  async function callOpenRouter(messages, tools, apiKey) {
317
- const resp = await fetch(OPENROUTER_URL, {
360
+ // Demo pass first — same OpenAI-compatible tool-loop contract, house z.ai key.
361
+ const demo = resolveFastBrainProvider();
362
+ const url = demo?.url || OPENROUTER_URL;
363
+ const model = demo?.model || OPENROUTER_MODEL;
364
+ const providerName = demo?.name || PROVIDER_NAME;
365
+ const resp = await fetch(url, {
318
366
  method: 'POST',
319
367
  headers: {
320
368
  'Authorization': `Bearer ${apiKey}`,
@@ -322,7 +370,7 @@ async function callOpenRouter(messages, tools, apiKey) {
322
370
  'X-OpenRouter-Title': 'Osborn Fast Brain',
323
371
  },
324
372
  body: JSON.stringify({
325
- model: OPENROUTER_MODEL,
373
+ model,
326
374
  messages,
327
375
  tools,
328
376
  tool_choice: 'auto',
@@ -331,7 +379,7 @@ async function callOpenRouter(messages, tools, apiKey) {
331
379
  });
332
380
  if (!resp.ok) {
333
381
  const body = await resp.text().catch(() => '');
334
- throw new Error(`${PROVIDER_NAME} ${resp.status}: ${body.substring(0, 200)}`);
382
+ throw new Error(`${providerName} ${resp.status}: ${body.substring(0, 200)}`);
335
383
  }
336
384
  return resp.json();
337
385
  }
@@ -369,7 +417,11 @@ export async function askPipelineFastBrain(workingDir, sessionId, question, opts
369
417
  if (!sessionId || sessionId === 'pending') {
370
418
  return { script: 'Session is still initializing.', type: 'acknowledgment', toolsUsed: [] };
371
419
  }
372
- const apiKey = process.env.FIREWORKS_API_KEY || process.env.OPENROUTER_API_KEY;
420
+ // Demo pass (house z.ai key) takes precedence when active; else the user's own
421
+ // pay-per-use providers (Fireworks preferred, OpenRouter fallback).
422
+ const apiKey = resolveFastBrainProvider()
423
+ ? (process.env.Z_AI_PERSONAL_API_KEY || process.env.ZAI_API_KEY)
424
+ : (process.env.FIREWORKS_API_KEY || process.env.OPENROUTER_API_KEY);
373
425
  if (!apiKey) {
374
426
  return { script: 'Search system not available right now.', type: 'acknowledgment', toolsUsed: [] };
375
427
  }
@@ -383,15 +435,18 @@ export async function askPipelineFastBrain(workingDir, sessionId, question, opts
383
435
  if (persistentMessages.length > 24) {
384
436
  persistentMessages = persistentMessages.slice(-24);
385
437
  }
386
- const systemPrompt = buildSystemPrompt(opts?.chatHistory, opts?.researchContext);
438
+ const systemPrompt = buildSystemPrompt();
439
+ const turnContext = buildTurnContext(opts?.chatHistory, opts?.researchContext);
387
440
  const sessionBaseDir = opts?.sessionBaseDir || workingDir;
388
441
  const tools = buildTools(!!opts?.agentControl);
389
442
  const toolsUsed = [];
390
- // 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).
391
446
  const messages = [
392
447
  { role: 'system', content: systemPrompt },
393
448
  ...persistentMessages,
394
- { role: 'user', content: question },
449
+ { role: 'user', content: turnContext ? `${turnContext}${question}` : question },
395
450
  ];
396
451
  try {
397
452
  let rounds = 0;
@@ -407,6 +462,14 @@ export async function askPipelineFastBrain(workingDir, sessionId, question, opts
407
462
  }
408
463
  rounds++;
409
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
+ }
410
473
  const choice = data.choices?.[0];
411
474
  const msg = choice?.message;
412
475
  if (!msg)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "osborn",
3
- "version": "0.9.268",
3
+ "version": "0.9.270",
4
4
  "description": "Voice AI coding assistant - local agent that connects to Osborn frontend",
5
5
  "type": "module",
6
6
  "bin": {