# browser

Adopt this skill: https://proskills.md/skills/other/code-yeongyu-lazycodex-plugins-omo-skills-browser

Page: https://proskills.md/skills/other/code-yeongyu-lazycodex-plugins-omo-skills-browser
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: plugins/omo/skills/browser/SKILL.md
size: 10500
sha: 168f1f6b61e090066d66c45e499a834f769ae04c
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/SKILL.md

````text
---
name: browser
description: "Drives a real browser through the omowright library from the js eval kernel: sites the user is already signed into, forms and clicks, JS-rendered pages, screenshots, web QA, extension popups, a human handoff for login, CAPTCHA or OTP, and a browser you own for scraping, bot-scored targets, network capture and QA traces. Use for any interactive browser task; not for a plain search or an unblocked static fetch."
---

# Browser

One library, two engines. omowright ships inside this skill; choose the engine before you act:

| You need | Engine | Entry point |
|---|---|---|
| A site the user is signed into, their open tabs, a form, a click-through, a screenshot, web QA, an extension popup | **attached** — the user's own browser through BrowserSkill | `connectBrowserSkill()` |
| A throwaway profile, bot-scoring evasion, a CAPTCHA, network interception, a QA flight trace, coordinate control, headless runs | **owned** — a browser your code launches | `connectPipe()` / `connectCloakProfile()` — [references/owned-engine/README.md](references/owned-engine/README.md) |
| A 403/WAF host the attached engine cannot open, a platform with a native reader, an archive snapshot | neither | the `ultimate-browsing` skill |

**Attached is the default,** because it is the only engine carrying the user's logins and the only
one where a human is a single call away. It works in an Agent Window inside the user's own browser profile, never in
a copy of that profile, and exists only where the user installed and enabled the BrowserSkill extension. Never substitute one engine for the other silently: if
the attached engine is not set up, run the onboarding script and tell the user its one remaining
step.

## Step 0 — inside OmO Desktop: everything above, plus the app's built-in browser

When `OMO_BROWSER_ENGINE` is set (the OmO desktop app sets it for every session), everything above works exactly
as in the terminal: `connectBrowserSkill()` for the user's own browser, `connectPipe()` / `connectCloakProfile()` /
`connect()` for a browser of your own, with the same table to choose between them. The app adds one more option:

| Option | What it is | Use it when |
|---|---|---|
| `connectBuiltinBrowser()` | OmO's built-in browser for this thread: the tab the user sees beside the chat, which they can watch, take over and share | the user should see the page while you work, the task is QA of something in the app, or a sign-in the user should do themselves in a visible tab |

```js
const browser = await omowright.connectBuiltinBrowser()
const [tab] = await browser.listTargets()
const page = await browser.attachPage(tab.id)
await page.goto(url)
```

It is an OmOWright connection like `connect()`. Work in few calls: take `page.snapshot()` once, act on its refs,
and chain several actions in one eval cell (`page.locator(ref).fill()`, `.click()`, `.selectOption(value)`,
`.setInputFiles(path)`), snapshotting again only after the page changed. It has one tab: navigate it rather than
opening new ones. `BuiltinBrowserUnavailableError` permits another engine only for `unavailable`, `timeout`, or
`invalid_grant`. For `user_stopped` or any other app refusal, stop browser work and report it; do not open another browser.

## Step 1 — load omowright and prove the stack

```js
const { loadOmowright } = await import("<skill-root>/scripts/omowright.mjs")
const { omowright } = await loadOmowright()          // { connectBrowserSkill, bskSnapshot, connectPipe, ... }
```

```bash
node "<skill-root>/scripts/browser-doctor.mjs" --json
```

| State | Meaning | Next |
|---|---|---|
| `ready` | CLI, daemon and a connected browser | start a session |
| `no-cli` / `no-daemon` / `no-extension` | something is missing | `node "<skill-root>/scripts/browser-install.mjs" [--browser=<id>]` prepares everything it can for **the browser the user uses**, then prints the **single** step only the user can do (relaunch that browser and click **Enable**); relay it verbatim, wait, re-run the doctor |
| `choose-browser` | the signals do not single out one browser (Safari/Firefox default, an idle default while another browser runs, several in use) | nothing was installed; take the browser from memory or ask the user, then `browser-install.mjs --browser=<id>` |
| `no-browser-support` | no Chromium-family profile on this machine | say so and stop |
| `outdated-extension` | the only connected extension is BrowserSkill 0.4.0, which leaves a "BrowserSkill" tab group in the user's browser after every task | start no session; relay the doctor's remedy (update the extension to 0.4.1 or later, delete saved "BrowserSkill" groups by hand), then re-run the doctor |

**Install into the browser the user actually uses, never into whatever happens to be on disk.** Before
installing, check your memory for the user's browser; otherwise read the doctor's `browser` (picked
from the OS default browser, running apps and recent use — `candidates` shows the evidence). If memory
and the doctor disagree, or the doctor says `choose-browser`, ask the user. Pass the answer as
`--browser=<id>` and record it in memory. A Chrome that is merely installed is not their browser.

**Never launch a headless browser because the attached one is missing.** It has none of the
user's sessions, so every login turns into a ladder you should not be climbing. Say which state
you hit and ask.

## The loop (attached)

```js
const session = await omowright.connectBrowserSkill({ name: "<task>", focused: false })
const sync = async () => (await session.cooperate("sync")).context_id                      // one context per page action
try {
  await session.navigate("https://example.com/", { waitUntil: "load", context: await sync() })
  const { tree, refs, css } = await omowright.bskSnapshot(session, { interactive: true, context: await sync() })  // OmOWright tree + refs, no trace in the page
  await session.click({ selector: css.e3 }, { context: await sync() })                      // css[ref] is null inside shadow roots:
  const vom = await session.observe({ maxTokens: 4000 })                                    //   then read the daemon's own tree ...
  await session.click("@e7", { context: await sync() })                                     //   ... and click its @eN ref
  await session.fill(css.e5, "hello", { context: await sync() })
  await session.press("Enter", { context: await sync() })
  await session.waitForNavigation({ waitUntil: "load" })
  const shot = await session.screenshot()                                                   // { buffer, width, height, captureId }
} finally {
  await session.stop()                                                                      // success AND failure; returns borrowed tabs
}
```

1. **Read before every action.** `bskSnapshot` refs and `observe` `@eN` refs are reissued on each
   call; use a ref in the same cycle you read it.
2. **Navigation and large DOM changes stale every ref.** Read again rather than reusing.
3. **Two identical failures mean change approach, not retry.** A third identical attempt is a defect.
4. **Borrow a user tab explicitly** (`tabList({ scope: "user" })`, `tabBorrow(id)`, `tabReturn(id)`).
   Borrowing prompts the user; never invent tab ids and never repeat a denied borrow.
5. **Always `stop()` the session,** on success and on failure.
6. **Sync before every page action.** The person at the keyboard can work in the same tab, so
   BrowserSkill 0.4 refuses an action (`permission_denied`, `data.reason: "cooperation_sync_required"`)
   unless it carries `{ context }` from the latest `session.cooperate("sync")`. A context is good
   for one action: sync, act with `{ context }`, sync again. Navigation, every input method,
   `evaluate` (and so `bskSnapshot`), `tabClose`, `resize`, `emulate`, `observe({ probeHover })` and
   `screenshot({ fullPage: true })` need it; plain reads (`observe`, `snapshot`, `getHtml`,
   `screenshot()`, `console`, `network`, `waitForNavigation`) do not.
7. **On `cooperation_sync_required`, wait for the person, then replan.** Call
   `session.cooperate("wait", { timeoutMs: 25_000 })` until it reports `ready`, read the page again
   and decide afresh; never replay the refused action blindly.
8. **Pass only the options a method takes.** A gated action throws a `TypeError` on any other key
   (a misspelt `contextId` would otherwise send no context). `bskSnapshot` and
   `screenshot({ fullPage: true })` do not throw: they drop the stray key, and the daemon then
   refuses the call with `cooperation_sync_required`.

Every method, its options, and the failure codes are in [references/commands.md](references/commands.md).

## When a human is the only way through

Login, CAPTCHA, OTP, a payment confirmation, a consent dialog:

```js
const outcome = await session.requestHelp({ prompt: "<what you need done>", targets: ["@e4"], timeoutMs: 300_000 })
```

Then read the page again. Respect a `cancelled` or `timed_out` outcome; do not work around it by
changing the extension's automation settings.

## Rules

- **Never read credentials through the page.** No `evaluate` that extracts a password, token,
  cookie or recovery code. The value of the attached engine is that the browser is already signed in.
- **Never clear cookies, cache or site data.** It is the user's real profile; clearing it logs them
  out everywhere. No flow here needs it.
- **`focused: false` by default.** The browser belongs to someone who is probably using it.
- **One short, named session per task,** always stopped.
- **Bot-scored or WAF targets never go through the attached engine** — route them to the `ultimate-browsing` skill, whose browser tier is the owned engine (`connectCloakProfile()`). The attached engine's daemon enables console
  capture on every tab it drives, which is a known automation signal.

## Where the rest lives

| Topic | Read |
|---|---|
| Session methods, targets, options, error codes | [references/commands.md](references/commands.md) |
| Installing: CLI, daemon, extension, the one human step, blocklisted extension | [references/install.md](references/install.md) |
| Agent on one machine, browser on another | [references/remote.md](references/remote.md) |
| Owned engine: launch, snapshot ladder, network, frames, human handoff | [references/owned-engine/README.md](references/owned-engine/README.md) |
| Reading a 1Password vault the user has unlocked | [references/recipes/1password.md](references/recipes/1password.md) |
````

## File: plugins/omo/skills/browser/references/owned-engine/README.md
size: 3326
sha: ca33c3ebd1a3e618443149e14da11a6f41774dd5
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/owned-engine/README.md

````text
# The owned engine

A browser **your code launches and owns**, driven over CDP by omowright with its own profile. The
opposite of the attached engine: no user logins, full control.

```js
const { omowright } = await loadOmowright()
const profile = mkdtempSync(join(tmpdir(), "omowright-"))
const browser = await omowright.connectPipe({
  browserPath: "<CloakBrowser or chrome-headless-shell binary>",
  browserArgs: ["--headless", "--no-first-run", `--user-data-dir=${profile}`],
  storageRoot: profile,
  dialogPolicy: { accept: true },
})
try {
  const page = await browser.newTab("https://example.com/")
  const tree = omowright.compactSnapshot(await page.snapshot())   // ALWAYS compact before a model reads it
  await page.locator("e3").click()                                 // refs come straight from the snapshot
  await Bun.write("shot.png", await page.screenshot())
} finally {
  await browser.close()
  rmSync(profile, { recursive: true, force: true })                // paired: a leftover profile is a logged-in browser nobody watches
}
```

`connectPipe` launches over `--remote-debugging-pipe`: no listening port, stdio drained, the
process reaped on `close()`. `connect("http://127.0.0.1:<port>")` attaches to a browser something
else launched. `connectCloakProfile({ profileDir })` launches CloakBrowser with a pinned
fingerprint seed — the stealth path for WAF and bot-scored targets, where the attached engine's
console capture would be a signal.

## When it is the right engine

| Reason | Why the attached engine cannot |
|---|---|
| A throwaway or pinned synthetic profile | the attached engine is the user's real profile |
| Bot-scoring or fingerprint evasion | you do not get to configure the user's browser |
| Solving a challenge widget programmatically | needs coordinate control and OCR |
| Reading the network instead of the DOM | needs request interception on your own target |
| A QA flight trace (steps, HAR, screenshots) | recording someone's real session is not acceptable |
| Headless or unattended runs | the user's browser is on their desk |

For anything that needs the user's login, the attached engine wins. For extracting text from a
blocked URL, neither: use the `ultimate-browsing` skill.

## The page

`OmOPage` is Playwright-shaped: `goto`, `snapshot`, `locator(ref | css)`, `click`, `fill`,
`press`, `hover`, `check`, `selectOption`, `dragTo`, `setInputFiles`, `screenshot`, `pdf`,
`evaluate`, `waitForURL`, `keyboard`, `mouse`, `frameLocator`. A snapshot is an accessibility tree
with virtual refs (`[ref=e3]`, cross-origin frames as `f1e3`); `compactSnapshot()` drops the refs
map, about half the bytes. Readiness is a content probe (body plus interactive elements, landmarks
or text), not a timer; `goto(url, { waitUntil: "commit" })` is the escape hatch for empty pages.

## Reference

- [ladder.md](ladder.md) — the escalation ladder, viewport pinning, `createCua`, `createCaptcha`
- [network.md](network.md) — `createNetworkSnoop`, `collectWhileScrolling`, `createTrace`, `createRoutes`
- [frames-and-humans.md](frames-and-humans.md) — `snapshotWithFrames`, `describeLayers`, dialog policy, `emulate`, `requestHuman`

The omowright repository's own agent guide and its `presets/*`
is the authoritative, longer treatment of each; these pages are the routing summary.
````

## File: plugins/omo/skills/browser/scripts/browser-doctor-report.mjs
size: 5665
sha: 0df308c0b23d09215dd0e7b47b5374d1a0c36433
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/scripts/browser-doctor-report.mjs

```text
// The browser doctor's report: one bskDoctor run turned into the `state` the browser skill routes on, its remedy, and a
// summary. browser-doctor.mjs is the CLI over it; `doctorOptions` reach bskDoctor unchanged (the CLI passes none).

// BrowserSkill extension 0.4.0 put every task tab into a native "BrowserSkill" tab group that the browser saves and
// syncs, so each task left a group in the user's own browser (upstream removed the grouping in 0.4.1).
const TAB_GROUPING_EXTENSION_VERSION = "0.4.0"

function stateOf(report, outdated) {
  if (report.browsersConnected.length > outdated.length) return "ready"
  if (outdated.length > 0) return "outdated-extension"
  if (!report.cli.installed) return "no-cli"
  if (!report.daemon.running) return "no-daemon"
  if (report.browsers.length === 0 && !report.primary) return "no-browser-support"
  return report.identification.needsChoice ? "choose-browser" : "no-extension"
}

const named = (browsers) => browsers.map((browser) => `${browser.browser_name} [${browser.instance_id}]`).join(", ")

// With a 0.4.0 browser connected beside an up-to-date one, a session started without `browser` may land on the 0.4.0
// one (the daemon picks), so the remedy names the up-to-date browser's instance and lists the browsers to avoid.
function readyRemedy(report, outdated) {
  const live = "Attached engine is live: const { connectBrowserSkill } = await import(omowrightEntry); "
  if (outdated.length === 0)
    return `${live}const session = await connectBrowserSkill({ name: "<task>", focused: false })`
  const usable = report.browsersConnected.filter((connected) => !outdated.includes(connected))
  const others = usable.length > 1 ? ` (or another up-to-date browser: ${named(usable.slice(1))})` : ""
  return `${live}const session = await connectBrowserSkill({ name: "<task>", focused: false, browser: "${usable[0].instance_id}" })${others}. Always pass browser: the BrowserSkill extension in ${named(outdated)} is 0.4.0, which leaves a "BrowserSkill" tab group in the user's browser after every task; never start a session there, and ask the user to update it to 0.4.1 or later and delete any saved "BrowserSkill" tab groups by hand.`
}

function remedyFor(state, report, outdated) {
  switch (state) {
    case "ready":
      return readyRemedy(report, outdated)
    case "outdated-extension":
      return `The connected BrowserSkill extension is 0.4.0 (${named(outdated)}), which leaves a "BrowserSkill" tab group in the user's browser after every task. Do not start a session. Ask the user to update the extension to 0.4.1 or later (chrome://extensions, Developer mode, Update) and to delete any saved "BrowserSkill" tab groups by hand, then re-run this doctor.`
    case "no-cli":
      return 'Run node "<skill-root>/scripts/browser-install.mjs". It installs the CLI, starts the daemon and registers the extension; then tell the user the single step it prints.'
    case "no-daemon":
      return 'Run node "<skill-root>/scripts/browser-install.mjs" (it starts the daemon through `bsk status`), then re-run this doctor.'
    case "no-extension":
      return (
        report.nextStep ??
        "Register the extension with browser-install.mjs, then relay its human step to the user and re-run this doctor."
      )
    case "choose-browser":
      return `Do not install anything yet. First check your memory for the browser this user works in; if it names one of the candidates, re-run with --browser=<id>. Otherwise ask the user which browser they actually use (${report.identification.reason}), record the answer in memory, then run node "<skill-root>/scripts/browser-install.mjs" --browser=<id>.`
    case "no-browser-support":
      return "No Chromium-family browser profile was found on this machine. Say so and stop; do not substitute another engine."
  }
}

/** @param {{ omowright: any, entry: string | undefined, browser?: string, doctorOptions?: Record<string, unknown> }} options */
export async function runBrowserDoctor({ omowright, entry, browser, doctorOptions = {} }) {
  const report = await omowright.bskDoctor({ waitForBrowserMs: 0, browser, ...doctorOptions })
  const outdated = report.browsersConnected.filter(
    (connected) => connected.extension_version === TAB_GROUPING_EXTENSION_VERSION,
  )
  const state = stateOf(report, outdated)
  return {
    state,
    omowright: entry,
    cli: report.cli,
    daemon: {
      running: report.daemon.running,
      version: report.daemon.version ?? null,
      protocolVersion: report.daemon.protocolVersion ?? null,
      error: report.daemon.error ?? null,
    },
    browser: report.primary
      ? {
          id: report.primary.id,
          label: report.primary.label,
          confidence: report.identification.confidence,
          reason: report.identification.reason,
        }
      : null,
    identificationReason: report.identification.reason,
    candidates: report.identification.candidates.map((c) => ({ id: c.id, label: c.label, signals: c.signals })),
    defaultBrowser: report.identification.defaultBrowser,
    registeredElsewhere: report.identification.registeredElsewhere,
    browsersDetected: report.browsers.map((detected) => ({
      id: detected.id,
      userDataDir: detected.userDataDir,
      extensionRegistered: detected.extensionRegistered,
    })),
    browsersConnected: report.browsersConnected.map((connected) => ({
      instanceId: connected.instance_id,
      name: connected.browser_name,
      version: connected.browser_version,
      extensionVersion: connected.extension_version ?? null,
    })),
    nextStep: report.nextStep,
    remedy: remedyFor(state, report, outdated),
  }
}
```

## File: plugins/omo/skills/browser/scripts/browser-doctor.mjs
size: 1907
sha: e7d8d9d967299f47e3275dbec0edde2eda7e0ff9
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/scripts/browser-doctor.mjs

```text
#!/usr/bin/env node
import { runBrowserDoctor } from "./browser-doctor-report.mjs"
import { loadOmowright } from "./omowright.mjs"

const { entry, omowright } = await loadOmowright()
const browserArg = process.argv.find((arg) => arg.startsWith("--browser="))
const { identificationReason, ...summary } = await runBrowserDoctor({
  omowright,
  entry,
  browser: browserArg ? browserArg.slice("--browser=".length) : undefined,
})

if (process.argv.includes("--json")) {
  console.log(JSON.stringify(summary, null, 2))
} else {
  console.log(`state: ${summary.state}`)
  console.log(`omowright: ${entry}`)
  console.log(`cli: ${summary.cli.installed ? `${summary.cli.bskBin} (${summary.cli.version})` : "not installed"}`)
  console.log(
    `daemon: ${summary.daemon.running ? `running (${summary.daemon.version}, protocol ${summary.daemon.protocolVersion})` : `not running${summary.daemon.error ? ` - ${summary.daemon.error}` : ""}`}`,
  )
  console.log(
    `browser the user uses: ${summary.browser ? `${summary.browser.label} [${summary.browser.id}] (${summary.browser.reason})` : `not identified (${identificationReason})`}`,
  )
  console.log(
    `candidates: ${summary.candidates.map((c) => `${c.id}${c.signals.length ? ` (${c.signals.join(", ")})` : ""}`).join(", ") || "none"}`,
  )
  if (summary.registeredElsewhere.length > 0)
    console.log(
      `extension entries left in other browsers: ${summary.registeredElsewhere.join(", ")} (not removed automatically)`,
    )
  console.log(
    `browsers detected: ${summary.browsersDetected.map((b) => `${b.id}${b.extensionRegistered ? " (extension registered)" : ""}`).join(", ") || "none"}`,
  )
  console.log(
    `browsers connected: ${summary.browsersConnected.map((b) => `${b.name} ${b.version} [${b.instanceId}]${b.extensionVersion ? ` extension ${b.extensionVersion}` : ""}`).join(", ") || "none"}`,
  )
  console.log(`\n${summary.remedy}`)
}
```

## File: plugins/omo/skills/browser/scripts/browser-engine-guard.mjs
size: 3554
sha: b842a50f48e10d74e9a87147bdb70563c4cca596
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/scripts/browser-engine-guard.mjs

```text
import { readFile } from "node:fs/promises"

export const BROWSER_ENGINE_ENV = "OMO_BROWSER_ENGINE"

const TOOLKIT_TOOL = "omo_desktop_toolkit"
const BUILTIN_UNAVAILABLE = {
  unavailable: "this app does not offer its built-in browser to this session",
  timeout: "the app did not answer the request for its built-in browser",
  invalid_grant: "the app answered the request for its built-in browser with something unusable",
}

export class BuiltinBrowserUnavailableError extends Error {
  constructor(reason) {
    const unavailable = Object.hasOwn(BUILTIN_UNAVAILABLE, reason)
    super(
      unavailable
        ? `OmO's built-in browser is not available here: ${BUILTIN_UNAVAILABLE[reason]}. Every other browser works as usual: connectBrowserSkill() for the user's own browser, connectPipe() for a browser of your own.`
        : `OmO's built-in browser was refused: ${reason === "user_stopped" ? "the user stopped browser work" : `the app refused it (${reason})`}. Stop browser work and report the refusal; do not open another browser.`,
    )
    this.name = "BuiltinBrowserUnavailableError"
    this.code = "browser_builtin_unavailable"
    this.reason = reason
  }
}

/**
 * Inside OmO Desktop (`OMO_BROWSER_ENGINE` set) the library is the terminal's own, unchanged, plus
 * `connectBuiltinBrowser()`: the app's built-in browser for this thread, the tab the user sees beside the chat.
 */
export function guardOmowright(raw, { env = process.env, host } = {}) {
  const engine = env[BROWSER_ENGINE_ENV]
  if (engine === undefined || engine === "") return raw

  const acquireBuiltinBrowser = async () => {
    let details
    try {
      details = (await host?.callTool(TOOLKIT_TOOL, { op: "acquire", toolkit: "browser" }))?.details
    } catch {
      details = undefined
    }
    if (details?.ok !== true)
      throw new BuiltinBrowserUnavailableError(typeof details?.reason === "string" ? details.reason : "unavailable")
    // Without an endpoint CdpClient falls back to 127.0.0.1:9222 and would send the token to whatever listens there.
    const endpoint = details.grant?.endpoint
    if (typeof endpoint !== "string" || endpoint === "") throw new BuiltinBrowserUnavailableError("invalid_grant")
    let token
    try {
      token = (await readFile(details.grant.tokenFile, "utf8")).trim()
    } catch {
      throw new BuiltinBrowserUnavailableError("invalid_grant")
    }
    return { endpoint, authorization: `Bearer ${token}` }
  }

  // A CDP endpoint that shows only this thread's tabs. The token is read from the file the grant names, so it never
  // passes through a tool result.
  const connectBuiltinBrowser = async (options = {}) => {
    let current = await acquireBuiltinBrowser()
    // Concurrent refreshes share one acquire, so a token is never paired with another grant's endpoint.
    let refreshing
    const authorizer = {
      async resolveAuthorization({ forceRefresh } = {}) {
        if (forceRefresh) {
          refreshing ??= acquireBuiltinBrowser()
            .then((next) => {
              current = next
              client.cdpUrl = next.endpoint
              return next
            })
            .finally(() => {
              refreshing = undefined
            })
          return (await refreshing).authorization
        }
        return current.authorization
      },
    }
    const client = new raw.CdpClient({ ...options.client, cdpUrl: current.endpoint, authorizer })
    return await new raw.BrowserConnection(client, options).initialize()
  }

  return { ...raw, connectBuiltinBrowser }
}
```

## File: plugins/omo/skills/browser/scripts/browser-install.mjs
size: 3030
sha: 6c1af09749de87f10cee2748e1efc222c9f2869f
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/scripts/browser-install.mjs

```text
#!/usr/bin/env node
import { loadOmowright } from "./omowright.mjs"

const json = process.argv.includes("--json")
const waitArg = process.argv.find((arg) => arg.startsWith("--wait-ms="))
const waitTotalMs = waitArg ? Number(waitArg.slice("--wait-ms=".length)) : 0
const browserArg = process.argv.find((arg) => arg.startsWith("--browser="))
const browser = browserArg ? browserArg.slice("--browser=".length) : undefined

const { omowright } = await loadOmowright()
const steps = []
const result = await omowright.bskOnboard({
  browser,
  onHumanStep: (step) => steps.push(step),
  waitForBrowserMs: waitTotalMs > 0 ? Math.min(15_000, waitTotalMs) : 0,
  waitTotalMs,
})

const summary = {
  ready: result.ready,
  cli: result.cli,
  installerRan: result.install !== null,
  daemon: {
    running: result.daemon.running,
    version: result.daemon.version ?? null,
    error: result.daemon.error ?? null,
  },
  browser: result.primary
    ? {
        id: result.primary.id,
        label: result.primary.label,
        confidence: result.identification.confidence,
        reason: result.identification.reason,
      }
    : null,
  needsChoice: result.needsChoice,
  candidates: result.identification.candidates.map((c) => ({ id: c.id, label: c.label, signals: c.signals })),
  registeredElsewhere: result.identification.registeredElsewhere,
  registrations: result.registrations.map((r) => ({
    browser: r.browser,
    registered: r.registered,
    alreadyPresent: r.alreadyPresent ?? false,
    reason: r.reason ?? null,
    needsRestart: r.needsRestart ?? null,
    humanStep: r.humanStep ?? null,
  })),
  browsersConnected: result.browsersConnected.map((b) => ({
    instanceId: b.instance_id,
    name: b.browser_name,
    version: b.browser_version,
  })),
  humanStep: result.humanStep,
}

if (json) {
  console.log(JSON.stringify(summary, null, 2))
} else if (result.ready) {
  console.log(`attached engine ready: ${summary.browsersConnected.map((b) => `${b.name} ${b.version}`).join(", ")}`)
} else {
  console.log(`cli: ${result.cli.installed ? `${result.cli.bskBin} (${result.cli.version})` : "install failed"}`)
  console.log(
    `daemon: ${result.daemon.running ? "running" : `not running${result.daemon.error ? ` - ${result.daemon.error}` : ""}`}`,
  )
  console.log(
    summary.browser
      ? `browser: ${summary.browser.label} [${summary.browser.id}] (${summary.browser.reason})`
      : `browser: not identified (${result.identification.reason})`,
  )
  for (const r of summary.registrations) {
    console.log(
      `extension for ${r.browser}: ${r.registered ? (r.alreadyPresent ? "already registered" : "registered") : `not registered (${r.reason})`}`,
    )
  }
  if (result.needsChoice) {
    console.log(
      `\nNothing was registered. ${result.humanStep}\nRe-run: node "<skill-root>/scripts/browser-install.mjs" --browser=<id>`,
    )
  } else {
    console.log(`\nTell the user exactly this, then re-run browser-doctor.mjs:\n  ${result.humanStep}`)
  }
}
process.exitCode = result.ready ? 0 : 2
```

## File: plugins/omo/skills/browser/scripts/omowright.mjs
size: 2112
sha: cc897b78d7d8c6fac4a883f5c6cff6fb303f73f6
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/scripts/omowright.mjs

```text
import { existsSync } from "node:fs"
import { dirname, join } from "node:path"
import { fileURLToPath, pathToFileURL } from "node:url"
import { guardOmowright } from "./browser-engine-guard.mjs"

export { BROWSER_ENGINE_ENV, BuiltinBrowserUnavailableError, guardOmowright } from "./browser-engine-guard.mjs"

const scriptDir = dirname(fileURLToPath(import.meta.url))
const skillRoot = dirname(scriptDir)

export function resolveOmowrightEntry(env = process.env) {
  const packageRoot = join(skillRoot, "..", "..", "..", "..", "node_modules", "omowright")
  // Same order as stage-omowright-runtime.mjs: sources before the build, `.ts` before `.js`. A git
  // install carries the sources (TypeScript since omowright's strict port, which only Bun imports);
  // a package built for its `exports` carries `dist/` only.
  const candidates = [
    env.OMOWRIGHT_ROOT ? join(env.OMOWRIGHT_ROOT, "index.js") : undefined,
    join(skillRoot, "runtime", "omowright", "index.js"),
    join(packageRoot, "src", "index.ts"),
    join(packageRoot, "src", "index.js"),
    join(packageRoot, "dist", "index.js"),
  ].filter((candidate) => candidate !== undefined)
  return candidates.find((candidate) => existsSync(candidate))
}

function kernelHost() {
  const { tool, tool_schema: toolSchema } = globalThis
  if (typeof toolSchema !== "function" || tool === undefined || tool === null) return undefined
  return {
    async listTools() {
      const listed = await toolSchema()
      return Array.isArray(listed?.tools) ? listed.tools : []
    },
    async callTool(name, args) {
      return await tool[name](args)
    },
  }
}

export async function loadOmowright(env = process.env, host = kernelHost()) {
  const entry = resolveOmowrightEntry(env)
  if (entry === undefined) {
    throw new Error(
      "omowright is not staged in this skill; run `node packages/shared-skills/stage-omowright-runtime.mjs` in a checkout, or set OMOWRIGHT_ROOT to a directory holding its bundled index.js",
    )
  }
  const raw = await import(pathToFileURL(entry).href)
  return { entry, omowright: guardOmowright(raw, { env, host }) }
}
```

## File: plugins/omo/skills/browser/references/commands.md
size: 8756
sha: a125ebad01881871046dd0638dd85c70cbaeac9e
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/commands.md

````text
# Session methods

`connectBrowserSkill()` returns a `BskSession`. Every method is one call on the BrowserSkill
daemon's tool surface; options are the daemon's parameter names in camelCase.

## Sessions

```js
const session = await omowright.connectBrowserSkill({ name: "<task>", focused: false, browser: "<instance id>", width: 1200, height: 800 })
session.sessionId            // four letters, e.g. "ckhg"
session.browserInstanceId    // which connected browser owns the Agent Window
await session.stop()         // ALWAYS, on success and failure
```

`browser` is needed only when more than one browser is connected (`bskDoctor()` lists them).
`focused: false` keeps the Agent Window from stealing focus; drop it only when the user is watching
on purpose. Throws `BskRpcError` `no_browser_connected` when no extension is attached — that is a
stop, not a cue to launch something else.

## Shared control (BrowserSkill 0.4+)

The person at the keyboard can work in the task tab while you do, so the extension refuses every
gated page action with `permission_denied` / `data.reason: "cooperation_sync_required"` unless it
carries the `context_id` of the latest `session.cooperate("sync")`. The daemon never fills it in
for you.

```js
const sync = async () => (await session.cooperate("sync")).context_id
await session.click("@e3", { context: await sync() })                 // one context, one action
await session.fill("#q", "hello", { clearBefore: true, context: await sync() })
```

| Call | Use |
|---|---|
| `session.cooperate("sync", { tabId, maxTokens })` | returns `{ context_id, ... }`; pass it as `{ context }` to the next gated action, then sync again |
| `session.cooperate("wait", { tabId, timeoutMs })` | after `cooperation_sync_required`: blocks (at most 25 s per call) until the person is done; repeat until it reports `ready`, then sync and replan from the live page |

- **Gated** (need `{ context }`): `navigate` (except the first navigation of the untouched blank tab),
  `back`, `forward`, `reload`, `click`, `hover`, `focus`, `blur`, `fill`, `press`, `select`,
  `scrollTo`, `wheel`, `evaluate` (and so `bskSnapshot`), `tabClose`, `resize`, `emulate`,
  `observe({ probeHover: true })`, `screenshot({ fullPage: true })`.
- **Not gated:** `observe`, `snapshot`, `getHtml`, `screenshot()`, `console`, `network`,
  `waitForNavigation`, the tab list/borrow/return calls, `requestHelp`.
- `dependsOn: ["@e2", ...]` narrows the check to the observed regions your decision used.
- A gated action accepts only its own options plus `{ context, dependsOn }`; any other key
  (`contextId`, a stray option copied from another method) throws a `TypeError` before anything is
  sent. Two exceptions: `bskSnapshot` and `screenshot({ fullPage: true })` pass unknown keys
  through instead of throwing, so a misspelt `contextId` there sends no context and the daemon
  refuses the call with `cooperation_sync_required`.
- Never replay a refused action blindly: the page may have changed under the person's hands.

## Targets

| Form | Meaning |
|---|---|
| `"@e3"` / `"e3"` | a ref from the last `observe()` / `snapshot()` |
| `"#login > button"` | a CSS selector, resolved live |
| `{ captureId, x, y }` | a point in a screenshot, from `screenshot()` |
| `css.e3` from `bskSnapshot` | the light-DOM CSS path of an OmOWright ref (`null` inside shadow roots — use the daemon ref instead) |

## Reading

| Call | Returns |
|---|---|
| `bskSnapshot(session, { interactive, maxDepth, context })` | `{ tree, refs, css }` — the OmOWright accessibility tree with refs, computed in the page **without** leaving a global or touching the DOM |
| `session.observe({ maxTokens, cursor, probeHover })` | the daemon's semantic tree (`@vom`) with `@eN` refs, layers and hover probes — **the default read for shadow DOM and iframes** |
| `session.snapshot({ maxDepth, maxTokens })` | the daemon's plain accessibility tree |
| `session.getHtml({ ref, maxBytes })` | exact markup |
| `session.screenshot({ ref })` / `screenshot({ fullPage: true })` | `{ buffer, width, height, captureId }`; full-page captures stream back in chunks |
| `session.evaluate(expression, { awaitPromise, timeoutMs, context })` | `{ ok, value, error }` — **check `.ok`**; a resolved promise does not mean the script succeeded |
| `session.console({ since })` / `session.network({ since })` | buffered console entries / request metadata (no bodies) |

**Refs are reissued by every read.** Read a ref and act on it in the same cycle. A ref captured
two calls ago silently addresses a different element — this is how a click lands on the
neighbouring row.

## Acting

Every call here is gated: add `context` (from `cooperate("sync")`) to its options object, as in
`session.click(target, { context })`, `session.resize(width, height, { context })`,
`session.tabClose(id, { context })`.

| Need | Call |
|---|---|
| Click | `session.click(target, { button, clickCount, modifiers })` |
| Fill | `session.fill(target, value, { clearBefore })` |
| Select | `session.select(target, ["<option value>"])` |
| Key | `session.press("Enter", { target, modifiers, holdMs })` |
| Hover | `session.hover(target, { settleMs })` |
| Scroll into view | `session.scrollTo(target)` |
| Wheel | `session.wheel({ deltaY: 600, target })` |
| Focus / blur | `session.focus(target)` / `session.blur(target)` |
| Navigate | `session.navigate(url, { waitUntil: "load" \| "domcontentloaded" \| "networkidle" \| "commit", timeoutMs })`, `back()`, `forward()`, `reload({ hard })`, `waitForNavigation()` |
| Window | `session.resize(width, height)`, `session.emulate({ overrides: { width, mobile } })` |

Traps:

- `select` takes the option's **value attribute**, not its visible label.
- `press` without `target` goes to the focused node; `press` with a CSS selector is fine, but a
  daemon ref must come from the current read.
- A menu that a `click` opens can be toggled shut by that same click. `focus` then `press("Enter")`
  opens it reliably.
- Hover-only controls report `element not visible`: hover the trigger, read again, then act on the
  revealed item's fresh ref. `observe({ probeHover: true })` finds one when no marker does, at the
  cost of touching the live page.
- The clipboard is unavailable in a window started `focused: false`, so read values out of the DOM.

## Tabs

```js
const { tabs } = await session.tabList({ scope: "user" })   // "user" | "agent" | "all"
await session.tabBorrow(tabId)                                // the user confirms in the browser (60 s)
await session.tabReturn(tabId)                                // stop() returns anything still borrowed
await session.tabCreate({ url }); await session.tabSelect(id); await session.tabClose(id, { context: await sync() })
```

Never invent tab ids and never repeat a denied borrow.

## Humans

```js
const { outcome } = await session.requestHelp({ prompt, title, targets: ["@e4"], completionCriteria, timeoutMs })
// outcome: "completed" | "continued" | "cancelled" | "timed_out" | "navigated" | "disabled"
```

## Errors

Every refusal is a `BskRpcError` with the daemon's own `code`:

| `code` | Meaning | Do |
|---|---|---|
| `no_browser_connected` | no extension attached | run the onboarding script, relay the human step, wait |
| `not_found` | stale ref or unknown session | read again; if the session is gone, start a new one |
| `invalid_params` | wrong option shape | fix the call, do not retry as-is |
| `permission_denied` with `data.reason: "cooperation_sync_required"` | a gated action without the latest sync context, or the person is using the tab | `cooperate("wait")` until `ready`, sync, read the page again, replan |
| `permission_denied` (any other reason) | `evaluate` on a tab outside the Agent Window, or a denied borrow | stop; the user said no |
| `timeout` | the tool did not finish in its budget | read the page state before retrying once |
| `user_aborted` | the user pressed Stop in the browser | stop the task and report |
| `cdp_failed` | the page cannot be attached (restricted URL, DevTools open) | say which page and why |

Inside OmO Desktop (`OMO_BROWSER_ENGINE` set), `connectBuiltinBrowser()` throws `BuiltinBrowserUnavailableError` (`code` `browser_builtin_unavailable`). Reasons `unavailable`, `timeout`, and `invalid_grant` mean the built-in browser is unavailable; `invalid_grant` includes a missing or unreadable token file. For `user_stopped` or any other app refusal, stop browser work and report it without opening another browser. Refresh uses the new grant's endpoint and token together; every other call behaves as in the terminal.

Long calls can be cancelled: `const h = session.client.callWithHandle("tool.navigate", {...})`
then `await session.client.cancel(h.rpcId)`.
````

## File: plugins/omo/skills/browser/references/install.md
size: 5853
sha: aa5d3de29c686241133a2b35916923392cb481a4
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/install.md

````text
# Installing the attached engine

Three pieces. The onboarding script prepares all three; a human finishes exactly one.

| Piece | Channel | Automatable |
|---|---|---|
| `bsk` CLI + daemon | upstream installer, GitHub Releases | **yes** |
| Browser extension | registered from the Web Store listing through Chrome's external-extension mechanism | **yes, up to one click** — the browser asks the user to enable it |
| Daemon process | auto-starts on the first call | nothing to do |

## Inside the OmO desktop app

The app installs the `bsk` CLI and starts its daemon itself, and keeps the daemon running when the app closes.
Do not run `browser-install.mjs` there unless the doctor says the app's engine is missing. `BSK_HOME` and `BSK_BIN`
still decide where the CLI and daemon are found, here and everywhere else.

## Supported

| | |
|---|---|
| Operating systems | macOS (Apple Silicon and Intel), Linux (x64, ARM64), Windows x64 |
| Browsers | Chrome, Microsoft Edge, Brave, Chromium, Arc, Dia, Vivaldi, Opera, Comet, Naver Whale — whichever the doctor lists under `candidates` |

## Which browser

The extension goes into exactly one browser: the one the user works in. Installed is not the same as
used — a Chrome launched once keeps its profile directory forever — so the scripts rank candidates by:

| Signal | Where it comes from |
|---|---|
| Default browser | macOS LaunchServices `https` handler, Linux `xdg-settings`, Windows `UserChoice` ProgId |
| Running now | the app in `/Applications` (macOS), the process table elsewhere |
| Used in the last 7 days | the profile's `Local State` / `History` modification time |

Order of authority:

1. **Your memory.** If you recorded the user's browser before, pass it: `--browser=<id>`.
2. **`--browser=<id>` / `OMOWRIGHT_BROWSER`** set by the user.
3. **The default browser, when it is also in use** (or nothing else is).
4. **The only browser in use** when no default can be read.

Anything else is `choose-browser` (doctor) / `needsChoice: true` (install): nothing is registered and
`candidates` lists every browser with its signals. Ask the user which one they use, run the install
with `--browser=<id>`, and save the answer to memory so the next session does not ask again. When
the default browser is Safari or Firefox, BrowserSkill cannot drive it — say so and ask which
Chromium-family browser to use.

The doctor also lists `registeredElsewhere`: browsers that still carry an entry from an older
onboarding. They are not removed automatically (removing the entry uninstalls an extension the user
may have enabled); remove one only when the user asks, with omowright's `unregisterExternalExtension`.

## One command

```bash
node "<skill-root>/scripts/browser-install.mjs" [--browser=<id>] [--json] [--wait-ms=180000]
```

In order it: runs upstream's official `install.sh` / `install.ps1` into `~/.local/bin` (any PATH
line the installer appends to a shell rc file is reverted — the library calls the binary by
absolute path); starts the daemon with `bsk status`; and, for **the one browser the user actually
uses**, registers the Web Store listing as an external extension:

| Platform | Where the entry goes | The user's one step |
|---|---|---|
| macOS | `<user data dir>/External Extensions/<id>.json` | quit the browser completely, open it again, click **Enable** in the dialog |
| Windows | `HKCU\Software\<vendor>\<browser>\Extensions\<id>` (`reg add`, no admin) | click **Enable** on the toolbar badge; no restart |
| Linux (Chromium) | `<user data dir>/External Extensions/<id>.json` | relaunch; installs without a prompt |
| Linux (Chrome / Edge / Brave) | `/opt/google/chrome/extensions/<id>.json` and siblings — root only | otherwise open the store link it prints and click **Add** |
| Opera, and Vivaldi / Whale off macOS | no external-extension path | open the store link it prints in that browser and click **Add** |

The script prints that step as `humanStep`. **Relay it verbatim and wait**; with `--wait-ms` it
keeps polling the daemon until the extension connects. An empty `browsersConnected` afterwards is
not a failure to work around — the browser is closed or the user has not clicked yet; say which
and ask.

If the user removed the extension from the browser before, Chrome blocklists its id for external
installs. The script detects that (`reason: "blocklisted"`) and prints the store link instead:

- Chrome: https://chromewebstore.google.com/detail/hhcmgoofomhgciiibhipgmgkgnoenaoi
- Edge: https://microsoftedge.microsoft.com/addons/detail/browserskill/emacgiaaaiojkkpkddmmdfhmokgmnikg

Enterprise force-install policies are deliberately not used: they brand the browser "managed by
your organization" and the user cannot remove the extension.

## Do not install upstream's skill

Upstream ships its own agent skill through `bsk install-skill`. **Do not run it here.** This
package already provides the skill, and upstream's copy installs under a different name into the
user skill directory, which takes precedence over a shipped skill — two descriptions of the same
engine, one of them shadowing the one that knows about omowright and this package's scripts.

## Diagnosing

```bash
node "<skill-root>/scripts/browser-doctor.mjs" --json   # this package's view: cli, daemon, the user's browser + candidates, registrations, connections
bsk doctor                                              # upstream's own checks
bsk logs                                                # daemon log
```

The daemon exits about ten minutes after the last browser disconnects and is not a system
service, so a reboot also stops it. Both heal on the next call — `connectBrowserSkill()` starts it
unless `BSK_AUTO_START=0` (sandboxes that reap background processes keep the daemon on the host
and share `BSK_HOME`; see upstream's sandboxed-agents guide).
````

## File: plugins/omo/skills/browser/references/owned-engine/frames-and-humans.md
size: 3215
sha: 9d24252ccfd1ec70b620acf005d64473e779140b
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/owned-engine/frames-and-humans.md

````text
# Frames, overlays, dialogs, and the human

## Cross-origin frames and shadow DOM

A cross-origin iframe is a separate target with its own snapshot. `snapshotWithFrames(page)`
reconciles the child trees into the parent so one tree describes the whole page, and reports
`missingFrames` for any it could not enter; address child elements through the page-level ref
(`f1e3`) — never by fetching a frame handle first. Shadow roots are traversed by the snapshot
engine; they are not a special case for you.

## Overlays that swallow clicks

Two identical misses on an element that is clearly visible usually means something invisible sits
on top: a consent banner, a modal backdrop, a sticky header, a full-viewport tracking layer.
`describeLayers(page)` names the topmost fixed or sticky element covering the viewport, and
`snapshotWithLayers(page)` prefixes a snapshot with `@layers blocking=<role> "<name>"` when one
exists. Either the overlay is named — dismiss it and continue — or `@layers none`, which means the
miss has another cause and you climb the ladder instead.

## Dialogs never block

`alert`, `confirm`, `prompt`, and `beforeunload` are answered at the protocol layer, before the
page sees them: by a `dialog` listener that answers, otherwise by the `dialogPolicy` passed to
`connectPipe` (or `browser.setDialogPolicy`). Default to accepting (`{ accept: true }`; a policy
function receives a plain `{ type, message, defaultPrompt, url }` and returns `{ accept, promptText }`).

`page.on("dialog", (dialog) => ...)` hands each listener a Playwright-style `Dialog` object, not a
plain object: read it through methods (`dialog.type()`, `dialog.message()`, `dialog.defaultValue()`,
and the `dialog.url` getter). A listener can answer it itself, which replaces the policy for that
dialog; a listener that only observes leaves it to the policy:

```js
page.on("dialog", (dialog) => dialog.type() === "prompt" ? dialog.accept("42") : dialog.dismiss())
```

A dialog is answered once; a second `accept()` / `dismiss()` throws. A run that hangs on
an unhandled dialog looks exactly like a hang with no cause, which is the most expensive kind to
diagnose.

## Device emulation

`emulate(page, "iphone-14")` applies viewport, device scale factor, user agent and touch together;
changing only the viewport produces a desktop page at a phone size, which is not what you are
testing. `emulate(page, null)` restores. Re-read the viewport after emulating, and re-pin
coordinates.

## Handing the page to a human

When every rung fails on a login, a one-time code, or a challenge you cannot clear, the human is
the fallback, not the failure:

```js
const { outcome } = await omowright.requestHuman(page, {
  prompt: "Please finish the sign-in in this window.",
  until: { url: /\/dashboard/ },          // or { selector } or async (page) => boolean
  timeoutMs: 300_000,
})
```

It brings the window to the front, shows a banner with a Done button, and waits on a
**condition** with a bounded timeout rather than a fixed delay. Respect the answer: `timed_out`
or `cancelled` is a stop, and the correct response is to report which rung failed with what
evidence. Working around the user's refusal is never correct.
````

## File: plugins/omo/skills/browser/references/owned-engine/ladder.md
size: 3891
sha: b4e56d1c25cffee8ce505e2085ed202ea55ec6c8
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/owned-engine/ladder.md

```text
# The escalation ladder

**Two identical failures on the same target mean climb, not retry. A third identical attempt is a
defect.** The failure itself selects the next rung; never pause to ask which.

| Rung | Use | Climb when |
|---|---|---|
| 1. `page.snapshot()` + `page.locator(ref)` | anything with a usable ref | the ref is absent, stale, obscured, or the click lands on the wrong node twice |
| 1b. `snapshotWithLayers(page)` / `describeLayers(page)` | a blocking overlay explains two identical misses | `@layers none`, or the overlay is gone and the click still misses |
| 2. `createCua(page)` coordinates | canvas, extension popups, custom controls, drag surfaces | the click misses, or the screenshot and the coordinates disagree |
| 3. pin the viewport (`emulate(page, "desktop-1440")` / `repinViewport`), redo rung 2 | coordinate drift after a resize, a DPI change, or a foreign tab | coordinates land correctly but the widget still refuses input |
| 4. `createCaptcha(page)` | a challenge is the blocker | it clears and the flow still stalls |
| 5. read the browser log (`browser.close()` surfaces the stdio tail) | a browser-level failure | the log names a cause outside the page |

**Rung 5 ends in a written diagnosis, never a speculative code change.** A missing entitlement, a
dead extension service worker, an unavailable authenticator — none of those is fixed by editing
automation code.

## Pin the viewport before trusting any coordinate

`createCua(page)` acts in viewport pixels. When the render surface and the coordinate space
disagree, every coordinate is off by the same constant and retrying just repeats the miss. Set the
device metrics explicitly (`emulate` applies width, height, `deviceScaleFactor` and touch
together), re-read the page's viewport size, then take a **fresh** `cua.getVisibleScreenshot()`.
Coordinates read off an unpinned screenshot are stale. Pin every page you act on, including tabs
you did not open (`createAgentTabs` re-pins on create).

## Refs

- Refs die on every new snapshot. Pass a ref straight from the latest snapshot; never reuse one
  across snapshots and never put one in a CSS selector.
- Refs stay page-level. A child-frame ref (`f1e3`) still resolves through `page.locator`, so you
  never fetch a frame handle to click inside an iframe.
- Always `compactSnapshot()` before sending a snapshot to a model.

## Challenge widgets

A challenge is an obstacle on the path, not a stop sign: clear it, confirm it cleared, continue.
`createCaptcha(page)` gives three techniques:

- **Checkbox** (the common embedded widgets): the control lives in a nested frame, so
  `captcha.click(bounds)` addresses it by viewport coordinates.
- **Slider / puzzle**: `captcha.drag(from, to, { steps })` with enough intermediate steps that the
  motion reads as human. Raise the step count before you change the endpoints.
- **Text or number**: `captcha.readText(bounds)` OCRs the region — the macOS Vision framework by
  default, or pass your own `ocr` function or a vision model.
- **Image grid**: annotate a screenshot, then click per cell with `createCua`.

**Bounds measured against an unpinned viewport are wrong by a constant offset.** If clicks have
been landing wrong, drop to rung 3 first, then re-read the bounds.

Verify with a fresh snapshot that the challenge is gone. Verification is part of the action, not a
separate optimistic assumption. When every technique fails on a page a real browser passes, the
engine is the variable: relaunch through `connectCloakProfile()`.

## Delegating the pixel loop

Coordinate work and challenge solving are iterative: screenshot, reason, act, verify. When that
loop would consume your own context, delegate the blocked page to a subagent armed with these
references and have it return the post-solve state. Drive it yourself when the flow is short or
the state is already in your hands.
```

## File: plugins/omo/skills/browser/references/owned-engine/network.md
size: 2990
sha: 5af72f48b732d6b127c2e1cb045659bcd5c81a8c
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/owned-engine/network.md

````text
# Read the network, not the DOM

When a page renders a list, a table, or search results, the data almost always arrived as JSON one
request earlier. That JSON is complete, typed, free of markup, and immune to the layout changing
next week. Watching traffic costs nothing on a target you own, and the page cannot observe it.

**Snoop before you scrape.** Scroll-and-parse is the fallback, not the default.

```js
const snoop = omowright.createNetworkSnoop(page, { maxBodyBytes: 512 * 1024 })
await page.goto(url)
const hit = await snoop.waitFor({ url: /\/api\/search/, mimeType: "application/json" }, { timeoutMs: 10_000 })
const rows = snoop.popJson()                 // every buffered JSON body, drained
console.log(snoop.summary({ max: 20 }))      // one line per request: method status mime size url
snoop.dispose()
```

## Wait for a request, never for a clock

A fixed sleep is a guess that fails on a slower machine and wastes time on a faster one.
`snoop.waitFor(match)` subscribes to the response you expect **before** you trigger the action,
then awaits it with a bounded timeout. This is the same rule that governs test code, for the same
reason.

## Collecting through infinite scroll

```js
for await (const batch of omowright.collectWhileScrolling(page, snoop, { minItems: 200, maxScrolls: 10, extract: (json) => json.items })) {
  items.push(...batch)
}
```

Scroll, collect what is new, stop on a target count or a scroll ceiling. Bound both, so a page
that keeps producing cannot run forever.

## Flight traces

For QA evidence, `createTrace(page, { dir })` records one entry per `trace.step(name, fn)` with
before/after screenshots, the network log and console output, written as `trace.jsonl` plus
`trace.har` (`toHar` builds the HAR from snoop entries). That triple is what makes a failure
reconstructable afterwards instead of re-runnable-in-theory. Call `trace.stop()` in `finally`.

Cap recorded body sizes. An untrimmed trace of a media-heavy page is mostly bytes nobody reads.

## Request interception

`createRoutes(page)` matches by glob, regular expression, or predicate and lets a handler
`continue`, `fulfill({ status, body })` or `abort()`: stub an endpoint, fail one request to test an
error path, block third-party noise. Interception is enabled on the first route and disabled on
`dispose()` — leaving it on slows every later navigation and changes the timing fingerprint, so
prefer passive snooping on bot-scored targets.

## Cookies

`injectCookies(page, cookies)` sanitizes what it injects (drops expired entries, keeps
host-prefixed cookies secure and root-scoped). Injecting an export into your own profile is
legitimate for ordinary sessions and useless for the ones you most want: accounts whose risk
engines bind a session to a device will invalidate it, and a password manager's session is
tab-bound and never portable.

**Never copy a session out of the user's real browser profile.** If you need their login, that is
the attached engine's job.
````

## File: plugins/omo/skills/browser/references/recipes/1password.md
size: 2853
sha: e4496ae580826c485211dad80c97f1b30a6b7062
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/recipes/1password.md

````text
# Reading a 1Password vault the user has unlocked

Scope: reading an item out of a vault **the user has already unlocked in their browser**. Signing
in is the user's job; see "Not in scope" below.

## The fact that shapes everything

1Password web is zero-knowledge. The unlocked vault key lives in **one tab's `sessionStorage`**,
not in a cookie. So:

- A **new** tab pointed at the vault redirects to the sign-in page even while a signed-in tab sits
  right beside it. Opening your own tab does not work and never will.
- Navigating the authenticated tab away, or closing it, **destroys the session** until a human
  signs in again.

Therefore: borrow the existing tab, read, return it. Do not open, do not navigate away, do not
"refresh to fix" anything.

```js
const { tabs } = await session.tabList({ scope: "user" })          // find the already-signed-in tab by URL
const vault = tabs.find((t) => /my\.1password\.com\/(?:vaults|app)/.test(t.url))
await session.tabBorrow(vault.tab_id)                               // the user confirms
// ... read ...
await session.tabReturn(vault.tab_id)
```

## Check liveness by URL, never by title

The app mutates its URL hash without updating the document title, so a signed-in vault can still
report a sign-in title. A live session's `location.href` contains the app path and never the
sign-in path. Read the URL from `tabList`, or `session.evaluate("location.href", { context })` with a
fresh `context` from `session.cooperate("sync")` (see the shared-control section of
[../commands.md](../commands.md)).

## The browser may be shared

Other automation may be driving the same window.

- **Clear the search box before typing** (`fill(target, value, { clearBefore: true, context })`). It often
  holds someone else's query, and typing alone appends to it, returning confident results for the
  wrong search.
- **Read the autocomplete listbox, not the results grid.** The grid holds whatever query was last
  committed, possibly by another actor. Scraping every option on the page silently merges two
  different searches.
- **Leave the tab on the item list** when you are done, so the next actor starts clean.

## If it is locked

```js
await session.requestHelp({ prompt: "Please unlock 1Password in this tab, then continue." })
```

Then read the page again.

## Not in scope

- **Do not type a master password, and do not automate the sign-in form.** Only the account owner
  signs in. If the vault is locked, hand it to them.
- **Do not extract secrets through the page** beyond the single value the user asked for, and
  report it masked (`abcd…9fb0 (len 37)`) unless they asked for the exact string.
- **Do not copy, inject, or reuse session cookies.** The session is device- and tab-bound; cookie
  reuse cannot work and trips account protections.
- Clear the clipboard if you ever populate it.
````

## File: plugins/omo/skills/browser/references/remote.md
size: 1131
sha: 6a49943489d7398767f57b81253f1549a95705d6
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/references/remote.md

````text
# Agent here, browser there

The agent and the browser do not have to be the same machine. Upstream supports this directly;
nothing in this package needs to bridge it.

Shape:

- The **browser machine** needs only the extension.
- The **agent machine** runs the `bsk` daemon, omowright and this skill.
- They are joined by a daemon in server mode plus a pairing link.

```bash
bsk daemon start --mode server      # on the machine the agent runs on; WSS is required off loopback
```

Then follow upstream's pairing guide, which owns the current flag surface and the TLS
prerequisites: https://github.com/Tencent/BrowserSkill/blob/main/docs/remote-extension-connection.md

Once paired, `connectBrowserSkill()` and every session method behave identically; screenshot
buffers arrive on the machine that ran the call. Windows named pipes are not discovered
automatically — pass `sockPath` to `connectBrowserSkill()`.

If pairing is not configured, say so and ask. Do not substitute a browser on the agent machine:
the point of the attached engine is the sessions that live in the user's browser, and a local
browser has none of them.
````

## File: plugins/omo/skills/browser/agents/openai.yaml
size: 42
sha: 10ab27150ea36a97b801a6e546778aeb8b7a2146
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/agents/openai.yaml

```text
interface:
  display_name: "(OmO) browser"
```

## File: plugins/omo/skills/browser/ATTRIBUTION.md
size: 2171
sha: 9986b91fbfc5b51ee4cb7650b0cff55385de28b2
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/ATTRIBUTION.md

```text
# ATTRIBUTION / NOTICE

This skill (`browser`, part of `@oh-my-opencode/shared-skills`) is project-original documentation
plus a staged copy of one library it drives.

## omowright — bundled

Both engines this skill documents are provided by **omowright**.

- Upstream: the `omowright` package (npm, source on GitHub). The root `package.json` declares it
  as a semver range (`^0.3.0` today); the exact version installed is recorded in `bun.lock` and in
  the staged `manifest.json`.
- License: MIT
- What ships here: `runtime/omowright/index.js` (the library bundled into one ESM file, including
  its `ws` and `zod` dependencies), `runtime/omowright/page-bundle.js` (the in-page snapshot
  script it reads at import time) and `runtime/omowright/LICENSE` (omowright's MIT text, copied
  verbatim), staged at build time by
  `packages/shared-skills/stage-omowright-runtime.mjs` from the pinned root devDependency, with a
  `manifest.json` recording the version and file digests. Staging fails when omowright has no
  `LICENSE`. The repository holds no copy; the staged files are gitignored and packed through the
  sibling `.npmignore`.
- Once omowright#297 is released, its entry also opens with a `/*!` MIT banner that survives
  bundling. Until then, and for every version, the staged `LICENSE` is the notice.

## BrowserSkill — driven, not vendored

The attached engine reaches the user's browser through **BrowserSkill** by Tencent.

- Upstream: https://github.com/Tencent/BrowserSkill
- License: MIT
- What ships here: nothing of upstream's. omowright speaks the daemon's IPC protocol; the user
  installs the `bsk` CLI from upstream's own installer (run by `scripts/browser-install.mjs`) and
  the extension from the Chrome Web Store / Edge Add-ons listings (registered by the same script
  through Chrome's external-extension mechanism). This package never bundles a browser binary or
  an extension payload.

## Owned-engine references

`references/owned-engine/` summarizes omowright's own skill and presets (escalation ladder,
network-first reading, frames, dialogs, human handoff) as routing text; the library's repository
is the authoritative treatment.
```

## File: plugins/omo/skills/browser/runtime/omowright/index.js
size: 1119666
sha: 28b9d9ce911c02321f77684a4323bc42c1e1ada9
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/runtime/omowright/index.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/runtime/omowright/index.js

## File: plugins/omo/skills/browser/runtime/omowright/LICENSE
size: 1068
sha: 09aac3c3b7f6e26e8520b362eb048d4d8f9165c3
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/runtime/omowright/LICENSE

```text
MIT License

Copyright (c) 2026 Yeongyu Kim

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: plugins/omo/skills/browser/runtime/omowright/manifest.json
size: 430
sha: 403f9f99017075fc5260ac74c4d538106023b1a8
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/runtime/omowright/manifest.json

```text
{
  "version": "0.3.1",
  "sourceDigest": "49d30530ff09a195a4f5ff5bb5a30a049bf03ab10311d5adc564378b3b3d56f7",
  "files": {
    "index.js": "54350524a28307711d17d092d0c169818cd2650899efda9e9e19b3244e29655e",
    "page-bundle.js": "c517fa11a62a1b83dc79f72b288159a420831426418b1d4d9d492fc6c414f78c",
    "LICENSE": "b083425948376611de9b92b0aeb7377e604505756ea427e541a34d9b030d4dc1"
  },
  "stagedAtUtc": "2026-11-21T21:52:52.353Z"
}
```

## File: plugins/omo/skills/browser/runtime/omowright/page-bundle.js
size: 57444
sha: c34de9de4614b785f09966df4827f93b39fc30d0
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/runtime/omowright/page-bundle.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/code-yeongyu/lazycodex/blob/main/plugins/omo/skills/browser/runtime/omowright/page-bundle.js

## File: README.md
upstream: https://github.com/code-yeongyu/lazycodex/blob/main/README.md

````text
<div align="center">
  <img src=".github/assets/omo-icon-light.svg" alt="LazyCodex" width="280">

  <h1>LazyCodex</h1>

  <p><strong>The one and only agent harness for complex codebases.</strong><br />
  Project memory, planning, execution, and verified completion inside Codex.</p>

  <p>
    <a href="https://github.com/code-yeongyu/lazycodex">
      <img alt="Stars" src="https://img.shields.io/github/stars/code-yeongyu/lazycodex?style=for-the-badge&color=c69ff5&logoColor=D9E0EE&labelColor=302D41" />
    </a>
  </p>

  <p>
    <a href="#-what-is-this">What is this?</a>
    ·
    <a href="https://github.com/code-yeongyu/oh-my-openagent">OmO</a>
    ·
    <a href="https://lazycodex.ai">lazycodex.ai</a>
  </p>

  <br />
</div>

<hr />

> [!NOTE]
> **[OmO] 60K Stars: the terrifying token burner has arrived in LazyCodex.**
>
> Sisyphus Labs' OmO is the quality-obsessed agent harness whose public lore says it loved Anthropic models hard enough to get third-party clients blocked. Now that same OmO quality bar is available for Codex through LazyCodex.
>
> If you wanted OmO but did not want the setup ceremony, start here:
>
> ```bash
> npx lazycodex-ai install
> ```
>
> Context: [OmO 60K Stars on X](https://x.com/justsisyphus/status/2060210365338939452?s=20)

## 🚀 Install

One line. No global install, no `npm i -g`. Always use `npx`:

```bash
npx lazycodex-ai install
```

This is shorthand for `npx --yes --package oh-my-openagent omo install --platform=codex`. For a fully autonomous, no-TUI setup:

```bash
npx lazycodex-ai install --no-tui --codex-autonomous
```

### Install from the Codex marketplace (experimental)

The npx installer above stays the primary path. As an additive, experimental
alternative you can install from inside Codex itself: type `/plugins`, open the
**Add Marketplace** tab ("Add a marketplace from a Git repo or local root."),
and enter `https://github.com/code-yeongyu/lazycodex`, then install `omo` from
the `sisyphuslabs` marketplace. Or from the CLI:

```bash
codex plugin marketplace add https://github.com/code-yeongyu/lazycodex
codex plugin add omo@sisyphuslabs
```

On the next launch, approve the omo hooks in Codex's startup review — hooks
never run before approval. The first approved session prints
`LazyCodex bootstrap running in background — restart the session when it completes`
while a background worker finishes the setup (config blocks, agent roles, bin
links, a pinned `sg` binary for the `ast_grep` MCP); restart when it is done.
The marketplace path never touches Codex permission settings — autonomous mode
remains the explicit `npx lazycodex-ai install --no-tui --codex-autonomous`
choice.

Upgrade with `codex plugin marketplace upgrade sisyphuslabs`. The next startup
review shows the hooks as **Modified** — expected after every upgrade —
re-approve them and the following session re-runs bootstrap on the new version.
If anything looks pending or degraded, `npx lazycodex-ai doctor` explains what
and why. Full details: [lazycodex.ai/docs](https://lazycodex.ai/docs).

### Verify it worked

```bash
npx lazycodex-ai doctor
```

`doctor` prints the installation health report: plugin cache, hooks, MCP
servers, agents, and config state. Inside Codex, type `$` in the composer to
browse every installed skill — `init-deep`, `ulw-loop`, `ulw-plan`,
`start-work`, and the rest — and hooks announce themselves with
`LazyCodex(<version>): ...` status messages during a session.

### Uninstall

```bash
npx lazycodex-ai uninstall
```

Removes the installed plugin cache, bin links, agent roles, and the managed
sections of `~/.codex/config.toml`.

## ⚡ Commands

LazyCodex installs these as OmO commands for Codex. Invoke them with the
`$command` syntax shown by the installer.

| Command | Type this | What it does |
| --- | --- | --- |
| `$ulw-loop` | `$ulw-loop "task" [--completion-promise=TEXT] [--strategy=reset\|continue]` | Self-referential loop that runs until Oracle-verified completion. Caps at 500 iterations in ultrawork mode, 100 in normal mode. |
| `$ulw-plan` | `$ulw-plan "what to build"` | Prometheus strategic planner. Writes a plan to `plans/<slug>.md`. Never writes product code. |
| `$start-work` | `$start-work [plan-name] [--worktree <path>]` | Executes a plan until every checkbox is done. Prints **ORCHESTRATION COMPLETE**. |

Full documentation lives at [lazycodex.ai/docs](https://lazycodex.ai/docs).

## Use the built-in workflows

LazyCodex should be judged by the features it actually installs. It is the
Codex distribution for OmO's agent harness: project memory, planning,
execution, verified completion, skills, hooks, model routing, and diagnostics.

### 1. `$init-deep` creates project memory

`$init-deep` generates hierarchical `AGENTS.md` context. It scores complex
directories, writes local guidance near the code that needs it, and gives future
agents landmarks before they edit. Type `$init-deep` in the Codex composer —
the `$` prefix is how every installed skill is invoked.

Use it when the repository is too large to explain from memory. Run it again
when the shape of the codebase changes.

### 2. The three command pillars stay up front

Use `$ulw-plan` when the work needs decisions before implementation. It writes a
plan to `plans/<slug>.md` and does not touch product code.

Use `$start-work` when a plan is ready. It executes the checklist with durable
Boulder progress and stops only when the plan is complete.

Use `$ulw-loop` when the task should keep moving until the result is verified by
evidence instead of a hopeful status update.

### 3. Skills cover specialized work

The command layer stays simple. The skill layer adds specialist judgment for the
actual work:

| Feature | Use it for |
| --- | --- |
| `$init-deep` | Hierarchical project memory through `AGENTS.md` |
| `$ulw-plan` | Decision-complete planning before code changes |
| `$start-work` | Durable plan execution with Boulder progress |
| `$ulw-loop` | Verified completion for open-ended tasks |
| `review-work` | Multi-angle post-implementation review |
| `remove-ai-slops` | Behavior-preserving cleanup of AI-looking code |
| `frontend-ui-ux` | Polished UI surfaces |
| `programming` | Strict TypeScript, Rust, Python, or Go discipline |
| `LSP` | Diagnostics, definitions, references, symbols, and renames |
| `AST-grep` | Structural search and rewrite across code |
| `rules` | Project instructions from AGENTS, rules, and instruction files |
| `comment-checker` | Feedback after edit-like operations |

### 4. Sub-agent roles ride Codex's native multi-agent tools

LazyCodex installs selectable agent roles into `~/.codex/agents/`: `explorer`,
`librarian`, `plan`, `momus`, `metis`, and `codex-ultrawork-reviewer`. Pick one
by passing `agent_type` to Codex's `spawn_agent` tool — the child agent runs
with that role's model and instructions:

```jsonc
spawn_agent({"message": "TASK: map the auth flow end to end.", "agent_type": "explorer"})
```

The installer exposes `agent_type` on `multi_agent_v2` sessions (Codex hides it
by default). If your Codex build's spawn tool has no `agent_type` parameter,
describe the role inside `message` instead — the skills are written to fall
back to that form automatically.

Start at [https://lazycodex.ai](https://lazycodex.ai).

<hr />

## 💤 What is this?

**LazyCodex** packages [OmO (oh-my-openagent)](https://github.com/code-yeongyu/oh-my-openagent) as the Codex agent harness for complex codebases.

Think [LazyVim](https://github.com/LazyVim/LazyVim) for [lazy.nvim](https://github.com/folke/lazy.nvim), but for Codex.

OmO is the agent harness: discipline agents, parallel orchestration, multi-model routing, skills, hooks, and verified completion. LazyCodex packages that harness for Codex.

> _"LazyVim made Neovim usable for the rest of us. LazyCodex does the same for Codex."_

Credit: The LazyCodex name idea is inspired by [LazyVim](https://github.com/LazyVim/LazyVim). The Ultragoal and UltraQA ideas are inspired by [oh-my-codex](https://github.com/Y
````
