Troy / Reference
Engine and bridge API
Reference for Troy's internal surfaces: the Cdp port, the window.troy and new tab bridges, the main-process modules and the read pipeline modules.
On this page
Troy has no published library or npm package. This page documents the programming surfaces inside the repository, for contributors and for anyone reading the code. The external interface for agents is the Chrome DevTools Protocol (CDP), unchanged, covered in Driving Troy from an agent.
Each surface is kept narrow on purpose. Code that needs only a few capabilities asks for only those, so it can be tested without a browser and reused by every host that can supply them.
The Cdp port
src/cdp/types.ts defines a narrow interface over one CDP session, so the same code can run under Playwright or against a live Electron tab. Its methods:
interface Cdp {
send<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>
on(event: string, handler: (params: unknown) => void): () => void
screenshot(clip?: Box): Promise<Buffer>
evaluate<T>(fn: string): Promise<T>
url(): Promise<string>
close(): Promise<void>
}
type Box = { x: number; y: number; w: number; h: number }
sendsends a raw CDP command. ForPage.navigateit also waits forPage.loadEventFiredorPage.navigatedWithinDocument, and resolves (never rejects) after a timeout of 30000 ms if neither arrives. PasstimeoutMsinparamsto change it. The result does not say which case happened; checkdocument.readyStateif it matters.onsubscribes to a CDP event and returns an unsubscribe function.screenshotreturns a Portable Network Graphics (PNG) image, optionally clipped to a box.evaluateruns an expression withRuntime.evaluateand returns the value. A thrown exception becomes anErrorwith the exception’s description.urlreturns the page address. On main it asks the page forlocation.href, which includes hash changes andpushStateupdates, and falls back to Playwright’s cached address.closereleases the session; what that means depends on how it was obtained.
Obtaining one
src/cdp/playwright.ts exports three constructors:
| Function | Browser | close() does |
|---|---|---|
launchHeadless() |
New headless Chromium | Closes that browser |
connectOverWs(url) |
An already running browser | Detaches only |
launchPersistent(dir) |
Chromium on a profile dir | Closes the browser |
connectOverWs never closes the browser it attached to, because that browser may hold a signed-in session. It uses the first context and first page, opening one if none exists. On main its close() also drops Playwright’s connection handle, which for a CDP connection disconnects without ending the browser.
Only Cdp is exported from these functions; Playwright types do not leak through the port. listenerCountForTests is a test-only helper.
The test suite uses these to drive real Chromium. On main, the read pipeline asks for an even narrower port (below), which a Cdp satisfies as is.
The chrome bridge: window.troy
The chrome page (tab strip, toolbar, agent panel) talks to the main process only through src/browser/preload.cjs, which exposes a fixed object on window.troy. Its types are written down in src/browser/bridge.d.ts.
Actions:
newTab(url?),selectTab(id),closeTab(id)back(),forward(),reload()go(input): resolve and load, returns{ kind, reason? }wherekindisurl,search,external,refusedoremptytogglePanel(): returns whether the panel is now openread(): reads the active tab, or returns{ error }
In v0.1.5, read() returns { url, text, degraded }. On main it runs the read pipeline and returns:
url,titleblockCount,domBlockCount,ocrBlockCount,regionCountcharacterCount,elapsedMssettled,degraded(truewhen settle timed out)ocrEngine("none"when no engine ran)markdown, the page rendered as Markdown
Subscriptions, each returning an unsubscribe function:
onTabs(handler): receives{ tabs, canGoBack, canGoForward, loading, panelOpen }. Each tab hasid,title,url,favicon,failed,loading,active.onNotice(handler): a sentence to show the user.onFocusOmnibox(handler): the Focus Address Bar menu item fired.
The new tab bridge: window.troyNewTab
src/browser/tab-preload.cjs is attached to every tab but exposes window.troyNewTab only on Troy’s own new tab page. The main process also checks the calling frame’s address on each of these channels and throws for any other page. The preload’s check is tidiness; the main process check is the guarantee, because a page cannot lie about the address of the frame it calls from.
On main:
state():{ rememberHistory, blockTrackers }setSetting(key, value): onlyrememberHistoryandblockTrackers
v0.1.5 also has the shortcut channels, and state() includes shortcuts:
addShortcut(url, title?),removeShortcut(url): return the updated listopen(url): opens a tile through the address bar rules
Main-process modules
Each is a plain module that can be tested without launching a browser.
omnibox.js:resolveOmnibox(input, { search }),ENGINEStracking.js:stripTrackingParams,isTrackerHost,shouldBlockRequest,installBlocker,TRACKING_PARAMS,TRACKER_HOSTSsettings.js:defaults,settingsFile,readSettings,writeSettingsshortcuts.js:MAX_SHORTCUTS(12),readShortcuts,writeShortcuts,addShortcut,removeShortcut,normalise. On main the file remains but the app no longer imports it.history.js(main):MAX_HISTORY(500),historyFile,readHistory,writeHistory,recordVisit,clearHistoryreadPort.js(main):readTab(webContents, { settleTimeoutMs? })runs the read pipeline on a live tab, attaching the debugger only for the read;summariseDocument(doc)builds the panel’sread()resultextensions.js:findExtensions,readManifest,loadExtensions,summariseresilience.js:installSafetyNet,formatError,appendLogendpoint.js:endpointFile,describeEndpoint,writeEndpoint,readEndpoint,clearEndpoint
The read pipeline modules (main)
The pipeline is plain JavaScript with types in JSDoc comments, so Electron’s main process and the scripts can import it with no build step. It asks for a ReadPort: an object with evaluate(expression) returning a promise of the result, and an optional screenshot(box) returning a promise of PNG bytes. Without screenshot, a read still returns everything the Document Object Model (DOM) explains.
pipeline.js:readPage(port, { settleTimeoutMs?, ocr? })returns aReadDocument.settleTimeoutMsdefaults to 10000;ocrdefaults to the stub engine.settle.js:settle(evaluate, opts),settleProbeExpression(reset)extract.js:extract(evaluate),extractExpression()cover.js:cover(candidates, blocks, viewport), a pure functionocr.js:stubEngine(),transcribe(port, regions, engine)apple-vision.js:appleVisionEngine(), macOS onlyfuse.js:fuse(domBlocks, ocrBlocks),columnsOf(items)render.js:toMarkdown(doc)types.js: the shared shapes (Box,DomBlock,CoverCandidate,CoverRegion,OcrLine,OcrEngine,FusedBlock,Extraction,ReadDocument)
An optical character recognition (OCR) engine is any object with name, available() and recognize(png), where recognize returns lines of { text, box, confidence } in image pixels. The pipeline asks available() before taking any screenshot, and a failing engine degrades to untranscribed markers instead of failing the read. Field-by-field output is on How Troy reads a page.
The agent modules (main)
src/agent/ holds the tool layer, the model loop and the key store. None of it is wired into the app yet. See Agent tool layer.