UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

248 lines (247 loc) • 15.9 kB
import { type Json, type Provider, type Target } from "./protocol.js"; /** A delivery the agent's turn ended without: the reason the phone shows. */ export declare const TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message."; export type DeliveryOutcome = "delivered" | "pending"; /** What a phone message is known to have become. `queued`: typed into the * pane and held by the agent until its turn ends. `failed` carries a reason * and may still turn `delivered` if the agent takes it late. */ export type DeliveryState = "queued" | "delivered" | "failed"; /** A transcript row carrying a message's words: its byte offset, and whether the agent fires UserPromptSubmit for it (a user row does; a mid-turn queue removal does not). */ /** A transcript row with a message's words: its byte offset, whether it is a user row, when it was stamped, and * the row's own id where the harness writes one (Claude's `uuid`). */ export interface TranscriptEntry { offset: number; hook: boolean; at?: number; uuid?: string; promptEntryId?: string; /** The row the conversation stream shows for this one, when that is another (a Codex rollout's user item). */ shown?: number; } export type TrackedState = DeliveryState | "unknown"; /** The transcript row a delivered message landed as: the line the conversation stream numbers it by (`Entry.line`, * 0-based) and, for Claude, the row's `uuid`. A phone matches its pending send to that row, not to its text. */ export interface LandedRow { line: number; uuid?: string; } export interface DeliveryStatus { state: TrackedState; reason?: string; session?: string; landed?: LandedRow; } /** A message is kept this long, by its id, so a late status or a retry still * finds it: a busy Codex turn can run far past the old ten minutes. */ export declare const DELIVERY_RETENTION_MS: number; /** An agent that ended its turn after the message was typed and then stayed * idle this long without taking it has dropped it. */ export declare const DELIVERY_GIVE_UP_MS = 30000; /** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no * UserPromptSubmit or Stop to settle it: a message such an agent took or dropped never settles. */ export declare const IN_FLIGHT_MS = 45000; /** What the agent hands its UserPromptSubmit hook is the terminal's pasted * form of what Phren typed; compare the words, not the wrapping. Claude Code * also takes each attached picture's path line out of the text and puts an * "[Image #N]" label at the front, so neither side keeps picture paths or * labels. */ export declare function promptKey(text: string): string; export declare const promptHash: (text: string) => string; /** One raw Claude transcript row and the byte offset it starts at: the queue rows a phone message's * identity is read from. */ export interface ClaudeQueueRow { offset: number; raw: Json; } /** One message per record, bound to the pane it was typed into (server, pane, * agent kind), not to the conversation: a Codex thread or a Claude /clear can * replace the conversation while the agent still holds the typed text, and * the conversation that submits it is the one it reached. Records hold a hash * of the words, never the text, and those with a phone id are written to * `file` so a Hook restart keeps their state. */ export declare class PromptDeliveries { private file?; private now; private landed; private records; private waiters; private writing; /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */ private hookPanes; /** When each pane (server, pane, agent) last sent a Stop since the Hook started. */ private lastStop; private paneKey; private static open; /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */ private static claimable; /** The queue bindings last read from each Claude conversation, and the transcript revision they describe. */ private queueCache; /** Messages whose `cursor` is still being read. */ private cursors; /** The size of a conversation's transcript: 0 before it has one, undefined when it cannot be read. */ private size; /** The line (0-based) of the row at a byte offset in a conversation's transcript, when one still starts there * (and carries `uuid`, when given). */ private lineOf; constructor(file?: string | undefined, now?: () => number, landed?: (record: { source: Provider; session: string; hash: string; at: number; }) => Promise<TranscriptEntry[]>, size?: (record: { source: Provider; session: string; }) => Promise<number | undefined>, lineOf?: (record: { source: Provider; session: string; }, offset: number, uuid?: string) => Promise<number | undefined>); private samePane; private sameDestination; private byId; private prune; private save; /** Settled writes, for tests and an orderly shutdown. */ flush(): Promise<void>; /** Register a message about to be typed into `target`'s pane. Settles * "delivered" once a conversation in that pane submits the words, or * "pending" after `waitMs`; the record outlives the wait. A retry of a * failed id replaces its record. Aborting (the terminal refused before * writing) drops it. */ expect(target: Target, text: string, waitMs: number, signal?: AbortSignal, id?: string, terminal?: string, sessionBound?: boolean): Promise<DeliveryOutcome>; private release; private open; /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */ pending(target: Target, text: string, id?: string): boolean; /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */ private inFlight; /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. * A pre-typing guard can exclude only its own freshly registered reservation by id. */ holding(target: Pick<Target, "server" | "pane" | "source">, exceptId?: string): boolean; /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */ held(id: string, target: Pick<Target, "server" | "pane" | "source">): boolean; /** Wait again for a message `expect` reported pending, after a second Enter. */ awaitLate(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>; private find; /** The Hook answered `id` as typed and held by the agent. */ queue(id: string, target: Target): void; /** Delivered without a hook: an app-server turn or a served OpenCode prompt. */ delivered(id: string | undefined, target: Target, text: string, sessionBound?: boolean): void; /** The message did not reach the agent, and why. It stays matchable, so a * late submission still turns it delivered. */ fail(id: string | undefined, target: Target, reason: string): void; /** The pane's Codex server moved to another thread (/new, /resume): * input still pending on the old one stays there, out of the pane's view. * Fails loudly; a late UserPromptSubmit from the old thread still settles it. */ threadChanged(previous: Target): void; /** False when `id` names another message: other words or another pane. */ sameMessage(id: string, target: Pick<Target, "server" | "pane" | "source">, text: string): boolean; /** What became of phone message `id` in `target`'s pane. `unknown` while the * Hook has not answered it, for another pane, or past retention. */ status(id: string, target: Pick<Target, "server" | "pane" | "source">): DeliveryStatus; /** Every known phone message in `target`'s pane, for its conversation's stream. */ forPane(target: Pick<Target, "server" | "pane" | "source">): ({ deliveryId: string; } & DeliveryStatus)[]; /** The phone delivery each of a Claude conversation's queue rows belongs to, by byte offset: the * enqueue a message was typed as, the `remove`/`popAll` that took it back, the prompt turn that * delivered it, and the `dequeue` that handed it to the model. Reads the transcript tail, binds * any occurrence not bound yet, and keeps the binding in `<file>.queue.json`, so a reopened chat, * a reconnect snapshot or a Hook restart gives the same row the same phone id. */ claudeQueueBindings(target: Pick<Target, "server" | "pane" | "source" | "session">, file: string): Promise<Map<number, string> | undefined>; /** Bind parsed Claude queue rows (with their byte offsets) to the phone messages tracked in * `target`, oldest occurrence first, per pane and conversation. A message binds at most one * enqueue, one removal, one submitted turn and one dequeue; a repeated identical enqueue takes * the next unbound message, never the same occurrence twice. Only rows after the cursor captured * before the send was typed can be its own, so an earlier identical turn keeps its own identity. * Only bindings are recorded here: an enqueue is still held, never taken, and a cancellation or * `popAll` is not a delivery. */ bindClaudeQueueRows(target: Pick<Target, "server" | "pane" | "source" | "session">, rows: ClaudeQueueRow[]): Promise<Map<number, string>>; /** Conversation `target` just submitted `prompt`. Its own record wins, then * the oldest open one in the same pane: the agent kept the text across a * conversation change, and the conversation now in the pane is where it * went. A Claude callback shares the claim with the transcript read. */ submitted(target: Target, prompt: string, promptEntryId?: string): Promise<void>; /** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's * hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles, * the longest run first at each line and the oldest of identical messages first, so "yes" never settles * inside "yes, but later". Only hashes of the line runs are compared, never stored. Only messages still held * (typed or queued) are matched: a failed one could take the lines of messages that are held, and a late * take of a failed message stays its own hook's to report. */ private settleJoined; private claudeClaimed; private static claudeHookRow; /** `record` takes transcript row `row` as its own: the entry no other message with these words may take, and, * for a phone message, the row its receipt names (`landed`), whose line is counted in the background. */ private claim; /** Phone messages whose row's line is being counted. */ private locating; /** Counts the line of the row the stream shows for a phone message's claimed entry, once, and keeps it. * In the background: a long transcript is read from its start. */ private locate; /** Marks `record` delivered, in `session` when given. */ private settle; /** Settlement needs the same occurrence ownership as a transcript read, even if no * client has opened that conversation. Custom transcript readers supply their own bindings. */ private refreshClaudeQueue; /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with. * An entry settles one message: the table of records' `entry` offsets (per conversation) is the only * state, so neither this path nor the hook's can settle two messages with one turn. A user row is a * turn start whose UserPromptSubmit hook settles the message itself, so while the agent works only a * mid-turn queue removal (no hook fires for it) settles from the transcript; once the agent is idle * (`working` false) a user row settles too, for a hook that never came. Of several identical open * messages the oldest take the entries. `pass` carries the entries still unclaimed within one observe. */ private taken; /** Whether a Codex transcript row can be `record`'s own: written after it was registered. A row at or past * its cursor was; one before it only if stamped after registration (written while the cursor was read), * which a row without a timestamp never is. A materialized Codex 0.155 thread's copy is append-only, so a row * past the cursor was copied after registration, but not necessarily created after it: an older item the copy * had not reached yet lands there too. Its rows are stamped with when the item was created (codex-threads.ts), * and the scan drops any row stamped more than `ENTRY_SLACK_MS` before registration, which is what keeps an * earlier identical message from being taken for this one. */ private static codexRowIsOwn; /** Rows of `record`'s words in its conversation, oldest first, and where the scan of them began: rows * before `start` are out of sight, so whether they exist cannot be told. */ private codexRows; /** Rows with `record`'s words in its conversation claimed by other messages. */ private codexClaimed; /** A Claude phone message its hook settled before its row was written takes the row once it appears: the first * unclaimed user row with its words stamped from when it was typed to `HOOK_ROW_MS` after its hook, the rule * `taken` applies to hook-settled messages. Only the receipt's `landed` depends on it. */ private claimClaudeRow; /** A Codex message its hook settled takes the first free row written after it was registered. */ private claimCodexRow; /** Whether Codex took `record`'s message: a row written after it was registered (`codexRowIsOwn`) that no * other message with these words claimed. An earlier message its hook settled whose row was not yet * claimed holds the first such row of its own first, but only when everything written after it is still * in the scanned tail: otherwise its row may be gone, and the row that is left is this message's. */ private takenCodex; /** A turn in `target`'s pane ended: the agent now takes held input or never will. */ stopped(target: Target): void; /** Called on the Hook's activity tick with a server's panes. A message * still held fails loudly when its pane closed, its agent restarted, or the * agent ended a turn and stayed idle without taking it (unless its * transcript shows it after all). */ observe(server: string, panes: Json[]): Promise<void>; } /** The byte offsets of the user rows with these words that reached the conversation's transcript * after the message was typed: the agent took it without its hook saying so * (a mid-turn steer). Reads at most the last 512 KiB. */ /** The byte offsets (in the file, `start` being the buffer's own offset) of the rows in `buffer` * whose user text has `record`'s words, newest first. One offset per row. */ export declare function matchingOffsets(buffer: Buffer, start: number, record: { hash: string; at: number; }): TranscriptEntry[]; export declare function transcriptSize(record: { source: Provider; session: string; }): Promise<number | undefined>; /** The 0-based line of the row starting at byte `offset`: the newlines before it, as the transcript index counts * rows (transcript-index.ts), so it is the `line` the conversation stream gives that row. */ export declare function transcriptLine(record: { source: Provider; session: string; }, offset: number, uuid?: string): Promise<number | undefined>; /** A transcript row's user-typed text: Claude's user rows, Codex's * user_message events and user response items. */ export declare function userTexts(row: Json): string[];