osborn 0.9.295 → 0.9.296

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.
Files changed (38) hide show
  1. package/Dockerfile +1 -1
  2. package/Dockerfile.sandbox +71 -7
  3. package/dist/claude-auth.d.ts +2 -2
  4. package/dist/claude-auth.js +5 -13
  5. package/dist/claude-llm.d.ts +1 -0
  6. package/dist/claude-llm.js +2 -1
  7. package/dist/content/compaction-lens.js +5 -5
  8. package/dist/content/content-checks.d.ts +7 -0
  9. package/dist/content/content-checks.js +4 -3
  10. package/dist/content/content-ingest.js +2 -3
  11. package/dist/content/content-llm.d.ts +69 -3
  12. package/dist/content/content-llm.js +127 -18
  13. package/dist/content/content-run.js +3 -4
  14. package/dist/content/lens-ingest.d.ts +2 -0
  15. package/dist/content/lens-ingest.js +2 -0
  16. package/dist/content/lens-launch.js +4 -3
  17. package/dist/content/lens-library-digest.js +8 -10
  18. package/dist/content/lens-library-sweep.js +2 -2
  19. package/dist/content/lens-library.js +2 -1
  20. package/dist/content/lens-model.d.ts +15 -6
  21. package/dist/content/lens-model.js +44 -32
  22. package/dist/content/period-run.d.ts +1 -1
  23. package/dist/content/period-run.js +7 -7
  24. package/dist/data-sender-auth.d.ts +14 -0
  25. package/dist/data-sender-auth.js +25 -0
  26. package/dist/env-key.d.ts +15 -0
  27. package/dist/env-key.js +25 -0
  28. package/dist/index.js +86 -42
  29. package/dist/meeting-tts.d.ts +2 -0
  30. package/dist/meeting-tts.js +3 -1
  31. package/dist/pipeline-direct-llm.d.ts +1 -0
  32. package/dist/pipeline-fastbrain.js +4 -6
  33. package/dist/prompts/chain-after-writer.md +1 -1
  34. package/dist/prompts/steward.md +3 -0
  35. package/dist/steward-verdict.js +2 -2
  36. package/dist/volume-sync-status.d.ts +15 -0
  37. package/dist/volume-sync-status.js +35 -0
  38. package/package.json +4 -5
package/Dockerfile CHANGED
@@ -6,7 +6,7 @@
6
6
  # Build: fly deploy
7
7
  # Local: docker build -t osborn-agent . && docker run -p 8741:8741 --env-file .env osborn-agent
8
8
 
9
- ARG NODE_VERSION=20
9
+ ARG NODE_VERSION=24
10
10
  FROM node:${NODE_VERSION}-slim AS base
11
11
  WORKDIR /app
12
12
  ENV NODE_ENV=production
@@ -35,7 +35,7 @@
35
35
  # no bind-mount complexity, the chroot version was retired.
36
36
  # Archive: docs/archive/Dockerfile.sandbox.chroot-2026-05-28.md
37
37
 
38
- FROM node:22-slim
38
+ FROM node:24-slim
39
39
 
40
40
  # Runtime deps (same as chroot variant — comes from image, image-swap upgrades)
41
41
  RUN apt-get update -qq && \
@@ -98,8 +98,10 @@ ENV OSBORN_CWD=/workspace
98
98
  # CLIs are immediately runnable. Verified end-to-end on real Fly 2026-06-01:
99
99
  # pure-JS (cowsay) AND native-compiled (node-pty via node-gyp) both install at
100
100
  # runtime, persist across restart, no OOM (toolchain is in the image).
101
- # Caveat: native user modules are tied to the image's Node ABI (currently 22) —
102
- # a future Node-major image bump would need an `npm rebuild` of volume globals.
101
+ # Caveat: a native user module built against the Node ABI (not Node-API) is tied
102
+ # to the image's Node major (currently 24) and needs an `npm rebuild` after a
103
+ # Node-major image bump. osborn's own native deps (better-sqlite3, node-pty,
104
+ # onnxruntime-node, @livekit/rtc-node) use Node-API, so the volume copy loads on 22 and 24.
103
105
  ENV NPM_CONFIG_PREFIX=/workspace/.npm-global
104
106
  ENV NPM_CONFIG_CACHE=/tmp/npm-cache
105
107
  ENV PATH=/workspace/.npm-global/bin:$PATH
@@ -231,14 +233,76 @@ fi
231
233
  # PATH prefers /workspace/.npm-global/bin over /usr/local/bin — so after an
232
234
  # image-swap the volume copy is stale. Detect mismatch and sync on boot so
233
235
  # the dashboard update button (image-swap + restart) actually takes effect.
234
- VOL_OSBORN_VER=$(grep -m1 '"version"' /workspace/.npm-global/lib/node_modules/osborn/package.json 2>/dev/null | sed 's/.*"version"[^"]*"\([^"]*\)".*/\1/' || echo "none")
236
+ # A placeholder copy (0.0.0-rollback) or a missing one never matches, so it
237
+ # resyncs too (machines.ts rollbackInitScript relies on that).
238
+ #
239
+ # npm installs into a staging prefix on the volume and the package is renamed
240
+ # in only when npm succeeded, so a failed sync (disk full, network) leaves the
241
+ # working copy untouched. Every boot writes the outcome as JSON to
242
+ # /workspace/.osborn-sync-status for /health (agent volume-sync-status.ts);
243
+ # when the volume cannot take even that, to /tmp/osborn-sync-status.
244
+ # SYNC_NEED_MB: osborn 0.9.295 installs to 1.5 GB (onnxruntime-node 513 MB,
245
+ # @anthropic-ai 380 MB); the old copy stays until the rename, and the npm
246
+ # cache is in /tmp, so the volume needs the full install plus headroom.
247
+ SYNC_NEED_MB=2048
248
+ SYNC_MODULES=/workspace/.npm-global/lib/node_modules
249
+ SYNC_STAGE=/workspace/.osborn-sync-stage
250
+ SYNC_STATUS=/workspace/.osborn-sync-status
251
+ SYNC_LOG=/tmp/osborn-sync.log
252
+ rm -f /tmp/osborn-sync-status
253
+ sync_free_mb() { df -Pm /workspace 2>/dev/null | awk 'NR==2 {print $4}'; }
254
+ # sync_status <ok> <reason> [freeMb] [detail]
255
+ sync_status() {
256
+ local json
257
+ json=$(node -e 'const [ok, reason, image, volume, free, need, detail] = process.argv.slice(1)
258
+ console.log(JSON.stringify({ ok: ok === "true", reason, image, volume, freeMb: free === "" ? null : Number(free), needMb: Number(need), detail: detail || undefined, at: new Date().toISOString() }))' \
259
+ "$1" "$2" "$IMAGE_SEED_VERSION" "$VOL_OSBORN_VER" "${3:-}" "$SYNC_NEED_MB" "${4:-}") || return 0
260
+ echo "[sandbox-d] sync status: $json"
261
+ if ! { printf '%s\n' "$json" > "$SYNC_STATUS.tmp" && mv -f "$SYNC_STATUS.tmp" "$SYNC_STATUS"; } 2>/dev/null; then
262
+ rm -f "$SYNC_STATUS.tmp" 2>/dev/null || true
263
+ printf '%s\n' "$json" > /tmp/osborn-sync-status || true
264
+ fi
265
+ }
266
+ VOL_OSBORN_VER=$(grep -m1 '"version"' "$SYNC_MODULES/osborn/package.json" 2>/dev/null | sed 's/.*"version"[^"]*"\([^"]*\)".*/\1/' || echo "none")
267
+ [ -z "$VOL_OSBORN_VER" ] && VOL_OSBORN_VER=none
235
268
  if [ -n "$IMAGE_SEED_VERSION" ] && [ "$IMAGE_SEED_VERSION" != "$VOL_OSBORN_VER" ]; then
236
269
  echo "[sandbox-d] volume osborn@${VOL_OSBORN_VER} != image@${IMAGE_SEED_VERSION} -- syncing"
237
- rm -rf /workspace/.npm-global/lib/node_modules/.osborn-* 2>/dev/null
238
- npm install -g "osborn@${IMAGE_SEED_VERSION}" --no-audit --no-fund 2>&1 | tail -3
239
- echo "[sandbox-d] sync done: osborn@${IMAGE_SEED_VERSION} on volume"
270
+ # Also the leftovers of machines.ts installOsbornSpec / rollbackInitScript (idle at boot),
271
+ # so our own staging dirs cannot read as a full disk.
272
+ rm -rf "$SYNC_MODULES"/.osborn-* "$SYNC_STAGE" /workspace/.osborn-stage* /workspace/.osborn-rollback-stage 2>/dev/null || true
273
+ SYNC_FREE=$(sync_free_mb)
274
+ if [ -n "$SYNC_FREE" ] && [ "$SYNC_FREE" -lt "$SYNC_NEED_MB" ]; then
275
+ echo "[sandbox-d] SYNC SKIPPED: disk full -- /workspace has ${SYNC_FREE} MB free, osborn needs ${SYNC_NEED_MB} MB; still on osborn@${VOL_OSBORN_VER}"
276
+ sync_status false disk_full "$SYNC_FREE"
277
+ elif npm install -g --prefix "$SYNC_STAGE" "osborn@${IMAGE_SEED_VERSION}" --no-audit --no-fund > "$SYNC_LOG" 2>&1 \
278
+ && [ -f "$SYNC_STAGE/lib/node_modules/osborn/package.json" ]; then
279
+ mkdir -p "$SYNC_MODULES" /workspace/.npm-global/bin
280
+ if [ -e "$SYNC_MODULES/osborn" ]; then mv "$SYNC_MODULES/osborn" "$SYNC_MODULES/.osborn-old"; fi
281
+ mv "$SYNC_STAGE/lib/node_modules/osborn" "$SYNC_MODULES/osborn"
282
+ for l in "$SYNC_STAGE"/bin/*; do
283
+ if [ -L "$l" ]; then ln -sfn "$(readlink "$l")" "/workspace/.npm-global/bin/$(basename "$l")" || true; fi
284
+ done
285
+ rm -rf "$SYNC_MODULES/.osborn-old" "$SYNC_STAGE"
286
+ echo "[sandbox-d] sync done: osborn@${IMAGE_SEED_VERSION} on volume"
287
+ sync_status true synced "$(sync_free_mb)"
288
+ else
289
+ # npm 10 ends with "A complete log of this run can be found in: ..." -- not the cause.
290
+ SYNC_TAIL=$( (grep -v 'complete log of this run' "$SYNC_LOG" || true) | tail -5)
291
+ # Measured before the stage is removed: ENOSPC is the volume's only when the
292
+ # volume is what filled up (the npm cache in /tmp can fill too).
293
+ SYNC_FREE=$(sync_free_mb)
294
+ rm -rf "$SYNC_STAGE"
295
+ SYNC_REASON=npm_failed
296
+ if grep -qiE 'ENOSPC|no space left' "$SYNC_LOG" 2>/dev/null && [ -n "$SYNC_FREE" ] && [ "$SYNC_FREE" -lt "$SYNC_NEED_MB" ]; then
297
+ SYNC_REASON=disk_full
298
+ fi
299
+ echo "[sandbox-d] SYNC FAILED ($SYNC_REASON): still on osborn@${VOL_OSBORN_VER}; npm said:"
300
+ echo "$SYNC_TAIL"
301
+ sync_status false "$SYNC_REASON" "$SYNC_FREE" "$SYNC_TAIL"
302
+ fi
240
303
  else
241
304
  echo "[sandbox-d] volume osborn@${VOL_OSBORN_VER} matches image -- no sync needed"
305
+ sync_status true up_to_date "$(sync_free_mb)"
242
306
  fi
243
307
  echo "[sandbox-d] exec'ing osborn (no chroot, HOME=$HOME)"
244
308
  exec osborn
@@ -13,6 +13,7 @@
13
13
  * On Linux/Docker, credentials go to ~/.claude/.credentials.json (file-based, no keyring).
14
14
  * The Fly.io volume at /workspace/.claude is symlinked to ~/.claude for persistence.
15
15
  */
16
+ import { cleanEnvKey } from './env-key.js';
16
17
  /**
17
18
  * Strip ALL ANSI escape sequences from a string — CSI (including private
18
19
  * prefixes like `?`), OSC (both BEL and ST terminators), and lone ESC bytes.
@@ -43,8 +44,7 @@ export interface ClaudeAuthHandle {
43
44
  */
44
45
  export declare function isClaudeAuthenticated(): boolean;
45
46
  export declare function consumeFallbackClearedByLogin(): boolean;
46
- /** Trim whitespace and strip one layer of surrounding quotes from an env value. */
47
- export declare function cleanEnvKey(value: string | undefined | null): string;
47
+ export { cleanEnvKey };
48
48
  /** Env vars that give the agent a working model backend without a Claude login. */
49
49
  export declare const FALLBACK_MODEL_KEY_VARS: readonly ["ANTHROPIC_API_KEY", "Z_AI_PERSONAL_API_KEY", "ZAI_API_KEY", "OPENROUTER_API_KEY"];
50
50
  /**
@@ -19,6 +19,7 @@ import { execSync } from 'child_process';
19
19
  import { homedir } from 'os';
20
20
  import { join } from 'path';
21
21
  import { FALLBACK_MODEL } from './claude-llm.js';
22
+ import { ZAI_CONTEXT_LENGTH, cleanEnvKey, zaiApiKey, zaiModel } from './env-key.js';
22
23
  /**
23
24
  * Resolve the full path to the `claude` binary.
24
25
  * node-pty uses posix_spawnp which may not find binaries in nvm/homebrew paths.
@@ -193,16 +194,7 @@ export function consumeFallbackClearedByLogin() {
193
194
  fallbackClearedByLogin = false;
194
195
  return v;
195
196
  }
196
- /** Trim whitespace and strip one layer of surrounding quotes from an env value. */
197
- export function cleanEnvKey(value) {
198
- if (!value)
199
- return '';
200
- let v = value.trim();
201
- if (v.length >= 2 && ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))) {
202
- v = v.slice(1, -1).trim();
203
- }
204
- return v;
205
- }
197
+ export { cleanEnvKey };
206
198
  /** Env vars that give the agent a working model backend without a Claude login. */
207
199
  export const FALLBACK_MODEL_KEY_VARS = [
208
200
  'ANTHROPIC_API_KEY',
@@ -285,14 +277,14 @@ export function applyAuthFallback() {
285
277
  // glm-5.3-flash 2026-11-10: the GLM Coding Plan now only lists GLM-5.3 and
286
278
  // GLM-5.3-Flash (docs.z.ai/devpack/overview; glm-4.7 is silently routed to
287
279
  // 5.3-Flash). Precedence: Z_AI_PERSONAL_API_KEY, then ZAI_API_KEY.
288
- const zaiKey = cleanEnvKey(process.env.Z_AI_PERSONAL_API_KEY) || cleanEnvKey(process.env.ZAI_API_KEY);
280
+ const zaiKey = zaiApiKey();
289
281
  if (zaiKey !== '') {
290
282
  snapshotModelEnv();
291
283
  // Native Anthropic-Messages endpoint - no local translation proxy needed.
292
284
  process.env.ANTHROPIC_BASE_URL = process.env.OSBORN_DEMO_BASE_URL || 'https://api.z.ai/api/anthropic';
293
285
  process.env.ANTHROPIC_AUTH_TOKEN = zaiKey;
294
286
  process.env.ANTHROPIC_API_KEY = ''; // required - a set key bypasses AUTH_TOKEN
295
- const demoModel = process.env.OSBORN_DEMO_MODEL || 'glm-5.3';
287
+ const demoModel = zaiModel();
296
288
  const demoFastModel = process.env.OSBORN_DEMO_FAST_MODEL || 'glm-5.3-flash';
297
289
  process.env.ANTHROPIC_MODEL = demoModel;
298
290
  process.env.ANTHROPIC_SMALL_FAST_MODEL = demoFastModel;
@@ -300,7 +292,7 @@ export function applyAuthFallback() {
300
292
  process.env.CLAUDE_CODE_SUBAGENT_MODEL_FORCE = demoModel;
301
293
  // GLM-5.3 and GLM-5.3-Flash expose a 1M-token window (docs.z.ai/guides/llm/glm-5.3,
302
294
  // verified 2026-11-10); pins the CLI's context-cap handling.
303
- process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = process.env.OSBORN_DEMO_MAX_CONTEXT || '1000000';
295
+ process.env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = process.env.OSBORN_DEMO_MAX_CONTEXT || String(ZAI_CONTEXT_LENGTH);
304
296
  // Signal for the fast brain (pipeline-fastbrain reads this per call) so the
305
297
  // WHOLE model layer - main agent AND fast brain - rides the same pass.
306
298
  process.env.OSBORN_DEMO_PASS = 'zai';
@@ -335,6 +335,7 @@ export declare class ClaudeLLM extends llm.LLM {
335
335
  subagentType?: string;
336
336
  description?: string;
337
337
  status: string;
338
+ startedAt: number;
338
339
  }>;
339
340
  /** `resume` id the live persistent query was spawned with (null = fresh / none). */
340
341
  get spawnedResumeId(): string | null;
@@ -1862,6 +1862,7 @@ export class ClaudeLLM extends llm.LLM {
1862
1862
  subagentType: msg.subagent_type,
1863
1863
  description: msg.description,
1864
1864
  status: 'running',
1865
+ startedAt: Date.now(),
1865
1866
  });
1866
1867
  if (msg.tool_use_id)
1867
1868
  this.#taskIdByToolUse.set(msg.tool_use_id, msg.task_id);
@@ -1883,7 +1884,7 @@ export class ClaudeLLM extends llm.LLM {
1883
1884
  getRunningTasks() {
1884
1885
  return [...this.#tasksById.entries()]
1885
1886
  .filter(([, t]) => t.status === 'running' || t.status === 'pending')
1886
- .map(([taskId, t]) => ({ taskId, subagentType: t.subagentType, description: t.description, status: t.status }));
1887
+ .map(([taskId, t]) => ({ taskId, subagentType: t.subagentType, description: t.description, status: t.status, startedAt: t.startedAt }));
1887
1888
  }
1888
1889
  // ============================================================
1889
1890
  // PERSISTENT SESSION — V1 query() with AsyncIterable<SDKUserMessage>
@@ -25,6 +25,7 @@ import { gateQueries, privateSegments } from './content-query-gate.js';
25
25
  import { alignRecording, findSessionRecording } from './lens-audio.js';
26
26
  import { appendProfile, formatEntry, writeScratch } from './lens-profile.js';
27
27
  import { findTranscriptBySessionId, isProjectDir, readHwm, refuseOutPath, resolveProjectDir, writeHwm } from './lens-paths.js';
28
+ import { hasContentModelKey } from './content-llm.js';
28
29
  const LIMITS = {
29
30
  map: { a: 4, c: 8 },
30
31
  incremental: { a: 3, c: 6 },
@@ -75,15 +76,14 @@ export async function runCompactionLens(opts) {
75
76
  if (why)
76
77
  throw new Error(`content lens: ${why}`);
77
78
  }
78
- const apiKey = process.env.OPENROUTER_API_KEY;
79
- if (!apiKey)
79
+ if (!hasContentModelKey())
80
80
  return { ...r, status: 'no-key' };
81
81
  r.dbPath = resolveSessionDb(opts.sessionId, projectDir, opts.cwd);
82
82
  if (!r.dbPath)
83
83
  return { ...r, status: 'no-db' };
84
84
  if (!projectDir)
85
85
  projectDir = r.projectDir = dirname(dirname(dirname(r.dbPath)));
86
- const info = await getModelInfo(apiKey);
86
+ const info = await getModelInfo();
87
87
  if (!info)
88
88
  return { ...r, status: 'model-unknown' };
89
89
  r.model = { id: info.id, contextLength: info.contextLength, promptPerM: info.promptPerTok * 1e6, completionPerM: info.completionPerTok * 1e6, verified: info.verified };
@@ -124,7 +124,7 @@ export async function runCompactionLens(opts) {
124
124
  r.windows.push({ rows: w.records.length, chars: w.chars, estTokens: w.estTokens, firstRowId: w.firstRowId, lastRowId: w.lastRowId });
125
125
  let res;
126
126
  try {
127
- res = await chat(budget, mapPrompt(w.text, w.index + 1, all.length, LIMITS.map.a, LIMITS.map.c), apiKey);
127
+ res = await chat(budget, mapPrompt(w.text, w.index + 1, all.length, LIMITS.map.a, LIMITS.map.c));
128
128
  }
129
129
  catch (err) {
130
130
  log(`map ${w.index + 1}/${all.length} failed: ${err instanceof Error ? err.message : err}`);
@@ -172,7 +172,7 @@ export async function runCompactionLens(opts) {
172
172
  const needReduce = r.windowsProcessed > 1 || pool.angles.length > lim.a || pool.capabilities.length > lim.c;
173
173
  if (needReduce && pool.angles.length + pool.capabilities.length > 0) {
174
174
  try {
175
- const res = await chat(budget, reducePrompt(JSON.stringify(pool), lim.a, lim.c), apiKey, 12_000);
175
+ const res = await chat(budget, reducePrompt(JSON.stringify(pool), lim.a, lim.c), 12_000);
176
176
  const out = res ? readCandidates(res.content, lim.a, lim.c, r) : null;
177
177
  if (out && out.angles.length + out.capabilities.length > 0)
178
178
  cands = out;
@@ -76,6 +76,13 @@ export interface CheckContext {
76
76
  /** Truth-check ground truth: library page + cited rows + research digest (already scrubbed). */
77
77
  sources: string;
78
78
  }
79
+ /** Pinned LLM judge with a content-addressed cache (exported for tests). Throws CapError / Error. */
80
+ export declare function pinnedJudge(kind: 'truth' | 'audience', system: string, user: string, ctx: CheckContext): Promise<{
81
+ flags: string[];
82
+ provider: string;
83
+ cacheKey: string;
84
+ cached: boolean;
85
+ }>;
79
86
  /**
80
87
  * All gates for one script. `flags` (hard) non-empty ⇒ blocked. `warnings` are advisory
81
88
  * quality flags (empty under OSBORN_CONTENT_STRICT=1, where they are hard flags instead).
@@ -176,14 +176,15 @@ export function structureCheck(s, brief, limits = scriptLimits()) {
176
176
  function cachePath(projectDir, key) {
177
177
  return projectDir ? join(projectDir, CHECK_CACHE_DIR, `${key}.json`) : null;
178
178
  }
179
- /** Pinned LLM judge with a content-addressed cache. Throws CapError / Error. */
180
- async function pinnedJudge(kind, system, user, ctx) {
179
+ /** Pinned LLM judge with a content-addressed cache (exported for tests). Throws CapError / Error. */
180
+ export async function pinnedJudge(kind, system, user, ctx) {
181
181
  const key = createHash('sha256').update(JSON.stringify({ kind, system, user, model: CHECK_MODEL, provider: CHECK_PROVIDER })).digest('hex');
182
182
  const p = cachePath(ctx.projectDir, key);
183
183
  if (p) {
184
184
  try {
185
185
  const c = JSON.parse(readFileSync(p, 'utf-8'));
186
- if (c?.key === key && Array.isArray(c.flags))
186
+ // Only a verdict the pinned judge itself gave counts (never another provider's).
187
+ if (c?.key === key && Array.isArray(c.flags) && c.provider === CHECK_PROVIDER_NAME)
187
188
  return { flags: c.flags, provider: String(c.provider), cacheKey: key, cached: true };
188
189
  }
189
190
  catch {
@@ -15,15 +15,14 @@
15
15
  * Every string in the payload goes through scrubDeep() (content-redact.ts) first.
16
16
  * Blocked pieces never reach this module (content-run).
17
17
  */
18
- import { createHash } from 'node:crypto';
19
18
  import { basename } from 'node:path';
20
- import { postContentIngest, resolveIngestConfig } from './lens-ingest.js';
19
+ import { ingestRowKey, postContentIngest, resolveIngestConfig } from './lens-ingest.js';
21
20
  import { CHECK_MODEL, CHECK_PROVIDER } from './content-llm.js';
22
21
  import { FORMAT_CATALOG, TIER_TEMPLATES } from './content-script-rules.js';
23
22
  import { scriptTranscript } from './content-script.js';
24
23
  export const AUTO_LABEL = 'Auto-generated draft';
25
24
  const SESSION_ID_RE = /^[a-zA-Z0-9._-]{1,128}$/;
26
- export const pieceContentHash = (sessionId, startRowId, pieceId) => createHash('sha256').update(`content-script\n${sessionId}\n${startRowId}\n${pieceId}`).digest('hex');
25
+ export const pieceContentHash = (sessionId, startRowId, pieceId) => ingestRowKey('content-script', sessionId, startRowId, pieceId);
27
26
  export const projectSlugFor = (projectDir) => (projectDir ? basename(projectDir) : null);
28
27
  const LABEL = { narrator: 'NARRATOR', dev: 'DEVELOPER (verbatim)', agent: 'AGENT' };
29
28
  /** The draft as markdown (the `body` field), labelled as auto-generated. */
@@ -1,6 +1,23 @@
1
1
  /**
2
- * content-llm.ts — Stage A's flags, spend caps and its ONE model-call path.
3
- * OpenRouter ONLY (OPENROUTER_API_KEY) — never the Claude subscription / Anthropic SDK.
2
+ * content-llm.ts — Stage A's flags, spend caps and the ONE provider seam every
3
+ * content / Library / lens model call goes through (contentChat). Never the
4
+ * Claude subscription / Anthropic SDK.
5
+ *
6
+ * Providers (contentProviders), tried in order per call:
7
+ * 1. OpenRouter, when OPENROUTER_API_KEY is set. A 401 (key rejected) marks it
8
+ * rejected for the rest of the process and the same call moves on; a 403
9
+ * (moderation or edge block) only fails that call.
10
+ * 2. z.ai, when Z_AI_PERSONAL_API_KEY or ZAI_API_KEY is set (same precedence as
11
+ * claude-auth.ts tier 3): the GLM Coding Plan's OpenAI-compatible endpoint
12
+ * https://api.z.ai/api/coding/paas/v4 (docs.z.ai/devpack/quick-start; the plain
13
+ * /api/paas/v4 bills the pay-as-you-go wallet instead of the plan). Model
14
+ * OSBORN_DEMO_MODEL, default glm-5.3 (the plan lists GLM-5.3 and GLM-5.3-Flash,
15
+ * docs.z.ai/devpack/overview; 1M context, docs.z.ai/guides/llm/glm-5.3). The plan is
16
+ * a flat subscription, but z.ai calls are still priced at ZAI_NOMINAL_PRICE so the
17
+ * caps below keep binding (they pace the sweep against the plan's usage quota).
18
+ * Neither key → hasContentModelKey() is false and callers report "no-key".
19
+ * A provider-pinned call (the content step's judges) runs on OpenRouter only and
20
+ * is refused when OpenRouter is unavailable: z.ai cannot honour the pin.
4
21
  *
5
22
  * Flags:
6
23
  * OSBORN_CONTENT_PIPELINE default ON; 0/off/false/no = off. OSBORN_CONTENT_LENS=0 also turns it off.
@@ -133,8 +150,57 @@ export interface LlmResult {
133
150
  }
134
151
  /** Lenient JSON extraction: strips fences, takes the outermost {...} or [...]. Null when unparseable. */
135
152
  export declare function parseJsonLoose(s: string): any;
153
+ export type ContentProviderId = 'openrouter' | 'zai';
154
+ /** z.ai prices: the Coding Plan is flat, so this is nominal (the default model's OpenRouter rate) to keep the caps binding. */
155
+ export declare const ZAI_NOMINAL_PRICE: {
156
+ p: number;
157
+ c: number;
158
+ };
159
+ /**
160
+ * GLM-5.3 can no longer switch reasoning off ("Disabling reasoning is no longer
161
+ * supported", docs.z.ai/guides/llm/glm-5.3); calls ask for reasoning_effort "low"
162
+ * and get this much extra output room so hidden reasoning cannot truncate the JSON.
163
+ */
164
+ export declare const ZAI_REASONING_HEADROOM = 8000;
165
+ export declare const NO_CONTENT_KEY = "no content model key (OPENROUTER_API_KEY, Z_AI_PERSONAL_API_KEY or ZAI_API_KEY)";
166
+ /**
167
+ * Remember for the rest of the process that OpenRouter rejected the key (HTTP 401); later calls skip it.
168
+ * A 403 is not a dead key (moderation-flagged input or an edge block; claude-auth.ts classifyProbeStatus
169
+ * treats it as ambiguous too): it fails that one call and never comes here.
170
+ */
171
+ export declare function markOpenRouterRejected(status: number): void;
172
+ /** Tests only: forget a rejected OpenRouter key. */
173
+ export declare function resetContentProviders(): void;
174
+ /** True when some content provider can be called (a rejected OpenRouter key does not count). */
175
+ export declare const hasContentModelKey: (env?: NodeJS.ProcessEnv) => boolean;
176
+ /** The provider the next call will try first, or null when there is none. */
177
+ export declare const contentProviderId: () => ContentProviderId | null;
178
+ /** The OpenRouter key while OpenRouter is still in play (for its /models lookup). */
179
+ export declare const openRouterKey: () => string | null;
180
+ /**
181
+ * Extra output tokens to reserve for a call: z.ai's reasoning headroom whenever a z.ai
182
+ * key exists, since z.ai may serve it (an OpenRouter 401 falls through mid-call).
183
+ */
184
+ export declare const extraOutputTokens: () => number;
185
+ export interface ContentChatReply {
186
+ data: any;
187
+ provider: ContentProviderId;
188
+ /** Who answered: OpenRouter's upstream provider name, or "z.ai". */
189
+ served: string;
190
+ model: string;
191
+ }
192
+ /**
193
+ * THE content model call: POST an OpenRouter-shaped chat-completions body to the
194
+ * first provider that takes it (see the header). A 401 from OpenRouter falls
195
+ * through to z.ai in the same call; any other non-OK status (403 included) throws
196
+ * "<provider> HTTP <n>". `openRouterOnly` (a provider-pinned call) never reaches z.ai.
197
+ */
198
+ export declare function contentChat(body: Record<string, any>, opts?: {
199
+ signal?: AbortSignal;
200
+ fetchImpl?: typeof fetch;
201
+ openRouterOnly?: boolean;
202
+ }): Promise<ContentChatReply>;
136
203
  export interface ContentLlmOptions {
137
- apiKey: string;
138
204
  guard: SpendGuard;
139
205
  scrub: (s: string) => string;
140
206
  fetchImpl?: typeof fetch;
@@ -1,6 +1,23 @@
1
1
  /**
2
- * content-llm.ts — Stage A's flags, spend caps and its ONE model-call path.
3
- * OpenRouter ONLY (OPENROUTER_API_KEY) — never the Claude subscription / Anthropic SDK.
2
+ * content-llm.ts — Stage A's flags, spend caps and the ONE provider seam every
3
+ * content / Library / lens model call goes through (contentChat). Never the
4
+ * Claude subscription / Anthropic SDK.
5
+ *
6
+ * Providers (contentProviders), tried in order per call:
7
+ * 1. OpenRouter, when OPENROUTER_API_KEY is set. A 401 (key rejected) marks it
8
+ * rejected for the rest of the process and the same call moves on; a 403
9
+ * (moderation or edge block) only fails that call.
10
+ * 2. z.ai, when Z_AI_PERSONAL_API_KEY or ZAI_API_KEY is set (same precedence as
11
+ * claude-auth.ts tier 3): the GLM Coding Plan's OpenAI-compatible endpoint
12
+ * https://api.z.ai/api/coding/paas/v4 (docs.z.ai/devpack/quick-start; the plain
13
+ * /api/paas/v4 bills the pay-as-you-go wallet instead of the plan). Model
14
+ * OSBORN_DEMO_MODEL, default glm-5.3 (the plan lists GLM-5.3 and GLM-5.3-Flash,
15
+ * docs.z.ai/devpack/overview; 1M context, docs.z.ai/guides/llm/glm-5.3). The plan is
16
+ * a flat subscription, but z.ai calls are still priced at ZAI_NOMINAL_PRICE so the
17
+ * caps below keep binding (they pace the sweep against the plan's usage quota).
18
+ * Neither key → hasContentModelKey() is false and callers report "no-key".
19
+ * A provider-pinned call (the content step's judges) runs on OpenRouter only and
20
+ * is refused when OpenRouter is unavailable: z.ai cannot honour the pin.
4
21
  *
5
22
  * Flags:
6
23
  * OSBORN_CONTENT_PIPELINE default ON; 0/off/false/no = off. OSBORN_CONTENT_LENS=0 also turns it off.
@@ -22,6 +39,7 @@
22
39
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
23
40
  import { homedir } from 'node:os';
24
41
  import { join } from 'node:path';
42
+ import { ZAI_CODING_BASE, cleanEnvKey, zaiApiKey, zaiModel } from '../env-key.js';
25
43
  import { isContentLensEnabled } from './lens-launch.js';
26
44
  import { withFileLock } from './lens-paths.js';
27
45
  const OPENROUTER = 'https://openrouter.ai/api/v1';
@@ -245,14 +263,110 @@ export function parseJsonLoose(s) {
245
263
  }
246
264
  return null;
247
265
  }
266
+ /** z.ai prices: the Coding Plan is flat, so this is nominal (the default model's OpenRouter rate) to keep the caps binding. */
267
+ export const ZAI_NOMINAL_PRICE = PRICES[DEFAULT_GEN_MODEL];
268
+ /**
269
+ * GLM-5.3 can no longer switch reasoning off ("Disabling reasoning is no longer
270
+ * supported", docs.z.ai/guides/llm/glm-5.3); calls ask for reasoning_effort "low"
271
+ * and get this much extra output room so hidden reasoning cannot truncate the JSON.
272
+ */
273
+ export const ZAI_REASONING_HEADROOM = 8_000;
274
+ export const NO_CONTENT_KEY = 'no content model key (OPENROUTER_API_KEY, Z_AI_PERSONAL_API_KEY or ZAI_API_KEY)';
275
+ let openRouterRejected = false;
276
+ /**
277
+ * Remember for the rest of the process that OpenRouter rejected the key (HTTP 401); later calls skip it.
278
+ * A 403 is not a dead key (moderation-flagged input or an edge block; claude-auth.ts classifyProbeStatus
279
+ * treats it as ambiguous too): it fails that one call and never comes here.
280
+ */
281
+ export function markOpenRouterRejected(status) {
282
+ if (openRouterRejected)
283
+ return;
284
+ openRouterRejected = true;
285
+ const next = zaiApiKey() ? 'using z.ai from now on' : 'no z.ai key to fall back on';
286
+ console.warn(`content-llm: OpenRouter rejected the key (HTTP ${status}); ${next}`);
287
+ }
288
+ /** Tests only: forget a rejected OpenRouter key. */
289
+ export function resetContentProviders() {
290
+ openRouterRejected = false;
291
+ }
292
+ /** The providers a content call may use, in the order it tries them. */
293
+ function contentProviders(env = process.env) {
294
+ const out = [];
295
+ const or = cleanEnvKey(env.OPENROUTER_API_KEY);
296
+ if (or && !openRouterRejected)
297
+ out.push({ id: 'openrouter', label: 'OpenRouter', key: or, base: OPENROUTER });
298
+ const z = zaiApiKey(env);
299
+ if (z)
300
+ out.push({ id: 'zai', label: 'z.ai', key: z, base: ZAI_CODING_BASE });
301
+ return out;
302
+ }
303
+ /** True when some content provider can be called (a rejected OpenRouter key does not count). */
304
+ export const hasContentModelKey = (env = process.env) => contentProviders(env).length > 0;
305
+ /** The provider the next call will try first, or null when there is none. */
306
+ export const contentProviderId = () => contentProviders()[0]?.id ?? null;
307
+ /** The OpenRouter key while OpenRouter is still in play (for its /models lookup). */
308
+ export const openRouterKey = () => contentProviders().find(p => p.id === 'openrouter')?.key ?? null;
309
+ /**
310
+ * Extra output tokens to reserve for a call: z.ai's reasoning headroom whenever a z.ai
311
+ * key exists, since z.ai may serve it (an OpenRouter 401 falls through mid-call).
312
+ */
313
+ export const extraOutputTokens = () => (zaiApiKey() ? ZAI_REASONING_HEADROOM : 0);
314
+ /** An OpenRouter chat-completions body → the z.ai one: GLM model, no OpenRouter-only fields, low reasoning. */
315
+ function zaiBody(b) {
316
+ return {
317
+ model: zaiModel(),
318
+ messages: b.messages,
319
+ temperature: b.temperature,
320
+ max_tokens: (Number(b.max_tokens) || 0) + ZAI_REASONING_HEADROOM,
321
+ thinking: { type: 'enabled' },
322
+ reasoning_effort: 'low',
323
+ };
324
+ }
325
+ /**
326
+ * THE content model call: POST an OpenRouter-shaped chat-completions body to the
327
+ * first provider that takes it (see the header). A 401 from OpenRouter falls
328
+ * through to z.ai in the same call; any other non-OK status (403 included) throws
329
+ * "<provider> HTTP <n>". `openRouterOnly` (a provider-pinned call) never reaches z.ai.
330
+ */
331
+ export async function contentChat(body, opts = {}) {
332
+ const list = contentProviders().filter(p => !opts.openRouterOnly || p.id === 'openrouter');
333
+ if (!list.length)
334
+ throw new Error(opts.openRouterOnly ? 'pinned call: OpenRouter is not available (unset or key rejected); z.ai cannot honour the pin' : NO_CONTENT_KEY);
335
+ let rejected = 0;
336
+ for (const p of list) {
337
+ const sent = p.id === 'zai' ? zaiBody(body) : body;
338
+ const resp = await (opts.fetchImpl ?? fetch)(`${p.base}/chat/completions`, {
339
+ method: 'POST',
340
+ signal: opts.signal,
341
+ headers: { Authorization: `Bearer ${p.key}`, 'Content-Type': 'application/json' },
342
+ body: JSON.stringify(sent),
343
+ });
344
+ if (p.id === 'openrouter' && resp.status === 401) {
345
+ markOpenRouterRejected((rejected = resp.status));
346
+ continue;
347
+ }
348
+ if (!resp.ok)
349
+ throw new Error(`${p.label} HTTP ${resp.status}`);
350
+ const data = await resp.json();
351
+ return { data, provider: p.id, served: p.id === 'zai' ? 'z.ai' : String(data?.provider ?? ''), model: String(sent.model) };
352
+ }
353
+ throw new Error(`OpenRouter HTTP ${rejected} (key rejected) and ${opts.openRouterOnly ? 'the call is pinned to OpenRouter' : 'no z.ai key'}`);
354
+ }
248
355
  /** One chat call → JSON. Throws CapError on a cap, Error on HTTP/timeout/provider mismatch. */
249
356
  export async function llmJson(o, call) {
250
357
  const model = call.model ?? genModel();
251
358
  const system = o.scrub(call.system);
252
359
  const user = o.scrub(call.user);
253
- const price = priceFor(model);
360
+ // A pin names an OpenRouter upstream; z.ai has one upstream and cannot honour it. Refuse before spending.
361
+ if (call.pin && !openRouterKey()) {
362
+ throw new Error(`${call.what}: pinned to ${call.pin.name} on OpenRouter, which is not available (unset or key rejected)`);
363
+ }
364
+ // Size the reservation for whichever provider may serve: z.ai can take over mid-call when a z.ai key exists.
365
+ const zaiMay = !call.pin && !!zaiApiKey();
366
+ const base = contentProviderId() === 'zai' ? ZAI_NOMINAL_PRICE : priceFor(model);
367
+ const price = zaiMay ? { p: Math.max(base.p, ZAI_NOMINAL_PRICE.p), c: Math.max(base.c, ZAI_NOMINAL_PRICE.c) } : base;
254
368
  const estPrompt = Math.ceil((system.length + user.length) / 3.5);
255
- const worst = estPrompt * price.p + call.maxOut * price.c;
369
+ const worst = estPrompt * price.p + (call.maxOut + (zaiMay ? ZAI_REASONING_HEADROOM : 0)) * price.c;
256
370
  const res = o.guard.reserve(worst);
257
371
  o.guard.calls++;
258
372
  const ctrl = new AbortController();
@@ -271,25 +385,20 @@ export async function llmJson(o, call) {
271
385
  };
272
386
  if (!call.pin)
273
387
  body.reasoning = { enabled: false };
274
- const resp = await (o.fetchImpl ?? fetch)(`${OPENROUTER}/chat/completions`, {
275
- method: 'POST',
276
- signal: ctrl.signal,
277
- headers: { Authorization: `Bearer ${o.apiKey}`, 'Content-Type': 'application/json' },
278
- body: JSON.stringify(body),
279
- });
280
- if (!resp.ok)
281
- throw new Error(`OpenRouter HTTP ${resp.status}`);
282
- const data = await resp.json();
388
+ const reply = await contentChat(body, { signal: ctrl.signal, fetchImpl: o.fetchImpl, openRouterOnly: !!call.pin });
389
+ const data = reply.data;
390
+ const p = reply.provider === 'zai' ? ZAI_NOMINAL_PRICE : priceFor(model);
283
391
  const pt = Number(data?.usage?.prompt_tokens) || estPrompt;
284
392
  const ct = Number(data?.usage?.completion_tokens) || 0;
285
393
  const reported = Number(data?.usage?.cost);
286
- const cost = Number.isFinite(reported) && reported > 0 ? reported : pt * price.p + ct * price.c;
394
+ const cost = Number.isFinite(reported) && reported > 0 ? reported : pt * p.p + ct * p.c;
287
395
  o.guard.settle(res, cost);
288
- const provider = String(data?.provider ?? '');
289
- if (call.pin && provider !== call.pin.name)
290
- throw new Error(`${call.what}: served by ${provider || '?'}, expected pinned ${call.pin.name}`);
396
+ o.log?.(`${call.what}: via ${reply.provider} (${reply.served || '?'}, ${reply.model})`);
397
+ if (call.pin && (reply.provider !== 'openrouter' || reply.served !== call.pin.name)) {
398
+ throw new Error(`${call.what}: served by ${reply.served || '?'}, expected pinned ${call.pin.name}`);
399
+ }
291
400
  const content = String(data?.choices?.[0]?.message?.content ?? '');
292
- return { content, json: parseJsonLoose(content), costUsd: cost, provider, model, finish: String(data?.choices?.[0]?.finish_reason ?? '') };
401
+ return { content, json: parseJsonLoose(content), costUsd: cost, provider: reply.served, model: reply.model, finish: String(data?.choices?.[0]?.finish_reason ?? '') };
293
402
  }
294
403
  catch (e) {
295
404
  if (e instanceof CapError)
@@ -20,7 +20,7 @@ import Database from 'better-sqlite3';
20
20
  import { loadConversationRows, recordView, resolveSessionDb } from './lens-db.js';
21
21
  import { pageFileName } from './lens-library-select.js';
22
22
  import { libraryDirFor, librarySegments, readManifest } from './lens-library.js';
23
- import { CapError, contentCaps, daySpent, genModel, isContentPipelineEnabled, isContentStrict, SpendGuard } from './content-llm.js';
23
+ import { CapError, contentCaps, daySpent, genModel, hasContentModelKey, isContentPipelineEnabled, isContentStrict, SpendGuard } from './content-llm.js';
24
24
  import { makeScrubber } from './content-redact.js';
25
25
  import { CONTENT_DIR, isPieceSettled, periodDirName, periodStatusFor, readContentManifest, writeAtomic, writeContentManifest, } from './content-manifest.js';
26
26
  import { buildBriefs, loadOwner, planPieces } from './content-brief.js';
@@ -160,8 +160,7 @@ export async function runContentStep(o) {
160
160
  try {
161
161
  if (!isContentPipelineEnabled())
162
162
  return { ...res, status: 'disabled' };
163
- const apiKey = (process.env.OPENROUTER_API_KEY || '').trim();
164
- if (!apiKey)
163
+ if (!hasContentModelKey())
165
164
  return { ...res, status: 'no-key' };
166
165
  const db = resolveSessionDb(o.sessionId, o.projectDir, o.cwd);
167
166
  if (!db)
@@ -189,7 +188,7 @@ export async function runContentStep(o) {
189
188
  manifest.periods[key] = entry;
190
189
  const caps = contentCaps();
191
190
  const g = (guard = new SpendGuard(projectDir, caps, entry.costUsd, deadline));
192
- const llm = { apiKey, guard: g, scrub: sc.scrub, log };
191
+ const llm = { guard: g, scrub: sc.scrub, log };
193
192
  const save = () => {
194
193
  entry.costUsd = Number(g.periodUsd.toFixed(6));
195
194
  entry.updatedAt = new Date().toISOString();
@@ -58,6 +58,8 @@ export type IngestConfig = {
58
58
  reason: string;
59
59
  };
60
60
  export declare function resolveIngestConfig(): IngestConfig;
61
+ /** A content_ingest row key (its content_hash): sha256 of the kind and its parts, one per line. */
62
+ export declare const ingestRowKey: (kind: string, ...parts: (string | number)[]) => string;
61
63
  export declare function contentHashFor(p: Pick<IngestPage, 'sessionId' | 'startRowId' | 'markdown'>): string;
62
64
  export declare const clip: (s: string, n: number) => string;
63
65
  /** Map a page to the content_ingest payload. Never includes status/published_at/owner. */
@@ -60,6 +60,8 @@ export function resolveIngestConfig() {
60
60
  return { ok: false, reason: 'no-key' };
61
61
  return { ok: true, url, anonKey, token };
62
62
  }
63
+ /** A content_ingest row key (its content_hash): sha256 of the kind and its parts, one per line. */
64
+ export const ingestRowKey = (kind, ...parts) => createHash('sha256').update([kind, ...parts].join('\n')).digest('hex');
63
65
  export function contentHashFor(p) {
64
66
  return createHash('sha256').update(`${p.sessionId}\n${p.startRowId}\n${p.markdown}`).digest('hex');
65
67
  }