/* auto-generated by NAPI-RS */ /* eslint-disable */ /** * macOS computer-use controller. * * This declaration and the named JS export are available on every platform so * consumers can import them portably; the native controller itself is built * only on macOS. */ export interface ComputerInputAction { action: "screenshot" | "click" | "double_click" | "move" | "drag" | "scroll" | "type" | "keypress" | "wait" x?: number y?: number toX?: number toY?: number scrollX?: number scrollY?: number button?: string text?: string keys?: Array ms?: number timeoutMs?: number timeoutGroup?: number } export interface ComputerBatchStepResult { index: number action: string screenshot?: ComputerScreenshot } export interface ComputerBatchResult { results: Array failureCode?: string failureIndex?: number failureMessage?: string primaryFailureCode?: string primaryFailureMessage?: string } export declare class ComputerController { constructor() executeBatch(expectedEpoch: number | undefined | null, actions: Array, timeoutMs?: number | undefined | null, signal?: unknown): Promise screenshot(): ComputerScreenshot click(expectedEpoch: number | undefined | null, x: number, y: number, button?: string | undefined | null): void doubleClick(expectedEpoch: number | undefined | null, x: number, y: number, button?: string | undefined | null): void move(expectedEpoch: number | undefined | null, x: number, y: number): void drag(expectedEpoch: number | undefined | null, x: number, y: number, toX: number, toY: number, button?: string | undefined | null): void scroll(expectedEpoch: number | undefined | null, x: number, y: number, scrollX: number, scrollY: number): void type(expectedEpoch: number | undefined | null, text: string): void keypress(expectedEpoch: number | undefined | null, keys: Array): void wait(expectedEpoch: number | undefined | null, ms: number): void } export declare class DoctorJournalAuthority { static createExact(root: string, runId: string): DoctorJournalCreateResult append(record: string): void close(): void } /** * Long-lived macOS appearance observer. * * Subscribes to `AppleInterfaceThemeChangedNotification` via * `CFDistributedNotificationCenter` and calls the provided callback * with `"dark"` or `"light"` on each change (and once on start). * * A 2-second polling timer also runs as fallback — distributed * notifications may not reliably reach background threads on all * macOS versions. * * On non-macOS platforms, `start()` returns a no-op observer. */ export declare class MacAppearanceObserver { static start(callback: (err: null | Error, appearance: MacOSAppearance) => void): MacAppearanceObserver stop(): void } /** * Long-lived macOS power assertion. * * On macOS this acquires one or more `IOKit` assertions that prevent the * requested sleep modes until the handle is stopped or dropped. On other * platforms it is a no-op handle so the caller can keep one cross-platform * code path. */ export declare class MacOSPowerAssertion { /** * Acquire a macOS power assertion. On non-macOS platforms returns a * no-op handle so callers can stay cross-platform. */ static start(options?: MacOSPowerAssertionOptions | undefined | null): MacOSPowerAssertion /** * Release every assertion held by this handle. Safe to call multiple * times; subsequent calls are a no-op. */ stop(): void } /** Retained no-follow authority for the SDK publication namespace. */ export declare class NativeRetainedBrokerPublication { /** * Read-only observation. Deliberately synchronous: it is the authority * boundary that must not admit an await between proof and effect. It reads * descriptor identity only -- no write, no fsync -- and never takes the * writer lock, so an unresolved heartbeat cannot block it. */ observe(): NativeBrokerPublicationObservation /** Read-only observation on the libuv blocking pool for watchdog paths. */ observeAsync(): Promise /** * Positional heartbeat write on the libuv blocking pool. The write is an * unbounded `pwrite` against retained authority: on the JS thread a stalled * filesystem would freeze the whole process, including the timers that are * supposed to notice the stall. */ heartbeatAsync(heartbeatAt: string): Promise /** * `fsync` on the libuv blocking pool. It returns when the device says so, * which is never bounded, so it may not run on the JS thread either. */ syncAsync(): Promise /** * Give up discovery, owner record, lock directory, and SDK root authority. * * Detaches the handle without waiting for anything: an unresolved worker * keeps its own `Arc` alive, observes the closed flag, and returns `closed` * without committing, and the descriptors are released when that last * reference drops on the pool thread. A shutdown blocked behind an * unbounded write is exactly the wedge this must not reproduce. */ close(): NativeBrokerPublicationOperation /** * Owner-side prepare: exclusively creates the retained restart-intent slot * and keeps its descriptor open, so a later commit/cancel from this same * process never reopens by name. */ prepareRestartIntentAsync(intent: NativeBrokerRestartIntent): Promise /** * Owner-side commit: rewrites the SAME retained descriptor from prepare, so * the transition can never race a different file occupying the name. */ commitRestartIntentAsync(intent: NativeBrokerRestartIntent): Promise /** * Owner-side cancel: exact-identity unlink of this process's own retained * slot. A lease expiry (no live owner to call this) leaves the file for the * successor's verified `clear_restart_intent_async` instead. */ cancelRestartIntentAsync(): Promise /** * Successor-side clear: exact-identity unlink of a predecessor's restart * slot this process never prepared itself. Only removes the name when its * current on-disk identity still matches the caller-proven dev/ino. */ clearRestartIntentAsync(identity: NativeBrokerRestartIntentIdentity): Promise } /** In-process notification server handle exposed to TypeScript. */ export declare class NotificationServer { /** * Create a server for `session_id` authenticated by `token`. * * `state_root` (when given) is where the endpoint discovery file is written * (e.g. `/.gjc/state`). `resolver_available` defaults to `true`. */ constructor(sessionId: string, token: string, stateRoot?: string | undefined | null, resolverAvailable?: boolean | undefined | null) /** Register the reply callback. Must be called before [`Self::start`]. */ onReply(callback: (err: null | Error, reply: ReplyEvent) => void): void /** * Register the authenticated inbound-message callback (free-text, * side-question request/cancel, and in-thread config/control commands). * Must be called before [`Self::start`]. */ onInbound(callback: (err: null | Error, msg: InboundEvent) => void): void /** * Register the raw v3 SDK frame callback. Must be called before * [`Self::start`]. */ onSdkFrame(callback: (err: null | Error, frame: SdkFrameEvent) => void): void /** * Register the negotiated-capabilities callback. Must be called before * [`Self::start`]. */ onNegotiatedCapabilities(callback: (err: null | Error, connectionId: string, capabilities: string[]) => void): void /** * Register the connection-close callback. Must be called before * [`Self::start`]. */ onConnectionClose(callback: (err: null | Error, connectionId: string) => void): void /** * Bind the loopback endpoint and start serving. Resolves with the bound * endpoint info once the socket is bound. * * # Errors * Fails if already started or the loopback socket cannot be bound. */ start(): Promise /** * Broadcast an `action_needed` ask. `needed_json` is a JSON `ActionNeeded`. * * `repliable` should be `true` only when an SDK workflow-gate resolver is * available. * * # Errors * Fails if not started or `needed_json` is invalid. */ registerAsk(neededJson: string, repliable: boolean): void /** * Register a correlated workflow-gate ask. `workflow_json` must be an * `action_needed` wire frame carrying a nonempty `workflowGateId`. */ registerWorkflowGateAsk(workflowJson: string, repliable: boolean): void /** * Register an ask and return an opaque in-process capability. Pass it * unchanged to [`Self::retire_if_unclaimed`]; do not construct, persist, * inspect, or treat it as workflow-gate authority. A supplied * `workflowGateId` is preserved. */ registerArbitratedAsk(neededJson: string, repliable: boolean): PresentationLease /** * Atomically terminalize the exact presentation named by an opaque lease. * The typed status proves whether it retired, was already terminal, was * claimed, or became stale without exposing claims, receipts, registration * state, or workflow-gate authority. */ retireIfUnclaimed(lease: PresentationLease): RetireIfUnclaimedResult /** * Broadcast an ephemeral `action_needed` idle ping. `needed_json` is JSON * `ActionNeeded`. * * # Errors * Fails if not started or `needed_json` is invalid. */ noteIdle(neededJson: string): void /** * Broadcast an ephemeral threaded-session frame. `frame_json` is a JSON * `ServerMessage` (e.g. `identity_header`, `context_update`, `turn_stream`, * `ephemeral_turn_result`, `image_attachment`, `session_closed`, * `config_update`, `hello`). Not buffered for replay. * * # Errors * Fails if not started or `frame_json` is not a valid `ServerMessage`. */ pushFrame(frameJson: string, excludedConnectionIds?: Array | undefined | null): void /** * Deliver a frame through every authenticated connection and wait for each * socket writer to settle within `timeout_ms`. */ pushFrameAndWait(frameJson: string, timeoutMs: number): Promise /** * Broadcast a TypeScript-constructed turn frame without re-parsing JSON. * Returns whether at least one non-excluded transport accepted the raw * frame. External frames must continue through [`Self::push_frame`] for * serde validation. */ pushTurnStreamUnchecked(sessionId: string, phase: string, text: string, finalAnswer?: boolean | undefined | null, messageRef?: string | undefined | null, excludedConnectionIds?: Array | undefined | null): boolean /** * Broadcast a file attachment from raw N-API bytes, encoding the unchanged * base64 wire field only in Rust. */ pushFileAttachmentUnchecked(sessionId: string, name: string, mime: string | undefined | null, data: Buffer, caption?: string | undefined | null, excludedConnectionIds?: Array | undefined | null): void /** * Return counters guarding the known-good frame crossing against * regressions. */ knownGoodFrameStats(): KnownGoodFrameStats /** * Proves that the loaded addon honors positioned-recipient exclusions on * raw notification fan-out. Kept as an explicit executable capability so a * stale linked addon cannot silently accept and ignore the optional N-API * arguments. */ supportsPositionedRawExclusion(): boolean /** Send a validated, bounded JSON envelope to one connected v3 SDK client. */ sendTo(connectionId: string, json: string): void /** * Send a directed frame and return an opaque receipt bound to the exact * connection generation that accepted it. */ sendToWithReceipt(connectionId: string, json: string): string /** * Queue an idle action only on writer generations that also accepted its * positioned or raw identity prerequisite. */ queueIdleAfterDirected(prerequisiteJson: string, positionedReceipts: Array, neededJson: string): DependentIdleDeliveryResult /** * Publish a replayable `session_ready` readiness signal. `ready_json` is a * JSON `SessionReady`. Unlike [`Self::push_frame`], this frame is buffered * and replayed to late-connecting clients, so an SDK client * can wait for readiness deterministically instead of treating WS-open as * readiness. * * # Errors * Fails if not started or `ready_json` is not a valid `SessionReady`. */ pushSessionReady(readyJson: string): void /** * Resolve a legacy/non-arbitrated action locally (the CLI/TUI answered). * Arbitrated presentations require their opaque exact lease to be passed to * [`Self::retire_if_unclaimed`], so an id-only local resolution fails * closed. */ resolveLocal(id: string, answerJson?: string | undefined | null): void /** * Resolve an unclaimed legacy action. Forward-mode replies are * receipt-bound and must use `resolveClaim` instead. * * # Errors * Fails if not started, `answer_json` is invalid, or the action is claimed. */ resolveClient(id: string, answerJson?: string | undefined | null, idempotencyKey?: string | undefined | null): void /** Resolve a reply claim after durable semantic settlement. */ resolveClaim(replyReceiptId: string, answerJson?: string | undefined | null, idempotencyKey?: string | undefined | null): void /** Close an invalid claim terminally. Retrying must use a fresh action id. */ closeClaimInvalid(replyReceiptId: string, reason: string): void /** Cancel a claim as part of abort or shutdown cleanup. */ cancelClaim(replyReceiptId: string, reason: string): void /** * Unicast an origin-bound live acknowledgement and resolve with its exact * correlated terminal outcome (or native timeout evidence). */ requestAskSelectedAck(replyReceiptId: string, requestJson: string): Promise /** * Select one current capable participant for a recovery acknowledgement and * resolve with its exact terminal outcome. */ requestRecoveredAskSelectedAck(requestJson: string): Promise /** Correlate and terminalize an acknowledgement request. */ cancelAskSelectedAck(requestId: string, commitKey: string, reason: string): AskSelectedAckOutcomeEvent /** * Reject an unclaimed legacy reply. Claimed forward-mode replies must use * `closeClaimInvalid` with the exact receipt. * * # Errors * Fails if not started or the action is claimed. */ reject(id: string, reason?: string | undefined | null): void /** * Update whether the SDK workflow-gate resolver is currently available. * * # Errors * Fails if not started. */ setResolverAvailable(available: boolean): void /** Number of currently connected clients. */ clientCount(): number /** Stop the server (idempotent) and remove the endpoint discovery file. */ stop(): void /** Stop the server and resolve only after all native socket owners exit. */ stopAndWait(): Promise } /** Stable process reference. */ export declare class Process { /** Open a stable process reference from a PID. */ static fromPid(pid: number): Process | null /** Open stable process references whose executable path matches exactly. */ static fromPath(path: string): Array /** * Read-only observation of whether `pid` currently names a verifiable * process incarnation. * * Unlike [`Self::from_pid`] returning `null` (which conflates a confirmed- * dead pid with one that simply could not be queried), this keeps positive * OS-reported absence separate from every inconclusive outcome. It never * signals, kills, reaps, waits on, or spawns any process. */ static observe(pid: number): NativeProcessObservation /** Operating-system process identifier for this process reference. */ get pid(): number /** Kernel-derived identity evidence for this exact process incarnation. */ get incarnation(): string /** Parent process id for this process, when available. */ get ppid(): number | null /** Launch arguments for this process. */ args(): Array /** * Send `signal` only to this pinned process reference. * * On Linux this uses the owned pidfd; on Windows it uses the owned process * handle. macOS has no atomic identity-bound signal primitive, so this * operation deliberately fails closed there. It never discovers descendants * or signals a process group. Returns `false` when the pinned process has * already exited, the platform cannot bind delivery to the process * identity, or the operating system rejects delivery. */ signalRoot(signal: number): boolean /** * Send `signal` to this process and its descendants, children first. * * On Linux and macOS the signal is forwarded as-is. On Windows there is no * signal abstraction, so the `signal` argument is ignored and the entire * tree is hard-killed via `TerminateProcess`. Defaults to the POSIX * hard-kill signal. */ killTree(signal?: number | undefined | null): number /** * Gracefully terminate this process and its descendants. * * By default this waits 1000ms after polite termination before * hard-killing. Pass `graceful_ms < 0` to skip the graceful phase. */ terminate(options?: ProcessTerminateOptions | undefined | null): Promise /** * Wait until this process exits. * * When `options.timeout_ms` is omitted, waits until the process exits. */ waitForExit(options?: ProcessWaitOptions | undefined | null): Promise /** Process group id for this process, when supported by the platform. */ groupId(): number | null /** Direct children of this process as stable process references. */ children(): Array /** Current status of this process reference. */ status(): ProcessStatus } /** Stateful PTY session for interactive stdin/stdout passthrough. */ export declare class PtySession { constructor() /** Start a PTY command and stream output chunks via callback. */ start(options: PtyStartOptions, onChunk?: ((error: Error | null, chunk: string) => void) | undefined | null): Promise /** Write raw input bytes to PTY stdin. */ write(data: string): void /** Resize the active PTY. */ resize(cols: number, rows: number): void /** Force-kill the active PTY command. */ kill(): void } /** Retained descriptor-relative regular-file authority for streamed imports. */ export declare class RecoveryFsFile { /** Return the current identity of the retained regular file. */ identity(): RecoveryFsResult /** Read one bounded chunk from the retained file descriptor. */ readChunk(offset: number, maxBytes: number): RecoveryFsResult /** Close the retained regular-file descriptor. */ close(): RecoveryFsResult } /** Retained trusted-root authority for Linux recovery artifacts. */ export declare class RecoveryFsRoot { /** Return the stable identity of the retained root descriptor. */ identity(): RecoveryFsResult /** * Derive a retained child-directory capability from this root and exact * identity evidence. */ retainManagedDirectory(relativePath: string, expectedDev: string, expectedIno: string): RecoveryFsRoot /** * Open one regular, single-linked descendant through retained no-follow * traversal. */ openFile(relativePath: string): RecoveryFsFile /** * Enumerate regular, single-linked descendants through retained directory * descriptors. The returned data is a JSON array of relative paths. */ listFiles(maxEntries: number): RecoveryFsResult /** Stat one existing regular, single-linked file without following links. */ stat(relativePath: string): RecoveryFsResult /** Read one existing regular, single-linked file without following links. */ read(relativePath: string, maxBytes: number): RecoveryFsResult /** Read one managed artifact with the managed-storage size bound. */ readManaged(relativePath: string): RecoveryFsResult /** * Create one previously absent regular, owner-only file and synchronously * persist its contents. Existing entries are never replaced. */ create(relativePath: string, data: Uint8Array): RecoveryFsResult /** Create one managed artifact with the managed-storage size bound. */ createManaged(relativePath: string, data: Uint8Array): RecoveryFsResult /** * Atomically replace one exact regular file with a newly written managed * artifact. The destination must retain the supplied identity throughout * authorization. */ replaceManaged(relativePath: string, data: Uint8Array, expectedDev: string, expectedIno: string, expectedSize: string, expectedMtimeNs: string, expectedCtimeNs: string, expectedSha256: string): RecoveryFsResult /** * Synchronously append one record to an exact retained managed file without * replacing its inode or creating recovery copies. */ appendManaged(relativePath: string, data: Uint8Array, expectedDev: string, expectedIno: string, expectedSize: string, expectedMtimeNs: string, expectedCtimeNs: string, expectedSha256: string): RecoveryFsResult /** Remove one exact managed regular file through retained authority. */ removeManaged(relativePath: string, expectedDev: string, expectedIno: string, expectedSize: string, expectedMtimeNs: string, expectedCtimeNs: string, expectedSha256: string): RecoveryFsRetainedCleanupResult /** * Create each absent directory component beneath the retained root with * owner-only security. Existing components are re-opened no-follow. */ ensureManagedDirectory(relativePath: string): RecoveryFsResult /** * Move an exact managed file to an absent name entirely beneath this * retained root. The source identity is rechecked after the no-replace * rename, and the move is rolled back on a mismatch. */ renameManagedFileNoReplace(sourceRelativePath: string, destinationRelativePath: string, expectedDev: string, expectedIno: string, expectedSize: string, expectedMtimeNs: string, expectedCtimeNs: string, expectedSha256: string): RecoveryFsPublishResult /** Snapshot a managed directory tree entirely through the retained root. */ snapshotManagedTree(relativePath: string): NativeDirectoryTreeResult /** * Move an exact managed directory tree to an absent name through retained * authority. */ renameManagedTreeNoReplace(sourceRelativePath: string, destinationRelativePath: string, expected: NativeDirectoryTreeSnapshot): RecoveryFsPublishResult /** Remove an exact managed directory tree through retained authority. */ removeManagedTree(relativePath: string, expected: NativeDirectoryTreeSnapshot): RecoveryFsRetainedCleanupResult /** * Atomically install an already-created regular file at an absent name. * Both names remain relative to this retained root and are never resolved * through a pathname after their parent descriptors are acquired. */ install(sourceRelativePath: string, destinationRelativePath: string): RecoveryFsPublishResult /** * Synchronize the retained root directory, making a preceding create or * install durable when the filesystem supports directory fsync. */ fsync(): RecoveryFsResult /** * Fsync one expected object relative to the retained root and prove * identity. */ fsyncExpected(relativePath: string, directory: boolean, expectedDev: string, expectedIno: string, expectedSize: string, expectedMtimeNs: string, expectedSha256?: string | undefined | null): RecoveryFsResult /** Verify owner-only directory security on the retained root descriptor. */ verifyOwnerOnlyDirectory(): RecoveryFsResult close(): RecoveryFsResult } /** Persistent brush-core shell session. */ export declare class Shell { /** * Create a new shell session from optional configuration. * * The options set session-scoped environment variables and a snapshot path. */ constructor(options?: ShellOptions | undefined | null) /** * Run a shell command using the provided options. * * The `on_chunk` callback receives streamed stdout/stderr output. Returns * the exit code when the command completes, or flags when cancelled or * timed out. */ run(options: ShellRunOptions, onChunk?: ((error: Error | null, chunk: string) => void) | undefined | null): Promise /** * Abort all running commands for this shell session. * * Returns `Ok(())` even when no commands are running. */ abort(): Promise /** * Abort in-flight commands and release the retained shell session. * * `abort` leaves a completed session alive for reuse, so a caller that is * finished with a shell must call this to release the native process and * let the host exit. Returns `Ok(())` even when nothing is retained. */ close(): Promise } /** * Publish-result wire-contract sentinel. * * The loader requires this in addition to the release sentinel, so a * same-version modern artifact built before the retained-publish contract * cannot be selected over a compatible baseline. */ export declare function __piNativesPublishOutcomeV1(): void /** * Version sentinel — exists solely so the JS loader can prove at load time * that the `.node` file on disk is from the same package release as the * `index.js` ESM wrapper invoking it. * * The `js_name` is bumped by `scripts/release.ts` to match the new * `Cargo.toml` / `package.json` version on every release. The JS loader * computes the expected name from `package.json#version` and refuses to use * a `.node` that doesn't expose it, turning the silent * ` is not a function` crash from a locked-file update (the canonical * Windows `bun install -g` failure mode) into a clear load-time error. * * Bump policy: `__piNativesV{major}_{minor}_{patch}` — non-alphanumerics in * the version string are mapped to `_` to keep it a valid JS identifier. * MUST stay in sync with `VERSION_SENTINEL_EXPORT` in * `packages/natives/native/index.js` (which derives the name from * `package.json#version`). */ export declare function __piNativesV0_17_2(): void /** * Apply conservative pre-execution rewrites to a bash command. * * Strips trailing `| head|tail [safe-args]` and redundant trailing `2>&1` * from each top-level pipeline. The full rules and bail conditions live in * `pi_shell::fixup`. Synchronous and cheap (one parse pass over the input). */ export declare function applyBashFixups(command: string): BashFixupResult /** * Apply owner-only security to the exact caller descriptor and its retained * no-follow path. The descriptor is duplicated with close-on-exec and is never * returned to JavaScript. */ export declare function applyOwnerOnlyFdSecurity(path: string, kind: "directory" | "file", callerFd: number): NativeOwnerOnlySecurityResult export declare function applyOwnerOnlyPathSecurity(path: string, kind: "directory" | "file"): NativeOwnerOnlySecurityResult /** Typed terminal acknowledgement result returned by acknowledgement promises. */ export interface AskSelectedAckOutcomeEvent { status: string messageId?: number reason?: string } /** * Apply ast-grep rewrite rules to matching files; honors `dryRun` and returns * a promise. */ export declare function astEdit(options: AstReplaceOptions): Promise /** One ast-grep match with source range and optional meta-variables. */ export interface AstFindMatch { /** Display path of the matching file. */ path: string /** Matched source text. */ text: string /** Start byte offset in the file (UTF-8 byte index). */ byteStart: number /** End byte offset in the file (exclusive UTF-8 byte index). */ byteEnd: number /** 1-based start line. */ startLine: number /** 1-based start column. */ startColumn: number /** 1-based end line. */ endLine: number /** 1-based end column. */ endColumn: number /** Meta-variable name to captured text, when `includeMeta` was enabled. */ metaVariables?: Record } /** Options for `astGrep`: patterns, scan scope, and match limits. */ export interface AstFindOptions { /** ast-grep patterns to search for (OR across patterns). */ patterns?: Array /** Language override; otherwise inferred from file extension per candidate. */ lang?: string /** Single file or directory to scan (combined with `glob` when set). */ path?: string /** Optional glob filter relative to the search root. */ glob?: string /** Rule selector for multi-rule ast-grep configurations. */ selector?: string /** Pattern strictness; defaults to smart matching when omitted. */ strictness?: AstMatchStrictness /** Maximum matches to return after `offset` (default applies when omitted). */ limit?: number /** Number of leading matches to skip before applying `limit`. */ offset?: number /** When true, include meta-variable bindings per match. */ includeMeta?: boolean /** * Reserved for contextual snippets; not used by the current native find * path. */ context?: number /** Optional cancellation handle (library-specific). */ signal?: unknown /** Wall-clock timeout for the worker task in milliseconds. */ timeoutMs?: number } /** Aggregated search statistics and any parse or compile diagnostics. */ export interface AstFindResult { /** Page of matches after sort, offset, and limit. */ matches: Array /** Total matches found before paging (can exceed `matches.length`). */ totalMatches: number /** Distinct files that contained at least one match. */ filesWithMatches: number /** Files examined for the query. */ filesSearched: number /** True when results were truncated by `limit`. */ limitReached: boolean /** Non-fatal parse or pattern errors collected during the run. */ parseErrors?: Array } /** * Search source files with ast-grep patterns; returns a promise resolved on a * worker thread. */ export declare function astGrep(options: AstFindOptions): Promise /** ast-grep pattern strictness (controls how patterns match syntax). */ export declare enum AstMatchStrictness { /** Match at the concrete syntax tree level. */ Cst = 'cst', /** Balanced default suitable for most searches. */ Smart = 'smart', /** Match at the AST level. */ Ast = 'ast', /** More permissive matching. */ Relaxed = 'relaxed', /** Match structural signatures. */ Signature = 'signature', /** Template-style pattern matching. */ Template = 'template' } /** * One textual replacement applied to a file (before/after slice and * coordinates). */ export interface AstReplaceChange { /** File path for this change. */ path: string /** Original matched text. */ before: string /** Replacement text. */ after: string /** Start byte offset of the replaced span. */ byteStart: number /** End byte offset of the replaced span (exclusive). */ byteEnd: number /** * Length of deleted text in bytes (may differ from `byteEnd - byteStart` * for edge cases). */ deletedLength: number /** 1-based start line of the match. */ startLine: number /** 1-based start column. */ startColumn: number /** 1-based end line. */ endLine: number /** 1-based end column. */ endColumn: number } /** Per-file replacement count after an `astEdit` run. */ export interface AstReplaceFileChange { /** File that had replacements. */ path: string /** Number of replacements in that file. */ count: number } /** * Options for `astEdit`: rewrite rules, scan scope, safety limits, and * dry-run. */ export interface AstReplaceOptions { /** Map of pattern string to replacement template. */ rewrites?: Record /** Language override; otherwise inferred from discovered files. */ lang?: string /** Single file or directory to rewrite. */ path?: string /** Optional glob filter within the search root. */ glob?: string /** Rule selector for multi-rule configurations. */ selector?: string /** Pattern strictness for rewrites. */ strictness?: AstMatchStrictness /** When true (default), compute changes without writing files. */ dryRun?: boolean /** Cap on replacement applications across all files. */ maxReplacements?: number /** Cap on distinct files that may be modified. */ maxFiles?: number /** Fail the operation when a file cannot be parsed for rewriting. */ failOnParseError?: boolean /** Optional cancellation handle. */ signal?: unknown /** Wall-clock timeout for the worker task in milliseconds. */ timeoutMs?: number } /** Summary of an ast-grep rewrite pass, including whether disk writes occurred. */ export interface AstReplaceResult { /** Individual replacement records (may be large). */ changes: Array /** Replacement counts grouped by file. */ fileChanges: Array /** Total replacements applied or previewed. */ totalReplacements: number /** Files that had at least one replacement. */ filesTouched: number /** Files considered for rewriting. */ filesSearched: number /** False when `dryRun` prevented writing. */ applied: boolean /** True when limits stopped further replacements. */ limitReached: boolean /** Parse or pattern errors when not failing the whole operation. */ parseErrors?: Array } /** * Result of [`apply_bash_fixups`]: a possibly-rewritten command plus the * substrings that were removed (in source order). */ export interface BashFixupResult { /** Possibly-rewritten command. Equal to the input when no fixup fired. */ command: string /** Substrings removed, in source order — suitable for a user-facing notice. */ stripped: Array } export interface BuildInfo { version: string languageSet: string } export declare function canonicalExistingDirectoryIdentity(path: string | Uint8Array): NativeCanonicalDirectoryIdentity /** Clipboard image payload encoded as PNG bytes. */ export interface ClipboardImage { /** PNG-encoded image bytes. */ data: Uint8Array /** MIME type for the encoded image payload. */ mimeType: string } /** * Capture the primary display for JS callers (macOS). * * Requires the Screen & System Audio Recording permission. This is the * read-only `screenshot` primitive of the computer-use tool; input primitives * land behind the same surface once the Accessibility gate is satisfied in a * granted `gjc` process. * * # Errors * Returns an error when capture fails (e.g. Screen Recording not granted). */ export declare function computerScreenshot(): ComputerScreenshot /** * A captured primary-display screenshot returned to JS. * * `width_px`/`height_px` are the physical pixels that define the action * coordinate space (see the coordinate contract); the scale/origin map them to * macOS logical points. */ export interface ComputerScreenshot { /** PNG-encoded image bytes. */ png: Uint8Array /** Screenshot width in physical pixels. */ widthPx: number /** Screenshot height in physical pixels. */ heightPx: number /** Physical-pixels-per-logical-point along X. */ scaleX: number /** Physical-pixels-per-logical-point along Y. */ scaleY: number /** Logical origin X of the display (points). */ originX: number /** Logical origin Y of the display (points). */ originY: number /** Stable hash of the display geometry used for stale-display checks. */ displayEpoch: number /** Process-local opaque capture id. */ captureId: number } /** A context line (before or after a match). */ export interface ContextLine { /** 1-indexed line number in the source file. */ lineNumber: number /** Raw line content (trimmed line ending). */ line: string } /** * Copy plain text to the system clipboard. * * # Parameters * - `text`: UTF-8 text to place on the clipboard. * * # Errors * Returns an error if clipboard access fails. */ export declare function copyToClipboard(text: string): void /** * Returns the operating system's canonical path for the running executable. * Unlike argv, this is not supplied by the process caller. */ export declare function currentExecutablePath(): string | null /** Explicit result of binding an idle action to an exact prerequisite cohort. */ export interface DependentIdleDeliveryResult { status: 'queued' | 'no_recipients' | 'rejected' | 'partial' recipientCount: number queuedCount: number } /** * Detect macOS system appearance via CoreFoundation. * Returns `"dark"` or `"light"` on macOS, `null` on other platforms. */ export declare function detectMacOSAppearance(): MacOSAppearance | null /** * Compute a line-level diff byte-identical to jsdiff `Diff.diffLines(old, * new)` with default options. Returns ordered `{added, removed, value}` parts. */ export declare function diffLines(oldStr: string, newStr: string): Array export interface DoctorJournalCreateResult { authority?: DoctorJournalAuthority sideEffectStarted: boolean reasonCode?: string } export interface DoctorLinkSwapResult { status: string changed: boolean verified: boolean code?: string } /** Ellipsis strategy for [`truncate_to_width`]. */ export declare enum Ellipsis { /** Use a single Unicode ellipsis character ("…"). */ Unicode = 0, /** Use three ASCII dots ("..."). */ Ascii = 1, /** Omit ellipsis entirely. */ Omit = 2 } /** * Encode image bytes into a SIXEL escape sequence for terminal rendering. * * The input image is decoded and resized to the requested pixel dimensions * before encoding. * * # Errors * Returns an error if decoding, resizing, or SIXEL encoding fails. */ export declare function encodeSixel(bytes: Uint8Array, targetWidthPx: number, targetHeightPx: number): string /** * Remove a directory tree only when a fresh descriptor-relative snapshot * exactly equals the persisted snapshot. POSIX first no-replace detaches the * verified root to its deterministic `.removing` sibling; the reopened * detached descriptor remains authoritative throughout payload scrubbing and * replay. */ export declare function exactRemoveDirectoryTree(path: string, snapshot: NativeDirectoryTreeSnapshot, parentIdentity?: NativeDirectoryParentIdentity | undefined | null, detachOnly?: boolean | undefined | null): NativeExactUnlinkResult /** * Atomically replace a staged regular file only after validating the exact * staged source and expected destination. * * Both identities must describe regular files in the same retained parent, not * directories or detach-only requests. Publication uses an atomic namespace * exchange so a substituted source or destination is never overwritten. */ export declare function exactReplacePath(sourcePath: string, destinationPath: string, expectedSource: NativeExactFileIdentity, expectedDestination: NativeExactFileIdentity): NativeExactUnlinkResult /** * Atomically replace an in-place executable (or other running-process * payload) only after validating the exact staged source and current * destination. * * The old destination bytes are retired to a caller-preauthorized backup * name instead of being scrubbed or unlinked. * * This exists for D4 self-replacement: [`exact_replace_path`] retires its * predecessor through the same descriptor-scrub/exchange-cleanup protocol * [`exact_unlink`] uses, which either truncates the old bytes in place * (POSIX, when the exchange succeeds) or deletes them outright (Windows). * Both are safe for a config file with no open executing mapping, but unsafe * for a binary a running process may still be mapped from or about to * re-exec: scrubbing or deleting those bytes out from under a live mapping * can crash the very process performing the update. `exact_replace_retained` * therefore never truncates or deletes the predecessor at all -- it commits * the atomic exchange (POSIX) or native rename swap (Windows) and then * renames the old destination to `backup_name` in the same parent, leaving * its bytes byte-for-byte intact and readable at that retained path. * * `backup_name` must be a bounded (<=255 bytes), single-path-component, * separator-free, non-`.`/`..` name; it is used verbatim, with no * auto-suffixing, and an already-occupied backup name is refused rather than * overwritten -- the caller is responsible for choosing a name that will not * collide with a foreign object, and a collision leaves the retired * predecessor's replacement decision to a later caller rather than losing * data. Both identities must describe regular files in the same retained * parent, never directories or detach-only requests, and both are * CAS-checked (parent identity + dev/ino/size/mtime/hash + regular/ * single-link ownership; hard-linked or symlinked source/destination are * rejected) before anything is mutated. On Windows a pre-mutation * `STATUS_SHARING_VIOLATION` on the destination open is reported as a * distinct `sharing_violation` code with `windows_error_code` set -- exactly * as [`exact_replace_path`] already reports it -- and is always surfaced * before any rename, so it is never mistaken for a post-effect failure. */ export declare function exactReplaceRetained(sourcePath: string, destinationPath: string, backupName: string, expectedSource: NativeExactFileIdentity, expectedDestination: NativeExactFileIdentity): NativeExactUnlinkResult /** * Restore only the detached object that still has the supplied exact * identity. The detached and original paths must retain the same validated * parent, and restoration never replaces an existing original path. */ export declare function exactRestore(detachedPath: string, originalPath: string, identity: NativeExactFileIdentity): NativeExactUnlinkResult /** * Exchange a staged symlink with the expected destination using the platform * atomic name-exchange primitive. * * The destination's parent is retained as a single opened descriptor for * every check and mutation. The retired link is moved into `quarantine_path` * with a no-replace rename; it is never deleted and a foreign occupant at * any of the three names is always refused rather than overwritten. */ export declare function exactSwapManagedLink(stagedPath: string, destinationPath: string, quarantinePath: string, parentDev: string, parentIno: string, oldDev: string, oldIno: string, oldTarget: string, stagedDev: string, stagedIno: string, newTarget: string): DoctorLinkSwapResult /** * Delete only the regular file that still has the supplied platform identity. * * This never follows a symlink or reparse point in the target path and reports * validation failures as typed results rather than deleting a replacement. */ export declare function exactUnlink(path: string, identity: NativeExactFileIdentity): NativeExactUnlinkResult /** * Delete only the regular file that still has the supplied platform identity, * without the exchange/quarantine protocol used by [`exact_unlink`]. * * This is reserved for already-detached inert debris: the operation first * moves the pathname to the caller's private no-replace quarantine, verifies * the moved object, and only then unlinks that private name. A successor * published at the original pathname is therefore never consumed by cleanup, * and this path cannot manufacture another exchange placeholder. */ export declare function exactUnlinkDirect(path: string, identity: NativeExactFileIdentity): NativeExactUnlinkResult /** * Start direct exact unlink without retaining an N-API task or promise. * * Cleanup is best effort: the detached operation is intentionally abandoned * when the process exits, while the exact identity checks still protect any * pathname that remains alive long enough to be examined. A bounded queue * keeps cleanup bursts from spawning an unbounded number of OS threads; work * that cannot be queued is left for the owning reconciliation pass. */ export declare function exactUnlinkDirectDetached(path: string, identity: NativeExactFileIdentity): boolean /** * Execute a brush shell command. * * Creates a fresh session for each call. The `on_chunk` callback receives * streamed stdout/stderr output. Returns the exit code when the command * completes, or flags when cancelled or timed out. */ export declare function executeShell(options: ShellExecuteOptions, onChunk?: ((error: Error | null, chunk: string) => void) | undefined | null): Promise /** * Extract the before/after slices around an overlay region. * * Preserves ANSI state so the `after` segment renders correctly after * truncation. */ export declare function extractSegments(line: string, beforeEnd: number, afterStart: number, afterLen: number, strictAfter: boolean, tabWidth: number): ExtractSegmentsResult /** Before/after UTF-16 segments around an overlay region, with measured widths. */ export interface ExtractSegmentsResult { /** UTF-16 content before the overlay region. */ before: string /** Visible width of the `before` segment. */ beforeWidth: number /** UTF-16 content after the overlay region. */ after: string /** Visible width of the `after` segment. */ afterWidth: number } /** Resolved filesystem entry kind for glob filters and match metadata. */ export declare enum FileType { /** Regular file. */ File = 1, /** Directory. */ Dir = 2, /** Symbolic link. */ Symlink = 3 } /** Fuzzy file path search for autocomplete. */ export declare function fuzzyFind(options: FuzzyFindOptions): Promise /** A single match in fuzzy find results. */ export interface FuzzyFindMatch { /** Relative path from the search root (uses `/` separators). */ path: string /** Whether this entry is a directory. */ isDirectory: boolean /** Match quality score (higher is better). */ score: number } /** Options for fuzzy file path search. */ export interface FuzzyFindOptions { /** Fuzzy query to match against file paths (case-insensitive). */ query: string /** Directory to search. */ path: string /** Include hidden files (default: false). */ hidden?: boolean /** Respect .gitignore (default: true). */ gitignore?: boolean /** Enable shared filesystem scan cache (default: false). */ cache?: boolean /** Maximum number of matches to return (default: 100). */ maxResults?: number /** Abort signal for cancelling the operation. */ signal?: unknown /** Timeout in milliseconds for the operation. */ timeoutMs?: number } /** Result of fuzzy file path search. */ export interface FuzzyFindResult { /** Matched entries (up to `maxResults`). */ matches: Array /** Total number of matches found (may exceed `matches.len()`). */ totalMatches: number } /** * Protocol version for [`exact_swap_managed_link`]'s argument contract. * * The caller checks this before staging anything so a stale addon (old * argument order/count) is refused up front rather than discovered * mid-mutation. */ export declare function getDoctorLinkProtocolVersion(): number /** Get list of supported languages. */ export declare function getSupportedLanguages(): Array /** * Get work profile data from the last N seconds. * * Always-on profiling - no need to start/stop. Just call this to get * recent activity. */ export declare function getWorkProfile(lastSeconds: number): WorkProfile /** * Find filesystem entries matching a glob pattern. * * Resolves the search root, scans entries, applies glob and optional file-type * filters, and optionally streams each accepted match through `on_match`. * * If `sortByMtime` is enabled, all matching entries are collected, sorted by * descending mtime, then truncated to `maxResults`. * * # Errors * Returns an error when the search path cannot be resolved, the path is not a * directory, the glob pattern is invalid, or cancellation/timeout is * triggered. */ export declare function glob(options: GlobOptions, onMatch?: ((error: Error | null, match: GlobMatch) => void) | undefined | null): Promise /** A single filesystem entry from a directory scan. */ export interface GlobMatch { /** Relative path from the search root, using forward slashes. */ path: string /** Resolved filesystem type for the match. */ fileType: FileType /** * Modification time in milliseconds since Unix epoch (from * `symlink_metadata`). */ mtime?: number /** File size in bytes for regular files. */ size?: number } /** Input options for `glob`, including traversal, filtering, and cancellation. */ export interface GlobOptions { /** Glob pattern to match (e.g., "*.ts"). */ pattern: string /** Directory to search. */ path: string /** * Filter by file type: "file", "dir", or "symlink". Symlinks are * matched for file/dir filters based on their target type. */ fileType?: FileType /** Match simple patterns recursively by default (`*.ts` -> recursive). */ recursive?: boolean /** Include hidden files (default: false). */ hidden?: boolean /** Maximum number of results to return. */ maxResults?: number /** Respect .gitignore files (default: true). */ gitignore?: boolean /** Enable shared filesystem scan cache (default: false). */ cache?: boolean /** Sort results by mtime (most recent first) before applying limit. */ sortByMtime?: boolean /** * Include `node_modules` entries when the pattern does not explicitly * mention them. */ includeNodeModules?: boolean /** Abort signal for cancelling the operation. */ signal?: unknown /** Timeout in milliseconds for the operation. */ timeoutMs?: number } /** Result payload returned by a glob operation. */ export interface GlobResult { /** Matched filesystem entries. */ matches: Array /** Number of returned matches (`matches.len()`), clamped to `u32::MAX`. */ totalMatches: number } /** * Search files for a regex pattern. * * # Arguments * - `options`: Pattern, path, filters, and output mode. * - `on_match`: Optional callback invoked per match/result. * * # Returns * Aggregated results across matching files. */ export declare function grep(options: GrepOptions, onMatch?: ((error: Error | null, match: GrepMatch) => void) | undefined | null): Promise /** A single match in a grep result. */ export interface GrepMatch { /** File path for the match (relative for directory searches). */ path: string /** 1-indexed line number (0 for count-only entries). */ lineNumber: number /** The matched line content (empty for count-only entries). */ line: string /** Context lines before the match. */ contextBefore?: Array /** Context lines after the match. */ contextAfter?: Array /** Whether the line was truncated. */ truncated?: boolean /** Per-file match count (count mode only). */ matchCount?: number } /** Options for searching files on disk. */ export interface GrepOptions { /** Regex pattern to search for. */ pattern: string /** Directory or file to search. */ path: string /** Glob filter for filenames (e.g., "*.ts"). */ glob?: string /** Filter by file type (e.g., "js", "py", "rust"). */ type?: string /** Case-insensitive search. */ ignoreCase?: boolean /** Enable multiline matching. */ multiline?: boolean /** Include hidden files (default: true). */ hidden?: boolean /** Respect .gitignore files (default: true). */ gitignore?: boolean /** Enable shared filesystem scan cache (default: false). */ cache?: boolean /** Maximum number of matches to return. */ maxCount?: number /** Skip first N matches. */ offset?: number /** Lines of context before matches. */ contextBefore?: number /** Lines of context after matches. */ contextAfter?: number /** Lines of context before/after matches (legacy). */ context?: number /** Truncate lines longer than this (characters). */ maxColumns?: number /** Output mode (content, filesWithMatches, or count). */ mode?: GrepOutputMode /** Abort signal for cancelling the operation. */ signal?: unknown /** Timeout in milliseconds for the operation. */ timeoutMs?: number } /** Output mode for [`search`] and [`grep`] (string values match JS callers). */ export declare enum GrepOutputMode { /** Emit matched lines (and optional context lines). */ Content = 'content', /** Emit per-file or total counts instead of line content. */ Count = 'count', /** Emit one row per file that matched, without line content. */ FilesWithMatches = 'filesWithMatches' } /** Result of searching files. */ export interface GrepResult { /** Matches or per-file counts, depending on output mode. */ matches: Array /** * Total matches across all files, or matched file count in filesWithMatches * mode. */ totalMatches: number /** Number of files with at least one match. */ filesWithMatches: number /** Number of files searched. */ filesSearched: number /** Whether the limit/offset stopped the search early. */ limitReached?: boolean } export interface H01BestFuzzyMatch { actualText: string startIndex: number startLine: number confidence: number } export interface H01BestFuzzyMatchResult { best?: H01BestFuzzyMatch aboveThresholdCount: number secondBestScore: number } export declare function h01FindBestFuzzyMatch(content: string, target: string, threshold: number): H01BestFuzzyMatchResult export declare function h02ScoreSequenceFuzzy(lines: Array, pattern: Array, start: number, eof: boolean): H02SequenceFuzzyResult export interface H02SequenceFuzzyResult { index?: number confidence: number matchCount: number matchIndices: Array secondBestScore: number } export declare function h06FormatHashLines(text: string, startLine?: number | undefined | null): string /** * Quick check if content matches a pattern. * * # Arguments * - `content`: `Uint8Array`/`Buffer` (zero-copy) or `string` (UTF-8). * - `pattern`: `Uint8Array`/`Buffer` (zero-copy) or `string` (UTF-8). * - `ignore_case`: Case-insensitive matching. * - `multiline`: Enable multiline regex mode. * * # Returns * True if any match exists; false on no match. */ export declare function hasMatch(content: string | Uint8Array, pattern: string | Uint8Array, ignoreCase?: boolean | undefined | null, multiline?: boolean | undefined | null): boolean /** * Highlight code and return ANSI-colored lines. * * # Arguments * * `code` - The source code to highlight * * `lang` - Language identifier (e.g., "rust", "typescript", "python") * * `colors` - Theme colors as ANSI escape sequences * * # Returns * Highlighted code with ANSI color codes, or the original code if highlighting * fails. */ export declare function highlightCode(code: string, lang: string | undefined | null, colors: HighlightColors): string /** * Theme colors for syntax highlighting. * Each color is an ANSI escape sequence (e.g., "\x1b[38;2;255;0;0m"). */ export interface HighlightColors { /** ANSI color for comments. */ comment: string /** ANSI color for keywords. */ keyword: string /** ANSI color for function names. */ function: string /** ANSI color for variables and identifiers. */ variable: string /** ANSI color for string literals. */ string: string /** ANSI color for numeric literals. */ number: string /** ANSI color for type identifiers. */ type: string /** ANSI color for operators. */ operator: string /** ANSI color for punctuation tokens. */ punctuation: string /** ANSI color for diff inserted lines. */ inserted?: string /** ANSI color for diff deleted lines. */ deleted?: string } /** * Convert HTML source to Markdown with optional preprocessing. * * # Errors * Returns an error if the conversion fails or the worker task aborts. */ export declare function htmlToMarkdown(html: string, options?: HtmlToMarkdownOptions | undefined | null): Promise /** Options for HTML to Markdown conversion. */ export interface HtmlToMarkdownOptions { /** Remove navigation elements, forms, headers, footers. */ cleanContent?: boolean /** Skip images during conversion. */ skipImages?: boolean } /** * An authenticated inbound message forwarded to the TypeScript host: free-text * injection, ephemeral side-question request/cancel, in-thread config command, * or deterministic control command. */ export interface InboundEvent { /** * Inbound kind (`user_message`, `ephemeral_turn`, * `ephemeral_turn_cancel`, `config_command`, or `control_command`). */ kind: string /** * Server-authenticated identity of the WebSocket connection that delivered * this event. */ connectionId: string /** The session this inbound belongs to. */ sessionId: string /** Free-text body (`user_message` or `ephemeral_turn` only). */ text?: string /** * Telegram update id for dedupe (`user_message`, `ephemeral_turn`, or * `ephemeral_turn_cancel` only). */ updateId?: number /** * Originating thread/topic id (`user_message`, `ephemeral_turn`, or * `ephemeral_turn_cancel` only). */ threadId?: string /** * Originating Telegram message id (`ephemeral_turn` and * `ephemeral_turn_cancel` only). */ messageId?: number /** Requested verbosity `"lean"|"verbose"` (`config_command` only). */ verbosity?: string /** Requested redaction state (`config_command` only). */ redact?: boolean /** * Client-generated request id (`ephemeral_turn`, `ephemeral_turn_cancel`, * or `control_command` only). */ requestId?: string /** Cancellation reason (`ephemeral_turn_cancel` only). */ reason?: string /** JSON-encoded command payload (`control_command` only). */ commandJson?: string /** * Inline image attachments forwarded with the message (`user_message` * only). */ images?: Array } /** One inline image attachment forwarded with an inbound user message. */ export interface InboundImageEvent { /** Base64-encoded image bytes. */ data: string /** MIME type when known (e.g. "image/jpeg"). */ mime?: string } /** * Installs a Rust panic hook only when `GJC_NATIVE_CRASH_DIAGNOSTICS` is set. * * This is an opt-in structured panic report, not a minidump/signal handler. * It intentionally avoids always-on work and does not attempt to recover from * panics crossing N-API boundaries. */ export declare function initNativeCrashDiagnostics(): boolean /** * Validate the exact permission repair preconditions without changing * metadata. */ export declare function inspectConfigFilePermissionRepair(path: string, identity: NativeExactFileIdentity, expectedMode: number): NativePermissionRepairResult /** * Invalidate the filesystem scan cache. * * When called with a path, removes entries for roots containing that path. * When called without a path, clears the entire cache. * * Intended to be called after agent file mutations (write, edit, rename, * delete). */ export declare function invalidateFsScanCache(path?: string | undefined | null): void /** Kind enum of the backend selected by default for this build target. */ export declare function isoBackend(): IsoBackendKind /** * Isolation backend identifier. Numeric so the JS side can `switch` on * the enum without string comparisons. */ export declare enum IsoBackendKind { Apfs = 0, Btrfs = 1, Zfs = 2, LinuxReflink = 3, Overlayfs = 4, WindowsBlockClone = 5, Projfs = 6, Rcopy = 7 } /** How a single file changed between `lower` and `merged`. */ export declare enum IsoChangeKind { Added = 0, Modified = 1, Removed = 2 } /** * Capture the changes between `lower` and `merged`. * * Uses [`pi_iso::IsolationBackend::diff`]'s default implementation — * `git diff` when `merged/.git` exists, otherwise a mtime-skipped tree * walk. The backend selection only affects the lifecycle methods; diff * behaviour is uniform. */ export declare function isoDiff(lower: string, merged: string): Promise export interface IsoDiff { files: Array } /** One entry in an [`IsoDiff`]. */ export interface IsoFileChange { /** Path relative to `merged`. */ path: string op: IsoChangeKind /** * Unified-diff text. `None` (`null` in JS) means the file is binary; * read it directly from `merged` if you need the bytes. */ diff?: string } /** * True if `message` is an error message produced by [`IsoError::Unavailable`]. * Use this to distinguish "this backend isn't installed" from a hard * failure when handling caught errors on the JS side. */ export declare function isoIsUnavailableError(message: string): boolean /** * Probe whether the requested backend can start on this host. Pass * `null`/omit `kind` to probe the platform-native backend. */ export declare function isoProbe(kind?: IsoBackendKind | undefined | null): IsoProbeResult /** Probe result for a specific isolation backend. */ export interface IsoProbeResult { /** True when the backend's prerequisites are satisfied. */ available: boolean /** Human-readable explanation when `available` is false. */ reason?: string /** Resolved backend kind. */ kind: IsoBackendKind } /** * Pick the best backend available right now. `preferred` is treated as * a hint — see [`pi_iso::resolve`] for the exact priority rules. */ export declare function isoResolve(preferred?: IsoBackendKind | undefined | null): IsoResolveResult /** Outcome of [`iso_resolve`]. */ export interface IsoResolveResult { /** Backend that will actually be tried first. */ kind: IsoBackendKind /** Host-available backends in retry order, starting with `kind`. */ candidates: Array /** * True when the resolver fell back from `preferred` (or from the * first automatic candidate) to a different backend. */ fellBack: boolean /** Human-readable reason for the fallback, if any. */ reason?: string } /** * Materialise `merged` as a writable view of `lower` using the requested * backend. `kind` defaults to the native backend. */ export declare function isoStart(kind: IsoBackendKind | undefined | null, lower: string, merged: string): Promise /** Tear down a previously started backend at `merged`. */ export declare function isoStop(kind: IsoBackendKind | undefined | null, merged: string): Promise /** Event types from Kitty keyboard protocol (flag 2). */ export declare enum KeyEventType { /** Key press event. */ Press = 1, /** Key repeat event. */ Repeat = 2, /** Key release event. */ Release = 3 } /** Observable counters for the internal known-good N-API frame lane. */ export interface KnownGoodFrameStats { /** Frames constructed as `TurnStream` without parsing a JSON string. */ knownGoodTurnStreamFrames: number /** JSON serde parses of externally supplied `turn_stream` frames. */ turnStreamSerdeValidationParses: number /** * Base64 characters encoded in Rust for `file_attachment` frames (the JS * side crosses raw `Buffer` bytes and never allocates the base64 string). */ fileAttachmentRustBase64Chars: number } /** * One diff component, mirroring jsdiff's change object (sans `count`, which * the TS `generateDiffString` formatter does not consume). */ export interface LineDiffPart { added: boolean removed: boolean value: string } /** * Publish a staged regular file under a destination name that must not already * exist, using `linkat(2)` instead of a rename flag. This is the stand-in for * `rename_no_replace_path` on filesystems that implement no rename flag at all * (NFS answers `EINVAL`, pre-3.15 kernels `ENOSYS`), and it carries the same * no-overwrite guarantee because `linkat` fails with `EEXIST`. * * The source name survives the call. Callers holding a descriptor on the * staged object must keep it across this publication and unlink the staging * name only after releasing it: NFS silly-renames a still-open name instead of * removing it, leaving a second link on the published inode. */ export declare function linkNoReplacePath(sourcePath: string, destinationPath: string): NativeNoReplaceResult /** * Async variant of [`link_no_replace_path`] scheduled on the libuv blocking * pool; see [`rename_no_replace_path_async`] for the rationale. */ export declare function linkNoReplacePathAsync(sourcePath: string, destinationPath: string): Promise /** * Walk the workspace once and return tree entries plus AGENTS.md candidates. * * File-level ignore rules for AGENTS.md are bypassed by checking each * traversed directory directly when `collectAgentsMd` is enabled, but ignored * directories are still pruned by the walker and are not searched. */ export declare function listWorkspace(options: ListWorkspaceOptions): Promise /** Input options for `listWorkspace`, the single-pass workspace startup scan. */ export interface ListWorkspaceOptions { /** Directory to scan. */ path: string /** Maximum depth for returned tree entries. Root children are depth 1. */ maxDepth: number /** Include hidden files and directories. Default: false. */ hidden?: boolean /** Respect .gitignore files. Default: true. */ gitignore?: boolean /** * Also surface AGENTS.md files in directories at depth 1..=4, even when * gitignore would otherwise hide the file. Walks deeper than `maxDepth` * to find them. Default: false. */ collectAgentsMd?: boolean /** Timeout in milliseconds for the operation. */ timeoutMs?: number /** Abort signal for cancelling the operation. */ signal?: unknown } /** Result payload returned by a workspace scan. */ export interface ListWorkspaceResult { /** Entries within `maxDepth`, with mtime and regular-file size metadata. */ entries: Array /** * Directory-scoped AGENTS.md files within depth 1..=4 (capped at 200). * Always empty when `collectAgentsMd` is false. */ agentsMdFiles: Array /** True when any output cap was hit. */ truncated: boolean } /** * System UI appearance reported by native macOS APIs (`detectMacOSAppearance` * and observer). */ export declare enum MacOSAppearance { /** Dark color scheme. */ Dark = 'dark', /** Light color scheme. */ Light = 'light' } /** * Options for starting a macOS power assertion. * * Each boolean maps to a `caffeinate(8)` flag and a corresponding `IOKit` * `IOPMAssertion` type. Multiple flags can be combined; when set, one * assertion is taken per flag and all are released together when the * handle is stopped or dropped. * * If every flag is unset (or omitted), the handle behaves as if `idle` * were `true` — preserving the historical default of `caffeinate -i`. */ export interface MacOSPowerAssertionOptions { /** Human-readable reason shown in macOS power diagnostics. */ reason?: string /** `caffeinate -i`: prevent the system from idle-sleeping. */ idle?: boolean /** `caffeinate -s`: prevent the system from sleeping (AC power only). */ system?: boolean /** `caffeinate -u`: declare the user is active (wakes the display). */ user?: boolean /** `caffeinate -d`: prevent the display from idle-sleeping. */ display?: boolean } /** A single match in the content. */ export interface Match { /** 1-indexed line number. */ lineNumber: number /** The matched line content. */ line: string /** Context lines before the match. */ contextBefore?: Array /** Context lines after the match. */ contextAfter?: Array /** Whether the line was truncated. */ truncated?: boolean } /** * Match input data against a key identifier string. * * Returns true when the bytes represent the specified key with modifiers. */ export declare function matchesKey(data: string, keyId: string, kittyProtocolActive: boolean): boolean /** * Match Kitty protocol input against a codepoint and modifier mask. * * Returns true when the parsed sequence matches the expected codepoint (or * base layout key) and modifier bits. */ export declare function matchesKittySequence(data: string, expectedCodepoint: number, expectedModifier: number): boolean /** * Check if input matches a legacy escape sequence for the given key name. * * Returns true only when the byte sequence maps to the exact key identifier. */ export declare function matchesLegacySequence(data: string, keyName: string): boolean /** N-API opt-in handle for the minimizer. */ export interface MinimizerOptions { /** Master switch. Absent / false = disabled. */ enabled?: boolean /** * Optional path to a TOML settings file whose values override * field-level defaults. `~` is expanded. */ settingsPath?: string /** * Optional xxHash64 digest (hex) of the settings file contents. When * supplied, the engine refuses to honor a settings file whose hash does * not match — a lightweight trust gate for agent-controllable paths. */ settingsHash?: string /** * Opt-in allowlist of program names (e.g. `"git"`). When empty or * absent, all built-in filters are active. */ only?: Array /** Program names explicitly excluded from minimization. */ except?: Array /** * Maximum captured bytes per command before the engine falls back to * the raw, un-minimized output. Default 4 MiB. */ maxCaptureBytes?: number } /** * Telemetry for a single minimization. * * Surfaced when the minimizer actually rewrote the command's output. The * session layer is expected to persist `original_text` via its * `ArtifactManager`, splice the resulting `artifact://` reference * into `text`, and replace any previously streamed raw output with the * minimized text. */ export interface MinimizerResult { /** * Dispatch label produced by the minimizer (e.g. `"git"`, * `"pipeline:gradle"`, `"pipeline+builtin"`). */ filter: string /** * The minimized replacement text. Callers that streamed raw chunks * during execution should clear and replace their accumulated output * with this text. */ text: string /** The full original capture, before minimization. */ originalText: string /** Captured byte length before minimization. */ inputBytes: number /** Byte length of the minimized text the consumer received. */ outputBytes: number } /** Evidence for one Linux POSIX ACL attribute. */ export interface NativeAclAttributeEvidence { clear: string query: string } /** Bounded Linux POSIX ACL evidence for an owner-only result. */ export interface NativeAclEvidence { access: NativeAclAttributeEvidence default?: NativeAclAttributeEvidence } /** Classification of a read-only retained-publication observation. */ export interface NativeBrokerPublicationObservation { kind: string } /** Result of a retained positional heartbeat write or sync. */ export interface NativeBrokerPublicationOperation { kind: string } export interface NativeBrokerRestartIntent { requestId: string lease: string expiresAt: number } /** * Existing file-identity cross-bind (never a secret) that authorizes a * successor to remove a predecessor's restart-intent slot it never itself * prepared. */ export interface NativeBrokerRestartIntentIdentity { dev: bigint ino: bigint } export declare function nativeBuildInfo(): BuildInfo /** Result of resolving an existing directory to its stable platform identity. */ export type NativeCanonicalDirectoryIdentity = | { ok: true; platform: "posix" | "win32"; canonicalPath: string; code?: never } | { ok: false; platform?: never; canonicalPath?: never; code: "not_found" | "not_directory" | "not_utf8" | "network_unsupported" | "identity_unavailable" | "io_error"; } export interface NativeDirectoryParentIdentity { dev: bigint ino: bigint } /** * A deterministic, no-follow description of a directory tree. `relative_path` * is UTF-8, uses `/` separators, and is empty only for the root entry. */ export interface NativeDirectoryTreeEntry { relativePath: string kind: string dev: string ino: string nlink: string size: string mtimeNs: string ctimeNs: string sha256?: string } export interface NativeDirectoryTreeResult { ok: boolean code?: string snapshot?: NativeDirectoryTreeSnapshot } /** * Stable evidence returned by `snapshot_directory_tree` and consumed verbatim * by `exact_remove_directory_tree`. */ export interface NativeDirectoryTreeSnapshot { rootDev: string rootIno: string entries: Array } /** * Caller-supplied identity and preauthorized quarantine evidence for exact * deletion. */ export interface NativeExactFileIdentity { dev: bigint ino: bigint nlink?: bigint parentDev?: bigint parentIno?: bigint size: bigint mtimeNs: bigint /** * When true, atomically detach a directory rather than deleting a regular * file. */ directory?: boolean /** * Keep a regular file in quarantine after its identity has been verified * instead of unlinking it. This makes cross-device retirement recoverable. */ detachOnly?: boolean /** * A caller-persisted, single-component no-replace quarantine destination. * Required for every exact deletion so authority survives a post-detach * crash. */ quarantineName?: string /** * SHA-256 of regular-file bytes. Required for regular-file deletion and * verified from the detached object before unlinking it. */ sha256?: string /** * Permit removing exactly this authorized pathname when the inode has other * hard links. Remaining links are retained after exact quarantine cleanup. */ allowHardLink?: boolean } /** Typed result of an identity-bound regular-file deletion or directory detach. */ export interface NativeExactUnlinkResult { ok: boolean code?: string /** * True only when retained directory payloads were descriptor-scrubbed and * every file plus containing directory namespace was fsynced before return. */ payloadDurable?: boolean /** * On Windows this is returned in the caller's namespace; retained handle * operations continue to use the volume-GUID canonical path internally. */ detachedPath?: string retainedSuccessorPath?: string /** * An internal exchange-placeholder cleanup entry retained after cleanup * could not complete. This is never a canonical publisher successor and * remains recoverable only at this path. */ retainedPlaceholderPath?: string /** * A retained cleanup entry whose identity could not be verified. This is * neither a stale detached object nor a publisher successor. */ retainedUnknownPath?: string /** * Hex-formatted Windows NTSTATUS of the underlying pre-mutation failure * (e.g. `0xC0000043` for `STATUS_SHARING_VIOLATION`). Path-free by design; * always absent on success, on non-Windows platforms, and after any * namespace mutation. */ windowsErrorCode?: string } /** Dedicated result for an atomic no-replace namespace publication. */ export interface NativeNoReplaceResult { ok: boolean code?: string mutationState: string durabilityState: string reason: string primitive: string phase: string diagnostic: NativePublishDiagnostic } /** Result of applying or checking owner-only path security. */ export type NativeOwnerOnlySecurityResult = | { ok: true; platform: "linux"; kind: "file"; protocol: "apply" | "verify"; aclEvidence: { access: { clear: "cleared" | "already_absent" | "unsupported" | "not_run"; query: "absent" | "unsupported"; }; default?: never; }; code?: never; operation?: never; attribute?: never; } | { ok: true; platform: "linux"; kind: "directory"; protocol: "apply" | "verify"; aclEvidence: { access: { clear: "cleared" | "already_absent" | "unsupported" | "not_run"; query: "absent" | "unsupported"; }; default: { clear: "cleared" | "already_absent" | "unsupported" | "not_run"; query: "absent" | "unsupported"; }; }; code?: never; operation?: never; attribute?: never; } | { ok: true; platform?: never; kind?: never; protocol?: never; aclEvidence?: never; code?: never; operation?: never; attribute?: never; } | { ok: false; code: "acl_denied" | "acl_io_error" | "acl_present" | "acl_malformed" | "acl_unknown"; operation: "clear" | "query"; attribute: "access" | "default"; platform?: never; kind?: never; protocol?: never; aclEvidence?: never; } | { ok: false; code: "acl_unavailable" | "acl_apply_failed" | "acl_verify_failed"; operation?: never; attribute?: never; platform?: never; kind?: never; protocol?: never; aclEvidence?: never; } | { ok: false; code: | "not_found" | "not_directory" | "network_unsupported" | "reparse_point" | "identity_unavailable" | "identity_mismatch" | "owner_mismatch" | "mode_mismatch" | "io_error"; operation?: never; attribute?: never; platform?: never; kind?: never; protocol?: never; aclEvidence?: never; } /** Result of removing group/other permission bits from one exact config file. */ export interface NativePermissionRepairResult { status: string changed: boolean verified: boolean code?: string } /** * Read-only, non-mutating observation of whether a pid currently names a * verifiable process incarnation. * * `status` discriminates the three outcomes described on * [`pi_shell::process::ProcessObservation`]: * - `"present"` — `incarnation` is the exact kernel-reported identity * evidence. * - `"absent"` — the OS positively confirmed no process currently has this * pid. * - `"unknown"` — `reasonCode` explains why liveness could not be determined * (e.g. an invalid pid, a permission denial, or a platform limitation); this * is never proof of death. */ export interface NativeProcessObservation { status: 'present' | 'absent' | 'unknown' incarnation?: string reasonCode?: string } /** Bounded, path-free evidence for one publish operation. */ export interface NativePublishDiagnostic { schemaVersion: number collectionState: string osCode?: number syncFailures?: Array } /** Bounded, path-free evidence for one publish operation. */ export interface NativePublishSyncFailure { phase: string parentRole: string osCode: number kind: string } /** Bound endpoint info returned from [`NotificationServer::start`]. */ export interface NotificationEndpoint { /** Bind host (loopback). */ host: string /** Bound port. */ port: number /** `ws://host:port` URL. */ url: string /** The session id this endpoint serves. */ sessionId: string } /** * Acquire an immutable trusted-root descriptor. Linux is required; every * other platform returns a durable unsupported-platform result. */ export declare function openRecoveryFsRoot(path: string): RecoveryFsRoot /** Parsed Kitty keyboard protocol sequence result for a Kitty input sequence. */ export interface ParsedKittyResult { /** Primary codepoint associated with the key. */ codepoint: number /** Optional shifted key codepoint from the sequence. */ shiftedKey?: number /** Optional base layout key codepoint from the sequence. */ baseLayoutKey?: number /** Modifier bitmask (shift/alt/ctrl), excluding lock bits. */ modifier: number /** Optional event type (1 = press, 2 = repeat, 3 = release). */ eventType?: KeyEventType } /** * Parse terminal input and return a normalized key identifier. * * Returns a key id like "escape" or "ctrl+c", or None if unrecognized. */ export declare function parseKey(data: string, kittyProtocolActive: boolean): string | null /** * Parse a Kitty keyboard protocol sequence. * * Returns a structured parse result when the input is a valid Kitty sequence. */ export declare function parseKittySequence(data: string): ParsedKittyResult | null /** * Opaque in-process presentation capability. * * Returned by [`NotificationServer::register_arbitrated_ask`]. Pass it * unchanged to [`NotificationServer::retire_if_unclaimed`]; do not construct, * persist, inspect, or treat it as workflow-gate authority. */ export interface PresentationLease { actionId: string registrationEpoch: number } export declare function probeWindowsJobMemory(): WindowsJobMemoryProbeResult /** Current state of a process reference. */ export declare enum ProcessStatus { /** The referenced process is still running. */ Running = 'running', /** The referenced process has exited or is no longer observable. */ Exited = 'exited' } export interface ProcessTerminateOptions { /** Also signal the process group when supported by the platform. */ group?: boolean /** * Milliseconds to wait after polite termination before hard-killing. * Omit to use the default grace period. Pass a negative value to skip the * graceful phase and hard-kill immediately. */ gracefulMs?: number /** Milliseconds to wait after hard-kill for the process tree to exit. */ timeoutMs?: number /** Abort signal for cancelling termination while waiting. */ signal?: unknown } /** Options for waiting on a process exit. */ export interface ProcessWaitOptions { /** Milliseconds to wait before returning false. Omit to wait indefinitely. */ timeoutMs?: number /** Abort signal for cancelling the wait. */ signal?: unknown } /** Result of a PTY command run. */ export interface PtyRunResult { /** Exit code when the command completes. */ exitCode?: number /** Whether command was cancelled by signal/user kill. */ cancelled: boolean /** Whether command timed out. */ timedOut: boolean } /** Options for running a command in a PTY session. */ export interface PtyStartOptions { /** Command string to execute. */ command: string /** Working directory for command execution. */ cwd?: string /** Environment variables for this command. */ env?: Record /** Timeout in milliseconds before cancelling. */ timeoutMs?: number /** Abort signal for cancelling the operation. */ signal?: unknown /** PTY column count. */ cols?: number /** PTY row count. */ rows?: number /** * Shell binary to use (e.g. "sh", "bash", or an absolute path). * Defaults to "sh" if not provided. */ shell?: string } export declare function ptyTimeoutCount(): bigint /** * Read an image from the system clipboard. * * Returns `Ok(None)` when no image data is available. * * # Errors * Returns an error if clipboard access fails or image encoding fails. */ export declare function readImageFromClipboard(): Promise export interface RecoveryFsIdentity { dev: string ino: string nlink: string size: string mtimeNs: string ctimeNs: string sha256?: string } /** Bounded, path-free diagnostic evidence for one retained publication. */ export interface RecoveryFsPublishDiagnostic { schemaVersion: number collectionState: string osCode?: number syncFailures?: Array } /** * Explicit mutation and durability outcome for retained no-replace * publication. */ export interface RecoveryFsPublishResult { ok: boolean code?: string identity?: RecoveryFsIdentity mutationState: string durabilityState: string reason: string primitive: string phase: string diagnostic: RecoveryFsPublishDiagnostic } /** Bounded, path-free diagnostic evidence for one retained publication. */ export interface RecoveryFsPublishSyncFailure { phase: string parentRole: string osCode?: number kind: string } export interface RecoveryFsResult { ok: boolean code?: string identity?: RecoveryFsIdentity data?: Uint8Array } /** * Fail-closed outcome for a removal whose detached object remains retained. * `recovery_path` identifies evidence only; it grants no authority to replay * or delete the retained object. */ export interface RecoveryFsRetainedCleanupResult { ok: boolean code?: string recoveryPath?: string identity?: RecoveryFsIdentity treeSnapshot?: NativeDirectoryTreeSnapshot } /** * Publish a staged directory under a destination name that must not already * exist. * * Uses descriptor-relative `mkdirat` ownership followed by `renameat`. * This is the directory stand-in for `renameat2(RENAME_NOREPLACE)` on mounts * that reject rename flags with `EINVAL`/`ENOSYS`. The native implementation * validates every path component without following symlinks and never * overwrites a non-empty destination directory. */ export declare function renameDirectoryNoReplacePath(sourcePath: string, destinationPath: string): NativeNoReplaceResult /** * Async variant of [`rename_directory_no_replace_path`] scheduled on the * libuv blocking pool. */ export declare function renameDirectoryNoReplacePathAsync(sourcePath: string, destinationPath: string): Promise export declare function renameNoReplacePath(sourcePath: string, destinationPath: string): NativeNoReplaceResult /** * Async variant of [`rename_no_replace_path`] scheduled on the libuv blocking * pool. * * Managed output publication awaits this boundary so a rename that stalls in * the kernel (oversized APFS directory namespaces, issue #4394) blocks one * pool thread instead of the agent's event loop: await timeouts, sibling * subagents, and watchdogs keep running, and a hung publication degrades to * one unresolved receipt rather than a frozen process. */ export declare function renameNoReplacePathAsync(sourcePath: string, destinationPath: string): Promise /** * Remove only group/other permission bits from an exact, user-owned regular * file. */ export declare function repairConfigFilePermissions(path: string, identity: NativeExactFileIdentity, expectedMode: number): NativePermissionRepairResult /** * Repair an owner-only ACL on a retained expected path. * * Its no-follow handle must still identify the expected object before repair * and again after final ACL verification. */ export declare function repairOwnerOnlyPathSecurityExpected(path: string, kind: "directory" | "file", expectedDev: bigint, expectedIno: bigint): NativeOwnerOnlySecurityResult /** A client reply forwarded to the TypeScript host for gate resolution. */ export interface ReplyEvent { /** * The transient action/presentation id being answered. This is not the * durable workflow gate id. */ id: string /** JSON-encoded `ReplyAnswer` (number, string, or `{selected,custom}`). */ answerJson: string /** Optional idempotency key supplied by the client. */ idempotencyKey?: string /** One-shot receipt binding this callback to the atomically claimed reply. */ replyReceiptId: string } /** * Retain the existing no-follow SDK publication objects after one-time * publication. */ export declare function retainBrokerPublication(agentDir: string): NativeRetainedBrokerPublication /** Public status of exact direct retirement. Claims and receipts remain native. */ export interface RetireIfUnclaimedResult { status: 'retired' | 'already_terminal' | 'claimed' | 'stale' } /** A raw v3 SDK frame paired with its actual WebSocket connection id. */ export interface SdkFrameEvent { connectionId: string json: string } /** * Search content for a pattern (one-shot, compiles pattern each time). * For repeated searches with the same pattern, use [`grep`] with file filters. * * # Arguments * - `content`: `Uint8Array`/`Buffer` (zero-copy) or `string` (UTF-8). * - `options`: Regex settings, context, and output mode. * * # Returns * Match list plus counts/limit status; errors are surfaced in `error`. */ export declare function search(content: string | Uint8Array, options: SearchOptions): SearchResult /** Options for searching file content. */ export interface SearchOptions { /** Regex pattern to search for. */ pattern: string /** Case-insensitive search. */ ignoreCase?: boolean /** Enable multiline matching. */ multiline?: boolean /** Maximum number of matches to return. */ maxCount?: number /** Skip first N matches. */ offset?: number /** Lines of context before matches. */ contextBefore?: number /** Lines of context after matches. */ contextAfter?: number /** Lines of context before/after matches (legacy). */ context?: number /** Truncate lines longer than this (characters). */ maxColumns?: number /** Output mode (content or count). */ mode?: GrepOutputMode } /** Result of searching content. */ export interface SearchResult { /** All matches found. */ matches: Array /** Total number of matches (may exceed `matches.len()` due to offset/limit). */ matchCount: number /** Whether the limit was reached. */ limitReached: boolean /** Error message, if any. */ error?: string } /** Options for executing a shell command via brush-core. */ export interface ShellExecuteOptions { /** Command string to execute in the shell. */ command: string /** Working directory for the command. */ cwd?: string /** Environment variables to apply for this command only. */ env?: Record /** Environment variables to apply once per session. */ sessionEnv?: Record /** Timeout in milliseconds before cancelling the command. */ timeoutMs?: number /** Optional snapshot file to source on session creation. */ snapshotPath?: string /** Optional per-command output minimizer configuration. */ minimizer?: MinimizerOptions /** Abort signal for cancelling the operation. */ signal?: unknown /** Keep external commands inside the embedding process group. */ containedProcessGroup?: boolean } /** Options for configuring a persistent shell session. */ export interface ShellOptions { /** Environment variables to apply once per session. */ sessionEnv?: Record /** Optional snapshot file to source on session creation. */ snapshotPath?: string /** Optional per-command output minimizer configuration. */ minimizer?: MinimizerOptions /** * Keep external commands inside the embedding process group. Used only by * an already-isolated shell worker whose parent supervises that group. */ containedProcessGroup?: boolean /** Private append-only ownership ledger used by the external guardian. */ ownershipLedgerPath?: string /** Authentication key for ownership ledger records. */ ownershipLedgerToken?: string } /** Options for running a shell command. */ export interface ShellRunOptions { /** Command string to execute in the shell. */ command: string /** Working directory for the command. */ cwd?: string /** Environment variables to apply for this command only. */ env?: Record /** Timeout in milliseconds before cancelling the command. */ timeoutMs?: number /** Abort signal for cancelling the operation. */ signal?: unknown } /** Result of running a shell command. */ export interface ShellRunResult { /** Exit code when the command completes normally. */ exitCode?: number /** Whether the command was cancelled via abort. */ cancelled: boolean /** Whether the command timed out before completion. */ timedOut: boolean /** * When the minimizer rewrote the captured output, this carries the * original buffer + telemetry so the session layer can persist it as * an artifact and splice an `artifact://` reference into the * minimized text shown to the agent. `None` when nothing was rewritten. */ minimized?: MinimizerResult } /** * Visible slice of a line after ANSI-aware column selection * (`sliceWithWidth`). */ export interface SliceResult { /** UTF-16 slice containing the selected text. */ text: string /** Visible width of the slice in terminal cells. */ width: number } /** * Slice a range of visible columns from a line. * * Counts terminal cells, skipping ANSI escapes, and optionally enforces strict * width. */ export declare function sliceWithWidth(line: string, startCol: number, length: number, strict: boolean | undefined | null, tabWidth: number): SliceResult /** * Capture a deterministic, descriptor-relative snapshot of a regular-file and * directory-only tree. Symlinks, special files, non-UTF-8 names, and topology * changes are rejected rather than followed. */ export declare function snapshotDirectoryTree(path: string): NativeDirectoryTreeResult export declare function summarizeCode(options: SummaryOptions): Promise export interface SummaryOptions { /** Source code to summarize. */ code: string /** Language alias (e.g. "rust", "typescript") used before path inference. */ lang?: string /** File path used to infer language by extension when `lang` is omitted. */ path?: string /** Minimum total node lines before eliding a body/literal node. */ minBodyLines?: number /** Minimum total comment lines before eliding a multiline block comment. */ minCommentLines?: number } export interface SummaryResult { /** Canonical language name when parsing succeeded. */ language?: string /** True when tree-sitter parsed the source without syntax errors. */ parsed: boolean /** True when at least one elision span was emitted. */ elided: boolean /** Total source lines. */ totalLines: number /** Kept/elided segments in source order. */ segments: Array } export interface SummarySegment { /** "kept" or "elided". */ kind: string /** 1-based inclusive start line. */ startLine: number /** 1-based inclusive end line. */ endLine: number /** Verbatim text for kept segments; absent for elided segments. */ text?: string } /** * Check if a language is supported for highlighting. * Returns true if the language has either direct support or a fallback * mapping. */ export declare function supportsLanguage(lang: string): boolean /** Truncate many strings to a visible width, preserving ANSI codes. */ export declare function truncateLinesToWidth(lines: Array, maxWidth: number, ellipsisKind: Ellipsis | undefined | null, pad: boolean | undefined | null, tabWidth: number): Array export declare function truncateToWidth(text: string, maxWidth: number, ellipsisKind: Ellipsis | undefined | null, pad: boolean | undefined | null, tabWidth: number): string /** * Verify owner-only security for the exact caller descriptor and retained * no-follow path. The descriptor is duplicated with close-on-exec and is never * returned to JavaScript. */ export declare function verifyOwnerOnlyFdSecurity(path: string, kind: "directory" | "file", callerFd: number): NativeOwnerOnlySecurityResult export declare function verifyOwnerOnlyPathSecurity(path: string, kind: "directory" | "file"): NativeOwnerOnlySecurityResult /** * Verify owner-only ACL security without mutation only when the retained * no-follow handle identifies the expected object before and after inspection. */ export declare function verifyOwnerOnlyPathSecurityExpected(path: string, kind: "directory" | "file", expectedDev: bigint, expectedIno: bigint): NativeOwnerOnlySecurityResult /** * Calculate visible width of text, excluding ANSI escape sequences. * * Tabs count as a fixed-width cell. */ export declare function visibleWidth(text: string, tabWidth: number): number /** Calculate visible widths of many strings, excluding ANSI escape sequences. */ export declare function visibleWidths(lines: Array, tabWidth: number): Array export interface WindowsJobMemoryProbeResult { kind: string platform: string isInJob?: boolean jobMemoryLimitBytes?: string jobMemoryUsedBytes?: string peakJobMemoryUsedBytes?: string processMemoryLimitBytes?: string processPrivateUsageBytes?: string processWorkingSetBytes?: string peakProcessWorkingSetBytes?: string call?: string code?: string } /** Profiling results returned to JavaScript. */ export interface WorkProfile { /** Folded stack format for flamegraph tools. */ folded: string /** Markdown summary of profiling results. */ summary: string /** SVG flamegraph (if generation succeeded). */ svg?: string /** Total profiled duration in milliseconds. */ totalMs: number /** Number of samples collected. */ sampleCount: number } /** * Wrap text to a visible width, preserving ANSI escape codes across line * breaks. * * Returns UTF-16 lines with active SGR codes carried across line boundaries. */ export declare function wrapTextWithAnsi(text: string, width: number, tabWidth: number): Array