import { a as GatewayResult, i as GatewayEvent } from "./protocol-CM1Hx439.js"; import Schema from "@deepseek-ai/schemastery"; import { Context } from "@deepseek-ai/cordis"; //#region src/config.d.ts type EventExposure = 'safe' | 'full'; interface Config { url: string; namespace: string; nodeId: string; displayName?: string; clientId?: string; protocolVersion?: 4 | 5; clean?: boolean; keepaliveSeconds?: number; connectTimeoutMs?: number; reconnectPeriodMs?: number; sessionExpirySeconds?: number; username?: string; password?: string; usernameEnv?: string; passwordEnv?: string; caFile?: string; certFile?: string; keyFile?: string; rejectUnauthorized?: boolean; stateFile?: string; workspaces?: Record; defaultWorkspace?: string; allowExternalSessions?: boolean; provider?: string; model?: string; maxTokens?: number; capabilities?: string[]; eventExposure?: EventExposure; maxMessageBytes?: number; maxMetadataBytes?: number; maxInputChars?: number; maxActiveRequests?: number; dedupTtlSeconds?: number; heartbeatSeconds?: number; managementPort?: number; managementHost?: string; managementCorsOrigin?: string; managementToken?: string; managementTokenEnv?: string; requireControllerAuth?: boolean; } interface ResolvedConfig { url: string; namespace: string; nodeId: string; displayName: string; clientId: string; protocolVersion: 4 | 5; clean: boolean; keepaliveSeconds: number; connectTimeoutMs: number; reconnectPeriodMs: number; sessionExpirySeconds: number; username?: string; password?: string; caFile?: string; certFile?: string; keyFile?: string; rejectUnauthorized: boolean; stateFile: string; workspaces: Readonly>; defaultWorkspace?: string; allowExternalSessions: boolean; agentOptions: { provider?: string; model?: string; maxTokens?: number; }; capabilities: readonly string[]; eventExposure: EventExposure; limits: { maxMessageBytes: number; maxMetadataBytes: number; maxInputChars: number; maxActiveRequests: number; dedupTtlMs: number; }; heartbeatSeconds: number; managementPort: number; managementHost: string; managementCorsOrigin?: string; managementToken?: string; requireControllerAuth: boolean; } /** * Plugin configuration schema. * * Grouped with `Schema.intersect` rather than nested objects: the DSH settings * form renders one titled section per member while the resolved value stays * flat, so grouping costs no migration. */ declare const Config: Schema; //#endregion //#region src/agent-host.d.ts type AgentAction = 'followup' | 'steer' | 'inject'; interface AgentEvent { sessionId: string; event: unknown; } interface AgentStatusEvent { sessionId: string; status: 'idle' | 'running'; } interface AgentErrorEvent { sessionId: string; turn: number; step: number; error: unknown; } interface AgentHostHandlers { onEvent(event: AgentEvent): void; onStatus(event: AgentStatusEvent): void; onError(event: AgentErrorEvent): void; } interface AcquireAgentOptions { requestId: string; sessionId?: string; /** Only meaningful for a new session; a resumed one keeps its own directory. */ workspace?: string; } interface AgentLease { sessionId: string; owned: boolean; } interface GatewayAgentHost { start(handlers: AgentHostHandlers): void; health(): Promise; acquire(options: AcquireAgentOptions): Promise; send(sessionId: string, action: AgentAction, input: string): void; cancel(sessionId: string): void; release(sessionId: string): Promise; dispose(): Promise; } interface AgentHostHealth { agent: 'ready' | 'degraded'; workspaces: Array<{ alias: string; status: 'ready' | 'missing' | 'not-directory' | 'unreadable'; }>; model: 'ready' | 'unavailable'; error?: string; } //#endregion //#region src/state-store.d.ts type StoredStatus = 'accepted' | 'active' | 'completed' | 'failed' | 'cancelled'; interface StoredControl { fingerprint: string; processedAt: number; } interface StoredRequest { id: string; fingerprint: string; status: StoredStatus; createdAt: number; updatedAt: number; expiresAt: number; sessionId?: string; /** Workspace alias the controller asked for, as sent. */ workspace?: string; /** Controller that submitted it, for attribution in the management UI. */ controllerId?: string; result?: GatewayResult; controls: Record; } /** What a request was submitted with; recorded once, at reservation. */ interface RequestOrigin { workspace?: string; controllerId?: string; } type StoredControllerStatus = 'pending' | 'authorized' | 'revoked'; interface ControllerSummary { id: string; name: string; scopes: string[]; status: StoredControllerStatus; createdAt: number; updatedAt: number; expiresAt: number; lastUsedAt?: number; } interface ControllerInvite { id: string; name: string; scopes: string[]; token: string; createdAt: number; expiresAt: number; } type ReserveResult = { kind: 'reserved'; record: StoredRequest; } | { kind: 'duplicate'; record: StoredRequest; } | { kind: 'conflict'; record: StoredRequest; }; type ControlClaimResult = { kind: 'claimed'; record: StoredRequest; } | { kind: 'duplicate'; record: StoredRequest; } | { kind: 'conflict'; record: StoredRequest; } | { kind: 'not-found'; } | { kind: 'terminal'; record: StoredRequest; }; declare class RequestStore { private readonly file; private readonly ttlMs; private readonly now; private state; private opened; private queue; /** Bytes of the last successful write; a mutation that changes nothing skips the disk. */ private written; constructor(file: string, ttlMs: number, now?: () => number); open(): Promise; reserve(id: string, requestFingerprint: string, origin?: RequestOrigin): Promise; activate(id: string, sessionId: string): Promise; /** * Record a session as ours, most-recently-seen last. * * Re-adding after a delete moves the id to the end of the `Set`, so the * insertion order is a recency order and the oldest entry is the first one to * evict once the ledger is full. */ private rememberSession; finish(id: string, result: GatewayResult): Promise; claimControl(id: string, commandId: string, controlFingerprint: string): Promise; /** * Give a claimed command id back. * * Dedup must not turn a retryable failure into a permanent one: when the * command was accepted for dedup purposes but never delivered, the controller * has to be able to send the same command id again. */ releaseControl(id: string, commandId: string): Promise; get(id: string): Promise; list(options?: { limit?: number; }): Promise; activeCount(): Promise; /** * Whether this gateway created the session. * * Reads the ledger, which is why a session id that only ever arrived on a * result is still recognised: `finish` records it as readily as activation. */ hasSession(sessionId: string): Promise; createController(name: string, scopes: string[], ttlMs: number): Promise; /** * Controllers, newest invite first. * * Ordered by creation rather than by `updatedAt`: a controller that keeps * working would otherwise climb the list on every authenticated message and * shuffle the rows under the operator's cursor. */ listControllers(): Promise; authorizeController(id: string): Promise; revokeController(id: string): Promise; authenticateController(id: string, token: string, scope: string): Promise<{ ok: true; controller: ControllerSummary; } | { ok: false; reason: 'not-found' | 'pending' | 'revoked' | 'expired' | 'invalid-token' | 'scope-denied'; }>; recoverInterrupted(makeResult: (record: StoredRequest) => GatewayResult): Promise; /** * Drain in-flight writes and refuse further ones. * * Closing has to be final: a late mutation would rewrite a state file the * gateway has already stopped reconciling with the broker. */ close(): Promise; private require; private requireController; private touch; private cleanup; /** * Hold the request ledger at `MAX_REQUESTS`, oldest terminal record first. * * Only terminal records are evictable: a live request still needs its row to * finish. If every record is live the cap is simply not met, which is already * bounded by `maxActiveRequests`. */ private capRequests; private mutate; private read; private assertOpen; private persist; } //#endregion //#region src/topics.d.ts declare class TopicLayout { readonly base: string; readonly requests: string; readonly controlFilter: string; readonly status: string; constructor(namespace: string, nodeId: string); control(requestId: string): string; events(requestId: string): string; result(requestId: string): string; requestIdFromControl(topic: string): string | undefined; requestIdFromEvents(topic: string): string | undefined; requestIdFromResult(topic: string): string | undefined; /** Reverse of `control`/`events`/`result`: string slicing, so topic ids never reach a regex. */ private requestIdFrom; private assertRequestId; } //#endregion //#region src/transport.d.ts interface IncomingMessage { topic: string; payload: Uint8Array; qos: 0 | 1 | 2; retain: boolean; } interface PublishOptions { qos: 0 | 1; retain?: boolean; } interface TransportHandlers { onMessage(message: IncomingMessage): void | Promise; onConnect(): void | Promise; onState?(state: TransportState): void | Promise; } type TransportState = 'connecting' | 'connected' | 'degraded' | 'offline' | 'stopped'; interface GatewayTransport { start(handlers: TransportHandlers): Promise; publish(topic: string, payload: string, options: PublishOptions): Promise; stop(): Promise; } interface Logger { debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } //#endregion //#region src/gateway.d.ts type NodeState = 'connecting' | 'ready' | 'busy' | 'degraded' | 'offline' | 'stopped'; interface NodeHealthCheck { name: string; status: 'ready' | 'degraded' | 'offline'; message?: string; } interface NodeStatus { version: 1; type: 'node.status'; timestamp: string; heartbeat_at: string; expires_at: string; node_id: string; display_name: string; state: NodeState; online: boolean; gateway_version: string; protocol_version: 1; capabilities: readonly string[]; workspaces: Array<{ alias: string; status: AgentHostHealth['workspaces'][number]['status']; }>; active_requests: number; request_capacity: number; controller_auth_required: boolean; health: NodeHealthCheck[]; } /** * One history row as the management UI sees it. * * Deliberately narrower than `StoredRequest`: no fingerprint, no control-dedup * table. Mirrors `RequestRecord` in the client. */ interface RequestSummary { id: string; status: StoredRequest['status']; createdAt: number; updatedAt: number; sessionId?: string; workspace?: string; controllerId?: string; cancelRequested?: boolean; result?: { status: string; summary?: string; error?: { code: string; message: string; }; }; } /** * Live gateway change pushed to management UI subscribers. * * Mirrors what already goes out over MQTT, so the UI observes the same * transitions controllers do instead of re-polling for them. */ type GatewayNotice = { kind: 'event'; event: GatewayEvent; } | { kind: 'result'; result: GatewayResult; } | { kind: 'status'; status: NodeStatus; }; type GatewayNoticeListener = (notice: GatewayNotice) => void; declare class MqttAgentGateway { private readonly config; private readonly transport; private readonly host; private readonly store; private readonly logger; readonly topics: TopicLayout; private readonly active; private readonly requestBySession; /** Serialization chains, keyed by session; `SHARED_CHAIN` holds the rest. */ private readonly chains; private stopping; private connectionState; private heartbeatTimer; private readonly noticeListeners; constructor(config: ResolvedConfig, transport: GatewayTransport, host: GatewayAgentHost, store: RequestStore, logger: Logger); start(): Promise; stop(): Promise; /** * Settle every chain. * * A draining chain can enqueue more work, so this loops until no chain is * left rather than awaiting one snapshot. */ whenIdle(): Promise; /** * Observe gateway changes as they happen. Returns an unsubscribe function. * * A listener that throws is dropped rather than allowed to break the publish * path: management UI delivery must never take the gateway down. */ subscribe(listener: GatewayNoticeListener): () => void; private notify; getStatus(): Promise; /** * History for the management UI. * * Projected rather than returned raw: the stored record also holds the request * fingerprint and the control-dedup table, neither of which the UI needs and * both of which describe payloads we should not hand back out. */ listRequests(limit?: number): Promise; listControllers(): Promise; createControllerInvite(name: string, scopes: string[], ttlMs: number): Promise; authorizeController(id: string): Promise; revokeController(id: string): Promise; /** * Cancel a running request from the management UI. * * Goes through the same queue as an MQTT `request.cancel` so the operator and * a controller cannot race, and emits the same events — a controller watching * the request sees an operator cancel exactly as it would see its own. */ cancelRequest(id: string): Promise<{ ok: boolean; reason?: 'not-found' | 'not-active'; }>; /** * Serialize gateway work, per chain. * * Ordering is the point, not throughput: a session's events have to reach the * broker in the order the agent produced them, and the submit/control path has * to hold mutual exclusion over `active` so two messages cannot both decide a * request is free to start. Splitting by session keeps one slow agent handler * from delaying another session's events, while unkeyed work (submits, * control, status) shares one chain, where that mutual exclusion lives. */ private enqueue; private handleMessage; private handleSubmitMessage; private handleControlMessage; private applyControl; private handleAgentEvent; private handleAgentStatus; private handleAgentError; /** * The request an agent session belongs to, or `undefined` once stopping. * * Session work runs on its own chain, so without the stopping guard a late * agent event could publish after `stop()` has already written the terminal * result for that request. */ private activeForSession; private finalize; private failReserved; private failUnauthenticated; private authorize; private handleProtocolError; /** * Publish one request event. * * Unlike `publishOnlineStatus` this has no connection guard, on purpose: an * event is a point in a request's history that nothing later repeats, so it is * handed to mqtt.js even while offline and delivered on reconnect. Status is * retained and each publish supersedes the last, which is why dropping one * mid-outage costs nothing there. */ private publishEvent; private publishResult; private publishOnlineStatus; private publishOfflineStatus; private buildStatus; } //#endregion //#region src/management-server.d.ts interface ManagementServerOptions { gateway: MqttAgentGateway; config: ResolvedConfig; logger: Logger; } declare class ManagementServer { private readonly options; private server; private readonly streams; /** Single-use SSE tickets, keyed by value; see `ManagementClient.streamTicket`. */ private readonly tickets; constructor(options: ManagementServerOptions); private issueTicket; /** Consumes the ticket: a replayed query string buys nothing. */ private redeemTicket; start(): Promise; stop(): Promise; private handle; /** * Push gateway changes over Server-Sent Events. * * Clients that cannot hold the stream open fall back to the polling endpoints, * which stay available unchanged. */ private streamNotices; private serveUi; } //#endregion //#region src/controller.d.ts interface ControllerInviteConfig { url: string; namespace: string; nodeId: string; controllerId: string; token: string; username?: string; password?: string; protocolVersion?: 4 | 5; clean?: boolean; keepaliveSeconds?: number; connectTimeoutMs?: number; ca?: Buffer; cert?: Buffer; key?: Buffer; rejectUnauthorized?: boolean; } interface SubmitOptions { id?: string; input: string; workspace?: string; sessionId?: string; metadata?: Record; } declare class MqttControllerClient { private readonly config; readonly topics: TopicLayout; private client; private readonly resultWaiters; private readonly results; private readonly eventListeners; private readonly statusListeners; private readonly errorListeners; constructor(config: ControllerInviteConfig); connect(): Promise; disconnect(): Promise; /** * Broker errors after a successful connect. Without a subscriber they are * swallowed rather than thrown, which is the safe default for an embedded * client that reconnects by itself. */ onError(listener: (error: Error) => void): () => void; onStatus(listener: (status: NodeStatus) => void): () => void; onEvent(listener: (event: GatewayEvent) => void): () => void; submit(options: SubmitOptions): Promise; control(requestId: string, type: 'request.steer' | 'request.inject' | 'request.cancel', input?: string): Promise; waitForResult(requestId: string, timeoutMs?: number): Promise; private publish; private handleMessage; /** Keep the newest results, evicting in insertion order once the cache is full. */ private rememberResult; } //#endregion //#region src/index.d.ts declare const name = "dsh-mqtt"; declare const inject: string[]; declare function apply(ctx: Context, input: Config): Promise; //#endregion export { Config, type Config as PluginConfig, type ControllerInviteConfig, ManagementServer, MqttAgentGateway, MqttControllerClient, RequestStore, type ResolvedConfig, type SubmitOptions, TopicLayout, apply, inject, name }; //# sourceMappingURL=index.d.ts.map