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