@a3s-lab/code 3.1.0 → 3.2.1

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