The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.
JavaScript agent-skillsai-agentautomationbrowserbrowser-automationclaude-codecodexhermes-agentskillsskills-sh
Fix update-notice ordering, boundary checks, and probe safety
0x053ba66a26f53
diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.tsindex 2f019d6..b4edefe 100644--- a/package/ego-browser/src/index.ts+++ b/package/ego-browser/src/index.ts@@ -12,6 +12,7 @@ import {bufferOutput,installLifecycleFlush,resetSink,+ setNoticeTrailer,} from "./output-sink.js";import { runMain } from "./run.js";import { emitUpdateNotice, type VersionSource } from "./update-notice.js";@@ -88,12 +89,13 @@ export function installEgoSdk(installLifecycleFlush(process.stdout);}if (target.ego && typeof target.ego === "object") {- // Fire-and-forget: emitUpdateNotice never throws, and writing straight to stdout- // keeps it out of the output-sink buffer entirely, so it's unaffected by hard-stop- // discard and needs no beforeExit re-fire guard.+ // Fire-and-forget update hint. Route the resolved line to the same channel the+ // command's own output uses: the buffered-sink path registers it as a trailer the+ // sink appends after that output (so it reads as a footer, not a prefix), while a+ // host-provided cliLog gets the line directly. Never touches process.stdout blindly.emitUpdateNotice(target.ego as { getBrowserVersion?: VersionSource },- process.stdout,+ usingDefaultLog ? setNoticeTrailer : (line) => options.cliLog?.(line),);target.ego.helpers = installed;target.ego.learnings = {};diff --git a/package/ego-browser/src/output-sink.ts b/package/ego-browser/src/output-sink.tsindex b9338cd..a23b836 100644--- a/package/ego-browser/src/output-sink.ts+++ b/package/ego-browser/src/output-sink.ts@@ -12,6 +12,8 @@* owned message once. At the end of the run we either:* - a hard stop occurred -> discard the whole buffer and emit the owned message once* - otherwise -> flush the buffered output verbatim+ * and in both cases append the update-notice trailer (if any) last, so an out-of-band+ * "ego lite update available" hint reads as a footer after the command's own output.** Buffering is the price of discarding pre-stop output: bytes already written cannot be* recalled, so nothing may be written until we know the run did not hard-stop. Each@@ -23,6 +25,7 @@ type WritableLike = { write(chunk: string): unknown };let buffer: string[] = [];let hardStopMessage: string | null = null;+let noticeTrailer: string | null = null;let flushed = false;let lifecycleHooked = false;@@ -31,6 +34,15 @@ export function bufferOutput(chunk: string): void {buffer.push(chunk);}+/**+ * Record the update-notice line to append after this run's output. Set out-of-band by+ * the fire-and-forget version check; appended by `flushSink` so it trails the command's+ * own output rather than racing ahead of it. Last write wins.+ */+export function setNoticeTrailer(line: string): void {+ noticeTrailer = line;+}+/*** Record the owned message of the first hard-stop error seen this run. Later hard stops* — the same error re-reported on each loop iteration — are ignored so the agent sees@@ -67,6 +79,13 @@ export function flushSink(stream: WritableLike, thrown: boolean): void {} else {for (const chunk of buffer) stream.write(chunk);}+ // The update hint is independent of the run's own output (and of a hard stop), so it+ // is appended last in every case — after the business output or the owned guidance.+ if (noticeTrailer !== null) {+ stream.write(+ noticeTrailer.endsWith("\n") ? noticeTrailer : `${noticeTrailer}\n`,+ );+ }buffer = [];}@@ -74,6 +93,7 @@ export function flushSink(stream: WritableLike, thrown: boolean): void {export function resetSink(): void {buffer = [];hardStopMessage = null;+ noticeTrailer = null;flushed = false;}diff --git a/package/ego-browser/src/update-notice.test.mjs b/package/ego-browser/src/update-notice.test.mjsindex fe975a9..831e8cb 100644--- a/package/ego-browser/src/update-notice.test.mjs+++ b/package/ego-browser/src/update-notice.test.mjs@@ -6,7 +6,6 @@ import {composeNotice,emitUpdateNotice,noticeSuppressed,- probeBrowserVersion,updateNoticeLine,} from "../dist/src/update-notice.js";@@ -60,6 +59,53 @@ test("composeNotice falls back to a generic phrase without a usable latest versi);});+test("composeNotice treats blank version strings as absent", () => {+ // The updater can report updateAvailable before the version strings resolve, so ""+ // is a realistic bridge value: a blank currentVersion is not usable -> null.+ assert.equal(+ composeNotice({+ currentVersion: "",+ updateAvailable: true,+ latestVersion: "0.4.4.0",+ }),+ null,+ );+ assert.equal(+ composeNotice({ currentVersion: " ", updateAvailable: true }),+ null,+ );+ // A blank latestVersion degrades to the generic phrase, never "ego lite is available".+ const line = composeNotice({+ currentVersion: "0.4.3.0",+ updateAvailable: true,+ latestVersion: "",+ });+ assert.match(line, /an ego lite update is available/);+ assert.doesNotMatch(line, / {2}/); // no stray double space from a blank version+});++test("composeNotice requires a boolean-true updateAvailable / mandatory", () => {+ // A truthy non-boolean (e.g. a stringified "false" or a numeric flag) must not count+ // as an update — only the literal boolean true does.+ assert.equal(+ composeNotice({ currentVersion: "0.4.3.0", updateAvailable: "false" }),+ null,+ );+ assert.equal(+ composeNotice({ currentVersion: "0.4.3.0", updateAvailable: 1 }),+ null,+ );+ // Likewise a truthy non-boolean mandatory must not flip the wording to "is required".+ const line = composeNotice({+ currentVersion: "0.4.3.0",+ updateAvailable: true,+ latestVersion: "0.4.4.0",+ mandatory: "no",+ });+ assert.match(line, /is available/);+ assert.doesNotMatch(line, /is required/);+});+test("composeNotice rejects input without a usable current version", () => {assert.equal(composeNotice({ updateAvailable: true }), null);});@@ -75,33 +121,7 @@ test("noticeSuppressed honors the opt-out var and CI", () => {assert.equal(noticeSuppressed({ CI: "true" }), true);});-// probeBrowserVersion (the mock seam) -----------------------------------------test("probeBrowserVersion returns null until the client injects the method", async () => {- const had = Object.prototype.hasOwnProperty.call(globalThis, "ego");- const prev = globalThis.ego;- try {- delete globalThis.ego;- assert.equal(await probeBrowserVersion(), null);- globalThis.ego = {}; // present but without getBrowserVersion (old build)- assert.equal(await probeBrowserVersion(), null);- globalThis.ego = {- getBrowserVersion: async () => ({- currentVersion: "0.4.3.0",- updateAvailable: false,- }),- };- assert.deepEqual(await probeBrowserVersion(), {- currentVersion: "0.4.3.0",- updateAvailable: false,- });- } finally {- if (had) globalThis.ego = prev;- else delete globalThis.ego;- }-});--// updateNoticeLine (the composed entry the emit points call) ----------------+// updateNoticeLine (the composed entry the emit point calls) ----------------test("updateNoticeLine surfaces a line when the source reports an update", async () => {const source = async () => ({@@ -151,18 +171,20 @@ test("updateNoticeLine swallows a throwing source", async () => {assert.equal(await updateNoticeLine({ source, env: {} }), null);});+test("updateNoticeLine gives up (null) when the source never resolves", async () => {+ // A stuck bridge must not leave the check pending forever; the timeout bounds it.+ const source = () => new Promise(() => {});+ assert.equal(+ await updateNoticeLine({ source, env: {}, timeoutMs: 10 }),+ null,+ );+});+// emitUpdateNotice (the installEgoSdk wiring point) ---------------------------function fakeStream() {- const chunks = [];- return {- write(chunk) {- chunks.push(String(chunk));- },- text() {- return chunks.join("");- },- };+function collect() {+ const lines = [];+ return { lines, emit: (line) => lines.push(line) };}// emitUpdateNotice is fire-and-forget: flush pending microtasks before asserting.@@ -170,7 +192,7 @@ function flushMicrotasks() {return new Promise((resolve) => setImmediate(resolve));}-test("emitUpdateNotice writes the notice line when the bridge reports an update", async () => {+test("emitUpdateNotice hands one line to emit when the bridge reports an update", async () => {const ego = {getBrowserVersion: async () => ({currentVersion: "0.4.3.0",@@ -178,11 +200,12 @@ test("emitUpdateNotice writes the notice line when the bridge reports an update"latestVersion: "0.4.4.0",}),};- const stream = fakeStream();- emitUpdateNotice(ego, stream, {});+ const { lines, emit } = collect();+ emitUpdateNotice(ego, emit, {});await flushMicrotasks();- assert.ok(stream.text().startsWith(NOTICE_PREFIX));- assert.match(stream.text(), /run: ego-browser upgrade in your shell/);+ assert.equal(lines.length, 1);+ assert.ok(lines[0].startsWith(NOTICE_PREFIX));+ assert.match(lines[0], /run: ego-browser upgrade in your shell/);});test("emitUpdateNotice stays silent when there is no update", async () => {@@ -192,24 +215,24 @@ test("emitUpdateNotice stays silent when there is no update", async () => {updateAvailable: false,}),};- const stream = fakeStream();- emitUpdateNotice(ego, stream, {});+ const { lines, emit } = collect();+ emitUpdateNotice(ego, emit, {});await flushMicrotasks();- assert.equal(stream.text(), "");+ assert.equal(lines.length, 0);});test("emitUpdateNotice stays silent when the bridge method is missing (older build)", async () => {- const stream = fakeStream();- emitUpdateNotice({}, stream, {});+ const { lines, emit } = collect();+ emitUpdateNotice({}, emit, {});await flushMicrotasks();- assert.equal(stream.text(), "");+ assert.equal(lines.length, 0);});test("emitUpdateNotice stays silent when there is no ego bridge at all", async () => {- const stream = fakeStream();- emitUpdateNotice(null, stream, {});+ const { lines, emit } = collect();+ emitUpdateNotice(null, emit, {});await flushMicrotasks();- assert.equal(stream.text(), "");+ assert.equal(lines.length, 0);});test("emitUpdateNotice is suppressed in CI even when an update is available", async () => {@@ -220,8 +243,28 @@ test("emitUpdateNotice is suppressed in CI even when an update is available", aslatestVersion: "0.4.4.0",}),};- const stream = fakeStream();- emitUpdateNotice(ego, stream, { CI: "true" });+ const { lines, emit } = collect();+ emitUpdateNotice(ego, emit, { CI: "true" });+ await flushMicrotasks();+ assert.equal(lines.length, 0);+});++test("emitUpdateNotice swallows a throwing emit rather than rejecting", async () => {+ const ego = {+ getBrowserVersion: async () => ({+ currentVersion: "0.4.3.0",+ updateAvailable: true,+ latestVersion: "0.4.4.0",+ }),+ };+ // A throwing emit must not surface as an unhandled rejection (which would fail the run).+ emitUpdateNotice(+ ego,+ () => {+ throw new Error("write failed");+ },+ {},+ );await flushMicrotasks();- assert.equal(stream.text(), "");+ assert.ok(true);});diff --git a/package/ego-browser/src/update-notice.ts b/package/ego-browser/src/update-notice.tsindex 2e6ce94..85e439b 100644--- a/package/ego-browser/src/update-notice.ts+++ b/package/ego-browser/src/update-notice.ts@@ -1,7 +1,7 @@/*** "ego lite has an update" hint for the agent-facing runtime.*- * Loosely modeled on lark cli's `_notice` — append one tagged line telling the+ * Loosely modeled on lark cli's `_notice` — surface one tagged line telling the* agent a newer ego lite exists — but deliberately WITHOUT lark's cache. lark* persists a throttled state file because every check is an HTTP round-trip to* npm, an expensive cost worth amortizing. Our source is `ego.getBrowserVersion()`:@@ -10,15 +10,18 @@* command just asks directly and the answer is always current. (Don't re-add a* cache; it would only reintroduce staleness this version exists to avoid.)*- * The version check is `ego.getBrowserVersion()`, a real bridge method on current app- * builds; on older builds without it, the default source (`probeBrowserVersion`)- * degrades to "no update". The remedy is *not* a symmetric `ego.upgradeBrowser()`- * bridge call — the app exposes that half as the native CLI subcommand- * `ego-browser upgrade` instead, so the composed line tells the agent to run it as a- * shell command.+ * The version source is injected — in production `installEgoSdk` builds it from the+ * app's `ego` bridge. On older app builds without `getBrowserVersion`, that source+ * yields null and the check degrades to "no update". The remedy is *not* a symmetric+ * `ego.upgradeBrowser()` bridge call — the app exposes that half as the native CLI+ * subcommand `ego-browser upgrade`, so the composed line tells the agent to run it as+ * a shell command.*- * The whole module is pure given an injected version source, so it is exercised- * without a real browser.+ * `emitUpdateNotice` never writes output itself: it hands the resolved line to a+ * caller-supplied `emit`, so the caller owns the channel and timing. The SDK path+ * registers it as an output-sink trailer, so the hint is appended after the command's+ * own output instead of racing ahead of it. The whole module is pure given an injected+ * version source, so it is exercised without a real browser.*//** Raw shape the client `ego.getBrowserVersion()` is expected to return. */@@ -37,6 +40,9 @@ export type VersionSource = () => Promise</** Prefix that marks the appended line as out-of-band, not real command output. */export const NOTICE_PREFIX = "[ego-browser:notice]";+/** Upper bound on how long the version probe may run before the check gives up. */+export const NOTICE_PROBE_TIMEOUT_MS = 2000;+/*** Suppress the hint entirely. Mirrors lark's opt-out (`*_NO_UPDATE_NOTIFIER`) and* stays quiet in CI, where a nag line is noise no one acts on.@@ -47,85 +53,97 @@ export function noticeSuppressed(return Boolean(env.EGO_BROWSER_NO_UPDATE_NOTIFIER || env.CI);}+function isNonEmptyString(value: unknown): value is string {+ return typeof value === "string" && value.trim() !== "";+}+/*** Format the version info into one line, or null when there is nothing to say.*- * This is also the single boundary check on the bridge's return: the source crosses- * a runtime seam (an injected app method), so untrusted fields are pinned down here- * — a missing/non-string `currentVersion` yields null, a non-string `latestVersion`- * degrades to the generic phrase.+ * This is the single boundary check on the bridge's return: the source crosses a+ * runtime seam (an injected app method), so every field is validated to its declared+ * type here. `updateAvailable`/`mandatory` must be the literal boolean `true` — a+ * truthy non-boolean (e.g. the string "false") does not count — and the version+ * strings must be non-blank, so a missing/empty `currentVersion` yields null and a+ * missing/empty `latestVersion` degrades to the generic phrase.*/export function composeNotice(info: BrowserVersionInfo | null | undefined,): string | null {if (!info ||- !info.updateAvailable ||- typeof info.currentVersion !== "string"+ info.updateAvailable !== true ||+ !isNonEmptyString(info.currentVersion)) {return null;}- const target =- typeof info.latestVersion === "string"- ? `ego lite ${info.latestVersion}`- : "an ego lite update";- const urgency = info.mandatory ? "is required" : "is available";+ const target = isNonEmptyString(info.latestVersion)+ ? `ego lite ${info.latestVersion}`+ : "an ego lite update";+ const urgency = info.mandatory === true ? "is required" : "is available";return `${NOTICE_PREFIX} ${target} ${urgency} (current ${info.currentVersion}) — run: ego-browser upgrade in your shell, then re-read the ego-browser skill`;}/**- * Default version source. Calls the client method if this app build injected it,- * otherwise returns null — older builds without the method simply report "no update"- * instead of erroring.+ * Race a promise against a timeout, resolving to null if the timeout wins. The timer is+ * unref'd so it never keeps the process alive on its own, and it is cleared as soon as+ * the probe settles. This bounds how long the check waits on the bridge: a slow (or+ * stuck) `getBrowserVersion()` can no longer leave the update check pending forever.+ * (It cannot cancel the underlying bridge call — that handle is the app's to release.)*/-export async function probeBrowserVersion(): Promise<BrowserVersionInfo | null> {- const ego = (globalThis as { ego?: { getBrowserVersion?: VersionSource } })- .ego;- if (!ego || typeof ego.getBrowserVersion !== "function") {- return null;- }- return (await ego.getBrowserVersion()) ?? null;+function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | null> {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const timeout = new Promise<null>((resolve) => {+ timer = setTimeout(() => resolve(null), ms);+ timer.unref?.();+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));}/**- * Ask the source, return the line to append, or null. Swallows every failure: an- * update check must never be what breaks a command.+ * Ask the injected source (bounded by a timeout) and return the line to append, or null.+ * Swallows every failure: an update check must never be what breaks a command.*/-export async function updateNoticeLine(- options: { source?: VersionSource; env?: NodeJS.ProcessEnv } = {},-): Promise<string | null> {- const env = options.env || process.env;- if (noticeSuppressed(env)) return null;- const source = options.source || probeBrowserVersion;+export async function updateNoticeLine(options: {+ source: VersionSource;+ env?: NodeJS.ProcessEnv;+ timeoutMs?: number;+}): Promise<string | null> {+ if (noticeSuppressed(options.env || process.env)) return null;try {- return composeNotice((await source()) ?? null);+ const info = await withTimeout(+ Promise.resolve(options.source()),+ options.timeoutMs ?? NOTICE_PROBE_TIMEOUT_MS,+ );+ return composeNotice(info);} catch {return null;}}-/** A stream that can receive the notice line. */-export type NoticeWritable = { write(chunk: string): unknown };-/**- * The one real emit point: given the app's injected `ego` bridge (or none, on older- * builds), fire the check and write the resulting line straight to `stream` if there- * is one. Fire-and-forget — `installEgoSdk()` calls this without awaiting it, so the- * check runs concurrently with the rest of the heredoc rather than delaying it.+ * The one real entry point: given the app's injected `ego` bridge (or none, on older+ * builds), fire the check and hand the resulting line to `emit`. Fire-and-forget —+ * `installEgoSdk()` calls this without awaiting it, so the check runs concurrently with+ * the rest of the heredoc rather than delaying it. `emit` decides where the line goes+ * and when: the SDK path routes it to the output sink so it is appended after the+ * command's own output.*- * Writes directly to `stream` rather than through the output-sink buffer: an update- * hint is unrelated to whether the command's own business logic hard-stopped, so it- * must not be swallowed by (or dilute) that unrelated discard-on-hard-stop path.+ * Fully guarded: `updateNoticeLine` never rejects, and the trailing `.catch` covers a+ * throwing `emit`, so neither a failed check nor a failed write can surface as an+ * unhandled rejection that breaks the command.*/export function emitUpdateNotice(ego: { getBrowserVersion?: VersionSource } | null | undefined,- stream: NoticeWritable,+ emit: (line: string) => void,env?: NodeJS.ProcessEnv,): void {updateNoticeLine({source: () => ego?.getBrowserVersion?.() ?? Promise.resolve(null),env,- }).then((line) => {- if (line) stream.write(`${line}\n`);- });+ })+ .then((line) => {+ if (line) emit(line);+ })+ .catch(() => {});}