import type { DeliveryFailureCause } from "./delivery-failure.ts"; import type { Envelope, EnvelopeOpts, PeerId, PeerState } from "./envelope.ts"; import type { PermissionMode } from "./permission-mode.ts"; import type { StartForm } from "../adapters/registry-types.ts"; import type { DoingKind } from "./peer-doing.ts"; export type SessionTitleResult = { ok: true } | { ok: false; reason: "already_named" | "invalid"; error?: string; mayHaveApplied?: true }; import type { CapabilityManifest } from "./capabilities.ts"; export interface DeliveryReceipt { id: string; state: "accepted" | "completed" | "failed_safe" | "needs_review"; reason?: string; /** Public-safe transport cause only, never native error text. */ failureCause?: DeliveryFailureCause; /** A provider refused before acceptance for quota; requeue without spending poison retries while paused. */ quota?: true; } /** Host-owned print child authority, revoked before stop/turn settlement. No terminal ownership. */ export interface OwnedToolsLaunch { launchId: string; generation: string; sessionId: string; signal: AbortSignal; task?: number; permissionHook: true; } /** Display-only identity for a live channel connection waiting for a person's handover. */ export interface PeerStandbySession { id: string; pid?: number; since: number; } /** * Display metadata about the CURRENT owner of an attached channel peer (#1310): who holds it, since when, and which native session the host has already verified. Never authentication, * delivery, takeover or permission evidence, and never derived from a standby id, a process name, a title or attach order. Every field is bounded; none is text from the client. */ export interface PeerOwnerAttachment { ownerPid?: number; attachedAt: number; nativeSessionId?: string; } /** Opaque, generation-fenced claim produced by a peer's person-requested takeover port. */ export interface PeerTakeoverClaim { standbyId: string; socket: object; generation: string | number; isCurrent(): boolean; attach(): boolean; } export interface FrontendProxyPort { readonly url: string; readonly attached: boolean; /** Only before a frontend attaches, while offline and with no native restoration debt. */ setStartupPermissionMode(mode: PermissionMode): void; /** Clear to ask while retaining any native restoration debt; false means its baseline is unknown. */ clearPermissionMode(): boolean; } export interface PeerAdapter { readonly id: PeerId; /** Live waiting sessions, for display only; ids and pids grant no native identity or authority. */ readonly standbySessions?: readonly PeerStandbySession[]; /** The current owner's attachment facts, for display only; absent unless a socket is attached and no newer claim is arriving (#1310). */ readonly ownerAttachment?: PeerOwnerAttachment; /** * #1385: the agent-hub client this peer runs in another process, for display only. Absent means the adapter runs inside the daemon, so it runs the daemon's own code; `attached` false * means no client is attached now, and an attached client without `version` did not report one. Never admission, compatibility or authorization evidence. */ readonly hubClient?: { attached: boolean; version?: string }; /** Person-authorized takeover port. The host still performs its own admission and claim fences. */ takeover?(standbyId: string | undefined, eligible: (socket: object) => boolean): PeerTakeoverClaim | undefined; /** Exact transport ownership check for guarding a selected standby through its asynchronous preface. */ ownsSocket?(socket: object): boolean; /** The explicit own-delivery settlement surface; only a live push channel session opts in. */ readonly acceptedSettlement?: "explicit"; /** Host-owned room transport binding; remote ids never gain local role/console authority. */ readonly remoteRoom?: string; /** Verified roster fingerprint, pinned separately from the reusable display label. */ readonly remoteMember?: string; /** Host arrival TTL for queued room traffic, default 24 hours. */ readonly remoteQueueTtlMs?: number; /** Host-only original enqueue deadline, handed over before one remote transport call. */ setRemoteDeadline?(envelopeId: string, expiresAt: number): void; ownedTools?(launchId: unknown): OwnedToolsLaunch | undefined; keepApprovalAlive?(): void; readonly state: PeerState; /** Host-observed native session identity. An absent port permits owner-token fallback; undefined means unknown. */ readonly sessionGeneration?: string | number; /** Defaults to fencing checkpoints when the generation port exists; native legacy exceptions opt out explicitly. */ readonly checkpointUsesSessionGeneration?: boolean; /** Effective native approval state; absent peers retain the hub-managed choice. */ readonly permissionModeState?: PermissionMode | "unknown" | "unmanaged"; /** Resolve only after native acknowledgement. This changes approval frequency, never the sandbox. */ setPermissionMode?(mode: PermissionMode): Promise; /** Never offered delivery retry; absent/false permits retry, present undefined refuses it. */ readonly deliveryOnly?: boolean; /** The hub owns this runtime and may stop it; absent or undefined refuses. */ readonly hubOwned?: boolean; /** An owned process remains whose exit is unconfirmed. */ readonly pendingOwnedProcess?: boolean; /** Native running form; absent keeps the site's default, present undefined is unknown. */ readonly form?: StartForm; /** Absent is settled; false or a present undefined value refuses recovery readiness. */ readonly recoveryReady?: boolean; /** Capture live resume evidence before a requested stop; throws when unavailable. */ captureResume?(): Promise>; /** Native session binding; absence or undefined is unbound, never inferred from a different reader. */ readonly nativeSession?: string; /** Verified native name, or the local session's own field. Empty means verified unnamed; undefined is unknown. */ readonly sessionTitle?: string; /** Opaque title-session identity, separate from context/provenance's nativeSession authority. */ readonly titleSession?: string; /** Native adapters check the live name at the actual write. The host guard is checked immediately before effects. */ setSessionTitle?(title: string, onlyIfUnnamed: boolean, current?: () => boolean): Promise; /** Fixed-builtin native proof only; present undefined is unknown, not an absent proxy. */ readonly frontendProxy?: FrontendProxyPort; /** Fixed operator notices from builtin native adapters, never provider text or native ids. */ readonly statusNotice?: { code: "unidentified-cancellation" | "qwen-detached" | "qwen-stalled" | "qwen-deny-quiescence" | "jcode-headless-after-recovery"; message: string }; /** Fixed builtins with session.nativeRevert only. Native conversation effects remain in the adapter. */ revertTurn?(nativeTurn: string): Promise; /** #445 C1: what this peer's native source lists right now (a probed version only), or an empty manifest. Never throws for an unprobed version; a transport failure rejects. */ capabilityManifest?(): Promise; /** Leave the roster without stopping a person's terminal. */ detachForRoster?(resetMode: PermissionMode): void | Promise; /** Return to the roster after detachForRoster. */ resumeFromRoster?(): Promise; /** #1402: the model the native surface reported for the turn that just ended, read once at its `turn_end`. Absent or undefined records nothing: unknown stays unknown. */ observedModel?(): import("./events.ts").ModelObservation | undefined; /** A peer the hub drives itself (Pi, the local worker). It cannot be trusted to rate its own urgency: the bus caps it. */ readonly hubNative?: boolean; /** Never handed a delivery: its queue waits for `Bus.pull` (a Claude session that cannot show channel pushes, issue #205). */ readonly pullOnly?: boolean; /** Inject now, as one prompt. Only called while `state === "idle"`. Rejecting puts the envelopes back at the queue head. */ deliver(envs: Envelope[], deliveryId?: string): Promise; /** Optional: feed envelopes into the turn that is running now. Only called while `state === "busy"`. */ steer?(envs: Envelope[], deliveryId?: string): Promise; start(): Promise; stop(reason?: string): Promise; /** Set by the bus. The peer said something worth sharing. */ onMessage?: (body: string, opts?: EnvelopeOpts) => unknown; /** Host-only Record guidance for the next owned headless turn; never native-client configuration. */ recordInstruction?: () => string | undefined; /** Raw model answer boundary, separate from explicit send tools and diagnostics. */ onFinalAnswer?: (body: string, opts?: EnvelopeOpts, complete?: boolean) => unknown; /** Set by the bus. */ onState?: (state: PeerState) => void; /** Set by the bus. A delivery that had resolved turned out not to reach the agent: put it back. */ onFailed?: (envs: Envelope[], failure?: { quota?: true; failureCause?: DeliveryFailureCause }) => void; /** Correlated durable-delivery lifecycle, emitted only when the bus supplied an id. */ onDelivery?: (receipt: DeliveryReceipt) => void; /** Set by the bus (#878): a native session title or current plan item the adapter observed; `reset` on a new session. */ onDoing?: (kind: DoingKind, text?: unknown) => void; /** Safe restart metadata only: ids and launch parameters, never prompt/message text. */ recoveryMetadata?(): Record; /** Current native TUI ownership, correlated to one launcher. A start acknowledgement is never evidence. */ terminalOwner?(launchId: string): { generation: string; nativePid?: number } | undefined; } export const DEFAULT_WATCHDOG_MS = 300_000; /** State holder with a per-turn inactivity watchdog: a busy peer that goes silent is forced back to idle. */ export abstract class BasePeer implements PeerAdapter { /** Returns a reason (a string) when the hub refused the message (issue #38). */ onMessage?: (body: string, opts?: EnvelopeOpts) => unknown; /** Host-only Record guidance for the next owned headless turn; never native-client configuration. */ recordInstruction?: () => string | undefined; /** Raw model answer boundary, separate from explicit send tools and diagnostics. */ onFinalAnswer?: (body: string, opts?: EnvelopeOpts, complete?: boolean) => unknown; onState?: (state: PeerState) => void; onFailed?: (envs: Envelope[], failure?: { quota?: true; failureCause?: DeliveryFailureCause }) => void; onDelivery?: (receipt: DeliveryReceipt) => void; onDoing?: (kind: DoingKind, text?: unknown) => void; private _state: PeerState = "offline"; private timer: ReturnType | undefined; private nextWatchdogMs: number | undefined; constructor( readonly id: PeerId, protected watchdogMs = DEFAULT_WATCHDOG_MS, ) {} get state(): PeerState { return this._state; } /** Decorate only a fixed prompt, once at the delivered-turn boundary. */ protected turnRecordPrompt(base: string): string { let instruction: string | undefined; try { instruction = this.recordInstruction?.(); } catch { return base; } if (!instruction || base.includes(instruction)) return base; return base ? `${base}\n\n${instruction}` : instruction; } protected finalAnswer(text: string, opts?: EnvelopeOpts, complete = true): unknown { return this.onFinalAnswer ? this.onFinalAnswer(text, opts, complete) : this.onMessage?.(text, opts); } /** Keep the active turn's inactivity bound; a changed setting belongs to the next busy turn. */ configureWatchdog(ms: number): void { if (!Number.isFinite(ms) || ms <= 0 || ms > 2_147_483_647) throw new Error("invalid watchdog interval"); this.nextWatchdogMs = ms; } protected setState(next: PeerState): void { if (next === "busy") { if (this._state !== "busy" && this.nextWatchdogMs !== undefined) this.watchdogMs = this.nextWatchdogMs; this.touch(); } else this.clearWatchdog(); if (next === this._state) return; this._state = next; this.onState?.(next); } /** Any sign of life from a busy peer re-arms the watchdog (it measures inactivity, not duration). */ protected touch(ms = this.watchdogMs): void { this.clearWatchdog(); this.timer = setTimeout(() => { if (this._state === "busy") this.onWatchdog(); }, ms); this.timer.unref?.(); } protected onWatchdog(): void { this.setState("idle"); } protected delivery(receipt: DeliveryReceipt): void { this.onDelivery?.(receipt); } protected clearWatchdog(): void { if (this.timer) clearTimeout(this.timer); this.timer = undefined; } abstract deliver(envs: Envelope[], deliveryId?: string): Promise; abstract start(): Promise; abstract stop(reason?: string): Promise; }