@a3s-lab/code 3.0.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -1,1473 +1,13 @@
1
- /* tslint:disable */
2
- /* eslint-disable */
3
-
4
- /* auto-generated by NAPI-RS */
5
-
6
- /** AHP event type. */
7
- export interface AhpEventType {
8
- /** Event type string: "handshake", "pre_action", "post_action", "pre_prompt", "post_response", "session_start", "session_end", "error", "query", "heartbeat", "idle" */
9
- eventType: string
10
- }
11
- /** A factual memory item. */
12
- export interface AhpFact {
13
- content: string
14
- source: string
15
- confidence: number
16
- }
17
- /** Memory state summary. */
18
- export interface AhpMemorySummary {
19
- memoryType: string
20
- totalItems: number
21
- recentTopics: Array<string>
22
- }
23
- /** Session statistics. */
24
- export interface AhpSessionStats {
25
- totalActions: number
26
- totalTokens: number
27
- durationMs: number
28
- errorCount: number
29
- }
30
- /** Decision from harness for idle events. */
31
- export interface AhpIdleDecision {
32
- /** Decision string: "allow" or "defer" */
33
- decision: string
34
- /** Reason if deferred */
35
- reason?: string
36
- }
37
- /** Context passed with AHP events. */
38
- export interface AhpEventContext {
39
- recentFacts?: Array<AhpFact>
40
- memorySummary?: AhpMemorySummary
41
- sessionStats?: AhpSessionStats
42
- currentTask?: string
43
- capabilities?: Record<string, string>
44
- }
45
- export interface AgentResult {
46
- text: string
47
- toolCallsCount: number
48
- promptTokens: number
49
- completionTokens: number
50
- totalTokens: number
51
- verificationStatus: string
52
- pendingVerificationCount: number
53
- failedVerificationCount: number
54
- verificationReportCount: number
55
- verificationSummaryJson: string
56
- verificationSummaryText: string
57
- }
58
- export declare function formatVerificationSummary(summary: any): string
59
- export interface AgentEvent {
60
- type: string
61
- text?: string
62
- toolName?: string
63
- toolId?: string
64
- toolOutput?: string
65
- exitCode?: number
66
- turn?: number
67
- prompt?: string
68
- error?: string
69
- totalTokens?: number
70
- verificationSummaryJson?: string
71
- verificationSummaryText?: string
72
- /** Extra data for events that don't map to standard fields (JSON-encoded) */
73
- data?: string
74
- /**
75
- * Structured discriminant for tool failures on `tool_end` events
76
- * (JSON-encoded with a `type` field on the top level, e.g.
77
- * `{"type":"version_conflict","path":"doc.md","expected":"etag-1","actual":"etag-2"}`).
78
- * Undefined on success or untyped failure. Streaming consumers parse
79
- * this to branch on the failure kind without scanning `toolOutput`.
80
- */
81
- errorKindJson?: string
82
- }
83
- export interface VerificationCommand {
84
- id: string
85
- kind: string
86
- description: string
87
- command: string
88
- required?: boolean
89
- timeoutMs?: number
90
- }
91
- export interface ToolResult {
92
- name: string
93
- output: string
94
- exitCode: number
95
- /** Raw JSON-encoded tool metadata returned by the Rust core API. */
96
- metadataJson?: string
97
- /** Convenience JSON view of `metadata.document_runtime` when present. */
98
- documentRuntimeJson?: string
99
- /**
100
- * Structured discriminant for tool failures, JSON-encoded with a
101
- * `type` field on the top level — e.g.
102
- * `{"type":"version_conflict","path":"doc.md","expected":"etag-1","actual":"etag-2"}`.
103
- * Undefined on success or untyped failure. SDK callers parse it to
104
- * branch on the failure kind without scanning the `output` string.
105
- */
106
- errorKindJson?: string
107
- }
108
-
109
1
  /**
110
- * Parsed shape of `ToolResult.errorKindJson` / `AgentEvent.errorKindJson`.
2
+ * Entry point for `@a3s-lab/code` type declarations.
111
3
  *
112
- * Use a discriminated union on the `type` field; new variants may be
113
- * added in future minor releases callers should match exhaustively on
114
- * the kinds they care about and fall through to a default branch for
115
- * unknown ones.
116
- */
117
- export type ToolErrorKind =
118
- | { type: 'version_conflict'; path: string; expected: string; actual: string | null }
119
- | { type: 'remote_git_conflict'; code: string; message: string }
120
- | { type: 'not_found'; path: string }
121
- | { type: 'invalid_argument'; message: string }
122
- | { type: 'unsupported'; message: string }
123
- | { type: 'timeout'; op: string; duration_ms: number }
124
-
125
- /** Execution limits for `Session.program`. */
126
- export interface ProgramScriptLimits {
127
- timeoutMs?: number
128
- maxToolCalls?: number
129
- maxOutputBytes?: number
130
- }
131
- /** Options for `Session.program`. */
132
- export interface ProgramScriptOptions {
133
- source?: string
134
- path?: string
135
- inputs?: any
136
- allowedTools?: Array<string>
137
- limits?: ProgramScriptLimits
138
- }
139
- /** Options for `Session.delegateTask`. */
140
- export interface DelegateTaskOptions {
141
- agent: string
142
- description: string
143
- prompt: string
144
- background?: boolean
145
- maxSteps?: number
146
- }
147
- /** Object-shaped request for `Session.sendRequest` and `Session.streamRequest`. */
148
- export interface SessionRequestOptions {
149
- prompt: string
150
- history?: Array<MessageObject>
151
- attachments?: Array<AttachmentObject>
152
- }
153
- export interface GitCommandOptions {
154
- command: string
155
- subcommand?: string
156
- name?: string
157
- path?: string
158
- newBranch?: boolean
159
- base?: string
160
- force?: boolean
161
- maxCount?: number
162
- message?: string
163
- includeUntracked?: boolean
164
- target?: string
165
- ref?: string
166
- reference?: string
167
- }
168
- /** Parameters for the web_search tool. */
169
- export interface JsWebSearchParams {
170
- /** The search query. */
171
- query: string
172
- /** List of search engines to use. */
173
- engines?: Array<string>
174
- /** Maximum number of results to return (default: 10, max: 50). */
175
- limit?: number
176
- /** Search timeout in seconds (default: 10, max: 60). */
177
- timeout?: number
178
- /** Proxy URL (e.g., http://127.0.0.1:8080 or socks5://127.0.0.1:1080). */
179
- proxy?: string
180
- /** Output format: "text" or "json". */
181
- format?: string
182
- }
183
- /** Result of a single `EventStream.next()` call. */
184
- export interface NextResult {
185
- value?: AgentEvent
186
- done: boolean
187
- }
188
- /**
189
- * An inline skill registered programmatically (no file required).
190
- *
191
- * Use `kind: "instruction"` for prompt injections or `kind: "persona"` to
192
- * replace the default role section of the system prompt.
193
- */
194
- export interface InlineSkill {
195
- /** Unique skill name (kebab-case recommended, e.g. "type-hints"). */
196
- name: string
197
- /** Skill kind: `"instruction"` or `"persona"`. */
198
- kind: string
199
- /** Markdown content for the skill. */
200
- content: string
201
- }
202
- export interface JsMemoryStore {
203
- backend: string
204
- dir?: string
205
- }
206
- export interface JsSessionStore {
207
- backend: string
208
- dir?: string
209
- }
210
- export interface JsSecurityProvider {
211
- kind: string
212
- }
213
- export interface JsWorkspaceBackend {
214
- kind: string
215
- root?: string
216
- s3?: JsS3BackendConfig
217
- }
218
- /**
219
- * Configuration for an S3-compatible workspace backend.
220
- *
221
- * Use this with [`S3WorkspaceBackend`] to point a session's built-in file
222
- * tools at any S3-compatible endpoint (AWS S3, MinIO, RustFS, R2, etc.).
223
- * `endpoint` is optional — omit it to use the AWS default. `prefix` is
224
- * the logical workspace root inside the bucket; every workspace path
225
- * becomes `<prefix>/<path>` when sent to S3.
226
- */
227
- export interface JsS3BackendConfig {
228
- /**
229
- * Optional S3 endpoint URL. Omit for AWS S3 (the SDK will compute it
230
- * from `region`). Set to `https://...` for MinIO / RustFS / R2 / etc.
231
- */
232
- endpoint?: string
233
- /** AWS region. Defaults to `us-east-1` when omitted. */
234
- region?: string
235
- /** Static access key. Use `sessionToken` together when STS-issued. */
236
- accessKeyId: string
237
- secretAccessKey: string
238
- sessionToken?: string
239
- /** Bucket name. */
240
- bucket: string
241
- /**
242
- * Logical workspace prefix inside the bucket (without leading/trailing
243
- * slashes). Use `""` to make the bucket root the workspace.
244
- */
245
- prefix: string
246
- /** `true` for MinIO / RustFS / most non-AWS endpoints; `false` for AWS S3. */
247
- forcePathStyle?: boolean
248
- /**
249
- * Maximum bytes a single `read` may return. The backend rejects any
250
- * response with `Content-Length` greater than this without buffering
251
- * the body. Defaults to 10 MiB on the Rust side when omitted.
252
- */
253
- maxReadBytes?: number
254
- /**
255
- * Enable degraded `grep` / `glob` against this S3 backend. Off by
256
- * default — object storage has no native search, so the only viable
257
- * strategy is `LIST` + `GET` + regex, which can be slow and expensive.
258
- */
259
- searchEnabled?: boolean
260
- /**
261
- * Upper bound on objects considered per `grep` / `glob` call. Defaults
262
- * to 500 on the Rust side. Ignored when `searchEnabled` is `false`.
263
- */
264
- maxObjectsScanned?: number
265
- /**
266
- * Per-object body-size ceiling for `grep` downloads. Larger objects are
267
- * skipped (debug-traced). Defaults to 1 MiB on the Rust side. Ignored
268
- * when `searchEnabled` is `false`.
269
- */
270
- maxGrepBytesPerObject?: number
271
- /**
272
- * Concurrent object downloads during `grep`. Defaults to 8 on the Rust
273
- * side. Set lower when the gitserver / S3 endpoint rate-limits
274
- * aggressively; set higher when latency dominates. Ignored when
275
- * `searchEnabled` is `false`.
276
- */
277
- searchConcurrency?: number
278
- }
279
- /**
280
- * Configuration for a `RemoteGitBackend` — an HTTP/JSON client that
281
- * brings the `git` tool to non-local workspaces (S3, future container /
282
- * DFS).
283
- *
284
- * Pass alongside `workspaceBackend` on a session to attach remote git
285
- * on top of any filesystem backend.
286
- */
287
- export interface JsRemoteGitBackendConfig {
288
- /**
289
- * Base URL of the gitserver, no trailing slash. The client builds
290
- * `{baseUrl}/v1/repos/{repoId}/git/{op}` per the RFC.
291
- */
292
- baseUrl: string
293
- /**
294
- * Opaque repository identifier, URL-safe. Negotiated out of band
295
- * with the gitserver operator.
296
- */
297
- repoId: string
298
- /**
299
- * Bearer token sent as `Authorization: Bearer <token>`. Required in
300
- * production; omitting it emits a server-side warning and is only safe
301
- * on a trusted localhost gitserver.
302
- */
303
- bearerToken?: string
304
- /**
305
- * mTLS client certificate path (PEM). When set together with `clientKeyPem`,
306
- * the backend reads both files at construction and configures mTLS on the
307
- * HTTP client. Setting only one of the pair errors at construction.
308
- */
309
- clientCertPem?: string
310
- /**
311
- * mTLS client private key path (PEM). PKCS#8 format expected for the
312
- * `rustls-tls` backend. See `clientCertPem`.
313
- */
314
- clientKeyPem?: string
315
- /** Per-call HTTP timeout in milliseconds. Defaults to 30 000. */
316
- requestTimeoutMs?: number
317
- /** Client-side cap on `diff` response bytes. Defaults to 1 MiB. */
318
- maxDiffBytes?: number
319
- /** Client-side cap on `log` `max_count`. Defaults to 200. */
320
- maxLogEntries?: number
321
- }
322
- /**
323
- * Union type for AHP transport configuration.
324
- * Accepts any of: StdioTransport, HttpTransport, WebSocketTransport, UnixSocketTransport.
325
- */
326
- export interface JsAhpTransport {
327
- kind: string
328
- program?: string
329
- args?: Array<string>
330
- url?: string
331
- authToken?: string
332
- path?: string
333
- }
334
- export interface PermissionPolicy {
335
- /** Tool invocation patterns that are always denied first. */
336
- deny?: Array<string>
337
- /** Tool invocation patterns that are auto-approved. */
338
- allow?: Array<string>
339
- /** Tool invocation patterns that always require confirmation. */
340
- ask?: Array<string>
341
- /** Default decision when no rule matches: "allow", "deny", or "ask". */
342
- defaultDecision?: string
343
- /** Whether this policy is enabled. Defaults to true. */
344
- enabled?: boolean
345
- }
346
- /**
347
- * Reproducible recipe for a disposable worker/subagent.
348
- *
349
- * This is the Node.js cattle-mode interface: define workers in data, pass them
350
- * to SessionOptions.workerAgents, Agent.sessionForWorker(), or
351
- * Session.registerWorkerAgent(). The Rust core compiles each spec into the
352
- * normal delegated-agent runtime definition.
353
- */
354
- export interface WorkerAgentSpec {
355
- /** Stable worker name used by task delegation. */
356
- name: string
357
- /** Human-readable worker purpose. */
358
- description: string
359
- /** Preset role: "read_only", "planner", "implementer", "verifier", "reviewer", or "custom". */
360
- kind?: string
361
- /** Hide from UI lists while allowing explicit delegation. */
362
- hidden?: boolean
363
- /** Optional permission policy override. */
364
- permissions?: PermissionPolicy
365
- /** Optional model override in "provider/model" format. */
366
- model?: string
367
- /** Optional worker-specific prompt. */
368
- prompt?: string
369
- /** Maximum execution steps/tool rounds. */
370
- maxSteps?: number
371
- /** How child runs resolve Ask decisions: "auto_approve" (default), "deny_on_ask", or "inherit_parent". */
372
- confirmationInheritance?: string
373
- }
374
- export interface AgentDefinition {
375
- name: string
376
- description: string
377
- native: boolean
378
- hidden: boolean
379
- model?: string
380
- prompt?: string
381
- maxSteps?: number
382
- /** How child runs resolve Ask decisions: "auto_approve", "deny_on_ask", or "inherit_parent". */
383
- confirmationInheritance?: string
384
- }
385
- /**
386
- * HITL confirmation policy configuration.
387
- *
388
- * Controls the runtime behavior of Human-in-the-Loop confirmation flow.
389
- */
390
- export interface ConfirmationPolicy {
391
- /** Whether HITL is enabled (default: false, all tools auto-approved). */
392
- enabled?: boolean
393
- /** Default timeout in milliseconds (default: 30000 = 30s). */
394
- defaultTimeoutMs?: number
395
- /** Action to take on timeout: "reject" or "auto_approve" (default: "reject"). */
396
- timeoutAction?: string
397
- /** Lanes that should auto-approve without confirmation: "control", "query", "execute", or "generate". */
398
- yoloLanes?: Array<string>
399
- }
400
- /** Snapshot of a pending HITL tool confirmation. */
401
- export interface PendingConfirmation {
402
- /** Tool call ID to pass to `confirmToolUse`. */
403
- toolId: string
404
- /** Tool name awaiting confirmation. */
405
- toolName: string
406
- /** Tool arguments for display in a confirmation UI. */
407
- args: any
408
- /** Milliseconds remaining before the confirmation times out. */
409
- remainingMs: number
410
- }
411
- export interface SessionOptions {
412
- /** Override the default model. Format: "provider/model" (e.g., "openai/gpt-4o"). */
413
- model?: string
414
- /** Enable built-in skills (4 skills: code-search, code-review, explain-code, find-bugs). */
415
- builtinSkills?: boolean
416
- /** Extra directories to scan for skill files (.md with YAML frontmatter). */
417
- skillDirs?: Array<string>
418
- /** Extra directories to scan for agent files. */
419
- agentDirs?: Array<string>
420
- /** Reproducible disposable workers to register for task delegation. */
421
- workerAgents?: Array<WorkerAgentSpec>
422
- /**
423
- * Optional advanced queue configuration for explicit external/hybrid lane dispatch.
424
- *
425
- * Ordinary sessions are queue-free unless this is provided.
426
- */
427
- queueConfig?: SessionQueueConfig
428
- /** Explicit permission policy for tool execution. */
429
- permissionPolicy?: PermissionPolicy
430
- /**
431
- * Explicit planning mode: "auto", "enabled", or "disabled".
432
- *
433
- * Prefer this over `planning` when the caller needs an unambiguous SDK contract.
434
- * If both are set, `planningMode` wins.
435
- */
436
- planningMode?: string
437
- /** Legacy planning shortcut. Omit for auto planning, true to force planning, false to disable. */
438
- planning?: boolean
439
- /** Enable goal tracking (default: false). */
440
- goalTracking?: boolean
441
- /** Max consecutive parse errors before abort. */
442
- maxParseRetries?: number
443
- /** Per-tool execution timeout in milliseconds. */
444
- toolTimeoutMs?: number
445
- /** Max LLM API failures before abort. */
446
- circuitBreakerThreshold?: number
447
- /** Enable auto-compaction when context window fills up (default: false). */
448
- autoCompact?: boolean
449
- /** Context usage threshold (0.0–1.0) to trigger auto-compaction (default: 0.8). */
450
- autoCompactThreshold?: number
451
- /**
452
- * Long-term memory store backend.
453
- *
454
- * Pass `new FileMemoryStore("./memory")` for file-based persistence.
455
- * ```js
456
- * agent.session('.', { memoryStore: new FileMemoryStore('./memory') });
457
- * ```
458
- */
459
- memoryStore?: JsMemoryStore
460
- /**
461
- * Session persistence store backend.
462
- *
463
- * Pass `new FileSessionStore("./sessions")` to persist sessions to disk,
464
- * or `new MemorySessionStore()` for an ephemeral in-process store.
465
- * ```js
466
- * agent.session('.', {
467
- * sessionStore: new FileSessionStore('./sessions'),
468
- * sessionId: 'my-session',
469
- * autoSave: true,
470
- * });
471
- * ```
472
- */
473
- sessionStore?: JsSessionStore
474
- /**
475
- * Security provider.
476
- *
477
- * Pass `new DefaultSecurityProvider()` to enable input taint tracking and
478
- * output sanitisation. Omit to disable security (default: no security).
479
- * ```js
480
- * agent.session('.', { securityProvider: new DefaultSecurityProvider() });
481
- * ```
482
- */
483
- securityProvider?: JsSecurityProvider
484
- /**
485
- * Workspace backend used by built-in tools.
486
- *
487
- * Pass `new LocalWorkspaceBackend("/repo")` to explicitly use the local
488
- * filesystem backend. This option is the SDK surface for future remote,
489
- * browser, DFS, and container-backed workspace implementations.
490
- * ```js
491
- * agent.session('/repo', { workspaceBackend: new LocalWorkspaceBackend('/repo') });
492
- * ```
493
- */
494
- workspaceBackend?: JsWorkspaceBackend
495
- /**
496
- * Optional remote git provider. When set, the resulting session attaches
497
- * a `RemoteGitBackend` on top of `workspaceBackend` so the built-in
498
- * `git` tool is available even on object-storage workspaces.
499
- *
500
- * ```js
501
- * agent.session('s3://workspace/u1/s1', {
502
- * workspaceBackend: new S3WorkspaceBackend({ ... }),
503
- * remoteGit: {
504
- * baseUrl: 'https://gitserver.internal',
505
- * repoId: 'u1/s1',
506
- * bearerToken: token,
507
- * },
508
- * });
509
- * ```
510
- */
511
- remoteGit?: JsRemoteGitBackendConfig
512
- /**
513
- * Custom role/identity prepended before the core agentic prompt.
514
- * Example: "You are a senior Python developer specializing in FastAPI."
515
- */
516
- role?: string
517
- /**
518
- * Custom coding guidelines appended after the core prompt.
519
- * Example: "Always use type hints. Follow PEP 8."
520
- */
521
- guidelines?: string
522
- /** Custom response style (replaces default Response Format section). */
523
- responseStyle?: string
524
- /** Freeform extra instructions appended at the end. */
525
- extra?: string
526
- /**
527
- * Inline skills registered programmatically without needing skill files on disk.
528
- * Each entry defines an instruction or persona skill injected into the system prompt.
529
- */
530
- inlineSkills?: Array<InlineSkill>
531
- /** Override maximum number of tool-call rounds for this session. */
532
- maxToolRounds?: number
533
- /**
534
- * Sampling temperature (0.0–1.0). Overrides the provider default.
535
- * Only applied when `model` is also set.
536
- */
537
- temperature?: number
538
- /**
539
- * Extended thinking token budget (e.g. 10_000). Enables chain-of-thought reasoning.
540
- * Only applied when `model` is also set. Provider must support extended thinking.
541
- */
542
- thinkingBudget?: number
543
- /**
544
- * Enable continuation injection (default: true).
545
- * When enabled, the loop injects a follow-up prompt when the LLM stops without completing.
546
- */
547
- continuationEnabled?: boolean
548
- /** Maximum continuation injections per execution (default: 3). */
549
- maxContinuationTurns?: number
550
- /**
551
- * Session ID (auto-generated if not set).
552
- *
553
- * Set a stable ID so the session can be saved and resumed later:
554
- * ```js
555
- * agent.session('.', { sessionId: 'my-session', sessionStore: new FileSessionStore('./sessions'), autoSave: true });
556
- * // Later:
557
- * agent.resumeSession('my-session', { sessionStore: new FileSessionStore('./sessions') });
558
- * ```
559
- */
560
- sessionId?: string
561
- /** Automatically save the session to the configured store after each turn (default: false). */
562
- autoSave?: boolean
563
- /**
564
- * AHP transport configuration for external agent supervision.
565
- *
566
- * Pass an AHP transport instance to enable Agent Harness Protocol supervision.
567
- * All agent lifecycle events will be forwarded to the harness server.
568
- *
569
- * ```js
570
- * // Stdio transport (local child process)
571
- * agent.session('.', { ahpTransport: new StdioTransport('python', ['ahp_server.py']) });
572
- *
573
- * // HTTP transport (remote server)
574
- * agent.session('.', { ahpTransport: new HttpTransport('http://localhost:8080/ahp') });
575
- *
576
- * // WebSocket transport (bidirectional streaming)
577
- * agent.session('.', { ahpTransport: new WebSocketTransport('ws://localhost:8080/ahp') });
578
- *
579
- * // Unix socket transport (local IPC)
580
- * agent.session('.', { ahpTransport: new UnixSocketTransport('/tmp/ahp.sock') });
581
- * ```
582
- */
583
- ahpTransport?: JsAhpTransport
584
- /**
585
- * HITL confirmation policy configuration.
586
- *
587
- * Pass a confirmation policy to enable Human-in-the-Loop confirmation for tool execution.
588
- * When enabled, tools that require confirmation will emit ConfirmationRequired events
589
- * and wait for user approval before executing.
590
- *
591
- * ```js
592
- * agent.session('.', {
593
- * confirmationPolicy: {
594
- * enabled: true,
595
- * defaultTimeoutMs: 30000,
596
- * timeoutAction: 'reject'
597
- * }
598
- * });
599
- * ```
600
- */
601
- confirmationPolicy?: ConfirmationPolicy
602
- /**
603
- * Maximum execution time in milliseconds.
604
- *
605
- * When set, the execution loop will abort if it exceeds this duration.
606
- * This prevents runaway executions and excessive API costs.
607
- *
608
- * ```js
609
- * agent.session('.', {
610
- * maxExecutionTimeMs: 300000 // 5 minutes
611
- * });
612
- * ```
613
- */
614
- maxExecutionTimeMs?: number
615
- }
616
- /** A single message in conversation history. */
617
- export interface MessageObject {
618
- role: string
619
- content: Array<ContentBlockObject>
620
- }
621
- /** A content block within a message. */
622
- export interface ContentBlockObject {
623
- type: string
624
- /** Text content (for "text" blocks). */
625
- text?: string
626
- /** Tool use ID (for "tool_use" blocks). */
627
- id?: string
628
- /** Tool name (for "tool_use" blocks). */
629
- name?: string
630
- /** Tool input (for "tool_use" blocks). */
631
- input?: any
632
- /** Tool use ID reference (for "tool_result" blocks). */
633
- toolUseId?: string
634
- /** Tool result content (for "tool_result" blocks). */
635
- resultContent?: string
636
- /** Whether this is an error result (for "tool_result" blocks). */
637
- isError?: boolean
638
- }
639
- /** An image attachment for multi-modal prompts. */
640
- export interface AttachmentObject {
641
- /** Raw image bytes. */
642
- data: Buffer
643
- /** MIME type (e.g., "image/jpeg", "image/png"). */
644
- mediaType: string
645
- }
646
- /**
647
- * Configuration for the optional advanced session lane queue.
648
- *
649
- * Ordinary sessions do not initialize queue infrastructure. Use this only for
650
- * explicit external/hybrid dispatch, priority experiments, or operational integrations.
651
- */
652
- export interface SessionQueueConfig {
653
- /** Max concurrency for Query lane (default: 4). */
654
- queryConcurrency?: number
655
- /** Max concurrency for Execute lane (default: 2). */
656
- executeConcurrency?: number
657
- /** Max concurrency for Generate lane (default: 1). */
658
- generateConcurrency?: number
659
- /** Enable dead letter queue. */
660
- enableDlq?: boolean
661
- /** Max DLQ size (default: 1000). */
662
- dlqMaxSize?: number
663
- /** Enable metrics collection. */
664
- enableMetrics?: boolean
665
- /** Enable queue alerts. */
666
- enableAlerts?: boolean
667
- /** Default command timeout (ms). */
668
- timeoutMs?: number
669
- /** Enable all features with sensible defaults. */
670
- enableAllFeatures?: boolean
671
- /**
672
- * Per-lane handler config. Keys: "control", "query", "execute", "generate".
673
- * Values: LaneHandlerConfig with mode ("internal"/"external"/"hybrid") and timeoutMs.
674
- */
675
- laneHandlers?: Record<string, LaneHandlerConfig>
676
- }
677
- /** Result of an external task completion. */
678
- export interface ExternalTaskResult {
679
- success: boolean
680
- result?: any
681
- error?: string
682
- }
683
- /** Lane handler configuration. */
684
- export interface LaneHandlerConfig {
685
- /** "internal", "external", or "hybrid" */
686
- mode: string
687
- /** Timeout for external processing (ms). */
688
- timeoutMs?: number
689
- }
690
- /** Queue statistics. */
691
- export interface QueueStats {
692
- totalPending: number
693
- totalActive: number
694
- externalPending: number
695
- }
696
- export interface McpServerStatusEntry {
697
- name: string
698
- connected: boolean
699
- toolCount: number
700
- error?: string
701
- }
702
- /** MCP server metadata exposed to slash command handlers. */
703
- export interface CommandMcpServerInfo {
704
- /** MCP server name. */
705
- name: string
706
- /** Number of tools currently exposed by the server. */
707
- toolCount: number
708
- }
709
- /** Context passed to custom slash command handlers. */
710
- export interface CommandContext {
711
- /** Current session ID. */
712
- sessionId: string
713
- /** Current workspace path. */
714
- workspace: string
715
- /** Current active model identifier. */
716
- model: string
717
- /** Number of messages in session history. */
718
- historyLen: number
719
- /** Total tokens used in this session so far. */
720
- totalTokens: number
721
- /** Estimated session cost in USD. */
722
- totalCost: number
723
- /** Registered tool names (builtin + MCP). */
724
- toolNames: Array<string>
725
- /** Connected MCP servers and their tool counts. */
726
- mcpServers: Array<CommandMcpServerInfo>
727
- }
728
- /** Metadata about a registered slash command. */
729
- export interface CommandInfo {
730
- /** Command name without the leading `/` (e.g., `"help"`, `"model"`) */
731
- name: string
732
- /** Short description shown in `/help` */
733
- description: string
734
- /** Optional usage hint (e.g., `"/model <provider/model>"`) */
735
- usage?: string
736
- }
737
- /** Matcher for filtering which events trigger a hook. */
738
- export interface HookMatcherObject {
739
- /** Match specific tool name (exact match) */
740
- tool?: string
741
- /** Match file path pattern (glob) */
742
- pathPattern?: string
743
- /** Match command pattern (regex for Bash commands) */
744
- commandPattern?: string
745
- /** Match session ID (exact match) */
746
- sessionId?: string
747
- /** Match skill name (supports glob patterns) */
748
- skill?: string
749
- }
750
- /** Configuration for a hook. */
751
- export interface HookConfigObject {
752
- /** Priority (lower values = higher priority, default: 100) */
753
- priority?: number
754
- /** Timeout in milliseconds (default: 30000) */
755
- timeoutMs?: number
756
- /** Whether to execute asynchronously (fire-and-forget) */
757
- asyncExecution?: boolean
758
- /** Maximum retry attempts */
759
- maxRetries?: number
760
- }
761
- /** Metadata about a built-in skill. */
762
- export interface SkillInfo {
763
- name: string
764
- description: string
765
- /** Skill kind: "instruction", "tool", or "agent". */
766
- kind: string
767
- }
768
- /**
769
- * Return a list of built-in skills compiled into the library.
770
- *
771
- * Each entry has `name`, `description`, and `kind` (instruction, tool, or agent).
772
- */
773
- export declare function builtinSkills(): Array<SkillInfo>
774
- /** Configuration for a search engine. */
775
- export interface SearchEngineConfig {
776
- enabled: boolean
777
- weight: number
778
- timeout?: number
779
- }
780
- /** Browser backend for headless search. */
781
- export const enum BrowserBackend {
782
- /** Chrome/Chromium headless. */
783
- Chrome = 0,
784
- /** Lightpanda headless browser (Linux/macOS only). */
785
- Lightpanda = 1
786
- }
787
- /** Headless browser configuration. */
788
- export interface HeadlessConfig {
789
- backend: BrowserBackend
790
- browserPath?: string
791
- maxTabs?: number
792
- launchArgs?: Array<string>
793
- proxyUrl?: string
794
- }
795
- /** Health monitor configuration for search engines. */
796
- export interface SearchHealthConfig {
797
- maxFailures: number
798
- suspendSeconds: number
799
- }
800
- /** Search engine configuration (a3s-search integration). */
801
- export interface SearchConfig {
802
- timeout: number
803
- health?: SearchHealthConfig
804
- engines: Record<string, SearchEngineConfig>
805
- headless?: HeadlessConfig
806
- }
807
- /** Streaming event iterator. Use `for await (const event of stream)` or call `.next()` manually. */
808
- export declare class EventStream {
809
- /**
810
- * Get the next event from the stream.
811
- *
812
- * Returns `{ value: AgentEvent | null, done: boolean }`.
813
- * When `done` is true, the stream is exhausted.
814
- */
815
- next(): Promise<NextResult>
816
- }
817
- /**
818
- * File-backed long-term memory store.
819
- *
820
- * ```js
821
- * agent.session('.', { memoryStore: new FileMemoryStore('./memory') });
822
- * ```
823
- */
824
- export declare class FileMemoryStore {
825
- backend: string
826
- dir: string
827
- /** Create a file-backed memory store at `dir`. */
828
- constructor(dir: string)
829
- }
830
- /**
831
- * File-backed session store (persists sessions to disk for later resumption).
832
- *
833
- * ```js
834
- * agent.session('.', {
835
- * sessionStore: new FileSessionStore('./sessions'),
836
- * sessionId: 'my-session',
837
- * autoSave: true,
838
- * });
839
- * ```
840
- */
841
- export declare class FileSessionStore {
842
- backend: string
843
- dir: string
844
- /** Create a file-backed session store at `dir`. */
845
- constructor(dir: string)
846
- }
847
- /**
848
- * In-memory (non-persistent) session store.
849
- *
850
- * Useful for testing, ephemeral runs, and CI pipelines where no disk state is needed.
851
- *
852
- * ```js
853
- * agent.session('.', { sessionStore: new MemorySessionStore() });
854
- * ```
855
- */
856
- export declare class MemorySessionStore {
857
- backend: string
858
- constructor()
859
- }
860
- /**
861
- * Default security provider: input taint tracking + output sanitisation.
862
- *
863
- * ```js
864
- * agent.session('.', { securityProvider: new DefaultSecurityProvider() });
865
- * ```
866
- */
867
- export declare class DefaultSecurityProvider {
868
- kind: string
869
- constructor()
870
- }
871
- /**
872
- * Local filesystem workspace backend.
873
- *
874
- * This is the explicit typed form of the default local workspace behavior.
875
- * It is useful when callers want to pass workspace backends through the same
876
- * option surface that remote/browser backends will use.
877
- *
878
- * ```js
879
- * agent.session('/repo', { workspaceBackend: new LocalWorkspaceBackend('/repo') });
880
- * ```
881
- */
882
- export declare class LocalWorkspaceBackend {
883
- kind: string
884
- root: string
885
- /** Create a local filesystem workspace backend rooted at `root`. */
886
- constructor(root: string)
887
- }
888
- /**
889
- * S3-compatible object-storage workspace backend.
890
- *
891
- * Points built-in file tools (`read`, `write`, `edit`, `patch`, `ls`) at an
892
- * S3-compatible bucket. Works with AWS S3, MinIO, RustFS, Cloudflare R2,
893
- * Backblaze B2, and other S3-API-compatible services.
894
- *
895
- * `bash`, `git`, `grep`, and `glob` are intentionally **not** registered
896
- * when this backend is in use — object storage cannot service them.
897
- *
898
- * ```js
899
- * const backend = new S3WorkspaceBackend({
900
- * endpoint: 'https://minio.local:9000',
901
- * region: 'us-east-1',
902
- * accessKeyId: 'AKIA...',
903
- * secretAccessKey: '...',
904
- * bucket: 'workspace',
905
- * prefix: 'users/u1/sessions/s1',
906
- * forcePathStyle: true,
907
- * });
908
- * agent.session('s3://workspace/users/u1/sessions/s1', { workspaceBackend: backend });
909
- * ```
910
- */
911
- export declare class S3WorkspaceBackend {
912
- kind: string
913
- s3: JsS3BackendConfig
914
- /** Create an S3-compatible workspace backend. */
915
- constructor(config: JsS3BackendConfig)
916
- }
917
- /**
918
- * Stdio transport for AHP (Agent Harness Protocol).
919
- *
920
- * Launches a child process and communicates via stdin/stdout using JSON-RPC 2.0.
921
- *
922
- * ```js
923
- * agent.session('.', {
924
- * ahpTransport: new StdioTransport('python', ['ahp_server.py'])
925
- * });
926
- * ```
927
- */
928
- export declare class StdioTransport {
929
- kind: string
930
- program?: string
931
- args?: Array<string>
932
- url?: string
933
- authToken?: string
934
- path?: string
935
- constructor(program: string, args: Array<string>)
936
- }
937
- /**
938
- * HTTP transport for AHP (Agent Harness Protocol).
939
- *
940
- * Connects to a remote AHP harness server via HTTP.
941
- *
942
- * ```js
943
- * agent.session('.', {
944
- * ahpTransport: new HttpTransport('http://localhost:8080/ahp')
945
- * });
946
- * ```
947
- */
948
- export declare class HttpTransport {
949
- kind: string
950
- program?: string
951
- args?: Array<string>
952
- url?: string
953
- authToken?: string
954
- path?: string
955
- constructor(url: string, authToken?: string | undefined | null)
956
- }
957
- /**
958
- * WebSocket transport for AHP (Agent Harness Protocol).
959
- *
960
- * Connects to a remote AHP harness server via WebSocket for bidirectional streaming.
961
- *
962
- * ```js
963
- * agent.session('.', {
964
- * ahpTransport: new WebSocketTransport('ws://localhost:8080/ahp')
965
- * });
966
- * ```
967
- */
968
- export declare class WebSocketTransport {
969
- kind: string
970
- program?: string
971
- args?: Array<string>
972
- url?: string
973
- authToken?: string
974
- path?: string
975
- constructor(url: string, authToken?: string | undefined | null)
976
- }
977
- /**
978
- * Unix socket transport for AHP (Agent Harness Protocol).
979
- *
980
- * Connects to a local AHP harness server via Unix domain socket.
4
+ * This file is hand-authored. The napi-rs build writes to `generated.d.ts`,
5
+ * which this aggregator re-exports. Cross-boundary types that aren't
6
+ * generated from Rust (because napi-derive would camelCase fields that
7
+ * need to mirror the wire JSON, or because they describe discriminated
8
+ * unions napi can't express) live in `extra-types.d.ts`.
981
9
  *
982
- * ```js
983
- * agent.session('.', {
984
- * ahpTransport: new UnixSocketTransport('/tmp/ahp.sock')
985
- * });
986
- * ```
10
+ * Edit those two files, not this one.
987
11
  */
988
- export declare class UnixSocketTransport {
989
- kind: string
990
- program?: string
991
- args?: Array<string>
992
- url?: string
993
- authToken?: string
994
- path?: string
995
- constructor(path: string)
996
- }
997
- /** AI coding agent. Create with `Agent.create()`, then call `agent.session()`. */
998
- export declare class Agent {
999
- /**
1000
- * Create an Agent from a config file path or inline config string.
1001
- *
1002
- * Accepts ACL-compatible config files (.acl) or inline config strings.
1003
- * JSON config is not supported.
1004
- *
1005
- * @param configSource - Path to a config file (.acl), or inline config string
1006
- */
1007
- static create(configSource: string): Promise<Agent>
1008
- /**
1009
- * Re-fetch tool definitions from all connected global MCP servers and
1010
- * update the agent-level cache.
1011
- *
1012
- * New sessions created after this call will see the refreshed tool list.
1013
- * Existing sessions are unaffected.
1014
- */
1015
- refreshMcpTools(): Promise<void>
1016
- /**
1017
- * Bind to a workspace directory, returning a Session.
1018
- *
1019
- * @param workspace - Path to the workspace directory
1020
- * @param options - Optional session overrides
1021
- */
1022
- session(workspace: string, options?: SessionOptions | undefined | null): Session
1023
- /**
1024
- * Resume a previously saved session by ID.
1025
- *
1026
- * `options.sessionStore` must be set to a `FileSessionStore` (or `MemorySessionStore`)
1027
- * that points to the directory where the session was originally saved.
1028
- *
1029
- * ```js
1030
- * const session = agent.resumeSession('my-session', {
1031
- * sessionStore: new FileSessionStore('./sessions'),
1032
- * });
1033
- * ```
1034
- *
1035
- * @param sessionId - The session ID to resume
1036
- * @param options - Session options; `sessionStore` is required
1037
- */
1038
- resumeSession(sessionId: string, options: SessionOptions): Session
1039
- /**
1040
- * Create a session pre-configured from a named agent definition.
1041
- *
1042
- * Loads the agent by name from built-in agents and optionally from
1043
- * additional directories, then creates a session with the agent's
1044
- * permissions, system prompt, model, and step limit applied.
1045
- *
1046
- * @param workspace - Path to the workspace directory
1047
- * @param agentName - Name of the agent to load (e.g. "explore", "general")
1048
- * @param agentDirs - Optional directories to scan for agent files
1049
- * @param options - Optional session overrides layered on top of the agent definition
1050
- */
1051
- sessionForAgent(workspace: string, agentName: string, agentDirs?: Array<string> | undefined | null, options?: SessionOptions | undefined | null): Session
1052
- /**
1053
- * Create a session pre-configured from a disposable worker spec.
1054
- *
1055
- * This avoids writing temporary agent files for one-off cattle workers.
1056
- *
1057
- * @param workspace - Path to the workspace directory
1058
- * @param worker - Worker spec to compile into an agent definition
1059
- * @param options - Optional session overrides layered on top of the worker definition
1060
- */
1061
- sessionForWorker(workspace: string, worker: WorkerAgentSpec, options?: SessionOptions | undefined | null): Session
1062
- }
1063
- /** Workspace-bound session. All LLM and tool operations happen here. */
1064
- export declare class Session {
1065
- /**
1066
- * Send a prompt or request and wait for the complete response.
1067
- *
1068
- * `send("prompt")` is the compact prompt-first form. `send({ prompt,
1069
- * history, attachments })` is the compact object-shaped form for growth.
1070
- */
1071
- send(request: string | SessionRequestOptions, history?: Array<MessageObject> | null): Promise<AgentResult>
1072
- /** Alias for `send(...)` with a name that matches run/replay terminology. */
1073
- run(request: string | SessionRequestOptions, history?: Array<MessageObject> | null): Promise<AgentResult>
1074
- /**
1075
- * Send a prompt or request and get a streaming event iterator.
1076
- *
1077
- * Returns an `EventStream`. Use `for await (const event of stream)` or call `.next()` manually.
1078
- * When `history` is omitted, the session history and verification evidence are
1079
- * updated after the stream completes. Supplying `history` keeps the stream isolated.
1080
- */
1081
- stream(request: string | SessionRequestOptions, history?: Array<MessageObject> | null): Promise<EventStream>
1082
- /**
1083
- * Send a request using the long-lived object-shaped API.
1084
- *
1085
- * Prefer this for new integrations when the call may need history,
1086
- * attachments, or future request options.
1087
- */
1088
- sendRequest(request: SessionRequestOptions): Promise<AgentResult>
1089
- /** Stream a request using the long-lived object-shaped API. */
1090
- streamRequest(request: SessionRequestOptions): Promise<EventStream>
1091
- /**
1092
- * Send a prompt with image attachments and wait for the complete response.
1093
- *
1094
- * @param prompt - The prompt to send
1095
- * @param attachments - Array of `{ data: Buffer, mediaType: string }`
1096
- * @param history - Optional conversation history
1097
- */
1098
- sendWithAttachments(prompt: string, attachments: Array<AttachmentObject>, history?: Array<MessageObject> | undefined | null): Promise<AgentResult>
1099
- /**
1100
- * Stream a prompt with image attachments.
1101
- *
1102
- * When `history` is omitted, the session history and verification evidence are
1103
- * updated after the stream completes. Supplying `history` keeps the stream isolated.
1104
- *
1105
- * @param prompt - The prompt to send
1106
- * @param attachments - Array of `{ data: Buffer, mediaType: string }`
1107
- * @param history - Optional conversation history
1108
- */
1109
- streamWithAttachments(prompt: string, attachments: Array<AttachmentObject>, history?: Array<MessageObject> | undefined | null): Promise<EventStream>
1110
- /** Return the session's conversation history. */
1111
- history(): Array<MessageObject>
1112
- /** Return run snapshots recorded by this session. */
1113
- runs(): Promise<any>
1114
- /** Return a run snapshot by ID, or null when it is unknown. */
1115
- runSnapshot(runId: string): Promise<any>
1116
- /** Return recorded runtime events for a run. */
1117
- runEvents(runId: string): Promise<any>
1118
- /** Return the currently running operation, or null when idle. */
1119
- currentRun(): Promise<any>
1120
- /** Return active tool calls observed for the currently running operation. */
1121
- activeTools(): Promise<any>
1122
- /** Cancel a specific run only if it is still the active run. */
1123
- cancelRun(runId: string): Promise<boolean>
1124
- /** Execute a tool by name, bypassing the LLM. */
1125
- tool(name: string, args: any): Promise<ToolResult>
1126
- /** Delegate a bounded task to a child agent through the built-in `task` tool. */
1127
- task(options: DelegateTaskOptions): Promise<ToolResult>
1128
- /** Delegate a bounded task to a child agent through the built-in `task` tool. */
1129
- delegateTask(options: DelegateTaskOptions): Promise<ToolResult>
1130
- /** Execute several delegated child-agent tasks concurrently through `parallel_task`. */
1131
- tasks(tasks: DelegateTaskOptions[]): Promise<ToolResult>
1132
- /** Execute several delegated child-agent tasks concurrently through `parallel_task`. */
1133
- parallelTask(tasks: DelegateTaskOptions[]): Promise<ToolResult>
1134
- /** Run a bounded JavaScript script through the embedded QuickJS `program` tool. */
1135
- program(options: ProgramScriptOptions): Promise<ToolResult>
1136
- /** Read a file from the workspace. */
1137
- readFile(path: string): Promise<string>
1138
- /** Write a file in the workspace. */
1139
- writeFile(path: string, content: string): Promise<ToolResult>
1140
- /** List a directory in the workspace. */
1141
- ls(path?: string | undefined | null): Promise<ToolResult>
1142
- /** Edit a file by replacing text in the workspace. */
1143
- editFile(path: string, oldString: string, newString: string, replaceAll?: boolean | undefined | null): Promise<ToolResult>
1144
- /** Apply a unified diff patch to a workspace file. */
1145
- patchFile(path: string, diff: string): Promise<ToolResult>
1146
- /** Execute a bash command in the workspace. */
1147
- bash(command: string): Promise<string>
1148
- /** Search for files matching a glob pattern. */
1149
- glob(pattern: string): Promise<Array<string>>
1150
- /** Search file contents with a regex pattern. */
1151
- grep(pattern: string): Promise<string>
1152
- /** Search the web using multiple search engines. */
1153
- webSearch(params: JsWebSearchParams): Promise<ToolResult>
1154
- /**
1155
- * Execute a git command.
1156
- *
1157
- * Prefer `git({ command: "status" })`; positional arguments remain for
1158
- * compatibility.
1159
- */
1160
- git(command: string | GitCommandOptions, subcommand?: string | null, name?: string | null, path?: string | null, newBranch?: boolean | null, base?: string | null, force?: boolean | null, maxCount?: number | null, message?: string | null, includeUntracked?: boolean | null, target?: string | null, reference?: string | null): Promise<ToolResult>
1161
- /**
1162
- * Execute a git command with an object-shaped API.
1163
- *
1164
- * Preferred over the positional `git(...)` overload for new callers.
1165
- *
1166
- * ```js
1167
- * await session.gitCommand({ command: 'status' })
1168
- * await session.gitCommand({ command: 'worktree', subcommand: 'list' })
1169
- * ```
1170
- */
1171
- gitCommand(args: GitCommandOptions): Promise<ToolResult>
1172
- /** Check if this session has an advanced lane queue configured. */
1173
- hasQueue(): boolean
1174
- /**
1175
- * Configure a lane's handler mode for explicit external/hybrid dispatch.
1176
- *
1177
- * @param lane - "control", "query", "execute", or "generate"
1178
- * @param config - { mode: "internal"|"external"|"hybrid", timeoutMs?: number }
1179
- */
1180
- setLaneHandler(lane: string, config: LaneHandlerConfig): Promise<void>
1181
- /**
1182
- * Complete an external queue task by ID.
1183
- *
1184
- * @param taskId - The task identifier
1185
- * @param result - { success: boolean, result?: any, error?: string }
1186
- * @returns true if found, false if not found
1187
- */
1188
- completeExternalTask(taskId: string, result: ExternalTaskResult): Promise<boolean>
1189
- /** Get pending external queue tasks. */
1190
- pendingExternalTasks(): Promise<any>
1191
- /** Return pending HITL tool confirmations for this session. */
1192
- pendingConfirmations(): Promise<Array<PendingConfirmation>>
1193
- /**
1194
- * Resolve a pending HITL tool confirmation.
1195
- *
1196
- * @param toolId - Tool call ID from a `confirmation_required` event.
1197
- * @param approved - Whether the tool execution should proceed.
1198
- * @param reason - Optional human-readable reason for audit/UI display.
1199
- * @returns true if a pending confirmation was found and completed.
1200
- */
1201
- confirmToolUse(toolId: string, approved: boolean, reason?: string | undefined | null): Promise<boolean>
1202
- /** Cancel all pending HITL confirmations for this session. */
1203
- cancelConfirmations(): Promise<number>
1204
- /** Get optional queue statistics. */
1205
- queueStats(): Promise<QueueStats>
1206
- /** Return compact execution trace events recorded for this session. */
1207
- traceEvents(): any
1208
- /** Return structured verification reports recorded for this session. */
1209
- verificationReports(): any
1210
- /** Return a structured verification summary for this session. */
1211
- verificationSummary(): any
1212
- /** Return a concise human-readable verification summary for this session. */
1213
- verificationSummaryText(): string
1214
- /** Run verification commands and return a structured verification report. */
1215
- verifyCommands(subject: string, commands: Array<VerificationCommand>): Promise<any>
1216
- /** Return project-aware verification command presets for this workspace. */
1217
- verificationPresets(): any
1218
- /** Get dead letters from the optional queue's DLQ. */
1219
- deadLetters(): Promise<any>
1220
- /**
1221
- * Get a detailed metrics snapshot from the queue.
1222
- *
1223
- * Returns `null` if metrics are not enabled (queue not configured or
1224
- * `enable_metrics` was not set in `SessionQueueConfig`).
1225
- *
1226
- * @returns Object with `counters`, `gauges`, and `histograms` maps, or null
1227
- */
1228
- queueMetrics(): Promise<any>
1229
- /**
1230
- * Add an MCP server to this live session.
1231
- *
1232
- * Connects the server and registers all its tools immediately so the agent
1233
- * can call them. Tool names follow the convention `mcp__<name>__<tool>`.
1234
- *
1235
- * @param name - Server identifier (used as prefix in tool names)
1236
- * @param transport - Transport type: `"stdio"` (default), `"http"`, or `"streamable-http"`
1237
- * @param command - Executable to launch (stdio only, e.g. `"npx"`)
1238
- * @param args - Arguments for the command (stdio only)
1239
- * @param url - Server URL (http / streamable-http only)
1240
- * @param headers - HTTP headers (http / streamable-http only)
1241
- * @param env - Optional extra environment variables (stdio only)
1242
- * @returns Number of tools registered from the server
1243
- */
1244
- addMcpServer(name: string, transport?: 'stdio' | 'http' | 'streamable-http', command?: string | undefined | null, args?: Array<string> | undefined | null, url?: string | undefined | null, headers?: Record<string, string> | undefined | null, env?: Record<string, string> | undefined | null, timeoutMs?: number | undefined | null): Promise<number>
1245
- /**
1246
- * Add an MCP server with a typed object config.
1247
- *
1248
- * Preferred over the positional overload for new SDK callers.
1249
- *
1250
- * ```js
1251
- * await session.addMcpServerConfig({
1252
- * name: 'github',
1253
- * transport: { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] },
1254
- * env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN },
1255
- * timeoutMs: 30000,
1256
- * })
1257
- * ```
1258
- */
1259
- addMcpServerConfig(config: McpServerConfig): Promise<number>
1260
- /** Add an MCP server with the compact object-shaped API. */
1261
- addMcp(config: McpServerConfig): Promise<number>
1262
- /**
1263
- * Dynamically register agent definitions from a directory into the live session.
1264
- *
1265
- * Scans the directory for `*.yaml`, `*.yml`, and `*.md` agent definition files
1266
- * and registers them into the shared AgentRegistry used by the `task` tool.
1267
- * New agents are immediately callable via `task({ agent: "…", … })` without
1268
- * restarting the session.
1269
- *
1270
- * @param path - Directory to scan for agent definition files
1271
- * @returns Number of agents successfully loaded
1272
- */
1273
- registerAgentDir(path: string): number
1274
- /**
1275
- * Register a disposable worker agent into the live session.
1276
- *
1277
- * The worker is immediately callable through the model-visible `task` tool.
1278
- *
1279
- * @param worker - Worker spec to register
1280
- * @returns Compiled agent definition
1281
- */
1282
- registerWorkerAgent(worker: WorkerAgentSpec): AgentDefinition
1283
- /**
1284
- * Register many disposable workers into the live session.
1285
- *
1286
- * @param workers - Worker specs to register
1287
- * @returns Compiled agent definitions
1288
- */
1289
- registerWorkerAgents(workers: Array<WorkerAgentSpec>): Array<AgentDefinition>
1290
- /**
1291
- * Disconnect and unregister an MCP server, removing its tools from the session.
1292
- *
1293
- * @param name - Server name (must match the name used in addMcpServer)
1294
- */
1295
- removeMcpServer(name: string): Promise<void>
1296
- /** Remove an MCP server with the compact API. */
1297
- removeMcp(name: string): Promise<void>
1298
- /**
1299
- * Return connection status for all MCP servers registered on this session.
1300
- *
1301
- * @returns Array of `{ name, connected, toolCount }` entries
1302
- */
1303
- mcpStatus(): Promise<Array<McpServerStatusEntry>>
1304
- /** Return MCP server status with the compact API. */
1305
- mcps(): Promise<Array<McpServerStatusEntry>>
1306
- /**
1307
- * Return the names of all tools currently registered on this session.
1308
- *
1309
- * @returns Array of tool name strings
1310
- */
1311
- toolNames(): Array<string>
1312
- /** Return full model-visible tool definitions currently registered on this session. */
1313
- toolDefinitions(): any
1314
- /**
1315
- * Register a hook for lifecycle event interception.
1316
- *
1317
- * Hooks registered on a session are automatically propagated to all sub-agents
1318
- * spawned by the `task` tool, including grandchild agents at arbitrary depth.
1319
- * This ensures security hooks (e.g. a sentinel) apply across the full agent tree
1320
- * without requiring explicit registration on each sub-agent session.
1321
- *
1322
- * @param hookId - Unique hook identifier
1323
- * @param eventType - Event type: "pre_tool_use", "post_tool_use", "generate_start",
1324
- * "generate_end", "session_start", "session_end", "skill_load", "skill_unload",
1325
- * "pre_prompt", "post_response", "on_error"
1326
- * @param matcher - Optional matcher: { tool?, pathPattern?, commandPattern?, sessionId?, skill? }
1327
- * @param config - Optional config: { priority?, timeoutMs?, asyncExecution?, maxRetries? }
1328
- * @param handler - Optional callback `(event: any) => { action: 'continue' | 'block' | 'skip',
1329
- * reason?: string } | null`. When provided, the function is called for every matching event
1330
- * and its return value controls execution. Return `{ action: 'block', reason: '...' }` to
1331
- * cancel the operation, `{ action: 'skip' }` to skip remaining hooks, or `null`/`undefined`
1332
- * for continue. Hooks with no handler still fire (observable via stream events) but always
1333
- * continue.
1334
- */
1335
- registerHook(hookId: string, eventType: string, matcher?: HookMatcherObject | undefined | null, config?: HookConfigObject | undefined | null, handler?: ((event: Record<string, unknown>) => { action: string; reason?: string } | null | undefined) | null | undefined): void
1336
- /**
1337
- * Unregister a hook by ID.
1338
- *
1339
- * @param hookId - The hook identifier to remove
1340
- * @returns true if the hook was found and removed
1341
- */
1342
- unregisterHook(hookId: string): boolean
1343
- /** Get the number of registered hooks. */
1344
- hookCount(): number
1345
- /** Return the session ID. */
1346
- get sessionId(): string
1347
- /** Return the workspace path. */
1348
- get workspace(): string
1349
- /** Return any deferred init warning (e.g. memory store failed to initialize). */
1350
- get initWarning(): string | null
1351
- /** Save the session to the configured store. */
1352
- save(): Promise<void>
1353
- /** Check if memory is configured for this session. */
1354
- get hasMemory(): boolean
1355
- /**
1356
- * Remember a successful task execution.
1357
- *
1358
- * @param task - Description of the task
1359
- * @param tools - List of tool names used
1360
- * @param result - Summary of the result
1361
- */
1362
- rememberSuccess(task: string, tools: Array<string>, result: string): Promise<void>
1363
- /**
1364
- * Remember a failed task execution.
1365
- *
1366
- * @param task - Description of the task
1367
- * @param error - Error message
1368
- * @param tools - List of tool names attempted
1369
- */
1370
- rememberFailure(task: string, error: string, tools: Array<string>): Promise<void>
1371
- /**
1372
- * Recall memories similar to a query.
1373
- *
1374
- * @param query - Search query
1375
- * @param limit - Maximum number of results (default: 5)
1376
- * @returns Array of memory items
1377
- */
1378
- recallSimilar(query: string, limit?: number | undefined | null): Promise<any>
1379
- /**
1380
- * Recall memories by tags.
1381
- *
1382
- * @param tags - Tags to search for
1383
- * @param limit - Maximum number of results (default: 10)
1384
- * @returns Array of memory items
1385
- */
1386
- recallByTags(tags: Array<string>, limit?: number | undefined | null): Promise<any>
1387
- /**
1388
- * Get recent memory items.
1389
- *
1390
- * @param limit - Maximum number of results (default: 10)
1391
- * @returns Array of memory items
1392
- */
1393
- memoryRecent(limit?: number | undefined | null): Promise<any>
1394
- /**
1395
- * Get memory statistics.
1396
- *
1397
- * @returns Object with longTermCount, shortTermCount, workingCount
1398
- */
1399
- memoryStats(): Promise<any>
1400
- /**
1401
- * Get current working memory items.
1402
- *
1403
- * Working memory holds the active context items for the current task.
1404
- *
1405
- * @returns Array of memory items currently in working memory
1406
- */
1407
- getWorking(): Promise<any>
1408
- /**
1409
- * Clear working memory.
1410
- *
1411
- * Removes all items from working memory without affecting short-term or long-term memory.
1412
- */
1413
- clearWorking(): Promise<void>
1414
- /**
1415
- * Get current short-term memory items.
1416
- *
1417
- * Short-term memory contains items stored during this session.
1418
- *
1419
- * @returns Array of memory items in short-term memory
1420
- */
1421
- getShortTerm(): Promise<any>
1422
- /**
1423
- * Clear short-term memory for this session.
1424
- *
1425
- * Removes all session-scoped memory items without affecting long-term or working memory.
1426
- */
1427
- clearShortTerm(): Promise<void>
1428
- /**
1429
- * Register a custom slash command.
1430
- *
1431
- * Slash commands are invoked via `session.send("/command args")` and execute
1432
- * before the LLM sees the input. The handler receives the command arguments
1433
- * and a context object with session metadata.
1434
- *
1435
- * @param name - Command name without the leading `/` (e.g., `"status"`)
1436
- * @param description - Short description shown in `/help`
1437
- * @param handler - Callback `(args: string, ctx: CommandContext) => string`
1438
- *
1439
- * @example
1440
- * ```typescript
1441
- * session.registerCommand("status", "Show session info", (args, ctx) => {
1442
- * return `Session ${ctx.sessionId} in ${ctx.workspace}`;
1443
- * });
1444
- * await session.send("/status");
1445
- * ```
1446
- */
1447
- registerCommand(name: string, description: string, handler: (args: string, ctx: CommandContext) => string): void
1448
- /**
1449
- * List all registered slash commands.
1450
- *
1451
- * Returns each command's name, description, and optional usage hint.
1452
- * Slash commands can be invoked via `session.send("/command args")`.
1453
- *
1454
- * @returns Array of CommandInfo objects sorted by name
1455
- */
1456
- listCommands(): Array<CommandInfo>
1457
- /**
1458
- * Cancel the current ongoing operation (send/stream).
1459
- *
1460
- * If an operation is in progress, this will trigger cancellation of the LLM streaming
1461
- * and tool execution. The operation will terminate as soon as possible.
1462
- *
1463
- * @returns `true` if an operation was cancelled, `false` if no operation was in progress
1464
- */
1465
- cancel(): boolean
1466
- /**
1467
- * Close the session and cancel any active operation.
1468
- *
1469
- * Call this when the session will no longer be used so Node.js can exit
1470
- * cleanly without waiting on session-scoped background workers.
1471
- */
1472
- close(): void
1473
- }
12
+ export * from './generated'
13
+ export * from './extra-types'