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.
Files changed (85) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +5 -4
  2. package/.claude/skills/browser-apply/candidate.example.env +4 -1
  3. package/.claude/skills/browser-apply/fill.mjs +13 -2
  4. package/.claude/skills/meetings/SKILL.md +26 -7
  5. package/.env.example +6 -0
  6. package/dist/agent-store.d.ts +6 -0
  7. package/dist/agent-store.js +36 -6
  8. package/dist/approval-policy.d.ts +99 -0
  9. package/dist/approval-policy.js +196 -0
  10. package/dist/claude-llm.d.ts +3 -2
  11. package/dist/claude-llm.js +49 -19
  12. package/dist/config.d.ts +12 -16
  13. package/dist/config.js +80 -22
  14. package/dist/content/compaction-lens-worker.d.ts +5 -0
  15. package/dist/content/compaction-lens-worker.js +78 -7
  16. package/dist/content/content-llm.d.ts +14 -3
  17. package/dist/content/content-llm.js +33 -142
  18. package/dist/content/lens-db.d.ts +16 -5
  19. package/dist/content/lens-db.js +58 -11
  20. package/dist/content/lens-ingest.d.ts +1 -0
  21. package/dist/content/lens-ingest.js +1 -1
  22. package/dist/content/lens-launch.d.ts +42 -1
  23. package/dist/content/lens-launch.js +202 -40
  24. package/dist/content/lens-library-digest.d.ts +85 -0
  25. package/dist/content/lens-library-digest.js +305 -0
  26. package/dist/content/lens-library-index.d.ts +14 -3
  27. package/dist/content/lens-library-index.js +35 -8
  28. package/dist/content/lens-library-select.d.ts +1 -1
  29. package/dist/content/lens-library-select.js +1 -1
  30. package/dist/content/lens-library-sweep.d.ts +36 -0
  31. package/dist/content/lens-library-sweep.js +331 -0
  32. package/dist/content/lens-library.d.ts +29 -0
  33. package/dist/content/lens-library.js +130 -20
  34. package/dist/content/lens-model.d.ts +4 -0
  35. package/dist/content/lens-model.js +5 -0
  36. package/dist/content/lens-paths.d.ts +72 -0
  37. package/dist/content/lens-paths.js +248 -5
  38. package/dist/content/period-run.js +2 -2
  39. package/dist/content/secret-rules.d.ts +51 -0
  40. package/dist/content/secret-rules.js +185 -0
  41. package/dist/content/transcript-sanitizer.d.ts +1 -41
  42. package/dist/content/transcript-sanitizer.js +4 -171
  43. package/dist/data-sender-auth.d.ts +43 -6
  44. package/dist/data-sender-auth.js +61 -45
  45. package/dist/env-keys.d.ts +10 -2
  46. package/dist/env-keys.js +26 -5
  47. package/dist/index.js +499 -106
  48. package/dist/phone-code.d.ts +76 -0
  49. package/dist/phone-code.js +124 -0
  50. package/dist/phone-voice-actions.d.ts +132 -0
  51. package/dist/phone-voice-actions.js +223 -0
  52. package/dist/pipeline-direct-llm.d.ts +7 -1
  53. package/dist/pipeline-direct-llm.js +12 -1
  54. package/dist/prompts/library-digest.md +11 -0
  55. package/dist/prompts.js +2 -2
  56. package/dist/pushover.d.ts +2 -1
  57. package/dist/pushover.js +7 -6
  58. package/dist/risk-tier.d.ts +14 -0
  59. package/dist/risk-tier.js +140 -0
  60. package/dist/session-store.d.ts +1 -0
  61. package/dist/session-store.js +3 -2
  62. package/dist/session-switch.d.ts +22 -7
  63. package/dist/session-switch.js +58 -24
  64. package/dist/steward-verdict.d.ts +16 -3
  65. package/dist/steward-verdict.js +37 -18
  66. package/dist/watch-gateway.js +3 -1
  67. package/package.json +1 -1
  68. package/dist/bridge-llm.d.ts +0 -22
  69. package/dist/bridge-llm.js +0 -39
  70. package/dist/codex-handler.d.ts +0 -38
  71. package/dist/codex-handler.js +0 -83
  72. package/dist/codex-llm.d.ts +0 -40
  73. package/dist/codex-llm.js +0 -144
  74. package/dist/fast-brain.d.ts +0 -176
  75. package/dist/fast-brain.js +0 -1887
  76. package/dist/index-3-2-26-legacy.d.ts +0 -1
  77. package/dist/index-3-2-26-legacy.js +0 -2233
  78. package/dist/leagcyprompts2.d.ts +0 -0
  79. package/dist/leagcyprompts2.js +0 -573
  80. package/dist/prompts-2-25-26.d.ts +0 -0
  81. package/dist/prompts-2-25-26.js +0 -518
  82. package/dist/prompts-3-2-26.d.ts +0 -78
  83. package/dist/prompts-3-2-26.js +0 -1319
  84. package/dist/summary-index.d.ts +0 -90
  85. package/dist/summary-index.js +0 -585
@@ -7,13 +7,13 @@
7
7
  * No awaits, no heavy imports (node: builtins only), never throws.
8
8
  */
9
9
  import { spawn } from 'node:child_process';
10
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
10
+ import { closeSync, existsSync, mkdirSync, openSync, writeFileSync } from 'node:fs';
11
11
  import { createRequire } from 'node:module';
12
12
  import { tmpdir } from 'node:os';
13
13
  import { dirname, join } from 'node:path';
14
14
  import { randomBytes } from 'node:crypto';
15
15
  import { fileURLToPath, pathToFileURL } from 'node:url';
16
- import { LOCK_FILE, acquireLock, findTranscriptBySessionId, releaseLock, resolveProjectDir } from './lens-paths.js';
16
+ import { LOCK_FILE, LOCK_TTL_MS, LOG_FILE, acquireLock, findTranscriptBySessionId, libraryHomeDir, readSweepStatus, releaseLock, resolveProjectDir, slugDir, sweepCoolingDown, writeLiveSessions, writeSweepStatus } from './lens-paths.js';
17
17
  /** ON by default; kill switch: OSBORN_CONTENT_LENS=0 | off | false | no. */
18
18
  export function isContentLensEnabled() {
19
19
  const v = (process.env.OSBORN_CONTENT_LENS ?? '').trim().toLowerCase();
@@ -41,24 +41,66 @@ export function resolveWorkerCommand() {
41
41
  return null;
42
42
  }
43
43
  let warnedSpawn = false;
44
+ /** The worker command, or why no worker can run (switched off, no OpenRouter key, no worker file). */
45
+ function workerOrSkip() {
46
+ if (!isContentLensEnabled())
47
+ return { status: 'disabled' };
48
+ // OpenRouter is the only model path; without a key the worker can do nothing.
49
+ if (!(process.env.OPENROUTER_API_KEY || '').trim())
50
+ return { status: 'no-key' };
51
+ return resolveWorkerCommand() ?? { status: 'no-worker' };
52
+ }
53
+ /**
54
+ * Spawn the detached worker on `argFile`. Its stderr goes to <logDir>/content-lens.log, so a
55
+ * crash before the worker's own logging (bad import, OOM) is not lost.
56
+ */
57
+ function spawnWorker(cmd, argFile, logDir, onError) {
58
+ let fd = null;
59
+ try {
60
+ if (logDir)
61
+ fd = openSync(join(logDir, LOG_FILE), 'a', 0o600);
62
+ }
63
+ catch {
64
+ fd = null;
65
+ }
66
+ try {
67
+ const child = spawn(process.execPath, [...cmd.args, argFile], {
68
+ detached: true,
69
+ stdio: ['ignore', 'ignore', fd ?? 'ignore'],
70
+ env: { ...process.env },
71
+ });
72
+ child.on('error', onError);
73
+ child.unref();
74
+ return child.pid;
75
+ }
76
+ finally {
77
+ if (fd !== null) {
78
+ try {
79
+ closeSync(fd);
80
+ }
81
+ catch {
82
+ /* ignore */
83
+ }
84
+ }
85
+ }
86
+ }
87
+ function writeArgFile(payload) {
88
+ const argFile = join(tmpdir(), `osborn-lens-${process.pid}-${randomBytes(6).toString('hex')}.json`);
89
+ writeFileSync(argFile, JSON.stringify(payload), { mode: 0o600, flag: 'wx' });
90
+ return argFile;
91
+ }
44
92
  /** Fire-and-forget. Returns synchronously; the worker is never awaited. */
45
93
  export function launchCompactionLens(payload) {
46
94
  let projectDir = null;
47
95
  let lockHeld = false;
48
96
  try {
49
- if (!isContentLensEnabled())
50
- return { status: 'disabled' };
51
- // OpenRouter is the only model path; without a key the worker can do nothing.
52
- if (!(process.env.OPENROUTER_API_KEY || '').trim())
53
- return { status: 'no-key' };
54
- const cmd = resolveWorkerCommand();
55
- if (!cmd)
56
- return { status: 'no-worker' };
57
- projectDir = resolveProjectDir(payload.transcriptPath, payload.cwd);
58
- if (!projectDir) {
59
- const t = findTranscriptBySessionId(payload.sessionId);
60
- projectDir = t ? dirname(t) : null;
61
- }
97
+ const cmd = workerOrSkip();
98
+ if ('status' in cmd)
99
+ return cmd;
100
+ // The session's own transcript decides the project (session-end launches pass none): a cwd
101
+ // that slugs to another project would lock the wrong one and let two workers race (#272).
102
+ const transcriptPath = payload.transcriptPath ?? findTranscriptBySessionId(payload.sessionId, payload.cwd ? slugDir(payload.cwd) : null) ?? undefined;
103
+ projectDir = resolveProjectDir(transcriptPath, payload.cwd);
62
104
  if (!projectDir)
63
105
  return { status: 'unlockable', projectDir: null };
64
106
  // mkdir then lock; if the dir can't be created or locked, skip the launch entirely
@@ -73,31 +115,24 @@ export function launchCompactionLens(payload) {
73
115
  return existsSync(join(projectDir, LOCK_FILE)) ? { status: 'locked', projectDir } : { status: 'unlockable', projectDir };
74
116
  }
75
117
  lockHeld = true;
76
- const argFile = join(tmpdir(), `osborn-lens-${process.pid}-${randomBytes(6).toString('hex')}.json`);
77
- writeFileSync(argFile, JSON.stringify({
118
+ const argFile = writeArgFile({
78
119
  sessionId: payload.sessionId,
79
- transcriptPath: payload.transcriptPath,
120
+ transcriptPath,
80
121
  cwd: payload.cwd,
81
122
  skipLens: !!payload.skipLens,
82
123
  lockDir: lockHeld ? projectDir : null,
83
- }), { mode: 0o600, flag: 'wx' });
84
- {
85
- const child = spawn(process.execPath, [...cmd.args, argFile], {
86
- detached: true,
87
- stdio: 'ignore',
88
- env: { ...process.env },
89
- });
90
- child.on('error', err => {
91
- if (lockHeld && projectDir)
92
- releaseLock(projectDir);
93
- if (!warnedSpawn) {
94
- warnedSpawn = true;
95
- console.error('⚠️ content-lens: worker spawn failed:', err?.message);
96
- }
97
- });
98
- child.unref();
99
- return { status: 'spawned', pid: child.pid, projectDir, worker: cmd.worker };
100
- }
124
+ ...(payload.sweep ? { sweep: payload.sweep } : {}),
125
+ });
126
+ const lockDir = projectDir;
127
+ const pid = spawnWorker(cmd, argFile, projectDir, err => {
128
+ if (lockHeld && lockDir)
129
+ releaseLock(lockDir);
130
+ if (!warnedSpawn) {
131
+ warnedSpawn = true;
132
+ console.error('⚠️ content-lens: worker spawn failed:', err?.message);
133
+ }
134
+ });
135
+ return { status: 'spawned', pid, projectDir, worker: cmd.worker };
101
136
  }
102
137
  catch (err) {
103
138
  if (lockHeld && projectDir)
@@ -111,12 +146,139 @@ export function launchCompactionLens(payload) {
111
146
  }
112
147
  }
113
148
  let lastRun = null;
149
+ // The last launch that actually spawned a worker: a later locked / no-key attempt does not erase it (#270).
150
+ let lastSpawned = null;
114
151
  export const lastLibraryRun = () => lastRun;
115
- export function launchLibraryOnSessionEnd(sessionId, cwd, reason) {
152
+ /** Sessions still running on this machine (set by the agent); retries and sweeps never touch them. */
153
+ let liveSessions = () => [];
154
+ let liveWriter = null;
155
+ /** Also keeps <osb-library>/live-sessions.json current (every 30s, written only on change), so a running sweep sees sessions that go live. */
156
+ export function setLibraryLiveSessions(fn) {
157
+ liveSessions = fn;
158
+ const write = () => {
159
+ try {
160
+ writeLiveSessions(liveSessions());
161
+ }
162
+ catch {
163
+ /* best-effort */
164
+ }
165
+ };
166
+ write();
167
+ if (!liveWriter) {
168
+ liveWriter = setInterval(write, 30_000);
169
+ liveWriter.unref?.();
170
+ }
171
+ }
172
+ /** A session end that found its project locked is retried after the lock can have expired (#268). */
173
+ export const sessionEndRetry = { delayMs: LOCK_TTL_MS + 60_000, max: 3 };
174
+ const retries = new Map();
175
+ /**
176
+ * `live` = sessions still running on this machine (never swept). The worker writes this
177
+ * session's page, then runs the catch-up sweep. When another worker holds this project's
178
+ * lock, a standalone sweep is launched for the other sessions, and this launch is retried
179
+ * (up to sessionEndRetry.max times) unless the session is live again by then.
180
+ */
181
+ export function launchLibraryOnSessionEnd(sessionId, cwd, reason, live = liveSessions(), attempt = 0) {
116
182
  if (!sessionId)
117
183
  return null;
118
- const r = launchCompactionLens({ sessionId, cwd, skipLens: true });
119
- lastRun = { at: new Date().toISOString(), session: sessionId.slice(0, 8), reason, status: r.status };
120
- console.log(`📚 library on session end (${reason}): ${lastRun.session} → ${r.status}`);
184
+ const exclude = live.filter(id => id && id !== sessionId);
185
+ const r = launchCompactionLens({ sessionId, cwd, skipLens: true, sweep: { exclude, trigger: `session-end:${reason}` } });
186
+ lastRun = { at: new Date().toISOString(), session: sessionId.slice(0, 8), reason, status: r.status, ...(attempt ? { attempt } : {}) };
187
+ console.log(`📚 library on session end (${reason}${attempt ? `, retry ${attempt}` : ''}): ${lastRun.session} → ${r.status}`);
188
+ if (r.status === 'spawned')
189
+ lastSpawned = lastRun;
190
+ if (r.status === 'locked' || r.status === 'unlockable') {
191
+ if (!attempt)
192
+ launchLibrarySweep(exclude, `session-end:${reason}`);
193
+ retryLater(`end:${sessionId}`, attempt, () => {
194
+ if (liveSessions().includes(sessionId))
195
+ return; // resumed: its next end launches again
196
+ launchLibraryOnSessionEnd(sessionId, cwd, reason, liveSessions(), attempt + 1);
197
+ });
198
+ }
121
199
  return lastRun;
122
200
  }
201
+ /** One bounded retry chain per key: run `fn` after sessionEndRetry.delayMs, while attempts < max. */
202
+ function retryLater(key, attempt, fn) {
203
+ if (attempt >= sessionEndRetry.max || retries.has(key))
204
+ return;
205
+ const timer = setTimeout(() => {
206
+ retries.delete(key);
207
+ fn();
208
+ }, sessionEndRetry.delayMs);
209
+ timer.unref?.();
210
+ retries.set(key, timer);
211
+ }
212
+ /**
213
+ * The PostCompact launch, with the same bounded retry as a session end: a compaction that finds
214
+ * its project locked (a sweep page or a session-end worker is running there) is launched again
215
+ * once the lock can have gone, instead of being dropped.
216
+ */
217
+ export function launchCompactionLensWithRetry(payload, attempt = 0) {
218
+ const r = launchCompactionLens(payload);
219
+ if (r.status === 'locked')
220
+ retryLater(`compact:${payload.sessionId}`, attempt, () => launchCompactionLensWithRetry(payload, attempt + 1));
221
+ return r;
222
+ }
223
+ /**
224
+ * Catch-up sweep (lens-library-sweep.ts) in a detached worker: every unwritten period and
225
+ * past-day digest on this machine, newest first, capped per run. The machine-wide sweep lock
226
+ * is taken here, so two sweeps never run at once; the worker inherits and releases it.
227
+ */
228
+ export function launchLibrarySweep(live, trigger) {
229
+ const home = libraryHomeDir();
230
+ let lockHeld = false;
231
+ try {
232
+ const cmd = workerOrSkip();
233
+ if ('status' in cmd)
234
+ return cmd;
235
+ mkdirSync(home, { recursive: true });
236
+ if (!acquireLock(home))
237
+ return { status: 'locked', projectDir: home };
238
+ lockHeld = true;
239
+ if (sweepCoolingDown()) {
240
+ releaseLock(home);
241
+ lockHeld = false;
242
+ return { status: 'cooldown' };
243
+ }
244
+ writeLiveSessions(live);
245
+ const argFile = writeArgFile({ sweep: { exclude: live.filter(Boolean), trigger }, sweepLockHeld: true });
246
+ const pid = spawnWorker(cmd, argFile, home, err => {
247
+ releaseLock(home);
248
+ writeSweepStatus({ status: 'error', trigger, at: new Date().toISOString(), errors: [{ kind: 'spawn', message: String(err?.message ?? err).slice(0, 160) }] }, home);
249
+ });
250
+ console.log(`📚 library sweep (${trigger}) → spawned`);
251
+ return { status: 'spawned', pid, projectDir: home, worker: cmd.worker };
252
+ }
253
+ catch (err) {
254
+ if (lockHeld)
255
+ releaseLock(home);
256
+ const msg = err instanceof Error ? err.message : String(err);
257
+ console.error('⚠️ library sweep: launch failed:', msg);
258
+ return { status: 'error', error: msg };
259
+ }
260
+ }
261
+ /**
262
+ * The /health view of the Library: the last launches, and the sweep status file (survives
263
+ * restarts). Counts, timestamps and status / error codes only: no ids, days, costs, messages
264
+ * or paths (/health is public).
265
+ */
266
+ export function librarySweepHealth() {
267
+ const s = readSweepStatus();
268
+ const launch = (r) => (r ? { at: r.at, reason: r.reason, status: r.status, ...(r.attempt ? { attempt: r.attempt } : {}) } : null);
269
+ const codes = (errs = []) => errs.reduce((n, e) => ((n[e.kind] = (n[e.kind] ?? 0) + 1), n), {});
270
+ return {
271
+ lastRun: launch(lastRun),
272
+ lastSpawned: launch(lastSpawned),
273
+ pendingRetries: retries.size,
274
+ lastStep: s?.lastStep ? { at: s.lastStep.at, status: s.lastStep.status } : null,
275
+ backlog: s?.backlog ?? null,
276
+ lastSweep: s?.at
277
+ ? {
278
+ status: s.status, trigger: s.trigger.replace(/[^a-z_:-]/gi, '').slice(0, 40), at: s.at, finishedAt: s.finishedAt ?? null,
279
+ pagesWritten: s.pagesWritten, digestsWritten: s.digestsWritten, modelCalls: s.modelCalls, capHit: !!s.capHit, errors: codes(s.errors),
280
+ }
281
+ : null,
282
+ workerError: s?.workerError ? { at: s.workerError.at, kind: s.workerError.kind } : null,
283
+ };
284
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * lens-library-digest.ts — the DAILY DIGEST of short chats.
3
+ *
4
+ * A stretch of conversation that spans less than the period minimum (1h by default) never
5
+ * becomes a period page. The catch-up sweep (lens-library-sweep.ts) gathers those short chats
6
+ * from every session on the machine, groups them by LOCAL calendar day, and writes one page per
7
+ * day that is over (never today, while chats can still be added):
8
+ * <claudeDir>/osb-library/digests/<YYYY-MM-DD>-digest.md (+ INDEX.md, .digest-manifest.json)
9
+ * Each chat gets a title and a one-to-two line summary from ONE model call per day, through the
10
+ * period map's model path (lens-model: OpenRouter, reasoning off, hard $ cap per call). Input
11
+ * rows go through the same strip + secret redaction as the period map (loadConversationRows)
12
+ * plus each project's client redactor; the page is scrubbed again before it is written.
13
+ *
14
+ * Idempotent: .digest-manifest.json records which chats each day holds. A day is rewritten (in
15
+ * place, same file and same cloud row) only when a chat it does not hold turns up for it.
16
+ * Ingest goes through the shared content_ingest seam (postContentIngest) with a stable
17
+ * per-day content hash, so an update replaces the day's draft instead of adding a second one.
18
+ */
19
+ import { type SessionStore } from './lens-db.js';
20
+ import { type IngestOptions, type IngestState } from './lens-ingest.js';
21
+ import type { LibraryPeriod } from './lens-library-select.js';
22
+ /** Hard cap for one day's call. */
23
+ export declare const DIGEST_CAP_USD = 0.25;
24
+ export type ShortChat = SessionStore & {
25
+ period: LibraryPeriod;
26
+ };
27
+ export interface DigestEntry {
28
+ day: string;
29
+ file: string;
30
+ /** chatKey() of every chat the page holds. */
31
+ chats: string[];
32
+ /** 'empty' = every chat that day was injected context only (nothing to summarise): no page, no call. */
33
+ status: 'ok' | 'error' | 'dry' | 'empty';
34
+ failures?: number;
35
+ /** Chats of the last failed attempt. */
36
+ tried?: string[];
37
+ costUsd: number;
38
+ errors: string[];
39
+ updatedAt: string;
40
+ /** Its contentHash is the page body's sha256, so an updated page is sent again. */
41
+ ingest?: IngestState;
42
+ }
43
+ export interface DigestManifest {
44
+ version: 1;
45
+ days: Record<string, DigestEntry>;
46
+ }
47
+ export type DigestStatus = 'written' | 'dry' | 'empty' | 'model-error' | 'failed';
48
+ export interface DigestResult {
49
+ status: DigestStatus;
50
+ page: string | null;
51
+ costUsd: number;
52
+ errors: string[];
53
+ }
54
+ /** YYYY-MM-DD of `ts` in the machine's local time zone (TZ). */
55
+ export declare function localDay(ts: string | number): string;
56
+ export declare const chatKey: (c: Pick<ShortChat, "sessionId" | "period">) => string;
57
+ export declare const digestDir: (home?: string) => string;
58
+ export declare function readDigestManifest(dir: string): DigestManifest;
59
+ export declare function writeDigestManifest(dir: string, m: DigestManifest): void;
60
+ /**
61
+ * Which past days need a (re)write: never digested, holding a chat the page does not, or holding
62
+ * a chat that is gone (`stale`: it grew into a written period page, or into a longer chat).
63
+ * Chats that touch today wait (they are returned as `today`). Each pending day comes with ALL
64
+ * its current chats, so an updated page is complete. `emptied` = digested days none of whose
65
+ * chats is left: their page should go. Pure.
66
+ */
67
+ export declare function pendingDigestDays(chats: ShortChat[], m: DigestManifest, now?: number, stale?: Set<string>): {
68
+ days: Map<string, ShortChat[]>;
69
+ today: ShortChat[];
70
+ emptied: string[];
71
+ };
72
+ /** Retry pass for written digests whose ingest never landed (no model call). Returns true if the manifest changed. */
73
+ export declare function ingestPendingDigests(dir: string, m: DigestManifest, o?: IngestOptions): Promise<boolean>;
74
+ export interface DigestOptions {
75
+ day: string;
76
+ chats: ShortChat[];
77
+ dir?: string;
78
+ /** No model call: titles from each chat's first line, no summaries (manifest status "dry"). */
79
+ dry?: boolean;
80
+ log?: (m: string) => void;
81
+ }
82
+ /** Write (or rewrite) one day's digest. One model call at most. Never throws. */
83
+ export declare function runDigestDay(o: DigestOptions): Promise<DigestResult>;
84
+ /** Remove a digested day none of whose chats is left (they grew into period pages). No model call. */
85
+ export declare function removeDigestDay(dir: string, day: string, o?: IngestOptions): Promise<void>;