agents
Version:
A home for your AI agents
251 lines (249 loc) • 8.34 kB
TypeScript
import {
Y as MCPServersState,
_ as AgentToolRunState,
g as AgentToolRunPart
} from "./agent-tool-types-BC-WFlsz.js";
import { ClientParameters } from "./serializable.js";
import {
AgentConnectionError,
AgentPromiseReturnType,
AgentStub,
CallOptions,
OptionalAgentMethods,
RequiredAgentMethods,
StreamOptions,
UntypedAgentStub,
createStubProxy
} from "./client.js";
import { PartySocket } from "partysocket";
import { usePartySocket } from "partysocket/react";
//#region src/react.d.ts
type QueryObject = Record<string, string | null>;
type TerminalReconnectOptions = {
shouldReconnectOnClose?: (event: CloseEvent) => boolean;
};
interface CacheEntry {
promise: Promise<QueryObject>;
expiresAt: number;
}
declare function createCacheKey(
agentNamespace: string,
name: string | undefined,
subChainOrDeps:
| ReadonlyArray<{
agent: string;
name: string;
}>
| unknown[],
deps?: unknown[]
): string;
declare function getCacheEntry(key: string): CacheEntry | undefined;
declare function setCacheEntry(
key: string,
promise: Promise<QueryObject>,
cacheTtl: number
): CacheEntry;
declare function deleteCacheEntry(key: string): void;
declare const _testUtils: {
queryCache: Map<string, CacheEntry>;
setCacheEntry: typeof setCacheEntry;
getCacheEntry: typeof getCacheEntry;
deleteCacheEntry: typeof deleteCacheEntry;
clearCache: () => void;
createStubProxy: typeof createStubProxy;
createCacheKey: typeof createCacheKey;
};
/**
* Options for the useAgent hook
* @template State Type of the Agent's state
*/
type UseAgentOptions<State = unknown> = Omit<
Parameters<typeof usePartySocket>[0],
"party" | "room" | "query"
> &
TerminalReconnectOptions & {
/** Name of the agent to connect to (ignored if basePath is set) */ agent: string /** Name of the specific Agent instance (ignored if basePath is set) */;
name?: string;
/**
* Full URL path - bypasses agent/name URL construction.
* When set, the client connects to this path directly.
* Server must handle routing manually (e.g., with getAgentByName + fetch).
* @example
* // Client connects to /user, server routes based on session
* useAgent({ agent: "UserAgent", basePath: "user" })
*/
basePath?: string /** Query parameters - can be static object or async function */;
query?:
| QueryObject
| (() => Promise<QueryObject>) /** Dependencies for async query caching */;
queryDeps?: unknown[] /** Cache TTL in milliseconds for auth tokens/time-sensitive data */;
cacheTtl?: number /** Called when the Agent's state is updated */;
onStateUpdate?: (
state: State,
source: "server" | "client"
) => void /** Called when a state update fails (e.g., connection is readonly) */;
onStateUpdateError?: (
error: string
) => void /** Called when MCP server state is updated */;
onMcpUpdate?: (mcpServers: MCPServersState) => void;
/**
* Called when the server sends the agent's identity on connect.
* Useful when using basePath, as the actual instance name is determined server-side.
* @param name The actual agent instance name
* @param agent The agent class name (kebab-case)
*/
onIdentity?: (name: string, agent: string) => void;
/**
* Called when identity changes on reconnect (different instance than before).
* If not provided and identity changes, a warning will be logged.
* @param oldName Previous instance name
* @param newName New instance name
* @param oldAgent Previous agent class name
* @param newAgent New agent class name
*/
onIdentityChange?: (
oldName: string,
newName: string,
oldAgent: string,
newAgent: string
) => void;
/**
* Additional path to append to the URL.
* Works with both standard routing and basePath.
* @example
* // With basePath: /user/settings
* { basePath: "user", path: "settings" }
* // Standard: /agents/my-agent/room/settings
* { agent: "MyAgent", name: "room", path: "settings" }
*/
path?: string;
/**
* Connect to a sub-agent (facet) via its parent. Flat array,
* root-first. Each step addresses one parent↔child hop.
*
* The hook's returned `.agent` / `.name` report the **leaf**
* identity (the deepest entry in `sub`), so downstream hooks
* like `useAgentChat` see the child they actually talk to.
* `.path` exposes the full chain for observability, deep links,
* and reconnect keying.
*
* @example
* ```ts
* // Two-level nesting: Inbox (Alice) → Chat (abc)
* useAgent({
* agent: "inbox", name: userId,
* sub: [{ agent: "chat", name: chatId }]
* });
*
* // Three-level: tenant → inbox → chat
* useAgent({
* agent: "tenant", name: tenantId,
* sub: [
* { agent: "inbox", name: userId },
* { agent: "chat", name: chatId }
* ]
* });
* ```
*
* @experimental The API surface may change before stabilizing.
*/
sub?: ReadonlyArray<{
agent: string;
name: string;
}>;
/**
* Default timeout (in milliseconds) applied to non-streaming `call()`s
* that don't pass an explicit `timeout`. Acts as a backstop so calls
* whose response is lost (e.g. the connection is replaced mid-flight)
* reject instead of hanging forever.
*
* Defaults to 30 000 ms. Set to `0` to disable the default timeout.
* Streaming calls never get a default timeout (long-lived streams are
* legitimate); pass an explicit `timeout` to bound them.
*/
defaultCallTimeout?: number /** Called when the connection closes with a terminal code and will not reconnect. */;
onConnectionError?: (error: AgentConnectionError) => void;
};
type OptionalArgsAgentMethodCall<AgentT> = <
K extends keyof OptionalAgentMethods<AgentT>
>(
method: K,
args?: ClientParameters<OptionalAgentMethods<AgentT>[K]>,
options?: CallOptions | StreamOptions
) => AgentPromiseReturnType<AgentT, K>;
type RequiredArgsAgentMethodCall<AgentT> = <
K extends keyof RequiredAgentMethods<AgentT>
>(
method: K,
args: ClientParameters<RequiredAgentMethods<AgentT>[K]>,
options?: CallOptions | StreamOptions
) => AgentPromiseReturnType<AgentT, K>;
type AgentMethodCall<AgentT> = OptionalArgsAgentMethodCall<AgentT> &
RequiredArgsAgentMethodCall<AgentT>;
type UntypedAgentMethodCall = <T = unknown>(
method: string,
args?: unknown[],
options?: CallOptions | StreamOptions
) => Promise<T>;
/**
* React hook for connecting to an Agent
*/
declare function useAgent<State = unknown>(
options: UseAgentOptions<State>
): Omit<PartySocket, "path"> & {
agent: string;
name: string /** Full root-first address chain, including leaf. Single entry when `sub` isn't set. */;
path: ReadonlyArray<{
agent: string;
name: string;
}>;
identified: boolean;
ready: Promise<void>;
state: State | undefined;
connectionError: AgentConnectionError | null;
setState: (state: State) => void;
call: UntypedAgentMethodCall;
stub: UntypedAgentStub;
getHttpUrl: () => string;
};
declare function useAgent<
AgentT extends {
get state(): State;
},
State
>(
options: UseAgentOptions<State>
): Omit<PartySocket, "path"> & {
agent: string;
name: string;
path: ReadonlyArray<{
agent: string;
name: string;
}>;
identified: boolean;
ready: Promise<void>;
state: State | undefined;
connectionError: AgentConnectionError | null;
setState: (state: State) => void;
call: AgentMethodCall<AgentT>;
stub: AgentStub<AgentT>;
getHttpUrl: () => string;
};
type AgentToolEventAgent = Pick<
PartySocket,
"addEventListener" | "removeEventListener"
>;
declare function useAgentToolEvents<
Part extends AgentToolRunPart = AgentToolRunPart
>(options: {
agent: AgentToolEventAgent;
}): {
runsById: Record<string, AgentToolRunState<Part>>;
runsByToolCallId: Record<string, AgentToolRunState<Part>[]>;
unboundRuns: AgentToolRunState<Part>[];
getRunsForToolCall(toolCallId: string): AgentToolRunState<Part>[];
resetLocalState(): void;
};
//#endregion
export { UseAgentOptions, _testUtils, useAgent, useAgentToolEvents };
//# sourceMappingURL=react.d.ts.map