source dump of claude code
at main 443 lines 13 kB view raw
1/** 2 * Main entrypoint for Claude Code Agent SDK types. 3 * 4 * This file re-exports the public SDK API from: 5 * - sdk/coreTypes.ts - Common serializable types (messages, configs) 6 * - sdk/runtimeTypes.ts - Non-serializable types (callbacks, interfaces) 7 * 8 * SDK builders who need control protocol types should import from 9 * sdk/controlTypes.ts directly. 10 */ 11 12import type { 13 CallToolResult, 14 ToolAnnotations, 15} from '@modelcontextprotocol/sdk/types.js' 16 17// Control protocol types for SDK builders (bridge subpath consumers) 18/** @alpha */ 19export type { 20 SDKControlRequest, 21 SDKControlResponse, 22} from './sdk/controlTypes.js' 23// Re-export core types (common serializable types) 24export * from './sdk/coreTypes.js' 25// Re-export runtime types (callbacks, interfaces with methods) 26export * from './sdk/runtimeTypes.js' 27 28// Re-export settings types (generated from settings JSON schema) 29export type { Settings } from './sdk/settingsTypes.generated.js' 30// Re-export tool types (all marked @internal until SDK API stabilizes) 31export * from './sdk/toolTypes.js' 32 33// ============================================================================ 34// Functions 35// ============================================================================ 36 37import type { 38 SDKMessage, 39 SDKResultMessage, 40 SDKSessionInfo, 41 SDKUserMessage, 42} from './sdk/coreTypes.js' 43// Import types needed for function signatures 44import type { 45 AnyZodRawShape, 46 ForkSessionOptions, 47 ForkSessionResult, 48 GetSessionInfoOptions, 49 GetSessionMessagesOptions, 50 InferShape, 51 InternalOptions, 52 InternalQuery, 53 ListSessionsOptions, 54 McpSdkServerConfigWithInstance, 55 Options, 56 Query, 57 SDKSession, 58 SDKSessionOptions, 59 SdkMcpToolDefinition, 60 SessionMessage, 61 SessionMutationOptions, 62} from './sdk/runtimeTypes.js' 63 64export type { 65 ListSessionsOptions, 66 GetSessionInfoOptions, 67 SessionMutationOptions, 68 ForkSessionOptions, 69 ForkSessionResult, 70 SDKSessionInfo, 71} 72 73export function tool<Schema extends AnyZodRawShape>( 74 _name: string, 75 _description: string, 76 _inputSchema: Schema, 77 _handler: ( 78 args: InferShape<Schema>, 79 extra: unknown, 80 ) => Promise<CallToolResult>, 81 _extras?: { 82 annotations?: ToolAnnotations 83 searchHint?: string 84 alwaysLoad?: boolean 85 }, 86): SdkMcpToolDefinition<Schema> { 87 throw new Error('not implemented') 88} 89 90type CreateSdkMcpServerOptions = { 91 name: string 92 version?: string 93 // eslint-disable-next-line @typescript-eslint/no-explicit-any 94 tools?: Array<SdkMcpToolDefinition<any>> 95} 96 97/** 98 * Creates an MCP server instance that can be used with the SDK transport. 99 * This allows SDK users to define custom tools that run in the same process. 100 * 101 * If your SDK MCP calls will run longer than 60s, override CLAUDE_CODE_STREAM_CLOSE_TIMEOUT 102 */ 103export function createSdkMcpServer( 104 _options: CreateSdkMcpServerOptions, 105): McpSdkServerConfigWithInstance { 106 throw new Error('not implemented') 107} 108 109export class AbortError extends Error {} 110 111/** @internal */ 112export function query(_params: { 113 prompt: string | AsyncIterable<SDKUserMessage> 114 options?: InternalOptions 115}): InternalQuery 116export function query(_params: { 117 prompt: string | AsyncIterable<SDKUserMessage> 118 options?: Options 119}): Query 120export function query(): Query { 121 throw new Error('query is not implemented in the SDK') 122} 123 124/** 125 * V2 API - UNSTABLE 126 * Create a persistent session for multi-turn conversations. 127 * @alpha 128 */ 129export function unstable_v2_createSession( 130 _options: SDKSessionOptions, 131): SDKSession { 132 throw new Error('unstable_v2_createSession is not implemented in the SDK') 133} 134 135/** 136 * V2 API - UNSTABLE 137 * Resume an existing session by ID. 138 * @alpha 139 */ 140export function unstable_v2_resumeSession( 141 _sessionId: string, 142 _options: SDKSessionOptions, 143): SDKSession { 144 throw new Error('unstable_v2_resumeSession is not implemented in the SDK') 145} 146 147// @[MODEL LAUNCH]: Update the example model ID in this docstring. 148/** 149 * V2 API - UNSTABLE 150 * One-shot convenience function for single prompts. 151 * @alpha 152 * 153 * @example 154 * ```typescript 155 * const result = await unstable_v2_prompt("What files are here?", { 156 * model: 'claude-sonnet-4-6' 157 * }) 158 * ``` 159 */ 160export async function unstable_v2_prompt( 161 _message: string, 162 _options: SDKSessionOptions, 163): Promise<SDKResultMessage> { 164 throw new Error('unstable_v2_prompt is not implemented in the SDK') 165} 166 167/** 168 * Reads a session's conversation messages from its JSONL transcript file. 169 * 170 * Parses the transcript, builds the conversation chain via parentUuid links, 171 * and returns user/assistant messages in chronological order. Set 172 * `includeSystemMessages: true` in options to also include system messages. 173 * 174 * @param sessionId - UUID of the session to read 175 * @param options - Optional dir, limit, offset, and includeSystemMessages 176 * @returns Array of messages, or empty array if session not found 177 */ 178export async function getSessionMessages( 179 _sessionId: string, 180 _options?: GetSessionMessagesOptions, 181): Promise<SessionMessage[]> { 182 throw new Error('getSessionMessages is not implemented in the SDK') 183} 184 185/** 186 * List sessions with metadata. 187 * 188 * When `dir` is provided, returns sessions for that project directory 189 * and its git worktrees. When omitted, returns sessions across all 190 * projects. 191 * 192 * Use `limit` and `offset` for pagination. 193 * 194 * @example 195 * ```typescript 196 * // List sessions for a specific project 197 * const sessions = await listSessions({ dir: '/path/to/project' }) 198 * 199 * // Paginate 200 * const page1 = await listSessions({ limit: 50 }) 201 * const page2 = await listSessions({ limit: 50, offset: 50 }) 202 * ``` 203 */ 204export async function listSessions( 205 _options?: ListSessionsOptions, 206): Promise<SDKSessionInfo[]> { 207 throw new Error('listSessions is not implemented in the SDK') 208} 209 210/** 211 * Reads metadata for a single session by ID. Unlike `listSessions`, this only 212 * reads the single session file rather than every session in the project. 213 * Returns undefined if the session file is not found, is a sidechain session, 214 * or has no extractable summary. 215 * 216 * @param sessionId - UUID of the session 217 * @param options - `{ dir?: string }` project path; omit to search all project directories 218 */ 219export async function getSessionInfo( 220 _sessionId: string, 221 _options?: GetSessionInfoOptions, 222): Promise<SDKSessionInfo | undefined> { 223 throw new Error('getSessionInfo is not implemented in the SDK') 224} 225 226/** 227 * Rename a session. Appends a custom-title entry to the session's JSONL file. 228 * @param sessionId - UUID of the session 229 * @param title - New title 230 * @param options - `{ dir?: string }` project path; omit to search all projects 231 */ 232export async function renameSession( 233 _sessionId: string, 234 _title: string, 235 _options?: SessionMutationOptions, 236): Promise<void> { 237 throw new Error('renameSession is not implemented in the SDK') 238} 239 240/** 241 * Tag a session. Pass null to clear the tag. 242 * @param sessionId - UUID of the session 243 * @param tag - Tag string, or null to clear 244 * @param options - `{ dir?: string }` project path; omit to search all projects 245 */ 246export async function tagSession( 247 _sessionId: string, 248 _tag: string | null, 249 _options?: SessionMutationOptions, 250): Promise<void> { 251 throw new Error('tagSession is not implemented in the SDK') 252} 253 254/** 255 * Fork a session into a new branch with fresh UUIDs. 256 * 257 * Copies transcript messages from the source session into a new session file, 258 * remapping every message UUID and preserving the parentUuid chain. Supports 259 * `upToMessageId` for branching from a specific point in the conversation. 260 * 261 * Forked sessions start without undo history (file-history snapshots are not 262 * copied). 263 * 264 * @param sessionId - UUID of the source session 265 * @param options - `{ dir?, upToMessageId?, title? }` 266 * @returns `{ sessionId }` — UUID of the new forked session 267 */ 268export async function forkSession( 269 _sessionId: string, 270 _options?: ForkSessionOptions, 271): Promise<ForkSessionResult> { 272 throw new Error('forkSession is not implemented in the SDK') 273} 274 275// ============================================================================ 276// Assistant daemon primitives (internal) 277// ============================================================================ 278 279/** 280 * A scheduled task from `<dir>/.claude/scheduled_tasks.json`. 281 * @internal 282 */ 283export type CronTask = { 284 id: string 285 cron: string 286 prompt: string 287 createdAt: number 288 recurring?: boolean 289} 290 291/** 292 * Cron scheduler tuning knobs (jitter + expiry). Sourced at runtime from the 293 * `tengu_kairos_cron_config` GrowthBook config in CLI sessions; daemon hosts 294 * pass this through `watchScheduledTasks({ getJitterConfig })` to get the 295 * same tuning. 296 * @internal 297 */ 298export type CronJitterConfig = { 299 recurringFrac: number 300 recurringCapMs: number 301 oneShotMaxMs: number 302 oneShotFloorMs: number 303 oneShotMinuteMod: number 304 recurringMaxAgeMs: number 305} 306 307/** 308 * Event yielded by `watchScheduledTasks()`. 309 * @internal 310 */ 311export type ScheduledTaskEvent = 312 | { type: 'fire'; task: CronTask } 313 | { type: 'missed'; tasks: CronTask[] } 314 315/** 316 * Handle returned by `watchScheduledTasks()`. 317 * @internal 318 */ 319export type ScheduledTasksHandle = { 320 /** Async stream of fire/missed events. Drain with `for await`. */ 321 events(): AsyncGenerator<ScheduledTaskEvent> 322 /** 323 * Epoch ms of the soonest scheduled fire across all loaded tasks, or null 324 * if nothing is scheduled. Useful for deciding whether to tear down an 325 * idle agent subprocess or keep it warm for an imminent fire. 326 */ 327 getNextFireTime(): number | null 328} 329 330/** 331 * Watch `<dir>/.claude/scheduled_tasks.json` and yield events as tasks fire. 332 * 333 * Acquires the per-directory scheduler lock (PID-based liveness) so a REPL 334 * session in the same dir won't double-fire. Releases the lock and closes 335 * the file watcher when the signal aborts. 336 * 337 * - `fire` — a task whose cron schedule was met. One-shot tasks are already 338 * deleted from the file when this yields; recurring tasks are rescheduled 339 * (or deleted if aged out). 340 * - `missed` — one-shot tasks whose window passed while the daemon was down. 341 * Yielded once on initial load; a background delete removes them from the 342 * file shortly after. 343 * 344 * Intended for daemon architectures that own the scheduler externally and 345 * spawn the agent via `query()`; the agent subprocess (`-p` mode) does not 346 * run its own scheduler. 347 * 348 * @internal 349 */ 350export function watchScheduledTasks(_opts: { 351 dir: string 352 signal: AbortSignal 353 getJitterConfig?: () => CronJitterConfig 354}): ScheduledTasksHandle { 355 throw new Error('not implemented') 356} 357 358/** 359 * Format missed one-shot tasks into a prompt that asks the model to confirm 360 * with the user (via AskUserQuestion) before executing. 361 * @internal 362 */ 363export function buildMissedTaskNotification(_missed: CronTask[]): string { 364 throw new Error('not implemented') 365} 366 367/** 368 * A user message typed on claude.ai, extracted from the bridge WS. 369 * @internal 370 */ 371export type InboundPrompt = { 372 content: string | unknown[] 373 uuid?: string 374} 375 376/** 377 * Options for connectRemoteControl. 378 * @internal 379 */ 380export type ConnectRemoteControlOptions = { 381 dir: string 382 name?: string 383 workerType?: string 384 branch?: string 385 gitRepoUrl?: string | null 386 getAccessToken: () => string | undefined 387 baseUrl: string 388 orgUUID: string 389 model: string 390} 391 392/** 393 * Handle returned by connectRemoteControl. Write query() yields in, 394 * read inbound prompts out. See src/assistant/daemonBridge.ts for full 395 * field documentation. 396 * @internal 397 */ 398export type RemoteControlHandle = { 399 sessionUrl: string 400 environmentId: string 401 bridgeSessionId: string 402 write(msg: SDKMessage): void 403 sendResult(): void 404 sendControlRequest(req: unknown): void 405 sendControlResponse(res: unknown): void 406 sendControlCancelRequest(requestId: string): void 407 inboundPrompts(): AsyncGenerator<InboundPrompt> 408 controlRequests(): AsyncGenerator<unknown> 409 permissionResponses(): AsyncGenerator<unknown> 410 onStateChange( 411 cb: ( 412 state: 'ready' | 'connected' | 'reconnecting' | 'failed', 413 detail?: string, 414 ) => void, 415 ): void 416 teardown(): Promise<void> 417} 418 419/** 420 * Hold a claude.ai remote-control bridge connection from a daemon process. 421 * 422 * The daemon owns the WebSocket in the PARENT process — if the agent 423 * subprocess (spawned via `query()`) crashes, the daemon respawns it while 424 * claude.ai keeps the same session. Contrast with `query.enableRemoteControl` 425 * which puts the WS in the CHILD process (dies with the agent). 426 * 427 * Pipe `query()` yields through `write()` + `sendResult()`. Read 428 * `inboundPrompts()` (user typed on claude.ai) into `query()`'s input 429 * stream. Handle `controlRequests()` locally (interrupt → abort, set_model 430 * → reconfigure). 431 * 432 * Skips the `tengu_ccr_bridge` gate and policy-limits check — @internal 433 * caller is pre-entitled. OAuth is still required (env var or keychain). 434 * 435 * Returns null on no-OAuth or registration failure. 436 * 437 * @internal 438 */ 439export async function connectRemoteControl( 440 _opts: ConnectRemoteControlOptions, 441): Promise<RemoteControlHandle | null> { 442 throw new Error('not implemented') 443}