osborn 0.9.271 → 0.9.275

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 (61) hide show
  1. package/.claude/skills/browser-apply/SKILL.md +82 -30
  2. package/.claude/skills/browser-apply/candidate.example.env +16 -0
  3. package/.claude/skills/browser-apply/fill.mjs +294 -0
  4. package/Dockerfile +1 -1
  5. package/dist/claude-auth.d.ts +85 -6
  6. package/dist/claude-auth.js +202 -22
  7. package/dist/claude-llm.d.ts +13 -0
  8. package/dist/claude-llm.js +171 -25
  9. package/dist/compaction-log.d.ts +67 -0
  10. package/dist/compaction-log.js +195 -0
  11. package/dist/config.d.ts +18 -0
  12. package/dist/config.js +122 -65
  13. package/dist/content/transcript-sanitizer.d.ts +20 -6
  14. package/dist/content/transcript-sanitizer.js +66 -11
  15. package/dist/data-sender-auth.d.ts +90 -0
  16. package/dist/data-sender-auth.js +158 -0
  17. package/dist/duck.d.ts +8 -0
  18. package/dist/duck.js +59 -0
  19. package/dist/env-keys.js +11 -0
  20. package/dist/index.js +493 -97
  21. package/dist/lib/safe-artifact-path.d.ts +17 -0
  22. package/dist/lib/safe-artifact-path.js +129 -0
  23. package/dist/meeting-addressing.d.ts +176 -0
  24. package/dist/meeting-addressing.js +288 -0
  25. package/dist/pipeline-direct-llm.d.ts +52 -1
  26. package/dist/pipeline-direct-llm.js +206 -61
  27. package/dist/prompts/direct-mode-fallback.md +1 -1
  28. package/dist/prompts/direct-mode-research.md +2 -2
  29. package/dist/prompts.d.ts +1 -1
  30. package/dist/prompts.js +3 -3
  31. package/dist/pushover.d.ts +77 -0
  32. package/dist/pushover.js +276 -0
  33. package/dist/recall-client.js +21 -2
  34. package/dist/session-store.d.ts +15 -5
  35. package/dist/session-store.js +37 -10
  36. package/dist/transcript-wiring.d.ts +121 -0
  37. package/dist/transcript-wiring.js +252 -0
  38. package/dist/voice-io.d.ts +0 -9
  39. package/dist/voice-io.js +5 -19
  40. package/dist/watch-gateway.d.ts +38 -0
  41. package/dist/watch-gateway.js +205 -0
  42. package/package.json +1 -1
  43. package/scripts/review.ts +1 -1
  44. package/dist/bridge-llm.d.ts +0 -22
  45. package/dist/bridge-llm.js +0 -39
  46. package/dist/codex-handler.d.ts +0 -38
  47. package/dist/codex-handler.js +0 -83
  48. package/dist/codex-llm.d.ts +0 -40
  49. package/dist/codex-llm.js +0 -144
  50. package/dist/fast-brain.d.ts +0 -176
  51. package/dist/fast-brain.js +0 -1887
  52. package/dist/index-3-2-26-legacy.d.ts +0 -1
  53. package/dist/index-3-2-26-legacy.js +0 -2233
  54. package/dist/leagcyprompts2.d.ts +0 -0
  55. package/dist/leagcyprompts2.js +0 -573
  56. package/dist/prompts-2-25-26.d.ts +0 -0
  57. package/dist/prompts-2-25-26.js +0 -518
  58. package/dist/prompts-3-2-26.d.ts +0 -78
  59. package/dist/prompts-3-2-26.js +0 -1319
  60. package/dist/summary-index.d.ts +0 -90
  61. package/dist/summary-index.js +0 -585
@@ -7,7 +7,7 @@ description: Interactively automate Workday and other multi-step JS-heavy job ap
7
7
 
8
8
  Automate Workday job applications interactively, one step at a time. Each step takes a screenshot, confirms what's on screen, fills the current page, and waits before proceeding.
9
9
 
10
- **This skill uses the Playwright MCP tools** (`mcp__playwright__browser_*`) for direct browser control — no scripts needed.
10
+ **This skill uses the Playwright MCP tools** (`mcp__playwright__browser_*`) for direct browser control. The only script is the `fill.mjs` helper, used for secret fields (see "One-time setup").
11
11
 
12
12
  ## When to Use
13
13
  - Any Workday ATS application (`*.wd1.myworkdayjobs.com`)
@@ -27,16 +27,42 @@ Do NOT write a monolithic automation script. Instead:
27
27
 
28
28
  This approach catches rendering issues, unexpected fields, and errors before they cascade.
29
29
 
30
+ ## One-time setup (user does this once per machine)
31
+
32
+ Secret fields (email, password, phone, address) are filled by the `fill.mjs` helper, not by the MCP tools. The helper and the Playwright MCP must drive the SAME browser, which means both attach to one Chrome over CDP on loopback.
33
+
34
+ 1. Secret file. The user creates it and types the values in their own editor (never ask for the values in chat, never write them yourself):
35
+ ```bash
36
+ mkdir -p ~/.osborn
37
+ cp ~/.claude/skills/browser-apply/candidate.example.env ~/.osborn/candidate.env
38
+ chmod 600 ~/.osborn/candidate.env
39
+ ```
40
+ The helper refuses the file if it is a symlink, not owned by the current user, or not mode 600.
41
+ 2. Playwright for the helper: `npm i -g playwright-core` (no browser download needed; it only attaches over CDP).
42
+ 3. One headed browser with CDP on loopback:
43
+ ```bash
44
+ google-chrome --remote-debugging-address=127.0.0.1 --remote-debugging-port=9222 \
45
+ --user-data-dir="$HOME/.osborn/apply-profile"
46
+ ```
47
+ 4. Point the Playwright MCP server at that browser with `--cdp-endpoint http://127.0.0.1:9222` (a `@playwright/mcp` flag) in the user's MCP config. Osborn's built-in Playwright catalog entry does not pass this flag yet; without it the MCP launches its own browser and the helper cannot see it.
48
+ 5. The helper reads NO environment variables and has no path or URL options. Its only config is the optional `CANDIDATE_CDP_URL=` line inside `~/.osborn/candidate.env` (default `http://127.0.0.1:9222`; non-loopback hosts are refused). Only the user edits that file; the model cannot change it.
49
+ 6. There is no list of approved job sites. Every fill names ONE exact host that the user confirms out loud just before it (see "Filling secret fields").
50
+ 7. Verify: `node ~/.claude/skills/browser-apply/fill.mjs check` should end with `cdp: reachable`.
51
+
30
52
  ## Step-by-Step Execution Pattern
31
53
 
32
- ### Step 0 — Open the browser
54
+ ### Step 0 — Check the helper, then open the browser
55
+ Run `node ~/.claude/skills/browser-apply/fill.mjs check` first. It prints variable names and `cdp: reachable` or `cdp: unreachable`, never values.
56
+ - File missing / refused: point the user at "One-time setup" step 1 and wait.
57
+ - `cdp: unreachable`: you can still navigate and fill the non-secret fields with the MCP tools, but for every secret field (email, password, phone, address) ask the user to type it into the browser themselves.
58
+
33
59
  Use: `mcp__playwright__browser_navigate` with the applyManually URL
34
60
 
35
61
  Then: `mcp__playwright__browser_take_screenshot` — show the user what loaded
36
62
 
37
63
  ### Step 1 — Create Account / Sign In
38
64
  Take a snapshot with `mcp__playwright__browser_snapshot` to see element refs.
39
- Fill fields using `mcp__playwright__browser_fill_form` or individual `mcp__playwright__browser_type` calls.
65
+ Ask the user to confirm the host, then fill the email and password fields with the helper (see "Filling secret fields" below), never by typing values through `mcp__playwright__browser_type` / `browser_fill_form`.
40
66
  Screenshot to confirm. Then ask user before clicking Create Account / Sign In.
41
67
 
42
68
  ### Step 2 — Start Application
@@ -48,8 +74,9 @@ Screenshot after.
48
74
  Snapshot → fill each field → screenshot → ask user before clicking Next.
49
75
 
50
76
  Fields to fill:
51
- - First Name, Last Name, Phone
52
- - Address, City, State (dropdown), Zip
77
+ - First Name, Last Name, Phone (via the helper)
78
+ - Address, City, Zip (via the helper)
79
+ - State (dropdown): ask the user which option to pick; do not read `$CANDIDATE_STATE` out
53
80
  - Work authorization: Yes
54
81
  - Sponsorship: No
55
82
 
@@ -73,13 +100,19 @@ Screenshot the full review page. Confirm with user before clicking Submit.
73
100
  ### Step 9 — Confirm submission
74
101
  Screenshot the confirmation dialog. Save it.
75
102
 
76
- ## Candidate Data (Osborn Ojure)
103
+ ## Candidate Data
77
104
 
78
- - Email: osbornojure@gmail.com
79
- - Password: Workday2026!
80
- - First: Osborn, Last: Ojure
81
- - Phone: 3127185561
82
- - Address: 1234 N Michigan Ave, Chicago, IL 60601
105
+ Personal values are NOT stored in this skill. They live in a local secret file that the model never reads:
106
+ `~/.osborn/candidate.env` (fixed path), `chmod 600`. Template: `candidate.example.env` next to this file.
107
+
108
+ | Value | Env name |
109
+ |---|---|
110
+ | Email | `$CANDIDATE_EMAIL` |
111
+ | Password | `$CANDIDATE_PASSWORD` |
112
+ | First / Last name | `$CANDIDATE_FIRST_NAME` / `$CANDIDATE_LAST_NAME` |
113
+ | Phone | `$CANDIDATE_PHONE` |
114
+ | Address line 1 | `$CANDIDATE_ADDRESS_LINE1` |
115
+ | City / State / Zip | `$CANDIDATE_CITY` / `$CANDIDATE_STATE` / `$CANDIDATE_ZIP` |
83
116
 
84
117
  Jobs:
85
118
  1. Meta API Consultant at Prehype / Audos — April 2024 to Present
@@ -89,23 +122,46 @@ Education:
89
122
  1. A.S. Information Systems
90
123
  2. B.S. Psychology
91
124
 
125
+ ### Filling secret fields
126
+ Use the helper `fill.mjs` next to this SKILL.md (normally `~/.claude/skills/browser-apply/fill.mjs`). It reads `~/.osborn/candidate.env` itself (regular file, owned by you, mode 600) and attaches to the loopback CDP browser from "One-time setup". It fills only on an https page whose host EXACTLY equals `--confirm-host`. Inside the page, right before each field, it checks again that the field's own frame is https on that host. The password goes only into an `<input type="password">`. It prints `about to fill NAME on HOST` before each field and `filled NAME -> selector` after, never a value.
127
+
128
+ Before EVERY fill command:
129
+ 1. Read the exact hostname of the current page (from the snapshot or URL), e.g. `acme.wd1.myworkdayjobs.com`.
130
+ 2. Ask the user out loud: "Fill your password on acme.wd1.myworkdayjobs.com?" (name the fields you are about to fill). Wait for a clear yes. No yes, no fill.
131
+ 3. Run the command with that same host. The Bash call goes through Osborn's permission prompt, so the user sees the host in the command before it runs.
132
+
133
+ ```bash
134
+ node ~/.claude/skills/browser-apply/fill.mjs check
135
+ node ~/.claude/skills/browser-apply/fill.mjs fill --confirm-host acme.wd1.myworkdayjobs.com \
136
+ CANDIDATE_EMAIL 'input[type="email"]' \
137
+ CANDIDATE_PASSWORD 'input[type="password"]'
138
+ ```
139
+
140
+ Rules:
141
+ - NEVER `cat`, `less`, `head`, `echo`, `printenv`, `env`, `grep`, `Read` or otherwise print the secret file or the `CANDIDATE_*` variables.
142
+ - NEVER pass a value to an MCP browser tool or put one in a command line; pass env NAMES only.
143
+ - If `check` reports the file missing or too open, tell the user to create it from `candidate.example.env` and run `chmod 600`; do not create it with values yourself.
144
+ - If `check` says `cdp: unreachable`, or `fill` refuses (no browser, wrong host, wrong field type), do not work around it: ask the user to type the secret fields themselves.
145
+ - Never edit `~/.osborn/candidate.env`. Only the user changes its values or its `CANDIDATE_CDP_URL` line.
146
+ - Never reuse an earlier confirmation for a different host or a later fill; ask again each time.
147
+
92
148
  ## Workday data-automation-id Selector Reference
93
149
 
94
- | Field | Selector |
95
- |---|---|
96
- | Email | `input[type="email"]` |
97
- | Password | `input[type="password"]` |
98
- | First name | `[data-automation-id="legalNameSection_firstName"]` |
99
- | Last name | `[data-automation-id="legalNameSection_lastName"]` |
100
- | Phone | `[data-automation-id="phone-number"]` |
101
- | Address | `[data-automation-id="addressSection_addressLine1"]` |
102
- | City | `[data-automation-id="addressSection_city"]` |
103
- | Zip | `[data-automation-id="addressSection_postalCode"]` |
104
- | Job title | `[data-automation-id="jobTitle"]` |
105
- | Company | `[data-automation-id="company"]` |
106
- | Description | `[data-automation-id="description"]` |
107
- | Next button | `[data-automation-id="bottom-navigation-next-btn"]` |
108
- | Create Account | `[data-automation-id="click_filter"][aria-label="Create Account"]` |
150
+ | Field | Selector | Value from |
151
+ |---|---|---|
152
+ | Email | `input[type="email"]` | `CANDIDATE_EMAIL` (helper) |
153
+ | Password | `input[type="password"]` | `CANDIDATE_PASSWORD` (helper) |
154
+ | First name | `[data-automation-id="legalNameSection_firstName"]` | `CANDIDATE_FIRST_NAME` (helper) |
155
+ | Last name | `[data-automation-id="legalNameSection_lastName"]` | `CANDIDATE_LAST_NAME` (helper) |
156
+ | Phone | `[data-automation-id="phone-number"]` | `CANDIDATE_PHONE` (helper) |
157
+ | Address | `[data-automation-id="addressSection_addressLine1"]` | `CANDIDATE_ADDRESS_LINE1` (helper) |
158
+ | City | `[data-automation-id="addressSection_city"]` | `CANDIDATE_CITY` (helper) |
159
+ | Zip | `[data-automation-id="addressSection_postalCode"]` | `CANDIDATE_ZIP` (helper) |
160
+ | Job title | `[data-automation-id="jobTitle"]` | Jobs list above |
161
+ | Company | `[data-automation-id="company"]` | Jobs list above |
162
+ | Description | `[data-automation-id="description"]` | Jobs list above |
163
+ | Next button | `[data-automation-id="bottom-navigation-next-btn"]` | - |
164
+ | Create Account | `[data-automation-id="click_filter"][aria-label="Create Account"]` | - |
109
165
 
110
166
  ## Critical Rules
111
167
  - headless: false always (Workday renders blank in headless)
@@ -113,7 +169,3 @@ Education:
113
169
  - After "You already applied to this job" error — that confirms a previous submission worked
114
170
  - Use `{ force: true }` on Workday buttons — overlay click filters block normal clicks
115
171
  - Always wait for networkidle or waitForSelector after navigation before interacting
116
-
117
- ## Playwright Install Location
118
- Run scripts from: `/Users/newupgrade/Desktop/Developer/osborn/frontend`
119
- (playwright is in `node_modules` there)
@@ -0,0 +1,16 @@
1
+ # browser-apply candidate data. PLACEHOLDERS ONLY: never commit real values.
2
+ # Copy to ~/.osborn/candidate.env (fixed path), fill it in yourself, then: chmod 600 ~/.osborn/candidate.env
3
+ # The fill.mjs helper refuses the file if it is a symlink, not yours, or readable by group or other.
4
+ # It reads no environment variables; this file is its only input.
5
+ CANDIDATE_EMAIL=you@example.com
6
+ CANDIDATE_PASSWORD=YOUR_ATS_ACCOUNT_PASSWORD
7
+ CANDIDATE_FIRST_NAME=YOUR_FIRST_NAME
8
+ CANDIDATE_LAST_NAME=YOUR_LAST_NAME
9
+ CANDIDATE_PHONE=YOUR_PHONE
10
+ CANDIDATE_ADDRESS_LINE1=YOUR_STREET_ADDRESS
11
+ CANDIDATE_CITY=YOUR_CITY
12
+ CANDIDATE_STATE=YOUR_STATE
13
+ CANDIDATE_ZIP=YOUR_ZIP
14
+
15
+ # Optional: loopback CDP endpoint of the shared browser (non-loopback hosts are refused).
16
+ # CANDIDATE_CDP_URL=http://127.0.0.1:9222
@@ -0,0 +1,294 @@
1
+ #!/usr/bin/env node
2
+ // browser-apply secret filler. Reads candidate values from a mode-600 file and types them into
3
+ // the browser in THIS process, so the values never appear in tool output or model context.
4
+ //
5
+ // node fill.mjs check
6
+ // Verifies the secret file (regular file, not a symlink, owned by you, chmod 600), prints
7
+ // variable NAMES only, and whether the loopback CDP browser is reachable.
8
+ // node fill.mjs fill --confirm-host HOST NAME SELECTOR [NAME SELECTOR ...]
9
+ // Attaches to the already-open browser over loopback CDP and fills each SELECTOR with the
10
+ // value of NAME on the most recent https page whose host is EXACTLY HOST. HOST is the host the
11
+ // user just confirmed out loud; it is visible in the command the user approves.
12
+ // Example: node fill.mjs fill --confirm-host acme.wd1.myworkdayjobs.com CANDIDATE_EMAIL 'input[type="email"]'
13
+ //
14
+ // Config comes from ONE place the model cannot redirect: the fixed file
15
+ // <passwd home>/.osborn/candidate.env (home from the OS user database, not $HOME). The helper reads
16
+ // NO environment variables and has no path or URL options. Besides the CANDIDATE_* values, that file
17
+ // may set CANDIDATE_CDP_URL (loopback only, default http://127.0.0.1:9222), edited only by the user.
18
+ // Each value is written inside the page in one synchronous step that first checks the element type
19
+ // (password only into <input type=password>) and that the element's own frame is https on HOST.
20
+ // The helper never prints a value.
21
+ import { execFileSync } from 'node:child_process'
22
+ import { lstatSync, readFileSync } from 'node:fs'
23
+ import { createRequire } from 'node:module'
24
+ import { userInfo } from 'node:os'
25
+ import { join } from 'node:path'
26
+ import { pathToFileURL } from 'node:url'
27
+
28
+ export const EXPECTED_VARS = [
29
+ 'CANDIDATE_EMAIL',
30
+ 'CANDIDATE_PASSWORD',
31
+ 'CANDIDATE_FIRST_NAME',
32
+ 'CANDIDATE_LAST_NAME',
33
+ 'CANDIDATE_PHONE',
34
+ 'CANDIDATE_ADDRESS_LINE1',
35
+ 'CANDIDATE_CITY',
36
+ 'CANDIDATE_STATE',
37
+ 'CANDIDATE_ZIP',
38
+ ]
39
+ export const CONFIG_KEYS = ['CANDIDATE_CDP_URL']
40
+ export const DEFAULT_CDP_URL = 'http://127.0.0.1:9222'
41
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]'])
42
+
43
+ /** Fixed secret-file path. Uses the passwd home directory so $HOME cannot redirect it. */
44
+ export function secretPath() {
45
+ return join(userInfo().homedir, '.osborn', 'candidate.env')
46
+ }
47
+
48
+ export function parseEnv(text) {
49
+ const out = {}
50
+ for (const raw of text.split(/\r?\n/)) {
51
+ const line = raw.trim()
52
+ if (!line || line.startsWith('#')) continue
53
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line)
54
+ if (!m) continue
55
+ let v = m[2]
56
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1)
57
+ out[m[1]] = v
58
+ }
59
+ return out
60
+ }
61
+
62
+ /** Reads and validates a secret file. The CLI only ever calls this with secretPath(). */
63
+ export function loadCandidateEnv(path) {
64
+ let st
65
+ try { st = lstatSync(path) } catch { throw new Error(`secret file not found: ${path} (copy candidate.example.env there and chmod 600)`) }
66
+ if (st.isSymbolicLink()) throw new Error(`refusing to read ${path}: it is a symlink; use a regular file`)
67
+ if (!st.isFile()) throw new Error(`secret file is not a regular file: ${path}`)
68
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
69
+ throw new Error(`refusing to read ${path}: owned by uid ${st.uid}, not the current user`)
70
+ }
71
+ if ((st.mode & 0o077) !== 0) {
72
+ throw new Error(`refusing to read ${path}: mode ${(st.mode & 0o777).toString(8)} is too open, run: chmod 600 ${path}`)
73
+ }
74
+ return parseEnv(readFileSync(path, 'utf8'))
75
+ }
76
+
77
+ /** Validates a CDP URL (from the secret file or the default). Throws unless loopback http(s)/ws(s). */
78
+ export function resolveCdpUrl(raw) {
79
+ let u
80
+ try { u = new URL(raw || DEFAULT_CDP_URL) } catch { throw new Error('CANDIDATE_CDP_URL is not a valid URL') }
81
+ if (!['http:', 'https:', 'ws:', 'wss:'].includes(u.protocol)) throw new Error('CANDIDATE_CDP_URL must be http(s) or ws(s)')
82
+ if (u.username || u.password) throw new Error('CANDIDATE_CDP_URL must not carry credentials')
83
+ if (!LOOPBACK_HOSTS.has(u.hostname)) throw new Error('refusing CDP URL: host is not loopback (127.0.0.1, localhost or ::1)')
84
+ return u.href.replace(/\/$/, '')
85
+ }
86
+
87
+ /** CDP URL comes only from the validated secret file, falling back to the hardcoded default. */
88
+ export function cdpFrom(fileEnv) {
89
+ return resolveCdpUrl(fileEnv.CANDIDATE_CDP_URL)
90
+ }
91
+
92
+ /** Validates the --confirm-host value: a bare hostname (no scheme, port, path or wildcard). */
93
+ export function normalizeConfirmHost(raw) {
94
+ const h = String(raw ?? '').trim().toLowerCase()
95
+ if (!h) throw new Error('missing --confirm-host HOST (ask the user to confirm the site first)')
96
+ if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(h)) {
97
+ throw new Error('--confirm-host must be a bare hostname like acme.wd1.myworkdayjobs.com')
98
+ }
99
+ return h
100
+ }
101
+
102
+ /** True only for an https URL whose hostname is EXACTLY host. */
103
+ export function hostMatches(pageUrl, host) {
104
+ let u
105
+ try { u = new URL(pageUrl) } catch { return false }
106
+ return u.protocol === 'https:' && u.hostname.toLowerCase() === host
107
+ }
108
+
109
+ /**
110
+ * Decides whether value NAME may be written into an element, from facts gathered in the element's
111
+ * own frame. Pure and self-contained (no outer references): it is also serialized into the page.
112
+ * facts: { tagName, type, href } where href is el.ownerDocument.location.href.
113
+ */
114
+ export function fieldVerdict(name, facts, host) {
115
+ let u
116
+ try { u = new URL(facts.href) } catch { return { ok: false, reason: 'frame has no valid URL' } }
117
+ if (u.protocol !== 'https:') return { ok: false, reason: 'frame is not https' }
118
+ if (u.hostname.toLowerCase() !== host) return { ok: false, reason: 'frame host is not the confirmed host' }
119
+ const tag = String(facts.tagName || '').toUpperCase()
120
+ const type = String(facts.type || '').toLowerCase()
121
+ const allow = {
122
+ CANDIDATE_PASSWORD: ['password'],
123
+ CANDIDATE_EMAIL: ['email', 'text'],
124
+ CANDIDATE_PHONE: ['tel', 'text'],
125
+ CANDIDATE_ZIP: ['text', 'number'],
126
+ }
127
+ const types = allow[name] || ['text']
128
+ if (tag === 'TEXTAREA' && name !== 'CANDIDATE_PASSWORD' && name !== 'CANDIDATE_EMAIL') return { ok: true }
129
+ if (tag !== 'INPUT') return { ok: false, reason: `target is <${tag.toLowerCase() || '?'}>, not <input>` }
130
+ if (!types.includes(type)) return { ok: false, reason: `${name} may only go into input type ${types.join('|')}, target is type ${type || '?'}` }
131
+ return { ok: true }
132
+ }
133
+
134
+ // Runs inside the page via locator.evaluate: gathers facts from the element's own frame, applies
135
+ // fieldVerdict, and only then sets the value and fires input/change. One synchronous call, so the
136
+ // frame cannot navigate between the check and the write.
137
+ export const IN_PAGE_FILL = new Function('el', 'arg', `
138
+ const fieldVerdict = ${fieldVerdict.toString()};
139
+ const doc = el && el.ownerDocument;
140
+ const view = doc && doc.defaultView;
141
+ const facts = {
142
+ tagName: el && el.tagName,
143
+ type: el && el.tagName === 'INPUT' ? String(el.type || '').toLowerCase() : '',
144
+ href: doc && doc.location ? String(doc.location.href) : '',
145
+ };
146
+ const v = fieldVerdict(arg.name, facts, arg.host);
147
+ if (!v.ok) return { ok: false, reason: v.reason };
148
+ const proto = el.tagName === 'TEXTAREA' ? view.HTMLTextAreaElement.prototype : view.HTMLInputElement.prototype;
149
+ const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
150
+ if (typeof el.focus === 'function') el.focus();
151
+ setter.call(el, arg.value);
152
+ el.dispatchEvent(new view.Event('input', { bubbles: true }));
153
+ el.dispatchEvent(new view.Event('change', { bubbles: true }));
154
+ return { ok: true };
155
+ `)
156
+
157
+ /** Picks the most recent https page whose host is exactly host. Throws otherwise. */
158
+ export function selectPage(pages, host) {
159
+ if (!pages.length) throw new Error('no open page in the CDP browser')
160
+ const ok = pages.filter(p => hostMatches(p.url(), host))
161
+ if (!ok.length) throw new Error(`refusing to fill: no open https page on ${host}`)
162
+ return ok.at(-1)
163
+ }
164
+
165
+ export function mask(msg, env) {
166
+ let s = String(msg)
167
+ for (const [k, v] of Object.entries(env)) {
168
+ if (!v || CONFIG_KEYS.includes(k)) continue
169
+ const forms = new Set([v, JSON.stringify(v).slice(1, -1), encodeURIComponent(v)])
170
+ for (const f of forms) {
171
+ if (!f || !s.includes(f)) continue
172
+ // Values too short to mask without mangling the message: suppress the whole message.
173
+ if (f.length < 4) return 'error (details suppressed to avoid echoing a value)'
174
+ s = s.split(f).join('***')
175
+ }
176
+ }
177
+ return s
178
+ }
179
+
180
+ /**
181
+ * Resolves the browser WebSocket endpoint ourselves and requires it to be loopback too, so a
182
+ * /json/version response cannot point Playwright at a remote host. Playwright's CDP-connected
183
+ * Browser does not expose the endpoint it used, so this is checked before connecting, and the
184
+ * validated ws:// URL is what we hand to connectOverCDP.
185
+ */
186
+ export async function resolveWsEndpoint(cdp, fetchImpl = fetch, timeoutMs = 1500) {
187
+ if (/^wss?:/.test(cdp)) return resolveCdpUrl(cdp)
188
+ let ws
189
+ try {
190
+ const r = await fetchImpl(`${cdp}/json/version`, { signal: AbortSignal.timeout(timeoutMs), redirect: 'error' })
191
+ if (!r.ok) throw new Error('bad status')
192
+ ws = (await r.json()).webSocketDebuggerUrl
193
+ } catch {
194
+ throw new Error(`no browser reachable over CDP at ${cdp}; ask the user to type the secret fields themselves`)
195
+ }
196
+ if (typeof ws !== 'string' || !/^wss?:/.test(ws)) throw new Error('CDP /json/version returned no WebSocket endpoint')
197
+ return resolveCdpUrl(ws)
198
+ }
199
+
200
+ export async function probeCdp(cdp, fetchImpl = fetch) {
201
+ try { await resolveWsEndpoint(cdp, fetchImpl); return true } catch { return false }
202
+ }
203
+
204
+ async function loadChromium() {
205
+ // ESM import() ignores NODE_PATH, so also resolve from the cwd and the global npm root.
206
+ const require = createRequire(import.meta.url)
207
+ let globalRoot = ''
208
+ try { globalRoot = execFileSync('npm', ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim() } catch { /* npm missing */ }
209
+ for (const mod of ['playwright-core', 'playwright']) {
210
+ try { const m = await import(mod); if (m.chromium) return m.chromium } catch { /* try next */ }
211
+ try {
212
+ const resolved = require.resolve(mod, { paths: [process.cwd(), globalRoot].filter(Boolean) })
213
+ const m = await import(pathToFileURL(resolved).href)
214
+ const chromium = m.chromium ?? m.default?.chromium
215
+ if (chromium) return chromium
216
+ } catch { /* try next */ }
217
+ }
218
+ throw new Error('playwright-core not installed: run `npm i -g playwright-core`')
219
+ }
220
+
221
+ export function parseFillArgs(args) {
222
+ let confirmHost
223
+ const pairs = []
224
+ for (let i = 0; i < args.length; i++) {
225
+ const a = args[i]
226
+ if (a === '--confirm-host') { confirmHost = args[++i]; continue }
227
+ if (a.startsWith('--')) throw new Error(`unknown option ${a.slice(0, 40)}`)
228
+ const selector = args[++i]
229
+ if (!selector) throw new Error(`missing selector after ${a.slice(0, 40)} (want NAME SELECTOR pairs)`)
230
+ pairs.push([a, selector])
231
+ }
232
+ const host = normalizeConfirmHost(confirmHost)
233
+ if (!pairs.length) throw new Error('nothing to fill: pass NAME SELECTOR pairs')
234
+ return { host, pairs }
235
+ }
236
+
237
+ /** fill command. fileEnv is the parsed secret file; deps are injectable for tests only. */
238
+ export async function runFill(args, fileEnv, deps = {}) {
239
+ const log = deps.log ?? console.log
240
+ const { host, pairs } = parseFillArgs(args)
241
+ for (const [name] of pairs) {
242
+ if (!/^CANDIDATE_[A-Z0-9_]+$/.test(name) || CONFIG_KEYS.includes(name)) throw new Error(`only CANDIDATE_* values may be filled: ${name.slice(0, 40)}`)
243
+ if (!fileEnv[name]) throw new Error(`${name} is not set in the secret file`)
244
+ }
245
+ // Validate the target before loading Playwright or opening any connection.
246
+ const cdp = cdpFrom(fileEnv)
247
+ const ws = await resolveWsEndpoint(cdp, deps.fetchImpl ?? fetch)
248
+ const chromium = await (deps.loadChromium ?? loadChromium)()
249
+ let browser
250
+ try { browser = await chromium.connectOverCDP(ws) } catch {
251
+ throw new Error(`no browser reachable over CDP at ${cdp}; ask the user to type the secret fields themselves`)
252
+ }
253
+ try {
254
+ const page = selectPage(browser.contexts().flatMap(c => c.pages()), host)
255
+ for (const [name, selector] of pairs) {
256
+ log(`about to fill ${name} on ${host}`)
257
+ const res = await page.locator(selector).first().evaluate(IN_PAGE_FILL, { name, value: fileEnv[name], host }, { timeout: 10_000 })
258
+ if (!res || !res.ok) throw new Error(`refusing to fill ${name} -> ${selector}: ${res?.reason ?? 'no result'}`)
259
+ log(`filled ${name} -> ${selector}`)
260
+ }
261
+ } finally {
262
+ // connectOverCDP: close() detaches this client only; the user's browser stays open.
263
+ await browser.close().catch(() => {})
264
+ }
265
+ }
266
+
267
+ /** check command output lines (names and config only, never values). */
268
+ export async function checkReport(path, fileEnv, fetchImpl = fetch) {
269
+ const set = EXPECTED_VARS.filter(k => fileEnv[k])
270
+ const missing = EXPECTED_VARS.filter(k => !fileEnv[k])
271
+ const cdp = cdpFrom(fileEnv)
272
+ const lines = [`ok: ${path} is a regular file owned by you, mode 600`, `set: ${set.join(', ') || '(none)'}`]
273
+ if (missing.length) lines.push(`missing: ${missing.join(', ')}`)
274
+ lines.push(`cdp: ${(await probeCdp(cdp, fetchImpl)) ? 'reachable' : 'unreachable'} (${cdp})`)
275
+ return lines
276
+ }
277
+
278
+ async function main() {
279
+ const [cmd, ...rest] = process.argv.slice(2)
280
+ const path = secretPath()
281
+ let fileEnv = {}
282
+ try {
283
+ fileEnv = loadCandidateEnv(path)
284
+ if (cmd === 'check') { for (const l of await checkReport(path, fileEnv)) console.log(l); return }
285
+ if (cmd === 'fill') return await runFill(rest, fileEnv)
286
+ console.error('usage: node fill.mjs check | fill --confirm-host HOST NAME SELECTOR [NAME SELECTOR ...]')
287
+ process.exitCode = 2
288
+ } catch (e) {
289
+ console.error(`browser-apply fill: ${mask(e?.message ?? e, fileEnv)}`)
290
+ process.exitCode = 1
291
+ }
292
+ }
293
+
294
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main()
package/Dockerfile CHANGED
@@ -1,7 +1,7 @@
1
1
  # syntax = docker/dockerfile:1
2
2
  #
3
3
  # Osborn Agent — Fly.io Deployment
4
- # Self-hosted voice AI research assistant with Claude Code CLI
4
+ # Self-hosted voice AI engineer and thinking partner with Claude Code CLI
5
5
  #
6
6
  # Build: fly deploy
7
7
  # Local: docker build -t osborn-agent . && docker run -p 8741:8741 --env-file .env osborn-agent
@@ -13,6 +13,20 @@
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
+ /**
17
+ * Strip ALL ANSI escape sequences from a string — CSI (including private
18
+ * prefixes like `?`), OSC (both BEL and ST terminators), and lone ESC bytes.
19
+ *
20
+ * This is a superset of the common `/\x1B\[[0-9;]*[A-Za-z]/g` pattern, which
21
+ * misses private-prefix modes like `\x1B[?2026h` and string terminators like
22
+ * `\x1B\\`. Claude's Ink UI uses these extensively and they leak into error
23
+ * messages and URLs when we only strip the basic CSI form.
24
+ */
25
+ /**
26
+ * Redact Claude tokens (sk-ant-oat01-…, sk-ant-api…) from CLI output before it
27
+ * is logged or forwarded — `claude setup-token` prints the token to the pty.
28
+ */
29
+ export declare function redactClaudeTokens(text: string): string;
16
30
  export interface ClaudeAuthCallbacks {
17
31
  onUrl: (url: string) => void;
18
32
  onWaitingForCode: () => void;
@@ -28,24 +42,57 @@ export interface ClaudeAuthHandle {
28
42
  * On Linux/Docker, Claude Code stores OAuth creds at ~/.claude/.credentials.json
29
43
  */
30
44
  export declare function isClaudeAuthenticated(): boolean;
45
+ 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;
48
+ /** Env vars that give the agent a working model backend without a Claude login. */
49
+ export declare const FALLBACK_MODEL_KEY_VARS: readonly ["ANTHROPIC_API_KEY", "Z_AI_PERSONAL_API_KEY", "ZAI_API_KEY", "OPENROUTER_API_KEY"];
50
+ /**
51
+ * True when any fallback model key (Anthropic API key, z.ai, OpenRouter) has a
52
+ * non-empty value after trimming and quote-stripping.
53
+ */
54
+ export declare function hasFallbackModelKey(env?: NodeJS.ProcessEnv): boolean;
55
+ /**
56
+ * Pure decision for ensureClaudeAuth(): skip the blocking interactive OAuth when
57
+ * Claude is not authenticated but a fallback key exists — the session starts
58
+ * immediately on the fallback tier and Claude sign-in is offered as an optional
59
+ * upgrade. OSBORN_FORCE_CLAUDE_LOGIN=1 restores the old blocking behaviour.
60
+ */
61
+ export declare function shouldSkipBlockingOAuth(env: NodeJS.ProcessEnv, authed: boolean): boolean;
31
62
  /**
32
- * Additive third onboarding tier. Runs AFTER ensureClaudeAuth() and BEFORE
33
- * session creation. Resolves which auth backend the agent will use, in order:
63
+ * Additive onboarding tier resolution. Runs AFTER ensureClaudeAuth() and BEFORE
64
+ * session creation. Resolves which auth backend the agent will use, in order
65
+ * (Claude → ANTHROPIC_API_KEY → z.ai → OpenRouter):
34
66
  *
35
67
  * Tier 1 — real Claude login active (expiry-aware): use it, no-op.
36
68
  * Tier 2 — user's own ANTHROPIC_API_KEY is set: use it, no-op.
37
- * Tier 3 — central OPENROUTER_API_KEY present: redirect the SDK to
69
+ * Tier 3 — house demo pass, Z_AI_PERSONAL_API_KEY (or ZAI_API_KEY): redirect
70
+ * the SDK to z.ai's Anthropic-compatible endpoint (GLM model).
71
+ * Tier 4 — central OPENROUTER_API_KEY present: redirect the SDK to
38
72
  * OpenRouter's native Anthropic-Messages endpoint via env vars and
39
73
  * point every model slot at FALLBACK_MODEL. Proven end-to-end
40
74
  * env-var-only (no proxy) — the Claude Code tool loop completes.
41
- * Tier 3 fail — no OpenRouter key: warn and no-op (do NOT throw; the SDK
42
- * may still find creds we didn't detect).
75
+ * Tier 4 fail — no fallback key at all: warn and no-op (do NOT throw; the
76
+ * SDK may still find creds we didn't detect).
77
+ *
78
+ * Key values are trimmed and quote-stripped (cleanEnvKey) — a stray trailing
79
+ * space in a secret would otherwise be sent verbatim as the bearer token.
43
80
  *
44
81
  * Env vars MUST be set here, before the first query() spawn — the SDK
45
82
  * subprocess inherits process.env at spawn time and reads auth/model config
46
83
  * once at cold start.
47
84
  */
48
85
  export declare function applyAuthFallback(): void;
86
+ /**
87
+ * Clear the fallback redirect (z.ai house pass or OpenRouter) — but ONLY if
88
+ * applyAuthFallback() set it. Called from the auth onComplete path so a user who later finishes real
89
+ * Claude login mid-session (or on the next cold start) is not stuck routing to
90
+ * the fallback. A user-supplied ANTHROPIC_BASE_URL is left untouched.
91
+ *
92
+ * Returns true iff a fallback was active and has now been cleared — callers use
93
+ * this to decide whether a running session needs a (deferred) restart.
94
+ */
95
+ export declare function clearAuthFallbackIfActive(): boolean;
49
96
  /**
50
97
  * Check auth via `claude auth status` (most reliable).
51
98
  * Uses resolved path to avoid posix_spawnp PATH issues.
@@ -85,6 +132,9 @@ export declare function replayInFlightAuth(send: (type: string, payload: unknown
85
132
  * 1. CLAUDE_CODE_OAUTH_TOKEN env var
86
133
  * 2. ~/.claude/.credentials.json file
87
134
  * 3. `claude auth status --json`
135
+ * 3b. Fallback model key present (hasFallbackModelKey) → return immediately
136
+ * and emit `claude_auth_optional`; skipped when OSBORN_FORCE_CLAUDE_LOGIN=1
137
+ * or opts.force (user explicitly asked to sign in via `claude_auth_start`)
88
138
  * 4. Interactive OAuth flow (setup-token)
89
139
  *
90
140
  * Concurrency: if a previous call is still running its OAuth flow, new
@@ -93,7 +143,36 @@ export declare function replayInFlightAuth(send: (type: string, payload: unknown
93
143
  * microphone-permission error) retrigger ensureClaudeAuth and the user
94
144
  * sees two different URLs / two different code_challenges racing.
95
145
  */
96
- export declare function ensureClaudeAuth(sendToFrontend: (type: string, payload: unknown) => void): Promise<{
146
+ export declare function ensureClaudeAuth(sendToFrontend: (type: string, payload: unknown) => void, opts?: {
147
+ force?: boolean;
148
+ }): Promise<{
97
149
  submitCode?: (code: string) => void;
98
150
  done?: Promise<void>;
99
151
  }>;
152
+ /** True while a claude_auth_start-initiated flow is running. */
153
+ export declare function isOnDemandAuthInFlight(): boolean;
154
+ /**
155
+ * Start Claude OAuth on demand — the upgrade path after ensureClaudeAuth()
156
+ * skipped the blocking flow because a fallback key exists. Guarded: a second
157
+ * call while one is running does NOT start another flow (started=false, same
158
+ * result promise).
159
+ *
160
+ * `submitCode` get/set bind the caller's pendingAuthSubmitCode slot; on settle
161
+ * the slot is cleared only if it still holds THIS flow's submitCode.
162
+ *
163
+ * Resolves `{ fallbackCleared }` — true only when a fallback redirect was
164
+ * active and is now gone (the caller should then request a deferred session
165
+ * restart). Already-authenticated → no flow, fallbackCleared reflects only
166
+ * whether a stale fallback was active.
167
+ */
168
+ export declare function startClaudeAuthOnDemand(sendToFrontend: (type: string, payload: unknown) => void, submitCode: {
169
+ get: () => ((code: string) => void) | null;
170
+ set: (fn: ((code: string) => void) | null) => void;
171
+ }, deps?: {
172
+ ensure?: typeof ensureClaudeAuth;
173
+ }): {
174
+ started: boolean;
175
+ result: Promise<{
176
+ fallbackCleared: boolean;
177
+ }>;
178
+ };