🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@cortexkit/subc-client

Package Overview
Dependencies
Maintainers
1
Versions
9
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cortexkit/subc-client - npm Package Compare versions

Comparing version
0.3.0
to
0.3.1
+19
dist/auth.d.ts
import type { ConnectionInfo } from "./connection-file.js";
import { SubcSocket } from "./socket.js";
export declare const NONCE_LEN = 32;
export declare const PROOF_LEN = 32;
export declare const MAX_AUTH_MESSAGE_LEN = 4096;
export declare const SERVER_PROOF_DOMAIN = "subc-server-v1";
export declare const CLIENT_AUTH_DOMAIN = "subc-client-v1";
export declare const DEFAULT_CLIENT_ROLE = "client";
export declare class AuthError extends Error {
}
/** HMAC-SHA256 over domain ‖ client_nonce ‖ server_nonce ‖ daemon_id. */
export declare function computeProof(key: Uint8Array, domain: string, clientNonce: Uint8Array, serverNonce: Uint8Array, daemonId: Uint8Array): Uint8Array;
/**
* Run the client handshake over an already-connected socket. Resolves on
* success; throws AuthError on any proof/identity mismatch or framing fault.
* The whole exchange is bounded by `deadlineMs` (epoch ms).
*/
export declare function authenticateClient(sock: SubcSocket, conn: ConnectionInfo, deadlineMs: number): Promise<void>;
//# sourceMappingURL=auth.d.ts.map
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAiBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,eAAO,MAAM,SAAS,KAAK,CAAC;AAC5B,eAAO,MAAM,SAAS,KAAK,CAAC;AAC5B,eAAO,MAAM,oBAAoB,OAAO,CAAC;AACzC,eAAO,MAAM,mBAAmB,mBAAmB,CAAC;AACpD,eAAO,MAAM,kBAAkB,mBAAmB,CAAC;AACnD,eAAO,MAAM,mBAAmB,WAAW,CAAC;AAE5C,qBAAa,SAAU,SAAQ,KAAK;CAAG;AAEvC,yEAAyE;AACzE,wBAAgB,YAAY,CAC1B,GAAG,EAAE,UAAU,EACf,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,UAAU,EACvB,WAAW,EAAE,UAAU,EACvB,QAAQ,EAAE,UAAU,GACnB,UAAU,CAOZ;AA2CD;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,UAAU,EAChB,IAAI,EAAE,cAAc,EACpB,UAAU,EAAE,MAAM,GACjB,OAAO,CAAC,IAAI,CAAC,CAwBf"}
// Port of subc-transport's auth.rs client handshake. The proof construction,
// domain strings, message framing, and verification order must match the Rust
// byte-for-byte: a single byte of drift fails authentication outright.
//
// Handshake (client side):
// 1. send ClientHello { client_nonce, role }
// 2. receive ServerProof { daemon_id, server_nonce, daemon_ver, server_proof }
// 3. verify server_proof == HMAC(key, "subc-server-v1" ‖ cn ‖ sn ‖ did) (constant-time)
// and daemon_id == the id from the connection file
// 4. send ClientAuth { client_auth = HMAC(key, "subc-client-v1" ‖ cn ‖ sn ‖ did) }
//
// Each message on the wire is a 4-byte little-endian length prefix followed by
// the JSON body. Byte arrays (nonces, proofs, ids) serialize as JSON arrays of
// numbers, matching serde's default for [u8; N].
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
export const NONCE_LEN = 32;
export const PROOF_LEN = 32;
export const MAX_AUTH_MESSAGE_LEN = 4096;
export const SERVER_PROOF_DOMAIN = "subc-server-v1";
export const CLIENT_AUTH_DOMAIN = "subc-client-v1";
export const DEFAULT_CLIENT_ROLE = "client";
export class AuthError extends Error {
}
/** HMAC-SHA256 over domain ‖ client_nonce ‖ server_nonce ‖ daemon_id. */
export function computeProof(key, domain, clientNonce, serverNonce, daemonId) {
const mac = createHmac("sha256", Buffer.from(key));
mac.update(Buffer.from(domain, "utf8"));
mac.update(Buffer.from(clientNonce));
mac.update(Buffer.from(serverNonce));
mac.update(Buffer.from(daemonId));
return new Uint8Array(mac.digest());
}
function constantTimeEq(a, b) {
if (a.length !== b.length)
return false;
return timingSafeEqual(Buffer.from(a), Buffer.from(b));
}
async function writeMessage(sock, value, deadlineMs) {
const json = Buffer.from(JSON.stringify(value), "utf8");
if (json.length > MAX_AUTH_MESSAGE_LEN) {
throw new AuthError(`auth message too large: ${json.length} > ${MAX_AUTH_MESSAGE_LEN}`);
}
const lenPrefix = new Uint8Array(4);
new DataView(lenPrefix.buffer).setUint32(0, json.length, true);
await sock.write(lenPrefix, deadlineMs);
await sock.write(json, deadlineMs);
}
async function readMessage(sock, deadlineMs) {
const lenBytes = await sock.readExact(4, deadlineMs);
const len = new DataView(lenBytes.buffer, lenBytes.byteOffset, 4).getUint32(0, true);
if (len > MAX_AUTH_MESSAGE_LEN) {
throw new AuthError(`auth message too large: ${len} > ${MAX_AUTH_MESSAGE_LEN}`);
}
const body = len === 0 ? new Uint8Array(0) : await sock.readExact(len, deadlineMs);
try {
return JSON.parse(Buffer.from(body).toString("utf8"));
}
catch (err) {
throw new AuthError(`auth message JSON decode failed: ${String(err)}`);
}
}
/**
* Run the client handshake over an already-connected socket. Resolves on
* success; throws AuthError on any proof/identity mismatch or framing fault.
* The whole exchange is bounded by `deadlineMs` (epoch ms).
*/
export async function authenticateClient(sock, conn, deadlineMs) {
const clientNonce = new Uint8Array(randomBytes(NONCE_LEN));
await writeMessage(sock, { client_nonce: Array.from(clientNonce), role: DEFAULT_CLIENT_ROLE }, deadlineMs);
const proof = await readMessage(sock, deadlineMs);
const serverNonce = Uint8Array.from(proof.server_nonce);
const daemonId = Uint8Array.from(proof.daemon_id);
const serverProof = Uint8Array.from(proof.server_proof);
const expected = computeProof(conn.key, SERVER_PROOF_DOMAIN, clientNonce, serverNonce, daemonId);
if (!constantTimeEq(expected, serverProof)) {
throw new AuthError("server proof mismatch — wrong key or impostor daemon");
}
if (!constantTimeEq(daemonId, conn.daemonId)) {
throw new AuthError("daemon id mismatch — connection file points at a different daemon");
}
const clientAuth = computeProof(conn.key, CLIENT_AUTH_DOMAIN, clientNonce, serverNonce, daemonId);
await writeMessage(sock, { client_auth: Array.from(clientAuth) }, deadlineMs);
}
//# sourceMappingURL=auth.js.map
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8E;AAC9E,uEAAuE;AACvE,EAAE;AACF,2BAA2B;AAC3B,+CAA+C;AAC/C,iFAAiF;AACjF,2FAA2F;AAC3F,wDAAwD;AACxD,qFAAqF;AACrF,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,iDAAiD;AAEjD,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAKvE,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAC5B,MAAM,CAAC,MAAM,SAAS,GAAG,EAAE,CAAC;AAC5B,MAAM,CAAC,MAAM,oBAAoB,GAAG,IAAI,CAAC;AACzC,MAAM,CAAC,MAAM,mBAAmB,GAAG,gBAAgB,CAAC;AACpD,MAAM,CAAC,MAAM,kBAAkB,GAAG,gBAAgB,CAAC;AACnD,MAAM,CAAC,MAAM,mBAAmB,GAAG,QAAQ,CAAC;AAE5C,MAAM,OAAO,SAAU,SAAQ,KAAK;CAAG;AAEvC,yEAAyE;AACzE,MAAM,UAAU,YAAY,CAC1B,GAAe,EACf,MAAc,EACd,WAAuB,EACvB,WAAuB,EACvB,QAAoB;IAEpB,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACnD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IACxC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACrC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACrC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AC;IAClD,MAAM,WAAW,GAAG,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAExD,MAAM,QAAQ,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,mBAAmB,EAAE,WAAW,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IACjG,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,WAAW,CAAC,EAAE,CAAC;QAC3C,MAAM,IAAI,SAAS,CAAC,sDAAsD,CAAC,CAAC;IAC9E,CAAC;IACD,IAAI,CAAC,cAAc,CAAC,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC7C,MAAM,IAAI,SAAS,CAAC,mEAAmE,CAAC,CAAC;IAC3F,CAAC;IAED,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,GAAG,EAAE,kBAAkB,EAAE,WAAW,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;IAClG,MAAM,YAAY,CAAC,IAAI,EAAE,EAAE,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC;AAChF,CAAC"}
import { type ConnectionInfo } from "./connection-file.js";
import { Priority } from "./envelope.js";
export declare const SUBC_MODULE_ID_ENV = "SUBC_MODULE_ID";
export declare const SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
export interface BindIdentity {
project_root: string;
harness: string;
session: string;
}
export type RouteTarget = {
kind: "tool_provider";
module_id: string;
} | {
kind: "management_surface";
module_id: string;
} | {
kind: "internal_service";
module_id: string;
service_id: string;
};
export type ManagedRouteKind = "management_surface" | "tool_provider";
export interface ConsumerIdentity {
module_id: string;
launch_nonce: string;
}
export interface RouteOpenOptions {
/** Optional override for the consumer identity; by default the SUBC_MODULE_ID and SUBC_LAUNCH_NONCE environment variables are used when both are non-empty. Set null to send route.open without consumer_identity. */
consumerIdentity?: ConsumerIdentity | null;
}
export interface CatalogEntry {
module_id: string;
roles: unknown[];
control_ops: string[];
}
export interface RequestOptions {
priority?: Priority;
timeoutMs?: number;
/** Called for each interim PUSH / StreamData frame before the terminal reply. */
onProgress?: (body: Uint8Array) => void;
}
export interface ManagedCallOptions extends RequestOptions {
/** Overrides the per-client identity used for route.open before this call. */
identity?: BindIdentity;
/** Defaults to management_surface, matching the store/host management APIs. */
targetKind?: ManagedRouteKind;
/** Optional override for the consumer identity; by default the SUBC_MODULE_ID and SUBC_LAUNCH_NONCE environment variables are used when both are non-empty. Set null to send route.open without consumer_identity. */
consumerIdentity?: ConsumerIdentity | null;
}
export interface SubscribeOptions {
priority?: Priority;
}
export interface CloseRouteOptions {
/**
* Await in-flight UNARY requests on the route to settle before tearing it down.
* Subscriptions are always aborted (a held-open stream cannot be drained).
* Defaults to false: close immediately, aborting everything in flight.
*/
drain?: boolean;
/** Consumer identity to use when looking up the route to close; only needed for routes opened with a non-default consumer identity. */
consumerIdentity?: ConsumerIdentity | null;
}
/**
* Capped exponential reconnect backoff. maxAttempts includes the first immediate
* reconnect attempt; sleeps happen only between failed transient attempts.
*/
export interface ReconnectBackoff {
/** First retry delay. */
baseMs: number;
/** Delay ceiling (doubling is capped here). */
capMs: number;
/** Max attempts (including the first) before giving up. */
maxAttempts: number;
}
export declare const DEFAULT_RECONNECT_BACKOFF: ReconnectBackoff;
export type SubcCallErrorKind = "not_sent" | "outcome_unknown" | "terminal";
/**
* Managed call failure with send-outcome semantics.
*
* `not_sent` is intentionally narrow: the request bytes provably never left the
* local process (the connection was already closed, or net.Socket.write failed
* before queuing bytes). Managed call() may retry only this case.
*
* `outcome_unknown` is the safe default once bytes have been handed to the local
* socket. The daemon or module may have received the request before the response
* was lost, so call() never retries it automatically; the caller must decide
* whether the operation is idempotent or needs a check-then-act recovery.
*
* `terminal` covers protocol Error frames and non-retryable client/setup errors.
*/
export declare class SubcCallError extends Error {
readonly kind: SubcCallErrorKind;
readonly code?: string | undefined;
readonly cause?: unknown | undefined;
constructor(kind: SubcCallErrorKind, message: string, code?: string | undefined, cause?: unknown | undefined);
}
/**
* A live subscription to a provider's event stream, riding a single held-open
* request. `onEvent` fires for each StreamData frame; `closed` resolves when the
* provider ends the stream (StreamEnd) and rejects on an Error terminal or a route
* GOODBYE. `unsubscribe` cancels the held-open request so the provider unwinds.
*/
export interface Subscription {
/** Cancel the subscription: sends Cancel on the held-open request; idempotent. */
unsubscribe(): void;
/** Resolves on StreamEnd; rejects on an Error terminal or route close. */
readonly closed: Promise<void>;
}
export declare class SubcError extends Error {
readonly code?: string | undefined;
constructor(message: string, code?: string | undefined);
}
export interface ConnectOptions {
connectionFile: string;
handshakeTimeoutMs?: number;
/** Default route identity used by managed call(); can be overridden per call. */
identity?: BindIdentity;
/** Default route target kind used by managed call(); defaults to management_surface. */
targetKind?: ManagedRouteKind;
/** Backoff for managed reconnect after a connection drop. */
reconnectBackoff?: ReconnectBackoff;
/** Injectable sleep for timer-free reconnect tests. */
sleep?: (ms: number) => Promise<void>;
/**
* Hard cap on the timeout-arbitration grace window (see
* TIMEOUT_ARBITRATION_GRACE_MS). A reply whose bytes are actively arriving when
* the request deadline fires is given up to this long to finish dispatching
* before the call settles as a timeout. Bounded and never a deadline extension;
* exposed mainly so tests can prove the arbitration deterministically.
*/
timeoutArbitrationGraceMs?: number;
}
export declare class SubcClient {
private sock;
private currentConn;
private readonly opts;
private nextCorr;
private readonly pending;
private readonly routes;
private closedErr;
private closeStarted;
private reconnecting;
private generation;
private readerActive;
private constructor();
get conn(): ConnectionInfo;
/** Read the connection file, connect, authenticate, and start the read loop. */
static connect(opts: ConnectOptions): Promise<SubcClient>;
/** List modules subc knows about (channel-0 catalog.list). */
catalogList(moduleId?: string): Promise<CatalogEntry[]>;
/** Open a route to a provider (channel-0 route.open); returns the route channel. */
routeOpen(target: RouteTarget, identity: BindIdentity, opts?: RouteOpenOptions): Promise<number>;
/** Send a data-plane request on a route channel and await its terminal reply. */
request(routeChannel: number, body: unknown, opts?: RequestOptions): Promise<unknown>;
/**
* Managed route + request convenience. Opens and caches a route for the module,
* reconnecting and re-opening cached routes after connection drops.
*/
call<Response = unknown>(moduleId: string, method: string, params?: unknown, opts?: ManagedCallOptions): Promise<Response>;
/**
* Open a held-open event subscription on a route channel. Sends one Request the
* provider keeps open, delivering each interim StreamData frame to `onEvent`; the
* returned `closed` settles on the StreamEnd terminal (resolve) or an Error / route
* GOODBYE (reject). Events ride this held-open request's correlation id — they are
* never unsolicited, so they are not dropped. Call `unsubscribe()` to cancel.
*/
subscribe(routeChannel: number, body: unknown, onEvent: (event: Uint8Array) => void, opts?: SubscribeOptions): Subscription;
/**
* Tear down ONE managed route (a route opened via `call()`), keyed by its
* (target, identity). Idempotent and never throws — callers over-call on
* session-end. The teardown:
* - flips a tombstone on the cached route and removes it from the cache, so an
* in-flight `openCachedRoute` for the same key will NOT install its channel
* (the generation guard: close beats a racing reopen), and a later `call()`
* opens a fresh route (this is NOT a permanent tombstone);
* - settles in-flight requests on the channel as RouteClosed (managed requests
* keep their at-most-once classification: outcome_unknown if already sent,
* not_sent otherwise; subscriptions always abort);
* - sends a best-effort route GOODBYE so subc releases the route and notifies
* the module to free per-session resources.
* `opts.drain` waits for in-flight UNARY requests to settle before tearing down.
*/
closeRoute(target: Extract<RouteTarget, {
kind: ManagedRouteKind;
}>, identity: BindIdentity, opts?: CloseRouteOptions): Promise<void>;
/**
* Tear down ONE route by its channel number — the primitive for callers that
* opened a route with `routeOpen` directly (e.g. a tool route carrying raw
* {name, arguments}) and hold the channel themselves. Idempotent, never throws.
* Settles in-flight requests on the channel as RouteClosed and sends a best-effort
* route GOODBYE. `opts.drain` awaits in-flight UNARY requests first; subscriptions
* are always aborted (a held-open stream cannot be drained).
*/
closeRouteChannel(channel: number, opts?: CloseRouteOptions): Promise<void>;
close(): void;
/** Resolve once every in-flight UNARY request on the channel (snapshot at call
* time) has settled. Subscriptions are excluded — they are aborted, not drained. */
private drainUnaryOnChannel;
/** Send a best-effort header-only route GOODBYE for `channel`. One-way: the daemon
* releases the route and relays a route-gone GOODBYE to the module; no ack. */
private sendRouteGoodbye;
private static openConnection;
private controlRpc;
private send;
/**
* A request-deadline timer has fired. Before settling as a timeout, arbitrate
* the timer-vs-poll race: a reply may already be in the socket buffer, unread
* only because the loop was starved. Yield one check phase (setImmediate) so a
* fully-buffered reply dispatches and wins via settle()'s identity guard; then,
* only while the reader is actively draining THIS socket (a frame mid-arrival),
* grant a single hard-capped grace before finally settling. Absent replies
* still settle right after the check phase. The settle carries the deadline
* marker so the managed classifier reports deadline-not-drop.
*/
private arbitrateTimeout;
private managedRequest;
private sendManaged;
private cachedRouteChannel;
private openCachedRoute;
private ensureConnectedForManaged;
private scheduleReconnectAfterDrop;
private reconnectAfterDrop;
private reconnectWithRetry;
private replaceConnection;
private reopenCachedRoutes;
private timeoutMessage;
private routeClosedDuringOpen;
private readLoop;
private dispatch;
/**
* Settle a pending exactly once. The object-identity guard (the map still
* holds THIS pending under `key`) is the single-winner primitive: whichever of
* dispatch, a timeout, fail(), failChannel(), a GOODBYE, or a deferred timeout
* arbitration reaches it first wins, and every later caller no-ops. This is what
* makes the deferred-timeout arbitration safe — it cannot double-settle, reject
* an already-resolved promise, or delete a pending re-created for a later corr.
* Returns true when this call was the settler.
*/
private settle;
private rejectPending;
private errorFromFrame;
private failChannel;
private fail;
private notSentCallError;
private outcomeUnknownCallError;
private terminalCallError;
private notSentRecoveryError;
private encode;
private parseJson;
}
export declare function isConsumerReconnectTransient(err: unknown): boolean;
/**
* The closed set of route.open rejection codes that mean "the target is
* momentarily unavailable but the request could succeed on retry" — the target
* is booting, mid-reload, transiently absent, or the bind relay timed out. A
* daemon-rejected route.open is provably pre-send (no data frame ever left the
* client), so these classify as not_sent; the managed path retries them in-place
* within ROUTE_OPEN_RETRY_DEADLINE_MS. Permanent rejections (bad_consumer_identity,
* config_divergence, unknown_target, ...) are excluded — they are pre-send but
* would never succeed, so retrying them would only storm the daemon. Kept
* byte-identical to subc-client-rs is_retryable_route_open_code for cross-client
* classification parity.
*/
export declare function isRetryableRouteOpenCode(code: string | undefined): boolean;
export declare function connectionFileExists(path: string): Promise<boolean>;
//# sourceMappingURL=client.d.ts.map
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAeA,OAAO,EAA2C,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACpG,OAAO,EAOL,QAAQ,EAET,MAAM,eAAe,CAAC;AA8CvB,eAAO,MAAM,kBAAkB,mBAAmB,CAAC;AACnD,eAAO,MAAM,qBAAqB,sBAAsB,CAAC;AAEzD,MAAM,WAAW,YAAY;IAC3B,YAAY,EAAE,MAAM,CAAC;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,MAAM,WAAW,GACnB;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GAC5C;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,CAAC;AAExE,MAAM,MAAM,gBAAgB,GAAG,oBAAoB,GAAG,eAAe,CAAC;AAEtE,MAAM,WAAW,gBAAgB;IAC/B,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,gBAAgB;IAC/B,sNAAsN;IACtN,gBAAgB,CAAC,EAAE,gBAAgB,GAAG,IAAI,CAAC;CAC5C;AAED,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,OAAO,EAAE,CAAC;IACjB,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,SAAS,CAAC,EAAE,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AgEL,kBAAkB;YA0ClB,eAAe;YAqEf,yBAAyB;IAMvC,OAAO,CAAC,0BAA0B;IASlC,OAAO,CAAC,kBAAkB;YAWZ,kBAAkB;IA0BhC,OAAO,CAAC,iBAAiB;YASX,kBAAkB;IA+BhC,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,qBAAqB;YAIf,QAAQ;IAkCtB,OAAO,CAAC,QAAQ;IAgDhB;;;;;;;;OAQG;IACH,OAAO,CAAC,MAAM;IASd,OAAO,CAAC,aAAa;IAIrB,OAAO,CAAC,cAAc;IAYtB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,IAAI;IAOZ,OAAO,CAAC,gBAAgB;IAIxB,OAAO,CAAC,uBAAuB;IAI/B,OAAO,CAAC,iBAAiB;IAKzB,OAAO,CAAC,oBAAoB;IAM5B,OAAO,CAAC,MAAM;IAId,OAAO,CAAC,SAAS;CAGlB;AAED,wBAAgB,4BAA4B,CAAC,GAAG,EAAE,OAAO,GAAG,OAAO,CAQlE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAO1E;AAED,wBAAsB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAOzE"}
// The consumer-facing subc client. Mirrors the canonical pure consumer
// (subc-core/src/bin/subc-probe.rs): authenticate -> catalog.list (optional) ->
// route.open -> request on the returned route channel. There is no client HELLO
// — HELLO is module-registration only.
//
// A single background loop reads every inbound frame and demuxes it by
// (channel, corr) to the matching in-flight request. Never assume positional
// read order: subc may interleave a control reply ahead of another exchange's
// response on the same connection, so frames are matched to their request by
// correlation id, not arrival order.
import { promises as fs } from "node:fs";
import { debuglog } from "node:util";
import { AuthError, authenticateClient } from "./auth.js";
import { ConnectionFileError, readConnectionFile } from "./connection-file.js";
import { buildFrame, buildFlags, decodeHeader, encodeFrame, FrameType, HEADER_LEN, Priority, } from "./envelope.js";
import { SocketClosedError, SocketTimeoutError, SocketWriteNotQueuedError, SocketWriteQueuedError, SubcSocket, } from "./socket.js";
const debug = debuglog("subc-client");
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
// When a request-timeout timer fires, its reply may already be sitting in the
// socket read buffer, unprocessed only because the event loop was starved (Node
// runs the TIMERS phase before the POLL phase, so an expired timer can beat an
// already-arrived frame). Rather than settle as a timeout immediately, arbitrate:
// yield one check-phase turn (setImmediate) so a fully-buffered reply dispatches
// and wins, and — only while the reader is actively draining the same socket —
// allow a small hard-capped grace for a reply whose header/body spans more than
// one loop turn. This is a demux tiebreak for a reply that RACED the deadline,
// NOT a deadline extension: an absent reply still settles right after the check
// phase. Capped so it can never approach BODY_READ_TIMEOUT_MS.
const TIMEOUT_ARBITRATION_GRACE_MS = 50;
// Internal marker set as the `code` on the SubcError a request-deadline timeout
// rejects with, so the managed classifier can tell a deadline (reply may simply
// not have been read in time) from an actual connection drop. Never surfaced to
// callers directly — it is refined into DEADLINE_NO_DROP_CODE by classifyFailure.
const REQUEST_DEADLINE_MARKER = "request_deadline";
// The consumer-facing code for a managed call whose deadline elapsed while its
// bytes were queued to the local socket and NO connection drop / GOODBYE was
// observed. Distinct from "connection_dropped" so a caller can skip a
// was-it-even-sent recovery path — but still kind=outcome_unknown (never safe to
// retry: "queued to the local socket" is NOT proof the daemon received or ran it).
const DEADLINE_NO_DROP_CODE = "deadline_exceeded_no_drop_observed";
// A retryable route.open rejection (target booting / reloading / momentarily
// absent) is retried in-place against the same connection up to this deadline
// before it is surfaced as not_sent. Mirrors subc-client-rs
// DEFAULT_ROUTE_RETRY_DEADLINE so a target that is briefly unavailable at daemon
// restart recovers without a misleading terminal error.
const ROUTE_OPEN_RETRY_DEADLINE_MS = 10_000;
// Once a header arrives, its body must follow promptly; bound it so a truncated
// frame cannot wedge the read loop forever.
const BODY_READ_TIMEOUT_MS = 30_000;
const EMPTY_BODY = new Uint8Array(0);
const DEFAULT_MANAGED_TARGET_KIND = "management_surface";
export const SUBC_MODULE_ID_ENV = "SUBC_MODULE_ID";
export const SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
export const DEFAULT_RECONNECT_BACKOFF = {
baseMs: 100,
capMs: 2_000,
maxAttempts: 6,
};
/**
* Managed call failure with send-outcome semantics.
*
* `not_sent` is intentionally narrow: the request bytes provably never left the
* local process (the connection was already closed, or net.Socket.write failed
* before queuing bytes). Managed call() may retry only this case.
*
* `outcome_unknown` is the safe default once bytes have been handed to the local
* socket. The daemon or module may have received the request before the response
* was lost, so call() never retries it automatically; the caller must decide
* whether the operation is idempotent or needs a check-then-act recovery.
*
* `terminal` covers protocol Error frames and non-retryable client/setup errors.
*/
export class SubcCallError extends Error {
kind;
code;
cause;
constructor(kind, message, code, cause) {
super(message);
this.kind = kind;
this.code = code;
this.cause = cause;
this.name = "SubcCallError";
}
}
export class SubcError extends Error {
code;
constructor(message, code) {
super(message);
this.code = code;
}
}
export class SubcClient {
sock;
currentConn;
opts;
nextCorr = 1n;
pending = new Map();
routes = new Map();
closedErr = null;
closeStarted = false;
reconnecting = null;
generation = 1;
// True while the read loop is actively reading/dispatching a frame off the
// current socket (between reading a header and finishing its dispatch). The
// timeout arbitration reads it to decide whether a just-fired timeout should
// grant a reply mid-arrival a small grace window before settling.
readerActive = false;
constructor(sock, currentConn, opts) {
this.sock = sock;
this.currentConn = currentConn;
this.opts = opts;
void this.readLoop(sock, this.generation);
}
get conn() {
return this.currentConn;
}
/** Read the connection file, connect, authenticate, and start the read loop. */
static async connect(opts) {
const normalized = normalizeConnectOptions(opts);
const opened = await SubcClient.openConnection(normalized);
return new SubcClient(opened.sock, opened.conn, normalized);
}
/** List modules subc knows about (channel-0 catalog.list). */
async catalogList(moduleId) {
const body = this.encode(moduleId === undefined ? { op: "catalog.list" } : { op: "catalog.list", module_id: moduleId });
const reply = await this.controlRpc(body);
const parsed = this.parseJson(reply);
return parsed.modules ?? [];
}
/** Open a route to a provider (channel-0 route.open); returns the route channel. */
async routeOpen(target, identity, opts = {}) {
const consumerIdentity = routeOpenConsumerIdentity(opts);
const body = this.encode({
op: "route.open",
target,
identity,
...(consumerIdentity ? { consumer_identity: consumerIdentity } : {}),
});
const reply = await this.controlRpc(body);
const parsed = this.parseJson(reply);
if (typeof parsed.route_channel !== "number") {
throw new SubcError(`route.open returned no route_channel: ${JSON.stringify(parsed)}`);
}
return parsed.route_channel;
}
/** Send a data-plane request on a route channel and await its terminal reply. */
async request(routeChannel, body, opts = {}) {
const bytes = body instanceof Uint8Array ? body : this.encode(body);
const priority = opts.priority ?? Priority.Interactive;
const reply = await this.send(routeChannel, bytes, priority, opts.timeoutMs, opts.onProgress);
return this.parseJson(reply);
}
/**
* Managed route + request convenience. Opens and caches a route for the module,
* reconnecting and re-opening cached routes after connection drops.
*/
async call(moduleId, method, params, opts = {}) {
const body = params === undefined ? { method } : { method, params };
for (;;) {
const routeChannel = await this.cachedRouteChannel(moduleId, opts);
try {
return (await this.managedRequest(routeChannel, body, opts));
}
catch (err) {
if (!(err instanceof SubcCallError))
throw this.terminalCallError("managed call failed", err);
if (err.kind === "not_sent") {
try {
await this.reconnectAfterDrop(err);
}
catch (reconnectErr) {
throw this.notSentRecoveryError("managed call was not sent", reconnectErr);
}
continue;
}
if (err.kind === "outcome_unknown" && err.code !== DEADLINE_NO_DROP_CODE) {
// A real drop schedules a reconnect. A deadline-with-no-drop does NOT:
// the socket was never observed to fail (the reply was likely just read
// late under load), so tearing it down would abandon a healthy connection
// and its other in-flight routes for nothing.
this.scheduleReconnectAfterDrop(err);
}
throw err;
}
}
}
/**
* Open a held-open event subscription on a route channel. Sends one Request the
* provider keeps open, delivering each interim StreamData frame to `onEvent`; the
* returned `closed` settles on the StreamEnd terminal (resolve) or an Error / route
* GOODBYE (reject). Events ride this held-open request's correlation id — they are
* never unsolicited, so they are not dropped. Call `unsubscribe()` to cancel.
*/
subscribe(routeChannel, body, onEvent, opts = {}) {
const bytes = body instanceof Uint8Array ? body : this.encode(body);
const priority = opts.priority ?? Priority.Interactive;
const corr = this.nextCorr++;
const key = `${routeChannel}:${corr}`;
const closed = new Promise((resolve, reject) => {
if (this.closedErr) {
reject(this.closedErr);
return;
}
// No timeout: a subscription stays open indefinitely until StreamEnd, Error,
// route GOODBYE, or unsubscribe.
this.pending.set(key, {
channel: routeChannel,
resolve: () => resolve(),
reject,
onProgress: onEvent,
timer: null,
subscription: true,
});
const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false), routeChannel, corr, bytes);
this.sock.write(encodeFrame(frame), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch((err) => {
const p = this.pending.get(key);
if (p)
this.rejectPending(key, p, err instanceof Error ? err : new SubcError(String(err)));
});
});
let cancelled = false;
const unsubscribe = () => {
if (cancelled)
return;
cancelled = true;
// Pure-header Cancel on the held-open (channel, corr): the provider aborts its
// handler and ends with StreamEnd, which settles `closed`.
const cancel = buildFrame(FrameType.Cancel, buildFlags(false, priority, false), routeChannel, corr, EMPTY_BODY);
this.sock.write(encodeFrame(cancel), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch(() => {
// Best-effort: if the socket is already gone, the read loop fails the
// pending waiter and `closed` rejects on its own.
});
};
return { unsubscribe, closed };
}
/**
* Tear down ONE managed route (a route opened via `call()`), keyed by its
* (target, identity). Idempotent and never throws — callers over-call on
* session-end. The teardown:
* - flips a tombstone on the cached route and removes it from the cache, so an
* in-flight `openCachedRoute` for the same key will NOT install its channel
* (the generation guard: close beats a racing reopen), and a later `call()`
* opens a fresh route (this is NOT a permanent tombstone);
* - settles in-flight requests on the channel as RouteClosed (managed requests
* keep their at-most-once classification: outcome_unknown if already sent,
* not_sent otherwise; subscriptions always abort);
* - sends a best-effort route GOODBYE so subc releases the route and notifies
* the module to free per-session resources.
* `opts.drain` waits for in-flight UNARY requests to settle before tearing down.
*/
async closeRoute(target, identity, opts = {}) {
const key = routeCacheKey(target, identity, routeOpenConsumerIdentity(opts));
const cached = this.routes.get(key);
if (!cached)
return; // never opened / already closed — idempotent no-op.
// Generation guard: an in-flight openCachedRoute holds this same object and
// re-checks `closed` before installing its channel, so flipping it here makes
// close win over a racing reopen. Removing the map entry lets a later call()
// create a fresh route for the key (not a permanent tombstone).
cached.closed = true;
this.routes.delete(key);
const channel = cached.channel;
cached.channel = null;
// channel === null means the route was still opening (no channel installed yet);
// the racing open will see closed=true and GOODBYE whatever it opens, so there is
// nothing local to tear down here.
if (channel !== null)
await this.closeRouteChannel(channel, opts);
}
/**
* Tear down ONE route by its channel number — the primitive for callers that
* opened a route with `routeOpen` directly (e.g. a tool route carrying raw
* {name, arguments}) and hold the channel themselves. Idempotent, never throws.
* Settles in-flight requests on the channel as RouteClosed and sends a best-effort
* route GOODBYE. `opts.drain` awaits in-flight UNARY requests first; subscriptions
* are always aborted (a held-open stream cannot be drained).
*/
async closeRouteChannel(channel, opts = {}) {
if (channel === 0)
return; // channel 0 is the control plane, never a route.
if (opts.drain) {
// Wait only for in-flight UNARY requests on this channel; subscriptions are
// aborted below (a held-open stream has no natural completion to drain to).
await this.drainUnaryOnChannel(channel);
}
// Settle anything still in flight on the channel (all of it in abort mode; only
// subscriptions + late stragglers after a drain). Managed requests are classified
// at-most-once via their classifyFailure; raw requests/subscriptions get a plain
// RouteClosed error.
this.failChannel(channel, new SubcError("route closed by closeRoute", "route_closed"));
// Best-effort GOODBYE: releases the route on the daemon and notifies the module.
this.sendRouteGoodbye(channel);
}
close() {
this.closeStarted = true;
this.fail(new SubcError("client closed"));
this.sock.close();
}
/** Resolve once every in-flight UNARY request on the channel (snapshot at call
* time) has settled. Subscriptions are excluded — they are aborted, not drained. */
drainUnaryOnChannel(channel) {
const waiters = [];
for (const pending of this.pending.values()) {
if (pending.channel === channel && !pending.subscription) {
waiters.push(new Promise((resolve) => {
const prev = pending.onSettle;
pending.onSettle = () => {
prev?.();
resolve();
};
}));
}
}
return Promise.all(waiters).then(() => undefined);
}
/** Send a best-effort header-only route GOODBYE for `channel`. One-way: the daemon
* releases the route and relays a route-gone GOODBYE to the module; no ack. */
sendRouteGoodbye(channel) {
if (this.closedErr)
return; // connection already gone — the route died with it.
const goodbye = buildFrame(FrameType.Goodbye, buildFlags(false, Priority.Interactive, false), channel, 0n, EMPTY_BODY);
this.sock.write(encodeFrame(goodbye), Date.now() + DEFAULT_REQUEST_TIMEOUT_MS).catch(() => {
// Best-effort: if the socket is already gone, the route is torn down anyway.
});
}
static async openConnection(opts) {
const conn = await readConnectionFile(opts.connectionFile);
const deadline = Date.now() + (opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);
const endpoint = conn.endpoints[0];
const sock = await SubcSocket.connect(endpoint.host, endpoint.port, deadline);
try {
await authenticateClient(sock, conn, deadline);
}
catch (err) {
sock.close();
throw err;
}
return { sock, conn };
}
async controlRpc(body) {
// Match the canonical probe: control requests go out Interactive on channel 0.
return this.send(0, body, Priority.Interactive, undefined, undefined);
}
send(channel, body, priority, timeoutMs, onProgress) {
if (this.closedErr)
return Promise.reject(this.closedErr);
const corr = this.nextCorr++;
const key = `${channel}:${corr}`;
const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false), channel, corr, body);
return new Promise((resolve, reject) => {
const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const pending = {
channel,
resolve,
reject,
onProgress,
timer: null,
};
pending.timer = setTimeout(() => {
this.arbitrateTimeout(key, pending, channel, corr, ms);
}, ms);
this.pending.set(key, pending);
this.sock.write(encodeFrame(frame), Date.now() + ms).catch((err) => {
const p = this.pending.get(key);
if (p)
this.rejectPending(key, p, err instanceof Error ? err : new SubcError(String(err)));
});
});
}
/**
* A request-deadline timer has fired. Before settling as a timeout, arbitrate
* the timer-vs-poll race: a reply may already be in the socket buffer, unread
* only because the loop was starved. Yield one check phase (setImmediate) so a
* fully-buffered reply dispatches and wins via settle()'s identity guard; then,
* only while the reader is actively draining THIS socket (a frame mid-arrival),
* grant a single hard-capped grace before finally settling. Absent replies
* still settle right after the check phase. The settle carries the deadline
* marker so the managed classifier reports deadline-not-drop.
*/
arbitrateTimeout(key, pending, channel, corr, ms) {
const settleAsTimeout = () => {
this.rejectPending(key, pending, new SubcError(this.timeoutMessage(channel, corr, ms), REQUEST_DEADLINE_MARKER));
};
const graceDeadline = Date.now() + this.opts.timeoutArbitrationGraceMs;
const arbitrate = () => {
// Already settled (by dispatch, fail, GOODBYE, or close)? Nothing to do.
if (this.pending.get(key) !== pending)
return;
// A reply is mid-arrival on this socket (or bytes are buffered), and we are
// still inside the grace window: give the reader another turn to finish
// dispatching it. The generation guard in readLoop keeps this scoped to the
// live socket; the grace cap keeps it from approaching the body-read timeout.
const readerDraining = this.readerActive || this.sock.bufferedBytes() > 0;
if (readerDraining && Date.now() < graceDeadline) {
setImmediate(arbitrate);
return;
}
settleAsTimeout();
};
setImmediate(arbitrate);
}
async managedRequest(routeChannel, body, opts) {
const bytes = body instanceof Uint8Array ? body : this.encode(body);
const priority = opts.priority ?? Priority.Interactive;
try {
const reply = await this.sendManaged(routeChannel, bytes, priority, opts.timeoutMs, opts.onProgress);
return this.parseJson(reply);
}
catch (err) {
if (err instanceof SubcCallError)
throw err;
throw this.terminalCallError("managed call failed", err);
}
}
sendManaged(channel, body, priority, timeoutMs, onProgress) {
if (this.closedErr) {
return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed", this.closedErr));
}
const corr = this.nextCorr++;
const key = `${channel}:${corr}`;
const frame = buildFrame(FrameType.Request, buildFlags(false, priority, false), channel, corr, body);
let handedToSocket = false;
const classifyFailure = (err) => {
// This is the load-bearing asymmetry: only the pre-write paths are NotSent.
// As soon as writeTracked reports that bytes were queued to Node's socket,
// those bytes may already be in the OS buffer or at the daemon. Any later
// close, write callback error, route GOODBYE, or timeout before a response is
// therefore OutcomeUnknown to avoid an unsafe double-mutation retry.
if (!handedToSocket) {
return this.notSentCallError("request bytes were not queued to the subc socket", err);
}
// A request-deadline timeout (arbitration expired without observing a drop)
// is refined from a real connection drop: the socket was NOT seen to fail, so
// the caller can skip a was-it-even-sent recovery path. Still outcome_unknown
// — queued-to-local-socket is not proof the daemon received or ran it.
if (err instanceof SubcError && err.code === REQUEST_DEADLINE_MARKER) {
return new SubcCallError("outcome_unknown", `managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${causeMessage(err)}`, DEADLINE_NO_DROP_CODE, err);
}
return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", err);
};
return new Promise((resolve, reject) => {
const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
const pending = {
channel,
resolve,
reject,
onProgress,
timer: null,
classifyFailure,
};
pending.timer = setTimeout(() => {
this.arbitrateTimeout(key, pending, channel, corr, ms);
}, ms);
this.pending.set(key, pending);
const write = this.sock.writeTracked(encodeFrame(frame), Date.now() + ms);
handedToSocket = write.queued;
write.completed.catch((err) => {
const p = this.pending.get(key);
if (p)
this.rejectPending(key, p, err instanceof Error ? err : new SubcError(String(err)));
});
});
}
async cachedRouteChannel(moduleId, opts) {
const identity = opts.identity ?? this.opts.identity;
if (!identity) {
throw new SubcCallError("terminal", "managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })", "missing_identity");
}
const target = { kind: opts.targetKind ?? this.opts.targetKind, module_id: moduleId };
const consumerIdentity = routeOpenConsumerIdentity(opts);
const key = routeCacheKey(target, identity, consumerIdentity);
let cached = this.routes.get(key);
if (!cached) {
cached = {
key,
moduleId,
target,
identity,
consumerIdentity,
channel: null,
generation: 0,
opening: null,
};
this.routes.set(key, cached);
}
if (cached.channel !== null && cached.generation === this.generation && !this.closedErr) {
return cached.channel;
}
if (!cached.opening) {
cached.opening = this.openCachedRoute(cached).finally(() => {
cached.opening = null;
});
}
return cached.opening;
}
async openCachedRoute(cached) {
const routeRetryDeadline = Date.now() + ROUTE_OPEN_RETRY_DEADLINE_MS;
let routeRetryDelay = this.opts.reconnectBackoff.baseMs;
let routeRetryAttempt = 0;
for (;;) {
if (cached.closed)
throw this.routeClosedDuringOpen();
try {
await this.ensureConnectedForManaged();
}
catch (err) {
throw this.notSentRecoveryError("route.open could not run because reconnect failed", err);
}
if (cached.channel !== null && cached.generation === this.generation && !this.closedErr) {
return cached.channel;
}
try {
const channel = await this.routeOpen(cached.target, cached.identity, {
consumerIdentity: cached.consumerIdentity ?? null,
});
// Generation guard: a closeRoute may have flipped the tombstone WHILE this
// route.open was in flight. If so, close wins — do NOT install the channel
// into the (already-removed) cache entry; GOODBYE the channel we just opened
// so the daemon/module don't leak it, and fail as RouteClosed.
if (cached.closed) {
this.sendRouteGoodbye(channel);
throw this.routeClosedDuringOpen();
}
cached.channel = channel;
cached.generation = this.generation;
return channel;
}
catch (err) {
if (err instanceof SubcCallError && err.code === "route_closed")
throw err;
if (!this.closeStarted && isConsumerReconnectTransient(err)) {
try {
await this.reconnectAfterDrop(err);
}
catch (reconnectErr) {
throw this.notSentRecoveryError("route.open was not sent and reconnect failed", reconnectErr);
}
continue;
}
// A daemon-rejected route.open with a RETRYABLE code (target booting /
// reloading / momentarily absent) is retried IN-PLACE against the same live
// connection — never a socket reconnect, which would needlessly disrupt this
// connection's other routes — until the route-retry deadline. Past the
// deadline it surfaces as not_sent: provably pre-send (no data frame ever
// left the client) AND still transient, so the caller's own retry policy may
// safely re-attempt later. Reason and set kept in parity with subc-client-rs.
if (!this.closeStarted && err instanceof SubcError && isRetryableRouteOpenCode(err.code)) {
routeRetryAttempt += 1;
if (routeRetryAttempt < this.opts.reconnectBackoff.maxAttempts && Date.now() < routeRetryDeadline) {
await this.opts.sleep(routeRetryDelay);
routeRetryDelay = Math.min(routeRetryDelay * 2, this.opts.reconnectBackoff.capMs);
continue;
}
throw this.notSentCallError(`route.open failed for module ${cached.moduleId}: ${err.code} (retry budget exhausted)`, err);
}
// A permanent route.open rejection (bad_consumer_identity, config_divergence,
// unknown_target, ...) is pre-send but would never succeed on retry, so it
// stays terminal — a not_sent class here would invite a retry storm against a
// request the daemon will always reject.
throw this.terminalCallError(`route.open failed for module ${cached.moduleId}`, err);
}
}
}
async ensureConnectedForManaged() {
if (this.closeStarted)
throw new SubcError("client closed");
if (this.reconnecting)
await this.reconnecting;
if (this.closedErr)
await this.reconnectAfterDrop(this.closedErr);
}
scheduleReconnectAfterDrop(err) {
if (this.closeStarted || this.reconnecting)
return;
void this.reconnectAfterDrop(err).catch(() => {
// The originating call keeps its OutcomeUnknown classification. A later call
// will retry reconnect with the same closed connection state if this attempt
// cannot restore the daemon yet.
});
}
reconnectAfterDrop(trigger) {
if (this.closeStarted)
return Promise.reject(new SubcError("client closed"));
if (this.reconnecting)
return this.reconnecting;
const promise = this.reconnectWithRetry(trigger).finally(() => {
if (this.reconnecting === promise)
this.reconnecting = null;
});
this.reconnecting = promise;
return promise;
}
async reconnectWithRetry(_trigger) {
let attempt = 0;
let delay = this.opts.reconnectBackoff.baseMs;
for (;;) {
if (this.closeStarted)
throw new SubcError("client closed");
attempt += 1;
try {
const opened = await SubcClient.openConnection(this.opts);
if (this.closeStarted) {
opened.sock.close();
throw new SubcError("client closed");
}
this.replaceConnection(opened);
await this.reopenCachedRoutes();
return;
}
catch (err) {
if (!isConsumerReconnectTransient(err) || attempt >= this.opts.reconnectBackoff.maxAttempts) {
throw err;
}
await this.opts.sleep(delay);
delay = Math.min(delay * 2, this.opts.reconnectBackoff.capMs);
}
}
}
replaceConnection(opened) {
this.sock.close();
this.sock = opened.sock;
this.currentConn = opened.conn;
this.closedErr = null;
this.generation += 1;
void this.readLoop(opened.sock, this.generation);
}
async reopenCachedRoutes() {
for (const cached of this.routes.values()) {
cached.channel = null;
cached.generation = 0;
}
for (const cached of this.routes.values()) {
if (cached.closed)
continue; // closed concurrently with reconnect — don't reopen.
// Thread the route's consumer identity through the reopen, exactly as the
// lazy per-call path (openCachedRoute) does. Dropping it here would make a
// route reopened after a reconnect send route.open with no consumer_identity,
// so the daemon would re-stamp it with a different (weaker) principal than the
// one it was originally bound under — a silent post-reconnect trust downgrade.
const channel = await this.routeOpen(cached.target, cached.identity, {
consumerIdentity: cached.consumerIdentity ?? null,
});
// A closeRoute may have raced this reopen (flipping the tombstone during the
// route.open await). If so, GOODBYE the channel instead of installing it, so the
// closed route isn't silently re-established on the new connection.
if (cached.closed) {
this.sendRouteGoodbye(channel);
continue;
}
cached.channel = channel;
cached.generation = this.generation;
}
}
// A request timeout carries the local socket port and (channel, corr) so a
// packet capture can pinpoint the exact on-wire exchange — the decisive evidence
// for whether a "timed out" reply was actually delivered to this socket (a
// client-local demux problem) or never sent (a daemon/module problem).
timeoutMessage(channel, corr, ms) {
const port = this.sock.localPort();
const where = port === null ? "channel" : `local_port=${port} channel`;
return `request on ${where} ${channel} corr ${corr} timed out after ${ms}ms`;
}
routeClosedDuringOpen() {
return new SubcCallError("not_sent", "route was closed before route.open completed", "route_closed");
}
async readLoop(sock, generation) {
try {
for (;;) {
// Header read waits indefinitely — idle time between frames is normal, and
// the reader is NOT "active" while parked here (a racing timeout must not
// grant grace just because the connection is idle between frames).
const headerBytes = await sock.readExact(HEADER_LEN, Number.POSITIVE_INFINITY);
// A frame is now arriving. Mark the reader active THROUGH dispatch so a
// timeout that fires mid-arrival grants the reply its bounded grace window
// instead of settling as a spurious timeout.
this.readerActive = true;
try {
const header = decodeHeader(headerBytes);
const body = header.len === 0
? new Uint8Array(0)
: await sock.readExact(header.len, Date.now() + BODY_READ_TIMEOUT_MS);
// Drop a frame read off a socket this client has already replaced
// (reconnect): its pendings were settled by fail(), and dispatching it
// against the current pending map could match a re-used (channel, corr).
if (this.sock === sock && this.generation === generation) {
this.dispatch({ header, body });
}
}
finally {
this.readerActive = false;
}
}
}
catch (err) {
if (this.sock === sock && this.generation === generation) {
this.fail(err instanceof Error ? err : new SubcError(String(err)));
}
}
}
dispatch(frame) {
const key = `${frame.header.channel}:${frame.header.corr}`;
const pending = this.pending.get(key);
if (pending) {
switch (frame.header.ty) {
case FrameType.Push:
case FrameType.StreamData:
pending.onProgress?.(frame.body);
return;
case FrameType.Response:
case FrameType.StreamEnd:
this.settle(key, pending, () => pending.resolve(frame));
return;
case FrameType.Error:
this.settle(key, pending, () => pending.reject(this.errorFromFrame(frame)));
return;
default:
return;
}
}
if (frame.header.ty === FrameType.Goodbye) {
this.failChannel(frame.header.channel, new SubcError("route closed by subc (GOODBYE)"));
return;
}
// A terminal frame (Response/Error/StreamEnd) with no waiter is almost always
// a reply that arrived AFTER its request already settled — the fingerprint of a
// premature timeout under event-loop starvation (the reply raced the deadline
// and lost). Metadata-only debug log (never the body) so every future
// occurrence is a one-line diagnosis instead of an invisible drop. Enable with
// NODE_DEBUG=subc-client.
if (frame.header.ty === FrameType.Response ||
frame.header.ty === FrameType.Error ||
frame.header.ty === FrameType.StreamEnd) {
debug("dropped terminal frame with no waiter: type=%d channel=%d corr=%s port=%s", frame.header.ty, frame.header.channel, frame.header.corr, this.sock.localPort() ?? "?");
return;
}
// Unmatched Push or stray frame: no registered waiter. Drop it — v1 has no
// unsolicited-push consumers.
}
/**
* Settle a pending exactly once. The object-identity guard (the map still
* holds THIS pending under `key`) is the single-winner primitive: whichever of
* dispatch, a timeout, fail(), failChannel(), a GOODBYE, or a deferred timeout
* arbitration reaches it first wins, and every later caller no-ops. This is what
* makes the deferred-timeout arbitration safe — it cannot double-settle, reject
* an already-resolved promise, or delete a pending re-created for a later corr.
* Returns true when this call was the settler.
*/
settle(key, pending, run) {
if (this.pending.get(key) !== pending)
return false;
this.pending.delete(key);
if (pending.timer)
clearTimeout(pending.timer);
run();
pending.onSettle?.();
return true;
}
rejectPending(key, pending, err) {
this.settle(key, pending, () => pending.reject(pending.classifyFailure?.(err) ?? err));
}
errorFromFrame(frame) {
try {
const parsed = JSON.parse(Buffer.from(frame.body).toString("utf8"));
return new SubcError(parsed.message ?? "subc error", parsed.code);
}
catch {
return new SubcError(Buffer.from(frame.body).toString("utf8") || "subc error");
}
}
failChannel(channel, err) {
for (const [key, pending] of this.pending) {
if (pending.channel === channel) {
this.rejectPending(key, pending, err);
}
}
}
fail(err) {
if (!this.closedErr)
this.closedErr = err;
for (const [key, pending] of this.pending) {
this.rejectPending(key, pending, err);
}
}
notSentCallError(message, cause) {
return new SubcCallError("not_sent", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
}
outcomeUnknownCallError(message, cause) {
return new SubcCallError("outcome_unknown", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
}
terminalCallError(message, cause) {
if (cause instanceof SubcCallError)
return cause;
return new SubcCallError("terminal", `${message}${causeMessage(cause)}`, errorCode(cause), cause);
}
notSentRecoveryError(message, cause) {
if (cause instanceof SubcCallError)
return cause;
if (isConsumerReconnectTransient(cause))
return this.notSentCallError(message, cause);
return this.terminalCallError(message, cause);
}
encode(value) {
return new Uint8Array(Buffer.from(JSON.stringify(value), "utf8"));
}
parseJson(frame) {
return JSON.parse(Buffer.from(frame.body).toString("utf8"));
}
}
export function isConsumerReconnectTransient(err) {
if (err instanceof SocketClosedError || err instanceof SocketTimeoutError)
return true;
if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError)
return true;
if (err instanceof SubcCallError)
return err.kind === "not_sent" || err.kind === "outcome_unknown";
if (err instanceof SubcError || err instanceof ConnectionFileError || err instanceof AuthError)
return false;
const code = errorCode(err);
return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT" || code === "ENOENT";
}
/**
* The closed set of route.open rejection codes that mean "the target is
* momentarily unavailable but the request could succeed on retry" — the target
* is booting, mid-reload, transiently absent, or the bind relay timed out. A
* daemon-rejected route.open is provably pre-send (no data frame ever left the
* client), so these classify as not_sent; the managed path retries them in-place
* within ROUTE_OPEN_RETRY_DEADLINE_MS. Permanent rejections (bad_consumer_identity,
* config_divergence, unknown_target, ...) are excluded — they are pre-send but
* would never succeed, so retrying them would only storm the daemon. Kept
* byte-identical to subc-client-rs is_retryable_route_open_code for cross-client
* classification parity.
*/
export function isRetryableRouteOpenCode(code) {
return (code === "unknown_module" ||
code === "module_reloading" ||
code === "target_unavailable" ||
code === "module_timeout");
}
export async function connectionFileExists(path) {
try {
await fs.access(path);
return true;
}
catch {
return false;
}
}
function normalizeConnectOptions(opts) {
return {
connectionFile: opts.connectionFile,
handshakeTimeoutMs: opts.handshakeTimeoutMs,
identity: opts.identity,
targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
sleep: opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS,
};
}
function routeCacheKey(target, identity, consumerIdentity) {
const consumerPart = consumerIdentity
? `${consumerIdentity.module_id}\0${consumerIdentity.launch_nonce}`
: "";
return `${target.kind}\0${target.module_id}\0${identity.project_root}\0${identity.harness}\0${identity.session}\0${consumerPart}`;
}
function routeOpenConsumerIdentity(opts = {}) {
if (opts.consumerIdentity !== undefined)
return opts.consumerIdentity ?? undefined;
const moduleId = process.env[SUBC_MODULE_ID_ENV];
const launchNonce = process.env[SUBC_LAUNCH_NONCE_ENV];
if (!moduleId || !launchNonce)
return undefined;
return { module_id: moduleId, launch_nonce: launchNonce };
}
function errorCode(err) {
if (typeof err === "object" && err !== null && "code" in err) {
const code = err.code;
if (typeof code === "string")
return code;
}
return undefined;
}
function causeMessage(cause) {
if (cause === undefined)
return "";
return `: ${cause instanceof Error ? cause.message : String(cause)}`;
}
//# sourceMappingURL=client.js.map
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,uEAAuE;AACvE,gFAAgF;AAChF,gFAAgF;AAChF,uCAAuC;AACvC,EAAE;AACF,uEAAuE;AACvE,6EAA6E;AAC7E,8EAA8E;AAC9E,6EAA6E;AAC7E,qCAAqC;AAErC,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE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OAAO,KAAK,QAAQ,CAAC,OAAO,KAAK,YAAY,EAAE,CAAC;AACpI,CAAC;AAED,SAAS,yBAAyB,CAAC,OAAyB,EAAE;IAC5D,IAAI,IAAI,CAAC,gBAAgB,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC,gBAAgB,IAAI,SAAS,CAAC;IACnF,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IACjD,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;IACvD,IAAI,CAAC,QAAQ,IAAI,CAAC,WAAW;QAAE,OAAO,SAAS,CAAC;IAChD,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,CAAC;AAC5D,CAAC;AAED,SAAS,SAAS,CAAC,GAAY;IAC7B,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,IAAI,MAAM,IAAI,GAAG,EAAE,CAAC;QAC7D,MAAM,IAAI,GAAI,GAA0B,CAAC,IAAI,CAAC;QAC9C,IAAI,OAAO,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC;IAC5C,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAClC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,CAAC;IACnC,OAAO,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AACvE,CAAC"}
export declare const SCHEMA_VERSION = 1;
export declare const MIN_KEY_LEN = 32;
export declare const DAEMON_ID_LEN = 16;
export interface Endpoint {
host: string;
port: number;
}
export interface ConnectionInfo {
schema: number;
endpoints: Endpoint[];
/** Transport key bytes. Serialized on disk as a JSON array of numbers. */
key: Uint8Array;
/** 16-byte daemon identity. Serialized on disk as a JSON array of numbers. */
daemonId: Uint8Array;
pid: number;
daemonVer: string;
}
export declare class ConnectionFileError extends Error {
}
/** Read, permission-check, and validate a connection file. */
export declare function readConnectionFile(path: string): Promise<ConnectionInfo>;
//# sourceMappingURL=connection-file.d.ts.map
{"version":3,"file":"connection-file.d.ts","sourceRoot":"","sources":["../src/connection-file.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,cAAc,IAAI,CAAC;AAChC,eAAO,MAAM,WAAW,KAAK,CAAC;AAC9B,eAAO,MAAM,aAAa,KAAK,CAAC;AAEhC,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,QAAQ,EAAE,CAAC;IACtB,0EAA0E;IAC1E,GAAG,EAAE,UAAU,CAAC;IAChB,8EAA8E;IAC9E,QAAQ,EAAE,UAAU,CAAC;IACrB,GAAG,EAAE,MAAM,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,qBAAa,mBAAoB,SAAQ,KAAK;CAAG;AA+CjD,8DAA8D;AAC9D,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAgC9E"}
// Port of subc-transport's connection_file.rs reader. The connection file is
// the daemon's published rendezvous record; its `key` is the shared transport
// secret. We refuse to trust a key from a file other local users can read,
// exactly as the Rust reader does, so a leaked (group/world-readable) key is a
// loud failure rather than a silent downgrade.
import { promises as fs } from "node:fs";
export const SCHEMA_VERSION = 1;
export const MIN_KEY_LEN = 32;
export const DAEMON_ID_LEN = 16;
export class ConnectionFileError extends Error {
}
function toBytes(value, field) {
if (!Array.isArray(value) || value.some((n) => typeof n !== "number")) {
throw new ConnectionFileError(`connection file field '${field}' must be a JSON array of bytes`);
}
return Uint8Array.from(value);
}
function validate(info) {
if (info.schema !== SCHEMA_VERSION) {
throw new ConnectionFileError(`unsupported connection file schema ${info.schema}; expected ${SCHEMA_VERSION}`);
}
if (info.endpoints.length === 0) {
throw new ConnectionFileError("connection file must include at least one endpoint");
}
if (info.key.length < MIN_KEY_LEN) {
throw new ConnectionFileError(`connection file key is too short: ${info.key.length} bytes, need at least ${MIN_KEY_LEN}`);
}
if (info.daemonId.length !== DAEMON_ID_LEN) {
throw new ConnectionFileError(`connection file daemon_id must be ${DAEMON_ID_LEN} bytes, got ${info.daemonId.length}`);
}
}
/**
* On unix, reject any group/other permission bit: the key is published
* owner-only (0600), so a wider mode means the secret has leaked. On Windows the
* file inherits the per-user profile directory ACL at create time and there are
* no portable mode bits to re-check, matching the Rust no-op.
*/
async function verifyOwnerOnly(path) {
if (process.platform === "win32")
return;
const stat = await fs.stat(path);
const mode = stat.mode & 0o777;
if ((mode & 0o077) !== 0) {
throw new ConnectionFileError(`connection file ${path} has insecure permissions 0o${mode.toString(8)}; expected owner-only 0600`);
}
}
/** Read, permission-check, and validate a connection file. */
export async function readConnectionFile(path) {
await verifyOwnerOnly(path);
const raw = await fs.readFile(path, "utf8");
let parsed;
try {
parsed = JSON.parse(raw);
}
catch (err) {
throw new ConnectionFileError(`connection file JSON read failed for ${path}: ${String(err)}`);
}
const endpointsRaw = parsed.endpoints;
if (!Array.isArray(endpointsRaw)) {
throw new ConnectionFileError("connection file 'endpoints' must be an array");
}
const endpoints = endpointsRaw.map((e) => {
const ep = e;
if (typeof ep.host !== "string" || typeof ep.port !== "number") {
throw new ConnectionFileError("connection file endpoint must be { host: string, port: number }");
}
return { host: ep.host, port: ep.port };
});
const info = {
schema: parsed.schema,
endpoints,
key: toBytes(parsed.key, "key"),
daemonId: toBytes(parsed.daemon_id, "daemon_id"),
pid: parsed.pid,
daemonVer: parsed.daemon_ver ?? "",
};
validate(info);
return info;
}
//# sourceMappingURL=connection-file.js.map
{"version":3,"file":"connection-file.js","sourceRoot":"","sources":["../src/connection-file.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,8EAA8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CAAC,CAAC,EAAE,EAAE;QACnD,MAAM,EAAE,GAAG,CAA4B,CAAC;QACxC,IAAI,OAAO,EAAE,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,EAAE,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC/D,MAAM,IAAI,mBAAmB,CAAC,iEAAiE,CAAC,CAAC;QACnG,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC;IAC1C,CAAC,CAAC,CAAC;IAEH,MAAM,IAAI,GAAmB;QAC3B,MAAM,EAAE,MAAM,CAAC,MAAgB;QAC/B,SAAS;QACT,GAAG,EAAE,OAAO,CAAC,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC;QAC/B,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC;QAChD,GAAG,EAAE,MAAM,CAAC,GAAa;QACzB,SAAS,EAAG,MAAM,CAAC,UAAqB,IAAI,EAAE;KAC/C,CAAC;IACF,QAAQ,CAAC,IAAI,CAAC,CAAC;IACf,OAAO,IAAI,CAAC;AACd,CAAC"}
export declare const PROTOCOL_VERSION = 1;
export declare const HEADER_LEN = 17;
export declare const FROZEN_PREFIX_LEN = 5;
export declare const MAX_FRAME_BODY_LEN: number;
/** `type` byte at offset 5. */
export declare enum FrameType {
Request = 0,
Response = 1,
Push = 2,
StreamData = 3,
StreamEnd = 4,
Error = 5,
Cancel = 6,
Ping = 7,
Pong = 8,
Hello = 9,
HelloAck = 10,
Goodbye = 11
}
/** Cancel/Ping/Pong/Goodbye carry only a header (`len` must be 0). */
export declare function isPureHeader(ty: FrameType): boolean;
/** Scheduling priority carried in flags bits 1-2. */
export declare enum Priority {
Passive = 0,
Interactive = 1,
Background = 2
}
/** Build the flags byte from typed components (mirrors Flags::new). */
export declare function buildFlags(binary: boolean, priority: Priority, last: boolean): number;
export interface EnvelopeHeader {
len: number;
ver: number;
ty: FrameType;
flags: number;
channel: number;
corr: bigint;
}
export interface Frame {
header: EnvelopeHeader;
body: Uint8Array;
}
/** Serialize a header to its fixed 17-byte little-endian form. */
export declare function encodeHeader(h: EnvelopeHeader): Uint8Array;
export declare class DecodeError extends Error {
}
/**
* Decode a header from the front of `bytes`, following the frozen-prefix
* discipline: need 5 bytes for len+ver, dispatch full header length on ver,
* then validate. Mirrors decode_header — never throws on a structurally short
* buffer beyond the typed DecodeError.
*/
export declare function decodeHeader(bytes: Uint8Array): EnvelopeHeader;
/** Build a full current-version frame, enforcing the body-length cap and the pure-header rule. */
export declare function buildFrame(ty: FrameType, flags: number, channel: number, corr: bigint, body: Uint8Array): Frame;
/** Build a full frame while preserving a peer-negotiated envelope version. */
export declare function buildFrameWithVersion(ver: number, ty: FrameType, flags: number, channel: number, corr: bigint, body: Uint8Array): Frame;
/** Encode a frame to wire bytes: 17-byte header followed by `len` body bytes. */
export declare function encodeFrame(frame: Frame): Uint8Array;
//# sourceMappingURL=envelope.d.ts.map
{"version":3,"file":"envelope.d.ts","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAClC,eAAO,MAAM,UAAU,KAAK,CAAC;AAC7B,eAAO,MAAM,iBAAiB,IAAI,CAAC;AACnC,eAAO,MAAM,kBAAkB,QAAmB,CAAC;AAEnD,+BAA+B;AAC/B,oBAAY,SAAS;IACnB,OAAO,IAAI;IACX,QAAQ,IAAI;IACZ,IAAI,IAAI;IACR,UAAU,IAAI;IACd,SAAS,IAAI;IACb,KAAK,IAAI;IACT,MAAM,IAAI;IACV,IAAI,IAAI;IACR,IAAI,IAAI;IACR,KAAK,IAAI;IACT,QAAQ,KAAK;IACb,OAAO,KAAK;CACb;AAID,sEAAsE;AACtE,wBAAgB,YAAY,CAAC,EAAE,EAAE,SAAS,GAAG,OAAO,CAOnD;AAED,qDAAqD;AACrD,oBAAY,QAAQ;IAClB,OAAO,IAAI;IACX,WAAW,IAAI;IACf,UAAU,IAAI;CACf;AAQD,uEAAuE;AACvE,wBAAgB,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAMrF;AAED,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,EAAE,EAAE,SAAS,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,KAAK;IACpB,MAAM,EAAE,cAAc,CAAC;IACvB,IAAI,EAAE,UAAU,CAAC;CAClB;AAED,kEAAkE;AAClE,wBAAgB,YAAY,CAAC,CAAC,EAAE,cAAc,GAAG,UAAU,CAU1D;AAED,qBAAa,WAAY,SAAQ,KAAK;CAAG;AAEzC;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,UAAU,GAAG,cAAc,CA+B9D;AAED,kGAAkG;AAClG,wBAAgB,UAAU,CACxB,EAAE,EAAE,SAAS,EACb,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,UAAU,GACf,KAAK,CAEP;AAED,8EAA8E;AAC9E,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,MAAM,EACX,EAAE,EAAE,SAAS,EACb,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,UAAU,GACf,KAAK,CAWP;AAED,iFAAiF;AACjF,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,GAAG,UAAU,CAMpD"}
// Byte-for-byte port of subc-protocol's 17-byte envelope header.
// Source of truth: crates/subc-protocol/src/lib.rs. Keep field offsets, the
// little-endian encoding, and the frame-type/flag numbering in lock-step with
// the Rust; a one-byte drift here desynchronizes every frame on the wire.
export const PROTOCOL_VERSION = 1;
export const HEADER_LEN = 17;
export const FROZEN_PREFIX_LEN = 5;
export const MAX_FRAME_BODY_LEN = 64 * 1024 * 1024;
/** `type` byte at offset 5. */
export var FrameType;
(function (FrameType) {
FrameType[FrameType["Request"] = 0] = "Request";
FrameType[FrameType["Response"] = 1] = "Response";
FrameType[FrameType["Push"] = 2] = "Push";
FrameType[FrameType["StreamData"] = 3] = "StreamData";
FrameType[FrameType["StreamEnd"] = 4] = "StreamEnd";
FrameType[FrameType["Error"] = 5] = "Error";
FrameType[FrameType["Cancel"] = 6] = "Cancel";
FrameType[FrameType["Ping"] = 7] = "Ping";
FrameType[FrameType["Pong"] = 8] = "Pong";
FrameType[FrameType["Hello"] = 9] = "Hello";
FrameType[FrameType["HelloAck"] = 10] = "HelloAck";
FrameType[FrameType["Goodbye"] = 11] = "Goodbye";
})(FrameType || (FrameType = {}));
const FRAME_TYPE_MAX = FrameType.Goodbye;
/** Cancel/Ping/Pong/Goodbye carry only a header (`len` must be 0). */
export function isPureHeader(ty) {
return (ty === FrameType.Cancel ||
ty === FrameType.Ping ||
ty === FrameType.Pong ||
ty === FrameType.Goodbye);
}
/** Scheduling priority carried in flags bits 1-2. */
export var Priority;
(function (Priority) {
Priority[Priority["Passive"] = 0] = "Passive";
Priority[Priority["Interactive"] = 1] = "Interactive";
Priority[Priority["Background"] = 2] = "Background";
})(Priority || (Priority = {}));
const FLAG_BINARY = 0b0000_0001; // bit 0
const FLAG_PRIORITY_MASK = 0b0000_0110; // bits 1-2
const FLAG_PRIORITY_SHIFT = 1;
const FLAG_LAST = 0b0000_1000; // bit 3
const FLAG_RESERVED_MASK = 0b1111_0000; // bits 4-7 must be zero
/** Build the flags byte from typed components (mirrors Flags::new). */
export function buildFlags(binary, priority, last) {
let b = 0;
if (binary)
b |= FLAG_BINARY;
b |= priority << FLAG_PRIORITY_SHIFT;
if (last)
b |= FLAG_LAST;
return b;
}
/** Serialize a header to its fixed 17-byte little-endian form. */
export function encodeHeader(h) {
const buf = new Uint8Array(HEADER_LEN);
const view = new DataView(buf.buffer);
view.setUint32(0, h.len, true);
buf[4] = h.ver;
buf[5] = h.ty;
buf[6] = h.flags;
view.setUint16(7, h.channel, true);
view.setBigUint64(9, h.corr, true);
return buf;
}
export class DecodeError extends Error {
}
/**
* Decode a header from the front of `bytes`, following the frozen-prefix
* discipline: need 5 bytes for len+ver, dispatch full header length on ver,
* then validate. Mirrors decode_header — never throws on a structurally short
* buffer beyond the typed DecodeError.
*/
export function decodeHeader(bytes) {
if (bytes.length < FROZEN_PREFIX_LEN) {
throw new DecodeError(`header shorter than frozen prefix: have ${bytes.length} bytes`);
}
const ver = bytes[4];
if (ver !== PROTOCOL_VERSION) {
throw new DecodeError(`unsupported envelope version ${ver}`);
}
if (bytes.length < HEADER_LEN) {
throw new DecodeError(`header too short for version: have ${bytes.length} bytes, need ${HEADER_LEN}`);
}
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const len = view.getUint32(0, true);
const tyByte = bytes[5];
if (tyByte > FRAME_TYPE_MAX) {
throw new DecodeError(`unknown frame type byte ${tyByte}`);
}
const ty = tyByte;
const flags = bytes[6];
if ((flags & FLAG_RESERVED_MASK) !== 0) {
throw new DecodeError(`reserved flag bits set in flags 0b${flags.toString(2)}`);
}
if (((flags & FLAG_PRIORITY_MASK) >> FLAG_PRIORITY_SHIFT) === 0b11) {
throw new DecodeError(`reserved priority bits set in flags 0b${flags.toString(2)}`);
}
if (isPureHeader(ty) && len !== 0) {
throw new DecodeError(`pure-header frame ${FrameType[ty]} declared non-zero body length ${len}`);
}
const channel = view.getUint16(7, true);
const corr = view.getBigUint64(9, true);
return { len, ver, ty, flags, channel, corr };
}
/** Build a full current-version frame, enforcing the body-length cap and the pure-header rule. */
export function buildFrame(ty, flags, channel, corr, body) {
return buildFrameWithVersion(PROTOCOL_VERSION, ty, flags, channel, corr, body);
}
/** Build a full frame while preserving a peer-negotiated envelope version. */
export function buildFrameWithVersion(ver, ty, flags, channel, corr, body) {
if (body.length > MAX_FRAME_BODY_LEN) {
throw new DecodeError(`frame body ${body.length} exceeds max ${MAX_FRAME_BODY_LEN}`);
}
if (isPureHeader(ty) && body.length !== 0) {
throw new DecodeError(`pure-header frame ${FrameType[ty]} cannot carry a body`);
}
return {
header: { len: body.length, ver, ty, flags, channel, corr },
body,
};
}
/** Encode a frame to wire bytes: 17-byte header followed by `len` body bytes. */
export function encodeFrame(frame) {
const header = encodeHeader(frame.header);
const out = new Uint8Array(header.length + frame.body.length);
out.set(header, 0);
out.set(frame.body, header.length);
return out;
}
//# sourceMappingURL=envelope.js.map
{"version":3,"file":"envelope.js","sourceRoot":"","sources":["../src/envelope.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,4EAA4E;AAC5E,8EAA8E;AAC9E,0EAA0E;AAE1E,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAClC,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAC;AAC7B,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC;AACnC,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEnD,+BAA+B;AAC/B,MAAM,CAAN,IAAY,SAaX;AAbD,WAAY,SAAS;IACnB,+CAAW,CAAA;IACX,iDAAY,CAAA;IACZ,yCAAQ,CAAA;IACR,qDAAc,CAAA;IACd,mDAAa,CAAA;IACb,2CAAS,CAAA;IACT,6CAAU,CAAA;IACV,yCAAQ,CAAA;IACR,yCAAQ,CAAA;IACR,2CAAS,CAAA;IACT,kDAAa,CAAA;IACb,gDAAY,CAAA;AACd,CAAC,EAbW,SAAS,KAAT,SAAS,QAapB;AAED,MAAM,cAAc,GAAG,SAAS,CAAC,OAAO,CAAC;AAEzC,sEAAsE;AACtE,MAAM,UAAU,YAAY,CAAC,EAAa;IACxC,OAAO,CACL,EAAE,KAAK,SAAS,CAAC,MAAM;QACvB,EAAE,KAA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AC;QACrC,MAAM,IAAI,WAAW,CAAC,cAAc,IAAI,CAAC,MAAM,gBAAgB,kBAAkB,EAAE,CAAC,CAAC;IACvF,CAAC;IACD,IAAI,YAAY,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1C,MAAM,IAAI,WAAW,CAAC,qBAAqB,SAAS,CAAC,EAAE,CAAC,sBAAsB,CAAC,CAAC;IAClF,CAAC;IACD,OAAO;QACL,MAAM,EAAE,EAAE,GAAG,EAAE,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE;QAC3D,IAAI;KACL,CAAC;AACJ,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,WAAW,CAAC,KAAY;IACtC,MAAM,MAAM,GAAG,YAAY,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC1C,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC9D,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;IACnB,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnC,OAAO,GAAG,CAAC;AACb,CAAC"}
export { SubcClient, SubcError, SubcCallError, DEFAULT_RECONNECT_BACKOFF, SUBC_MODULE_ID_ENV, SUBC_LAUNCH_NONCE_ENV, isConsumerReconnectTransient, connectionFileExists, type BindIdentity, type RouteTarget, type ManagedRouteKind, type ConsumerIdentity, type RouteOpenOptions, type CatalogEntry, type RequestOptions, type ManagedCallOptions, type ConnectOptions, type ReconnectBackoff, type SubcCallErrorKind, type SubscribeOptions, type Subscription, type CloseRouteOptions, } from "./client.js";
export { readConnectionFile, ConnectionFileError, type ConnectionInfo, type Endpoint, } from "./connection-file.js";
export { FrameType, Priority, PROTOCOL_VERSION, HEADER_LEN, buildFrame, buildFrameWithVersion, buildFlags, encodeFrame, decodeHeader, encodeHeader, DecodeError, type Frame, type EnvelopeHeader, } from "./envelope.js";
export { authenticateClient, computeProof, AuthError, NONCE_LEN, PROOF_LEN, SERVER_PROOF_DOMAIN, CLIENT_AUTH_DOMAIN, } from "./auth.js";
export { SubcSocket, SocketClosedError, SocketTimeoutError } from "./socket.js";
export { SubcProvider, SubcProviderError, HELLO_CORR, managementSurfaceManifest, jsonProviderHandler, type ProviderRequestContext, type BindDecision, type Principal, type BindingsInput, type CircuitBreakerInput, type Concurrency, type ConsumerRoleInput, type ExecutionMode, type IdentityBindingInput, type IdentityScope, type InternalTransport, type LeaseScope, type ManagementOperationInput, type ManagementOperationKind, type ManagementSurfaceManifestOptions, type ManifestInput, type ModelPolicyInput, type ModuleHelloAckBody, type ObservabilityKind, type ObservabilitySurfaceInput, type PipelineAppliesToInput, type PipelineStageKind, type ProviderConnectionState, type ProviderHandler, type ProviderRoleInput, type RouteBindRequest, type ScheduledTaskInput, type StorageBindingInput, type StorageKind, type StorageScope, type SubcProviderConnectOptions, type TaskEligibilityInput, type ToolInput, type TrustTier, type VaultGrantInput, } from "./provider.js";
//# sourceMappingURL=index.d.ts.map
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,SAAS,EACT,aAAa,EACb,yBAAyB,EACzB,kBAAkB,EAClB,qBAAqB,EACrB,4BAA4B,EAC5B,oBAAoB,EACpB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,YAAY,EACjB,KAAK,iBAAiB,GACvB,MAAM,aA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AK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,eAAe,GACrB,MAAM,eAAe,CAAC"}
export { SubcClient, SubcError, SubcCallError, DEFAULT_RECONNECT_BACKOFF, SUBC_MODULE_ID_ENV, SUBC_LAUNCH_NONCE_ENV, isConsumerReconnectTransient, connectionFileExists, } from "./client.js";
export { readConnectionFile, ConnectionFileError, } from "./connection-file.js";
export { FrameType, Priority, PROTOCOL_VERSION, HEADER_LEN, buildFrame, buildFrameWithVersion, buildFlags, encodeFrame, decodeHeader, encodeHeader, DecodeError, } from "./envelope.js";
export { authenticateClient, computeProof, AuthError, NONCE_LEN, PROOF_LEN, SERVER_PROOF_DOMAIN, CLIENT_AUTH_DOMAIN, } from "./auth.js";
export { SubcSocket, SocketClosedError, SocketTimeoutError } from "./socket.js";
export { SubcProvider, SubcProviderError, HELLO_CORR, managementSurfaceManifest, jsonProviderHandler, } from "./provider.js";
//# sourceMappingURL=index.js.map
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,SAAS,EACT,aAAa,EACb,yBAAyB,EACzB,kBAAkB,EAClB,qBAAqB,EACrB,4BAA4B,EAC5B,oBAAoB,GAerB,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,kBAAkB,EAClB,mBAAmB,GAGpB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,UAAU,EACV,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,WAAW,GAGZ,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,SAAS,EACT,SAAS,EACT,SAAS,EACT,mBAAmB,EACnB,kBAAkB,GACnB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAChF,OAAO,EACL,YAAY,EACZ,iBAAiB,EACjB,UAAU,EACV,yBAAyB,EACzB,mBAAmB,GAoCpB,MAAM,eAAe,CAAC"}
import { type BindIdentity, type ReconnectBackoff, type RouteTarget } from "./client.js";
import { type ConnectionInfo } from "./connection-file.js";
export declare const HELLO_CORR = 1n;
export type TrustTier = "first_party" | "reviewed" | "untrusted";
export type ExecutionMode = "pure" | "mutating" | "unfenceable";
export type Concurrency = "serial" | "module_managed" | "stateless_parallel";
export type IdentityScope = "session" | "project";
export type PipelineStageKind = "transform" | "codec" | "auth";
export type ManagementOperationKind = "query" | "mutate";
export type ObservabilityKind = "snapshot" | "stream";
export type InternalTransport = "bulk";
export type StorageKind = "sqlite";
export type StorageScope = "project";
export type LeaseScope = "project";
export interface ManifestInput {
module_id: string;
module_version: string;
protocol_ver: number;
trust_tier: TrustTier;
provides: ProviderRoleInput[];
consumes: ConsumerRoleInput[];
scheduled_tasks: ScheduledTaskInput[];
bindings: BindingsInput;
}
export type ProviderRoleInput = {
role: "tool_provider";
tools: ToolInput[];
identity_scope: IdentityScope[];
concurrency: Concurrency;
emits_push: boolean;
sub_supervises: boolean;
} | {
role: "pipeline_stage";
stage: PipelineStageKind;
applies_to: PipelineAppliesToInput;
interface: string;
declares_frozen_floor: boolean;
needs_signals: string[];
conformance_class: string;
} | {
role: "management_surface";
operations: ManagementOperationInput[];
config_schema: unknown;
observability: ObservabilitySurfaceInput[];
identity_scope: IdentityScope[];
} | {
role: "internal_service";
service_id: string;
transport: InternalTransport;
agent_facing: boolean;
operations: string[];
};
export interface ToolInput {
name: string;
execution_mode: ExecutionMode;
schema: unknown;
}
export interface PipelineAppliesToInput {
provider: string;
model: string;
}
export interface ManagementOperationInput {
name: string;
kind: ManagementOperationKind;
}
export interface ObservabilitySurfaceInput {
name: string;
kind: ObservabilityKind;
}
export type ConsumerRoleInput = {
role: "tool_client";
of: string[];
} | {
role: "llm_client";
via: string;
auth: string;
} | {
role: "service_client";
of: string[];
};
export interface ScheduledTaskInput {
task_id: string;
eligibility: TaskEligibilityInput;
lease_scope: LeaseScope;
renews_during_calls: boolean;
toolset: string[];
model_policy: ModelPolicyInput;
step_cap: number;
circuit_breaker: CircuitBreakerInput;
}
export interface TaskEligibilityInput {
cooldown: string;
window: string;
}
export interface ModelPolicyInput {
tier: string;
fallback_chain: string[];
}
export interface CircuitBreakerInput {
identical_failures: number;
}
export interface BindingsInput {
storage: StorageBindingInput;
vault_grants: VaultGrantInput[];
identity: IdentityBindingInput;
}
export interface StorageBindingInput {
kind: StorageKind;
scope: StorageScope;
owns_schema: boolean;
}
export interface VaultGrantInput {
secret: string;
reason: string;
}
export interface IdentityBindingInput {
requires: IdentityScope[];
optional: IdentityScope[];
}
export interface ManagementSurfaceManifestOptions {
moduleId: string;
operations: Array<string | ManagementOperationInput>;
moduleVersion?: string;
}
/**
* Per-request context handed to a provider handler. A unary handler ignores it and
* just returns its response bytes; a streaming handler uses `emit` to push interim
* events and `signal` to learn when the consumer cancelled or the route went away.
*/
export interface ProviderRequestContext {
/**
* Emit an interim event as a StreamData frame on this request's (channel, corr).
* The consumer receives it via its subscription `onEvent`. A no-op once the
* request has been aborted (cancelled or route-gone).
*/
emit(body: Uint8Array): Promise<void>;
/** Aborts when the consumer sends Cancel for this request, or the route is torn down. */
signal: AbortSignal;
/**
* The provider's current transport connection epoch: 1 on the initial connection,
* +1 on each successful reconnect + re-registration. Read at the moment the handler
* calls it (so it reflects any reconnect that happened while the handler ran). A
* handler that reports connection liveness to its consumer (e.g. stamping the epoch
* on a response so the consumer can detect a reconnect) should read it from here —
* this is the single authoritative source of the transport epoch, so it can never
* drift from a separately-maintained counter.
*/
currentEpoch(): number;
}
/**
* A request handler. Return a `Uint8Array` for a single Response (unary), or
* `void` to end a streaming subscription with a StreamEnd terminal (after emitting
* events via `ctx.emit`). Throwing produces an Error terminal.
*/
export type ProviderHandler = (routeChannel: number, body: Uint8Array, ctx: ProviderRequestContext) => Promise<Uint8Array | void> | Uint8Array | void;
export type Principal = {
kind: "reserved";
module_id: string;
} | {
kind: "direct";
} | {
kind: "unverified";
};
export interface RouteBindRequest {
route_channel: number;
target: RouteTarget;
identity: BindIdentity;
principal?: Principal;
}
export type BindDecision = boolean | {
accept: boolean;
code?: string;
message?: string;
};
export type ProviderConnectionState = {
state: "connected";
epoch: number;
} | {
state: "down";
cause: Error;
} | {
state: "reconnecting";
attempt: number;
} | {
state: "restored";
epoch: number;
};
export interface SubcProviderConnectOptions {
connectionFile: string;
manifest: ManifestInput;
handler: ProviderHandler;
handshakeTimeoutMs?: number;
controlOps?: string[] | null;
onBind?: (request: RouteBindRequest) => Promise<BindDecision> | BindDecision;
onRouteGone?: (routeChannel: number) => void | Promise<void>;
/** Backoff for provider reconnect after an unexpected socket drop. */
reconnectBackoff?: ReconnectBackoff;
/** Injectable sleep for timer-free reconnect and debounce tests. */
sleep?: (ms: number) => Promise<void>;
/** Milliseconds to wait before emitting restored after the provider re-registers following a reconnect. */
restoredDebounceMs?: number;
/** Callback that receives ProviderConnectionState events one at a time and in order. */
onConnectionState?: (event: ProviderConnectionState) => void | Promise<void>;
/**
* The one-time launch nonce to echo in HELLO for a reserved module. Defaults to
* the `SUBC_LAUNCH_NONCE` environment variable subc injects on spawn; pass
* explicitly to override. Omitted from the wire when empty (non-reserved modules).
*/
launchNonce?: string;
}
export interface ModuleHelloAckBody {
negotiated_ver: number;
subc_ops: string[];
subc_capabilities: string[];
/**
* The module's resolved storage descriptor, present when the daemon's central
* config configures managed storage. Carried opaquely (the wire crate has no
* storage dependency); a module using managed storage reads this and hands it to
* the storage library. Absent when no storage is configured.
*/
storage?: unknown;
}
export declare class SubcProviderError extends Error {
readonly code?: string | undefined;
constructor(message: string, code?: string | undefined);
}
export declare function managementSurfaceManifest(opts: ManagementSurfaceManifestOptions): ManifestInput;
export declare function jsonProviderHandler<Request = unknown, Response = unknown>(handler: (routeChannel: number, request: Request) => Promise<Response> | Response): ProviderHandler;
export declare class SubcProvider {
private sock;
private currentConn;
private readonly opts;
private readonly closed;
private resolveClosed;
private closeStarted;
private closedErr;
private readonly inflight;
private reconnecting;
private generation;
private connectionEpoch;
private stateQueue;
private drainingStateQueue;
private restoredDebounceToken;
/**
* The resolved storage descriptor the daemon delivered in HELLO_ACK, or
* `undefined` when no managed storage is configured. A module that persists
* hands this to the storage library.
*/
storage: unknown;
private constructor();
get conn(): ConnectionInfo;
currentEpoch(): number;
/** Read the connection file, authenticate as a client, register the manifest with HELLO, and serve frames. */
static connect(opts: SubcProviderConnectOptions): Promise<SubcProvider>;
close(): Promise<void>;
private static openConnection;
private readLoop;
private dispatch;
/** Abort every in-flight request on a route channel for the current socket generation. */
private abortChannel;
private abortGeneration;
private abortAllInflight;
private handleControlRequest;
private handleDataRequest;
private sendError;
private sendOn;
private handleUnexpectedDrop;
private scheduleReconnectAfterDrop;
private reconnectWithRetry;
private replaceConnection;
private scheduleRestored;
private cancelRestoredDebounce;
private enqueueConnectionState;
private drainConnectionStateQueue;
private failFatal;
private finishClosed;
}
//# sourceMappingURL=provider.d.ts.map
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAGA,OAAO,EAA6B,KAAK,YAAY,EAAE,KAAK,gBAAgB,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AACpH,OAAO,EAA2C,KAAK,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAyBpG,eAAO,MAAM,UAAU,KAAK,CAAC;AAE7B,MAAM,MAAM,SAAS,GAAG,aAAa,GAAG,UAAU,GAAG,WAAW,CAAC;AACjE,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,UAAU,GAAG,aAAa,CAAC;AAChE,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,gBAAgB,GAAG,oBAAoB,CAAC;AAC7E,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,SAAS,CAAC;AAClD,MAAM,MAAM,iBAAiB,GAAG,WAAW,GAAG,OAAO,GAAG,MAAM,CAAC;AAC/D,MAAM,M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sB;IAIvC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAsC;IAC/D,OAAO,CAAC,YAAY,CAA8B;IAClD,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,eAAe,CAAK;IAC5B,OAAO,CAAC,UAAU,CAAiC;IACnD,OAAO,CAAC,kBAAkB,CAAS;IACnC,OAAO,CAAC,qBAAqB,CAAK;IAElC;;;;OAIG;IACH,OAAO,EAAE,OAAO,CAAC;IAEjB,OAAO;IAcP,IAAI,IAAI,IAAI,cAAc,CAEzB;IAED,YAAY,IAAI,MAAM;IAItB,8GAA8G;WACjG,OAAO,CAAC,IAAI,EAAE,0BAA0B,GAAG,OAAO,CAAC,YAAY,CAAC;IAavE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;mBAiBP,cAAc;YAgBrB,QAAQ;YA6BR,QAAQ;IA8CtB,0FAA0F;IAC1F,OAAO,CAAC,YAAY;IAOpB,OAAO,CAAC,eAAe;IAOvB,OAAO,CAAC,gBAAgB;YAIV,oBAAoB;YAkCpB,iBAAiB;YAuDjB,SAAS;YAsBT,MAAM;IAKpB,OAAO,CAAC,oBAAoB;IAS5B,OAAO,CAAC,0BAA0B;YAYpB,kBAAkB;IAyBhC,OAAO,CAAC,iBAAiB;IAYzB,OAAO,CAAC,gBAAgB;IAuBxB,OAAO,CAAC,sBAAsB;IAI9B,OAAO,CAAC,sBAAsB;YAMhB,yBAAyB;IAyBvC,OAAO,CAAC,SAAS;IASjB,OAAO,CAAC,YAAY;CAGrB"}
import { Buffer } from "node:buffer";
import { AuthError, authenticateClient } from "./auth.js";
import { DEFAULT_RECONNECT_BACKOFF } from "./client.js";
import { ConnectionFileError, readConnectionFile } from "./connection-file.js";
import { buildFlags, buildFrame, buildFrameWithVersion, decodeHeader, encodeFrame, FrameType, HEADER_LEN, Priority, PROTOCOL_VERSION, } from "./envelope.js";
import { SocketClosedError, SocketTimeoutError, SocketWriteNotQueuedError, SocketWriteQueuedError, SubcSocket, } from "./socket.js";
const DEFAULT_HANDSHAKE_TIMEOUT_MS = 10_000;
const BODY_READ_TIMEOUT_MS = 30_000;
const WRITE_TIMEOUT_MS = 30_000;
const DEFAULT_RESTORED_DEBOUNCE_MS = 250;
export const HELLO_CORR = 1n;
export class SubcProviderError extends Error {
code;
constructor(message, code) {
super(message);
this.code = code;
}
}
export function managementSurfaceManifest(opts) {
const operations = opts.operations.map((operation) => typeof operation === "string"
? { name: operation, kind: "query" }
: { name: operation.name, kind: operation.kind });
return {
module_id: opts.moduleId,
module_version: opts.moduleVersion ?? "0.0.0",
protocol_ver: PROTOCOL_VERSION,
trust_tier: "first_party",
provides: [
{
role: "management_surface",
operations,
config_schema: { type: "object" },
observability: [],
identity_scope: [],
},
],
consumes: [],
scheduled_tasks: [],
bindings: {
storage: {
kind: "sqlite",
scope: "project",
owns_schema: false,
},
vault_grants: [],
identity: {
requires: [],
optional: [],
},
},
};
}
export function jsonProviderHandler(handler) {
return async (routeChannel, body) => {
const request = JSON.parse(Buffer.from(body).toString("utf8"));
const response = await handler(routeChannel, request);
return encodeJson(response);
};
}
export class SubcProvider {
sock;
currentConn;
opts;
closed;
resolveClosed = () => undefined;
closeStarted = false;
closedErr = null;
// In-flight data requests are keyed by generation, channel, and correlation id.
// A socket drop only makes the reply path stale; handlers may still finish their
// durable work, and their late sends are ignored by the generation guard.
inflight = new Map();
reconnecting = null;
generation = 1;
connectionEpoch = 1;
stateQueue = [];
drainingStateQueue = false;
restoredDebounceToken = 0;
/**
* The resolved storage descriptor the daemon delivered in HELLO_ACK, or
* `undefined` when no managed storage is configured. A module that persists
* hands this to the storage library.
*/
storage;
constructor(sock, currentConn, opts, storage) {
this.sock = sock;
this.currentConn = currentConn;
this.opts = opts;
this.storage = storage;
this.closed = new Promise((resolve) => {
this.resolveClosed = resolve;
});
void this.readLoop(sock, this.generation);
this.enqueueConnectionState({ state: "connected", epoch: this.connectionEpoch });
}
get conn() {
return this.currentConn;
}
currentEpoch() {
return this.connectionEpoch;
}
/** Read the connection file, authenticate as a client, register the manifest with HELLO, and serve frames. */
static async connect(opts) {
if (opts.manifest.protocol_ver !== PROTOCOL_VERSION) {
throw new SubcProviderError(`manifest protocol_ver ${opts.manifest.protocol_ver} does not match client protocol ${PROTOCOL_VERSION}`, "invalid_manifest");
}
const normalized = normalizeProviderConnectOptions(opts);
const opened = await SubcProvider.openConnection(normalized);
return new SubcProvider(opened.sock, opened.conn, normalized, opened.ack.storage);
}
async close() {
if (!this.closeStarted) {
this.closeStarted = true;
this.cancelRestoredDebounce();
const sock = this.sock;
try {
await sendFrame(sock, buildFrame(FrameType.Goodbye, controlFlags(), 0, 0n, new Uint8Array(0)));
}
catch {
// The daemon may already have closed the connection; close() remains best-effort.
}
finally {
sock.close();
this.finishClosed();
}
}
await this.closed;
}
static async openConnection(opts) {
const conn = await readConnectionFile(opts.connectionFile);
const deadline = Date.now() + (opts.handshakeTimeoutMs ?? DEFAULT_HANDSHAKE_TIMEOUT_MS);
const endpoint = conn.endpoints[0];
const sock = await SubcSocket.connect(endpoint.host, endpoint.port, deadline);
try {
await authenticateClient(sock, conn, deadline);
await sendFrame(sock, buildHelloFrame(opts));
const ack = await expectHelloAck(sock, deadline);
return { sock, conn, ack };
}
catch (err) {
sock.close();
throw err;
}
}
async readLoop(sock, generation) {
try {
for (;;) {
// Header read waits indefinitely — idle time between frames is normal.
const headerBytes = await sock.readExact(HEADER_LEN, Number.POSITIVE_INFINITY);
const header = decodeHeader(headerBytes);
const body = header.len === 0
? new Uint8Array(0)
: await sock.readExact(header.len, Date.now() + BODY_READ_TIMEOUT_MS);
const keepGoing = await this.dispatch({ header, body }, sock, generation);
if (!keepGoing) {
if (this.sock === sock && this.generation === generation)
this.closeStarted = true;
break;
}
}
}
catch (err) {
if (this.sock === sock && this.generation === generation && !this.closeStarted) {
this.handleUnexpectedDrop(sock, generation, err instanceof Error ? err : new SubcProviderError(String(err)));
return;
}
}
finally {
if (this.sock === sock && this.generation === generation) {
sock.close();
if (this.closeStarted)
this.finishClosed();
}
}
}
async dispatch(frame, sock, generation) {
switch (frame.header.ty) {
case FrameType.Ping:
if (frame.header.channel === 0) {
await this.sendOn(sock, generation, buildFrameWithVersion(frame.header.ver, FrameType.Pong, frame.header.flags, 0, frame.header.corr, new Uint8Array(0)));
}
return true;
case FrameType.Goodbye:
if (frame.header.channel === 0)
return false;
// The route is gone: abort in-flight requests on that route so streaming
// handlers unwind, then notify the provider owner.
this.abortChannel(generation, frame.header.channel);
await this.opts.onRouteGone?.(frame.header.channel);
return true;
case FrameType.Cancel:
// The consumer cancelled one request: abort the matching handler. Its
// streaming handler observes ctx.signal and ends with a StreamEnd terminal.
this.inflight.get(routeKey(generation, frame.header.channel, frame.header.corr))?.abort();
return true;
case FrameType.Request:
if (frame.header.channel === 0) {
await this.handleControlRequest(frame, sock, generation);
}
else {
void this.handleDataRequest(frame, sock, generation).catch((err) => {
if (!this.closeStarted && this.sock === sock && this.generation === generation) {
console.warn("SubcProvider handler failed after its request was dispatched", err);
}
});
}
return true;
default:
return true;
}
}
/** Abort every in-flight request on a route channel for the current socket generation. */
abortChannel(generation, channel) {
const prefix = `${generation}:${channel}:`;
for (const [key, controller] of this.inflight) {
if (key.startsWith(prefix))
controller.abort();
}
}
abortGeneration(generation) {
const prefix = `${generation}:`;
for (const [key, controller] of this.inflight) {
if (key.startsWith(prefix))
controller.abort();
}
}
abortAllInflight() {
for (const controller of this.inflight.values())
controller.abort();
}
async handleControlRequest(frame, sock, generation) {
const request = parseJson(frame.body);
if (request.op !== "route.bind") {
throw new SubcProviderError(`unsupported module control request ${request.op ?? "<missing op>"}`);
}
const bindRequest = {
route_channel: numberField(request.route_channel, "route_channel"),
target: request.target,
identity: request.identity,
principal: request.principal,
};
const decision = await this.opts.onBind?.(bindRequest);
const rejection = bindRejection(decision);
if (rejection) {
await this.sendError(frame, rejection.code, rejection.message, controlFlags(), sock, generation);
return;
}
await this.sendOn(sock, generation, buildFrameWithVersion(frame.header.ver, FrameType.Response, controlFlags(), 0, frame.header.corr, encodeJson({ op: "route.bind" })));
}
async handleDataRequest(frame, sock, generation) {
const { channel, corr, ver } = frame.header;
const key = routeKey(generation, channel, corr);
const controller = new AbortController();
this.inflight.set(key, controller);
const dataFlags = buildFlags(false, Priority.Interactive, false);
const ctx = {
signal: controller.signal,
currentEpoch: () => this.connectionEpoch,
emit: async (eventBody) => {
// Once aborted (cancel / route-gone / socket drop), drop further events silently.
if (controller.signal.aborted)
return;
await this.sendOn(sock, generation, buildFrameWithVersion(ver, FrameType.StreamData, dataFlags, channel, corr, eventBody));
},
};
try {
const body = await this.opts.handler(channel, frame.body, ctx);
if (body === undefined) {
// A streaming handler that ended: close the held-open request with a
// StreamEnd terminal (the consumer's subscription resolves).
await this.sendOn(sock, generation, buildFrameWithVersion(ver, FrameType.StreamEnd, dataFlags, channel, corr, new Uint8Array(0)));
}
else if (body instanceof Uint8Array) {
await this.sendOn(sock, generation, buildFrameWithVersion(ver, FrameType.Response, dataFlags, channel, corr, body));
}
else {
throw new SubcProviderError("provider handler must return a Uint8Array or void", "invalid_handler_response");
}
}
catch (err) {
await this.sendError(frame, err instanceof SubcProviderError && err.code ? err.code : "handler_error", err instanceof Error ? err.message : String(err), dataFlags, sock, generation);
}
finally {
if (this.inflight.get(key) === controller)
this.inflight.delete(key);
}
}
async sendError(frame, code, message, flags, sock, generation) {
await this.sendOn(sock, generation, buildFrameWithVersion(frame.header.ver, FrameType.Error, flags, frame.header.channel, frame.header.corr, encodeJson({ code, message })));
}
async sendOn(sock, generation, frame) {
if (this.sock !== sock || this.generation !== generation || this.closeStarted || this.closedErr)
return;
await sendFrame(sock, frame);
}
handleUnexpectedDrop(sock, generation, cause) {
this.cancelRestoredDebounce();
this.abortGeneration(generation);
this.generation += 1;
sock.close();
this.enqueueConnectionState({ state: "down", cause });
this.scheduleReconnectAfterDrop(cause);
}
scheduleReconnectAfterDrop(trigger) {
if (this.closeStarted || this.reconnecting)
return;
const promise = this.reconnectWithRetry(trigger)
.catch((err) => {
if (!this.closeStarted)
this.failFatal(err instanceof Error ? err : new SubcProviderError(String(err)));
})
.finally(() => {
if (this.reconnecting === promise)
this.reconnecting = null;
});
this.reconnecting = promise;
}
async reconnectWithRetry(_trigger) {
let attempt = 0;
let delay = this.opts.reconnectBackoff.baseMs;
for (;;) {
if (this.closeStarted)
throw new SubcProviderError("provider closed");
attempt += 1;
this.enqueueConnectionState({ state: "reconnecting", attempt });
try {
const opened = await SubcProvider.openConnection(this.opts);
if (this.closeStarted) {
opened.sock.close();
throw new SubcProviderError("provider closed");
}
this.replaceConnection(opened);
return;
}
catch (err) {
if (this.closeStarted)
throw err;
if (!isProviderReconnectTransient(err))
throw err;
await this.opts.sleep(delay);
delay = Math.min(delay * 2, this.opts.reconnectBackoff.capMs);
}
}
}
replaceConnection(opened) {
this.sock.close();
this.sock = opened.sock;
this.currentConn = opened.conn;
this.storage = opened.ack.storage;
this.closedErr = null;
this.connectionEpoch += 1;
const generation = this.generation;
void this.readLoop(opened.sock, generation);
this.scheduleRestored(generation, this.connectionEpoch);
}
scheduleRestored(generation, epoch) {
if (!this.opts.onConnectionState)
return;
const token = ++this.restoredDebounceToken;
void this.opts
.sleep(this.opts.restoredDebounceMs)
.then(() => {
if (token === this.restoredDebounceToken &&
!this.closeStarted &&
this.sock &&
this.generation === generation &&
this.connectionEpoch === epoch) {
this.enqueueConnectionState({ state: "restored", epoch });
}
})
.catch((err) => {
if (token === this.restoredDebounceToken && !this.closeStarted) {
console.warn("SubcProvider restored debounce timer failed", err);
}
});
}
cancelRestoredDebounce() {
this.restoredDebounceToken += 1;
}
enqueueConnectionState(event) {
if (!this.opts.onConnectionState)
return;
this.stateQueue.push(event);
if (!this.drainingStateQueue)
void this.drainConnectionStateQueue();
}
async drainConnectionStateQueue() {
if (this.drainingStateQueue)
return;
this.drainingStateQueue = true;
try {
while (this.stateQueue.length > 0) {
const event = this.stateQueue[0];
try {
await this.opts.onConnectionState?.(event);
this.stateQueue.shift();
}
catch (err) {
if (event.state === "restored") {
console.warn("SubcProvider restored callback failed; retrying delivery", err);
await pauseBeforeStateRetry();
continue;
}
console.warn("SubcProvider connection-state callback failed", err);
this.stateQueue.shift();
}
}
}
finally {
this.drainingStateQueue = false;
if (this.stateQueue.length > 0)
void this.drainConnectionStateQueue();
}
}
failFatal(err) {
if (!this.closedErr)
this.closedErr = err;
this.closeStarted = true;
this.cancelRestoredDebounce();
this.abortAllInflight();
this.sock.close();
this.finishClosed();
}
finishClosed() {
this.resolveClosed();
}
}
function routeKey(generation, channel, corr) {
return `${generation}:${channel}:${corr}`;
}
function launchNonce(opts) {
const nonce = opts.launchNonce ?? process.env[SUBC_LAUNCH_NONCE_ENV];
return nonce && nonce.length > 0 ? nonce : undefined;
}
const SUBC_LAUNCH_NONCE_ENV = "SUBC_LAUNCH_NONCE";
function normalizeProviderConnectOptions(opts) {
return {
connectionFile: opts.connectionFile,
manifest: opts.manifest,
handler: opts.handler,
handshakeTimeoutMs: opts.handshakeTimeoutMs,
controlOps: opts.controlOps,
onBind: opts.onBind,
onRouteGone: opts.onRouteGone,
reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
sleep: opts.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
restoredDebounceMs: opts.restoredDebounceMs ?? DEFAULT_RESTORED_DEBOUNCE_MS,
onConnectionState: opts.onConnectionState,
launchNonce: opts.launchNonce,
};
}
function buildHelloFrame(opts) {
const nonce = launchNonce(opts);
return buildFrame(FrameType.Hello, controlFlags(), 0, HELLO_CORR, encodeJson({
manifest: normalizeManifest(opts.manifest),
protocol_ver: PROTOCOL_VERSION,
control_ops: opts.controlOps === undefined ? null : opts.controlOps,
// Echo the one-time launch nonce subc injects for a reserved module
// (SUBC_LAUNCH_NONCE), so only the daemon-spawned process can register a
// reserved module_id. Omitted when unset (non-reserved / self-connecting).
...(nonce ? { launch_nonce: nonce } : {}),
}));
}
function isProviderReconnectTransient(err) {
if (err instanceof SubcProviderError)
return err.code === "duplicate_module_id";
if (err instanceof SocketClosedError || err instanceof SocketTimeoutError)
return true;
if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError)
return true;
if (err instanceof ConnectionFileError || err instanceof AuthError)
return false;
const code = errorCode(err);
return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EPIPE" || code === "ETIMEDOUT" || code === "ENOENT";
}
function errorCode(err) {
if (typeof err === "object" && err !== null && "code" in err) {
const code = err.code;
if (typeof code === "string")
return code;
}
return undefined;
}
async function pauseBeforeStateRetry() {
await new Promise((resolve) => setTimeout(resolve, 0));
}
function controlFlags() {
return buildFlags(false, Priority.Passive, false);
}
async function sendFrame(sock, frame) {
await sock.write(encodeFrame(frame), Date.now() + WRITE_TIMEOUT_MS);
}
async function expectHelloAck(sock, deadline) {
const header = decodeHeader(await sock.readExact(HEADER_LEN, deadline));
const body = header.len === 0 ? new Uint8Array(0) : await sock.readExact(header.len, deadline);
const frame = { header, body };
switch (header.ty) {
case FrameType.HelloAck:
return parseJson(body);
case FrameType.Error: {
const error = parseJson(body);
throw new SubcProviderError(`subc rejected HELLO: ${error.code ?? "unknown"} — ${error.message ?? "subc error"}`, error.code);
}
default:
throw new SubcProviderError(`unexpected frame ${FrameType[frame.header.ty]} awaiting HELLO_ACK`);
}
}
function encodeJson(value) {
return new Uint8Array(Buffer.from(JSON.stringify(value), "utf8"));
}
function parseJson(bytes) {
return JSON.parse(Buffer.from(bytes).toString("utf8"));
}
function numberField(value, field) {
if (typeof value !== "number" || !Number.isInteger(value)) {
throw new SubcProviderError(`route.bind ${field} must be an integer`);
}
return value;
}
function bindRejection(decision) {
if (decision === undefined || decision === true)
return null;
if (decision === false) {
return { code: "route_rejected", message: "route.bind rejected by provider" };
}
if (decision.accept)
return null;
return {
code: decision.code ?? "route_rejected",
message: decision.message ?? "route.bind rejected by provider",
};
}
function normalizeManifest(manifest) {
return {
module_id: manifest.module_id,
module_version: manifest.module_version,
protocol_ver: manifest.protocol_ver,
trust_tier: manifest.trust_tier,
provides: manifest.provides.map(normalizeProviderRole),
consumes: manifest.consumes.map(normalizeConsumerRole),
scheduled_tasks: manifest.scheduled_tasks.map(normalizeScheduledTask),
bindings: {
storage: {
kind: manifest.bindings.storage.kind,
scope: manifest.bindings.storage.scope,
owns_schema: manifest.bindings.storage.owns_schema,
},
vault_grants: manifest.bindings.vault_grants.map((grant) => ({
secret: grant.secret,
reason: grant.reason,
})),
identity: {
requires: [...manifest.bindings.identity.requires],
optional: [...manifest.bindings.identity.optional],
},
},
};
}
function normalizeProviderRole(role) {
switch (role.role) {
case "tool_provider":
return {
role: "tool_provider",
tools: role.tools.map((tool) => ({
name: tool.name,
execution_mode: tool.execution_mode,
schema: tool.schema,
})),
identity_scope: [...role.identity_scope],
concurrency: role.concurrency,
emits_push: role.emits_push,
sub_supervises: role.sub_supervises,
};
case "pipeline_stage":
return {
role: "pipeline_stage",
stage: role.stage,
applies_to: {
provider: role.applies_to.provider,
model: role.applies_to.model,
},
interface: role.interface,
declares_frozen_floor: role.declares_frozen_floor,
needs_signals: [...role.needs_signals],
conformance_class: role.conformance_class,
};
case "management_surface":
return {
role: "management_surface",
operations: role.operations.map((operation) => ({
name: operation.name,
kind: operation.kind,
})),
config_schema: role.config_schema,
observability: role.observability.map((surface) => ({
name: surface.name,
kind: surface.kind,
})),
identity_scope: [...role.identity_scope],
};
case "internal_service":
return {
role: "internal_service",
service_id: role.service_id,
transport: role.transport,
agent_facing: role.agent_facing,
operations: [...role.operations],
};
}
}
function normalizeConsumerRole(role) {
switch (role.role) {
case "tool_client":
return { role: "tool_client", of: [...role.of] };
case "llm_client":
return { role: "llm_client", via: role.via, auth: role.auth };
case "service_client":
return { role: "service_client", of: [...role.of] };
}
}
function normalizeScheduledTask(task) {
return {
task_id: task.task_id,
eligibility: {
cooldown: task.eligibility.cooldown,
window: task.eligibility.window,
},
lease_scope: task.lease_scope,
renews_during_calls: task.renews_during_calls,
toolset: [...task.toolset],
model_policy: {
tier: task.model_policy.tier,
fallback_chain: [...task.model_policy.fallback_chain],
},
step_cap: task.step_cap,
circuit_breaker: {
identical_failures: task.circuit_breaker.identical_failures,
},
};
}
//# sourceMappingURL=provider.js.map
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC1D,OAAO,EAAE,yBAAyB,EAA8D,MAAM,aAAa,CAAC;AACpH,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAuB,MAAM,sBAAsB,CAAC;AACpG,OAAO,EACL,UAAU,EACV,UAAU,EACV,qBAAqB,EACrB,YAAY,EACZ,WAAW,EACX,SAAS,EACT,UAAU,EACV,QAAQ,EACR,gBAAgB,GAEjB,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,iBAAiB,EACjB,kBAAkB,EAClB,yBAAyB,EACzB,sBAAsB,EACtB,UAAU,GACX,MAAM,aAAa,CAAC;AAErB,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAC5C,MAAM,oBAAoB,GAAG,MAAM,CAAC;AACpC,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,4BAA4B,GAAG,GAAG,CAAC;AACzC,MAAM,CAAC,MAAM,UAAU,GAAG,EAAE,CAAC;AAmQ7B,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAG/B;IAFX,YACE,OAAe,EACN,IAAa;QAEtB,KAAK,CAAC,OAAO,CAAC,CAAC;QAFN,SAAI,GAAJ,IAAI,CAAS;IAGxB,CAAC;CACF;AAED,MAAM,UAAU,yBAAyB,CAAC,IAAsC;IAC9E,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CACnD,OAAO,SAAS,KAAK,QAAQ;QAC3B,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,IAAI,EAAE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AAe,CAAC,kBAAkB;SAC5D;KACF,CAAC;AACJ,CAAC"}
export declare class SocketClosedError extends Error {
}
export declare class SocketTimeoutError extends Error {
}
export declare class SocketWriteNotQueuedError extends Error {
readonly cause?: Error | undefined;
constructor(message: string, cause?: Error | undefined);
}
export declare class SocketWriteQueuedError extends Error {
readonly cause?: Error | undefined;
constructor(message: string, cause?: Error | undefined);
}
export interface SocketWriteResult {
/** True once bytes were handed to Node's net.Socket.write. This is not a delivery guarantee. */
queued: boolean;
/** Resolves when Node reports the write complete; rejects with a classified write error. */
completed: Promise<void>;
}
export declare class SubcSocket {
private readonly sock;
private chunks;
private buffered;
private waiter;
private closedErr;
/** Bytes currently buffered but not yet consumed by a reader. A timeout
* arbitration uses this to tell "a reply already arrived, keep draining" from
* "nothing is here, settle the timeout". */
bufferedBytes(): number;
private constructor();
/**
* The OS-assigned local TCP port of this connection, or null if not yet
* connected/closed. Used to correlate a client-side timeout with a specific
* socket in a packet capture when diagnosing reply-delivery issues.
*/
localPort(): number | null;
static connect(host: string, port: number, deadlineMs: number): Promise<SubcSocket>;
/** Read exactly `n` bytes, rejecting if `deadlineMs` (epoch ms) passes first. */
readExact(n: number, deadlineMs: number): Promise<Uint8Array>;
write(bytes: Uint8Array, deadlineMs: number): Promise<void>;
writeTracked(bytes: Uint8Array, deadlineMs: number): SocketWriteResult;
close(): void;
private tryServe;
private take;
}
//# sourceMappingURL=socket.d.ts.map
{"version":3,"file":"socket.d.ts","sourceRoot":"","sources":["../src/socket.ts"],"names":[],"mappings":"AAQA,qBAAa,iBAAkB,SAAQ,KAAK;CAAG;AAC/C,qBAAa,kBAAmB,SAAQ,KAAK;CAAG;AAEhD,qBAAa,yBAA0B,SAAQ,KAAK;IAGhD,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK;gBADtB,OAAO,EAAE,MAAM,EACN,KAAK,CAAC,EAAE,KAAK,YAAA;CAIzB;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAG7C,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK;gBADtB,OAAO,EAAE,MAAM,EACN,KAAK,CAAC,EAAE,KAAK,YAAA;CAIzB;AAED,MAAM,WAAW,iBAAiB;IAChC,gGAAgG;IAChG,MAAM,EAAE,OAAO,CAAC;IAChB,4FAA4F;IAC5F,SAAS,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AASD,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAa;IAClC,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,SAAS,CAAsB;IAEvC;;gDAE4C;IAC5C,aAAa,IAAI,MAAM;IAIvB,OAAO;IAgBP;;;;OAIG;IACH,SAAS,IAAI,MAAM,GAAG,IAAI;IAI1B,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAmBnF,iFAAiF;IACjF,SAAS,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC;IAyBvD,KAAK,CAAC,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAWjE,YAAY,CAAC,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,GAAG,iBAAiB;IA4EtE,KAAK,IAAI,IAAI;IAIb,OAAO,CAAC,QAAQ;IAiBhB,OAAO,CAAC,IAAI;CAmBb"}
// A pull-based buffered wrapper over a node TCP socket. Node sockets are
// event-driven; the handshake and frame loop want "give me exactly N bytes, but
// don't exceed this absolute deadline". readExact provides that, draining an
// internal buffer and parking a single waiter until enough bytes arrive, the
// deadline passes, or the socket ends.
import net from "node:net";
export class SocketClosedError extends Error {
}
export class SocketTimeoutError extends Error {
}
export class SocketWriteNotQueuedError extends Error {
cause;
constructor(message, cause) {
super(message);
this.cause = cause;
}
}
export class SocketWriteQueuedError extends Error {
cause;
constructor(message, cause) {
super(message);
this.cause = cause;
}
}
export class SubcSocket {
sock;
chunks = [];
buffered = 0;
waiter = null;
closedErr = null;
/** Bytes currently buffered but not yet consumed by a reader. A timeout
* arbitration uses this to tell "a reply already arrived, keep draining" from
* "nothing is here, settle the timeout". */
bufferedBytes() {
return this.buffered;
}
constructor(sock) {
this.sock = sock;
sock.on("data", (chunk) => {
this.chunks.push(chunk);
this.buffered += chunk.length;
this.tryServe();
});
const fail = (err) => {
if (!this.closedErr)
this.closedErr = err;
this.tryServe();
};
sock.on("error", (err) => fail(err instanceof Error ? err : new Error(String(err))));
sock.on("end", () => fail(new SocketClosedError("subc closed the connection")));
sock.on("close", () => fail(new SocketClosedError("subc connection closed")));
}
/**
* The OS-assigned local TCP port of this connection, or null if not yet
* connected/closed. Used to correlate a client-side timeout with a specific
* socket in a packet capture when diagnosing reply-delivery issues.
*/
localPort() {
return this.sock.localPort ?? null;
}
static connect(host, port, deadlineMs) {
return new Promise((resolve, reject) => {
const sock = net.connect({ host, port });
sock.setNoDelay(true);
const timer = setTimeout(() => {
sock.destroy();
reject(new SocketTimeoutError(`timed out connecting to ${host}:${port}`));
}, Math.max(0, deadlineMs - Date.now()));
sock.once("connect", () => {
clearTimeout(timer);
resolve(new SubcSocket(sock));
});
sock.once("error", (err) => {
clearTimeout(timer);
reject(err);
});
});
}
/** Read exactly `n` bytes, rejecting if `deadlineMs` (epoch ms) passes first. */
readExact(n, deadlineMs) {
if (this.waiter) {
return Promise.reject(new Error("concurrent readExact is not supported"));
}
if (n === 0)
return Promise.resolve(new Uint8Array(0));
return new Promise((resolve, reject) => {
// A non-finite deadline means "wait indefinitely" (the background frame
// loop relies on this; per-request timeouts live on the request waiters).
let timer = null;
if (Number.isFinite(deadlineMs)) {
const remaining = deadlineMs - Date.now();
if (remaining <= 0) {
reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
return;
}
timer = setTimeout(() => {
this.waiter = null;
reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
}, remaining);
}
this.waiter = { need: n, resolve, reject, timer };
this.tryServe();
});
}
async write(bytes, deadlineMs) {
try {
await this.writeTracked(bytes, deadlineMs).completed;
}
catch (err) {
if (err instanceof SocketWriteNotQueuedError || err instanceof SocketWriteQueuedError) {
throw err.cause ?? err;
}
throw err;
}
}
writeTracked(bytes, deadlineMs) {
if (this.closedErr) {
return {
queued: false,
completed: Promise.reject(new SocketWriteNotQueuedError("subc socket was closed before bytes could be queued", this.closedErr)),
};
}
let queued = false;
let settled = false;
let timer = null;
const completed = new Promise((resolve, reject) => {
const settle = (run) => {
if (settled)
return;
settled = true;
if (timer)
clearTimeout(timer);
run();
};
const remaining = deadlineMs - Date.now();
if (remaining <= 0) {
settle(() => reject(new SocketWriteNotQueuedError("timed out before bytes could be queued to subc", new SocketTimeoutError("timed out writing to subc"))));
return;
}
timer = setTimeout(() => {
const timeout = new SocketTimeoutError("timed out writing to subc");
settle(() => reject(queued
? new SocketWriteQueuedError("timed out after bytes were handed to the subc socket", timeout)
: new SocketWriteNotQueuedError("timed out before bytes could be queued to subc", timeout)));
}, remaining);
try {
this.sock.write(Buffer.from(bytes), (err) => {
settle(() => {
if (err) {
reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
}
else {
resolve();
}
});
});
queued = true;
}
catch (err) {
settle(() => reject(new SocketWriteNotQueuedError("subc socket write threw before bytes could be queued", err instanceof Error ? err : new Error(String(err)))));
}
});
return { queued, completed };
}
close() {
this.sock.destroy();
}
tryServe() {
const w = this.waiter;
if (!w)
return;
if (this.buffered >= w.need) {
const out = this.take(w.need);
this.waiter = null;
if (w.timer)
clearTimeout(w.timer);
w.resolve(out);
return;
}
if (this.closedErr) {
this.waiter = null;
if (w.timer)
clearTimeout(w.timer);
w.reject(this.closedErr);
}
}
take(n) {
const out = Buffer.allocUnsafe(n);
let off = 0;
while (off < n) {
const head = this.chunks[0];
const want = n - off;
if (head.length <= want) {
head.copy(out, off);
off += head.length;
this.chunks.shift();
}
else {
head.copy(out, off, 0, want);
this.chunks[0] = head.subarray(want);
off += want;
}
}
this.buffered -= n;
return out;
}
}
//# sourceMappingURL=socket.js.map
{"version":3,"file":"socket.js","sourceRoot":"","sources":["../src/socket.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,gFAAgF;AAChF,6EAA6E;AAC7E,6EAA6E;AAC7E,uCAAuC;AAEvC,OAAO,GAAG,MAAM,UAAU,CAAC;AAE3B,MAAM,OAAO,iBAAkB,SAAQ,KAAK;CAAG;AAC/C,MAAM,OAAO,kBAAmB,SAAQ,KAAK;CAAG;AAEhD,MAAM,OAAO,yBAA0B,SAAQ,KAAK;IAGvC;IAFX,YACE,OAAe,EACN,KAAa;QAEtB,KAAK,CAAC,OAAO,CAAC,CAAC;QAFN,UAAK,GAAL,KAAK,CAAQ;IAGxB,CAAC;CACF;AAED,MAAM,OAAO,sBAAuB,SAAQ,KAAK;IAGpC;IAFX,YACE,OAAe,EACN,KAAa;QAEtB,KAAK,CAAC,OAAO,CAAC,CAAC;QAFN,UAAK,GAAL,KAAK,CAAQ;IAGxB,CAAC;CACF;AAgBD,MAAM,OAAO,UAAU;IACJ,IAAI,CAAa;IAC1B,MAAM,GAAa,EAAE,CAAC;IACtB,QAAQ,GAAG,CAAC,CAAC;IACb,MAAM,GAAkB,IAAI,CAAC;IAC7B,SAAS,GAAiB,IAAI,CAAC;IAEvC;;gDAE4C;IAC5C,aAAa;QACX,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,YAAoB,IAAgB;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAa,EAAE,EAAE;YAChC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACxB,IA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G,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;QAClC,IAAI,GAAG,GAAG,CAAC,CAAC;QACZ,OAAO,GAAG,GAAG,CAAC,EAAE,CAAC;YACf,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAE,CAAC;YAC7B,MAAM,IAAI,GAAG,CAAC,GAAG,GAAG,CAAC;YACrB,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,EAAE,CAAC;gBACxB,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;gBACpB,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC;gBACnB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YACtB,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;gBAC7B,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;gBACrC,GAAG,IAAI,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,IAAI,CAAC,QAAQ,IAAI,CAAC,CAAC;QACnB,OAAO,GAAG,CAAC;IACb,CAAC;CACF"}
+6
-3
{
"name": "@cortexkit/subc-client",
"version": "0.3.0",
"version": "0.3.1",
"description": "TypeScript client for the subc daemon. Wire-compatible (byte-for-byte) with the Rust subc-transport handshake and subc-protocol envelope.",

@@ -8,7 +8,8 @@ "type": "module",

".": {
"types": "./src/index.ts",
"import": "./src/index.ts"
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"files": [
"dist",
"src",

@@ -18,2 +19,4 @@ "README.md"

"scripts": {
"build": "rm -rf dist && tsc -p tsconfig.build.json",
"prepublishOnly": "npm run build",
"test": "bun test",

@@ -20,0 +23,0 @@ "typecheck": "tsc --noEmit && tsc -p tsconfig.test.json --noEmit"