From af103c7d64a8c1cbc66fee7329e6ec19d16d5475 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 23 May 2026 23:06:28 +0800 Subject: [PATCH] fix(node-sdk): protect hand-authored types from napi-rs regen churn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before this commit, every `napi build` overwrote `index.d.ts` and silently dropped the hand-added types (`ToolErrorKind`, `VerificationStatus`, `VerificationCheck`, `VerificationReport`, `ToolArtifact`). These types aren't generatable from Rust — they describe JSON wire shapes whose field names must stay snake_case to match the core's serialization, which napi-derive would auto-camelCase. Reshape the SDK so generated and hand-authored types live in separate files: - napi build now writes to `generated.d.ts` (was `index.d.ts`). - `extra-types.d.ts` holds the hand-authored types. - `index.d.ts` becomes a small hand-authored aggregator that re-exports both. It is never touched by the build. - `package.json` `files[]` ships all three .d.ts files; `types` field still points at `index.d.ts` so consumers' imports are unchanged. Adds `test-types.ts` + `npm run test:types` as a tsc-based smoke check that fails if the aggregator ever drops a type from either file. --- sdk/node/extra-types.d.ts | 56 ++ sdk/node/generated.d.ts | 1506 +++++++++++++++++++++++++++++++++++ sdk/node/index.d.ts | 1554 +------------------------------------ sdk/node/package.json | 7 +- sdk/node/test-types.ts | 48 ++ 5 files changed, 1624 insertions(+), 1547 deletions(-) create mode 100644 sdk/node/extra-types.d.ts create mode 100644 sdk/node/generated.d.ts create mode 100644 sdk/node/test-types.ts diff --git a/sdk/node/extra-types.d.ts b/sdk/node/extra-types.d.ts new file mode 100644 index 0000000..c79572a --- /dev/null +++ b/sdk/node/extra-types.d.ts @@ -0,0 +1,56 @@ +/** + * Hand-authored type declarations that complement the auto-generated + * `generated.d.ts`. These describe shapes that cross the SDK boundary as + * JSON (e.g. payloads inside `runs()`, `verificationReports()`, + * `errorKindJson` strings), not napi-bound objects. + * + * Keep field names matching the actual JSON wire format (snake_case where + * the Rust core serializes that way). Do not move these into Rust source — + * napi-derive would camelCase them and break consumers parsing the JSON. + */ + +/** + * Parsed shape of `ToolResult.errorKindJson` / `AgentEvent.errorKindJson`. + * + * Use a discriminated union on the `type` field; new variants may be + * added in future minor releases — callers should match exhaustively on + * the kinds they care about and fall through to a default branch for + * unknown ones. + */ +export type ToolErrorKind = + | { type: 'version_conflict'; path: string; expected: string; actual: string | null } + | { type: 'remote_git_conflict'; code: string; message: string } + | { type: 'not_found'; path: string } + | { type: 'invalid_argument'; message: string } + | { type: 'unsupported'; message: string } + | { type: 'timeout'; op: string; duration_ms: number } + +export type VerificationStatus = 'passed' | 'failed' | 'needs_review' | 'skipped' + +export interface VerificationCheck { + id: string + kind: string + description: string + status: VerificationStatus + required?: boolean + suggested_tools?: Array + evidence_uris?: Array + residual_risk?: string +} + +export interface VerificationReport { + schema: string + subject: string + status: VerificationStatus + checks: Array + residual_risks?: Array +} + +export interface ToolArtifact { + artifact_id: string + artifact_uri: string + tool_name: string + content: string + original_bytes: number + shown_bytes: number +} diff --git a/sdk/node/generated.d.ts b/sdk/node/generated.d.ts new file mode 100644 index 0000000..81b4682 --- /dev/null +++ b/sdk/node/generated.d.ts @@ -0,0 +1,1506 @@ +/* tslint:disable */ +/* eslint-disable */ + +/* auto-generated by NAPI-RS */ + +/** AHP event type. */ +export interface AhpEventType { + /** Event type string: "handshake", "pre_action", "post_action", "pre_prompt", "post_response", "session_start", "session_end", "error", "query", "heartbeat", "idle" */ + eventType: string +} +/** A factual memory item. */ +export interface AhpFact { + content: string + source: string + confidence: number +} +/** Memory state summary. */ +export interface AhpMemorySummary { + memoryType: string + totalItems: number + recentTopics: Array +} +/** Session statistics. */ +export interface AhpSessionStats { + totalActions: number + totalTokens: number + durationMs: number + errorCount: number +} +/** Decision from harness for idle events. */ +export interface AhpIdleDecision { + /** Decision string: "allow" or "defer" */ + decision: string + /** Reason if deferred */ + reason?: string +} +/** Context passed with AHP events. */ +export interface AhpEventContext { + recentFacts?: Array + memorySummary?: AhpMemorySummary + sessionStats?: AhpSessionStats + currentTask?: string + capabilities?: Record +} +export interface AgentResult { + text: string + toolCallsCount: number + promptTokens: number + completionTokens: number + totalTokens: number + verificationStatus: string + pendingVerificationCount: number + failedVerificationCount: number + verificationReportCount: number + verificationSummaryJson: string + verificationSummaryText: string +} +export declare function formatVerificationSummary(summary: any): string +export interface AgentEvent { + type: string + text?: string + toolName?: string + toolId?: string + toolOutput?: string + exitCode?: number + turn?: number + prompt?: string + error?: string + totalTokens?: number + verificationSummaryJson?: string + verificationSummaryText?: string + /** Extra data for events that don't map to standard fields (JSON-encoded) */ + data?: string + /** + * Structured discriminant for tool failures on `tool_end` events + * (JSON-encoded with a `type` field). `None` on success or untyped + * failure. Lets streaming consumers branch on the failure kind + * without scanning `tool_output`. + */ + errorKindJson?: string +} +export interface VerificationCommand { + id: string + kind: string + description: string + command: string + required?: boolean + timeoutMs?: number +} +export interface ToolResult { + name: string + output: string + exitCode: number + /** Raw JSON-encoded tool metadata returned by the Rust core API. */ + metadataJson?: string + /** Convenience JSON view of `metadata.document_runtime` when present. */ + documentRuntimeJson?: string + /** + * Structured discriminant for tool failures, JSON-encoded with a + * `type` field on the top level — e.g. + * `{"type":"version_conflict","path":"doc.md","expected":"etag-1","actual":"etag-2"}`. + * `None` on success or untyped failure. SDK callers parse it to + * branch on the failure kind without scanning the `output` string. + */ + errorKindJson?: string +} +/** Execution limits for `Session.program`. */ +export interface ProgramScriptLimits { + timeoutMs?: number + maxToolCalls?: number + maxOutputBytes?: number +} +/** Options for `Session.program`. */ +export interface ProgramScriptOptions { + source?: string + path?: string + inputs?: any + allowedTools?: Array + limits?: ProgramScriptLimits +} +/** Options for `Session.delegateTask`. */ +export interface DelegateTaskOptions { + agent: string + description: string + prompt: string + background?: boolean + maxSteps?: number +} +/** Object-shaped request for `Session.sendRequest` and `Session.streamRequest`. */ +export interface SessionRequestOptions { + prompt: string + history?: Array + attachments?: Array +} +export interface GitCommandOptions { + command: string + subcommand?: string + name?: string + path?: string + newBranch?: boolean + base?: string + force?: boolean + maxCount?: number + message?: string + includeUntracked?: boolean + target?: string + ref?: string + reference?: string +} +/** Parameters for the web_search tool. */ +export interface JsWebSearchParams { + /** The search query. */ + query: string + /** List of search engines to use. */ + engines?: Array + /** Maximum number of results to return (default: 10, max: 50). */ + limit?: number + /** Search timeout in seconds (default: 10, max: 60). */ + timeout?: number + /** Proxy URL (e.g., http://127.0.0.1:8080 or socks5://127.0.0.1:1080). */ + proxy?: string + /** Output format: "text" or "json". */ + format?: string +} +/** Result of a single `EventStream.next()` call. */ +export interface NextResult { + value?: AgentEvent + done: boolean +} +/** + * An inline skill registered programmatically (no file required). + * + * Use `kind: "instruction"` for prompt injections or `kind: "persona"` to + * replace the default role section of the system prompt. + */ +export interface InlineSkill { + /** Unique skill name (kebab-case recommended, e.g. "type-hints"). */ + name: string + /** Skill kind: `"instruction"` or `"persona"`. */ + kind: string + /** Markdown content for the skill. */ + content: string +} +export interface JsMemoryStore { + backend: string + dir?: string +} +export interface JsSessionStore { + backend: string + dir?: string +} +export interface JsSecurityProvider { + kind: string +} +export interface JsWorkspaceBackend { + kind: string + root?: string + s3?: JsS3BackendConfig +} +/** + * Configuration for an S3-compatible workspace backend. + * + * Use this with [`S3WorkspaceBackend`] to point a session's built-in file + * tools at any S3-compatible endpoint (AWS S3, MinIO, RustFS, R2, etc.). + * `endpoint` is optional — omit it to use the AWS default. `prefix` is + * the logical workspace root inside the bucket; every workspace path + * becomes `/` when sent to S3. + */ +export interface JsS3BackendConfig { + /** + * Optional S3 endpoint URL. Omit for AWS S3 (the SDK will compute it + * from `region`). Set to `https://...` for MinIO / RustFS / R2 / etc. + */ + endpoint?: string + /** AWS region. Defaults to `us-east-1` when omitted. */ + region?: string + /** Static access key. Use `sessionToken` together when STS-issued. */ + accessKeyId: string + secretAccessKey: string + sessionToken?: string + /** Bucket name. */ + bucket: string + /** + * Logical workspace prefix inside the bucket (without leading/trailing + * slashes). Use `""` to make the bucket root the workspace. + */ + prefix: string + /** `true` for MinIO / RustFS / most non-AWS endpoints; `false` for AWS S3. */ + forcePathStyle?: boolean + /** + * Maximum bytes a single `read` may return. The backend rejects any + * response with `Content-Length` greater than this without buffering + * the body. Defaults to 10 MiB on the Rust side when omitted. + */ + maxReadBytes?: number + /** + * Enable degraded `grep` / `glob` against this S3 backend. Off by + * default — object storage has no native search, so the only viable + * strategy is `LIST` + `GET` + regex, which can be slow and expensive. + */ + searchEnabled?: boolean + /** + * Upper bound on objects considered per `grep` / `glob` call. Defaults + * to 500 on the Rust side. Ignored when `searchEnabled` is `false`. + */ + maxObjectsScanned?: number + /** + * Per-object body-size ceiling for `grep` downloads. Larger objects are + * skipped (debug-traced). Defaults to 1 MiB on the Rust side. Ignored + * when `searchEnabled` is `false`. + */ + maxGrepBytesPerObject?: number + /** + * Concurrent object downloads during `grep`. Defaults to 8 on the + * Rust side. Set lower when the gitserver / S3 endpoint rate-limits + * aggressively; set higher when latency dominates. Ignored when + * `searchEnabled` is `false`. + */ + searchConcurrency?: number +} +/** + * Configuration for a [`RemoteGitBackend`] — an HTTP/JSON client that + * brings the `git` tool to non-local workspaces (S3, future container / + * DFS). + * + * Pass alongside `workspaceBackend` on a session to attach remote git + * on top of any filesystem backend. The protocol is specified in the + * repository RFC `apps/docs/content/docs/en/code/rfcs/workspace-remote-git.mdx`. + */ +export interface JsRemoteGitBackendConfig { + /** + * Base URL of the gitserver, no trailing slash. The client builds + * `{baseUrl}/v1/repos/{repoId}/git/{op}` per the RFC. + */ + baseUrl: string + /** + * Opaque repository identifier, URL-safe. Negotiated out of band + * with the gitserver operator. + */ + repoId: string + /** + * Bearer token sent as `Authorization: Bearer `. Required in + * production; omitting it emits a `tracing::warn!` and is only safe + * on a trusted localhost gitserver. + */ + bearerToken?: string + /** + * mTLS client certificate path (PEM). When set together with + * `clientKeyPem`, the backend reads both files at construction and + * configures mTLS on the HTTP client. Setting only one of the pair + * errors at construction. + */ + clientCertPem?: string + /** + * mTLS client private key path (PEM). PKCS#8 format expected for the + * `rustls-tls` backend. See `clientCertPem`. + */ + clientKeyPem?: string + /** Per-call HTTP timeout in milliseconds. Defaults to 30 000. */ + requestTimeoutMs?: number + /** Client-side cap on `diff` response bytes. Defaults to 1 MiB. */ + maxDiffBytes?: number + /** Client-side cap on `log` `max_count`. Defaults to 200. */ + maxLogEntries?: number +} +/** + * Union type for AHP transport configuration. + * Accepts any of: StdioTransport, HttpTransport, WebSocketTransport, UnixSocketTransport. + */ +export interface JsAhpTransport { + kind: string + program?: string + args?: Array + url?: string + authToken?: string + path?: string +} +export interface PermissionPolicy { + /** Tool invocation patterns that are always denied first. */ + deny?: Array + /** Tool invocation patterns that are auto-approved. */ + allow?: Array + /** Tool invocation patterns that always require confirmation. */ + ask?: Array + /** Default decision when no rule matches: "allow", "deny", or "ask". */ + defaultDecision?: string + /** Whether this policy is enabled. Defaults to true. */ + enabled?: boolean +} +/** + * Reproducible recipe for a disposable worker/subagent. + * + * This is the Node.js cattle-mode interface: define workers in data, pass them + * to SessionOptions.workerAgents, Agent.sessionForWorker(), or + * Session.registerWorkerAgent(). The Rust core compiles each spec into the + * normal delegated-agent runtime definition. + */ +export interface WorkerAgentSpec { + /** Stable worker name used by task delegation. */ + name: string + /** Human-readable worker purpose. */ + description: string + /** Preset role: "read_only", "planner", "implementer", "verifier", "reviewer", or "custom". */ + kind?: string + /** Hide from UI lists while allowing explicit delegation. */ + hidden?: boolean + /** Optional permission policy override. */ + permissions?: PermissionPolicy + /** Optional model override in "provider/model" format. */ + model?: string + /** Optional worker-specific prompt. */ + prompt?: string + /** Maximum execution steps/tool rounds. */ + maxSteps?: number + /** How child runs resolve Ask decisions: "auto_approve" (default), "deny_on_ask", or "inherit_parent". */ + confirmationInheritance?: string +} +export interface AgentDefinition { + name: string + description: string + native: boolean + hidden: boolean + model?: string + prompt?: string + maxSteps?: number + /** How child runs resolve Ask decisions: "auto_approve", "deny_on_ask", or "inherit_parent". */ + confirmationInheritance?: string +} +/** + * HITL confirmation policy configuration. + * + * Controls the runtime behavior of Human-in-the-Loop confirmation flow. + */ +export interface ConfirmationPolicy { + /** Whether HITL is enabled (default: false, all tools auto-approved). */ + enabled?: boolean + /** Default timeout in milliseconds (default: 30000 = 30s). */ + defaultTimeoutMs?: number + /** Action to take on timeout: "reject" or "auto_approve" (default: "reject"). */ + timeoutAction?: string + /** Lanes that should auto-approve without confirmation: "control", "query", "execute", or "generate". */ + yoloLanes?: Array +} +/** Snapshot of a pending HITL tool confirmation. */ +export interface PendingConfirmation { + /** Tool call ID to pass to `confirmToolUse`. */ + toolId: string + /** Tool name awaiting confirmation. */ + toolName: string + /** Tool arguments for display in a confirmation UI. */ + args: any + /** Milliseconds remaining before the confirmation times out. */ + remainingMs: number +} +export interface AutoDelegationOptions { + /** Enable runtime-driven automatic child-agent delegation. */ + enabled?: boolean + /** + * Allow automatic delegation to launch multiple child agents in parallel. + * + * Manual `parallel_task` calls remain available when this is false. + */ + autoParallel?: boolean + /** Minimum local confidence required to auto-delegate a child task. */ + minConfidence?: number + /** Maximum number of automatic child tasks per user request. */ + maxTasks?: number +} +export interface SessionOptions { + /** Override the default model. Format: "provider/model" (e.g., "openai/gpt-4o"). */ + model?: string + /** Enable built-in skills (4 skills: code-search, code-review, explain-code, find-bugs). */ + builtinSkills?: boolean + /** Extra directories to scan for skill files (.md with YAML frontmatter). */ + skillDirs?: Array + /** Extra directories to scan for agent files. */ + agentDirs?: Array + /** Reproducible disposable workers to register for task delegation. */ + workerAgents?: Array + /** + * Optional advanced queue configuration for explicit external/hybrid lane dispatch. + * + * Ordinary sessions are queue-free unless this is provided. + */ + queueConfig?: SessionQueueConfig + /** Explicit permission policy for tool execution. */ + permissionPolicy?: PermissionPolicy + /** + * Explicit planning mode: "auto", "enabled", or "disabled". + * + * Prefer this over `planning` when the caller needs an unambiguous SDK contract. + * If both are set, `planningMode` wins. + */ + planningMode?: string + /** Legacy planning shortcut. Omit for auto planning, true to force planning, false to disable. */ + planning?: boolean + /** Enable goal tracking (default: false). */ + goalTracking?: boolean + /** Max consecutive parse errors before abort. */ + maxParseRetries?: number + /** Per-tool execution timeout in milliseconds. */ + toolTimeoutMs?: number + /** Max LLM API failures before abort. */ + circuitBreakerThreshold?: number + /** Enable auto-compaction when context window fills up (default: false). */ + autoCompact?: boolean + /** Context usage threshold (0.0–1.0) to trigger auto-compaction (default: 0.8). */ + autoCompactThreshold?: number + /** Retention limits for large tool/program artifacts. */ + artifactStoreLimits?: ArtifactStoreLimits + /** + * Long-term memory store backend. + * + * Pass `new FileMemoryStore("./memory")` for file-based persistence. + * ```js + * agent.session('.', { memoryStore: new FileMemoryStore('./memory') }); + * ``` + */ + memoryStore?: JsMemoryStore + /** + * Session persistence store backend. + * + * Pass `new FileSessionStore("./sessions")` to persist sessions to disk, + * or `new MemorySessionStore()` for an ephemeral in-process store. + * ```js + * agent.session('.', { + * sessionStore: new FileSessionStore('./sessions'), + * sessionId: 'my-session', + * autoSave: true, + * }); + * ``` + */ + sessionStore?: JsSessionStore + /** + * Security provider. + * + * Pass `new DefaultSecurityProvider()` to enable input taint tracking and + * output sanitisation. Omit to disable security (default: no security). + * ```js + * agent.session('.', { securityProvider: new DefaultSecurityProvider() }); + * ``` + */ + securityProvider?: JsSecurityProvider + /** + * Workspace backend used by built-in tools. + * + * Pass `new LocalWorkspaceBackend("/repo")` to explicitly use the local + * filesystem backend. This option is the SDK surface for future remote, + * browser, DFS, and container-backed workspace implementations. + * ```js + * agent.session('/repo', { workspaceBackend: new LocalWorkspaceBackend('/repo') }); + * ``` + */ + workspaceBackend?: JsWorkspaceBackend + /** + * Optional remote git provider. When set, the resulting session attaches + * a `RemoteGitBackend` on top of `workspaceBackend` so the built-in + * `git` tool is available even on object-storage workspaces. + * + * ```js + * agent.session('s3://workspace/u1/s1', { + * workspaceBackend: new S3WorkspaceBackend({ ... }), + * remoteGit: { + * baseUrl: 'https://gitserver.internal', + * repoId: 'u1/s1', + * bearerToken: token, + * }, + * }); + * ``` + */ + remoteGit?: JsRemoteGitBackendConfig + /** + * Custom role/identity prepended before the core agentic prompt. + * Example: "You are a senior Python developer specializing in FastAPI." + */ + role?: string + /** + * Custom coding guidelines appended after the core prompt. + * Example: "Always use type hints. Follow PEP 8." + */ + guidelines?: string + /** Custom response style (replaces default Response Format section). */ + responseStyle?: string + /** Freeform extra instructions appended at the end. */ + extra?: string + /** + * Inline skills registered programmatically without needing skill files on disk. + * Each entry defines an instruction or persona skill injected into the system prompt. + */ + inlineSkills?: Array + /** Override maximum number of tool-call rounds for this session. */ + maxToolRounds?: number + /** Override maximum sibling parallel branches for this session. */ + maxParallelTasks?: number + /** Override automatic child-agent delegation for this session. */ + autoDelegation?: AutoDelegationOptions + /** + * Global session-level kill switch for automatic parallel child-agent fan-out. + * + * Manual `parallel_task` calls remain available when this is false. + */ + autoParallel?: boolean + /** + * Sampling temperature (0.0–1.0). Overrides the provider default. + * Only applied when `model` is also set. + */ + temperature?: number + /** + * Extended thinking token budget (e.g. 10_000). Enables chain-of-thought reasoning. + * Only applied when `model` is also set. Provider must support extended thinking. + */ + thinkingBudget?: number + /** + * Enable continuation injection (default: true). + * When enabled, the loop injects a follow-up prompt when the LLM stops without completing. + */ + continuationEnabled?: boolean + /** Maximum continuation injections per execution (default: 3). */ + maxContinuationTurns?: number + /** + * Session ID (auto-generated if not set). + * + * Set a stable ID so the session can be saved and resumed later: + * ```js + * agent.session('.', { sessionId: 'my-session', sessionStore: new FileSessionStore('./sessions'), autoSave: true }); + * // Later: + * agent.resumeSession('my-session', { sessionStore: new FileSessionStore('./sessions') }); + * ``` + */ + sessionId?: string + /** Automatically save the session to the configured store after each turn (default: false). */ + autoSave?: boolean + /** + * AHP transport configuration for external agent supervision. + * + * Pass an AHP transport instance to enable Agent Harness Protocol supervision. + * All agent lifecycle events will be forwarded to the harness server. + * + * ```js + * // Stdio transport (local child process) + * agent.session('.', { ahpTransport: new StdioTransport('python', ['ahp_server.py']) }); + * + * // HTTP transport (remote server) + * agent.session('.', { ahpTransport: new HttpTransport('http://localhost:8080/ahp') }); + * + * // WebSocket transport (bidirectional streaming) + * agent.session('.', { ahpTransport: new WebSocketTransport('ws://localhost:8080/ahp') }); + * + * // Unix socket transport (local IPC) + * agent.session('.', { ahpTransport: new UnixSocketTransport('/tmp/ahp.sock') }); + * ``` + */ + ahpTransport?: JsAhpTransport + /** + * HITL confirmation policy configuration. + * + * Pass a confirmation policy to enable Human-in-the-Loop confirmation for tool execution. + * When enabled, tools that require confirmation will emit ConfirmationRequired events + * and wait for user approval before executing. + * + * ```js + * agent.session('.', { + * confirmationPolicy: { + * enabled: true, + * defaultTimeoutMs: 30000, + * timeoutAction: 'reject' + * } + * }); + * ``` + */ + confirmationPolicy?: ConfirmationPolicy + /** + * Maximum execution time in milliseconds. + * + * When set, the execution loop will abort if it exceeds this duration. + * This prevents runaway executions and excessive API costs. + * + * ```js + * agent.session('.', { + * maxExecutionTimeMs: 300000 // 5 minutes + * }); + * ``` + */ + maxExecutionTimeMs?: number +} +/** Retention limits for large tool/program artifacts. */ +export interface ArtifactStoreLimits { + /** Maximum number of artifacts retained by a session. */ + maxArtifacts?: number + /** Maximum total artifact content bytes retained by a session. */ + maxBytes?: number +} +/** A single message in conversation history. */ +export interface MessageObject { + role: string + content: Array +} +/** A content block within a message. */ +export interface ContentBlockObject { + type: string + /** Text content (for "text" blocks). */ + text?: string + /** Tool use ID (for "tool_use" blocks). */ + id?: string + /** Tool name (for "tool_use" blocks). */ + name?: string + /** Tool input (for "tool_use" blocks). */ + input?: any + /** Tool use ID reference (for "tool_result" blocks). */ + toolUseId?: string + /** Tool result content (for "tool_result" blocks). */ + resultContent?: string + /** Whether this is an error result (for "tool_result" blocks). */ + isError?: boolean +} +/** An image attachment for multi-modal prompts. */ +export interface AttachmentObject { + /** Raw image bytes. */ + data: Buffer + /** MIME type (e.g., "image/jpeg", "image/png"). */ + mediaType: string +} +/** + * Configuration for the optional advanced session lane queue. + * + * Ordinary sessions do not initialize queue infrastructure. Use this only for + * explicit external/hybrid dispatch, priority experiments, or operational integrations. + */ +export interface SessionQueueConfig { + /** Max concurrency for Query lane (default: 4). */ + queryConcurrency?: number + /** Max concurrency for Execute lane (default: 2). */ + executeConcurrency?: number + /** Max concurrency for Generate lane (default: 1). */ + generateConcurrency?: number + /** Enable dead letter queue. */ + enableDlq?: boolean + /** Max DLQ size (default: 1000). */ + dlqMaxSize?: number + /** Enable metrics collection. */ + enableMetrics?: boolean + /** Enable queue alerts. */ + enableAlerts?: boolean + /** Default command timeout (ms). */ + timeoutMs?: number + /** Enable all features with sensible defaults. */ + enableAllFeatures?: boolean + /** + * Per-lane handler config. Keys: "control", "query", "execute", "generate". + * Values: LaneHandlerConfig with mode ("internal"/"external"/"hybrid") and timeoutMs. + */ + laneHandlers?: Record +} +/** Result of an external task completion. */ +export interface ExternalTaskResult { + success: boolean + result?: any + error?: string +} +/** Lane handler configuration. */ +export interface LaneHandlerConfig { + /** "internal", "external", or "hybrid" */ + mode: string + /** Timeout for external processing (ms). */ + timeoutMs?: number +} +/** Queue statistics. */ +export interface QueueStats { + totalPending: number + totalActive: number + externalPending: number +} +export interface McpServerStatusEntry { + name: string + connected: boolean + toolCount: number + error?: string +} +/** MCP server metadata exposed to slash command handlers. */ +export interface CommandMcpServerInfo { + /** MCP server name. */ + name: string + /** Number of tools currently exposed by the server. */ + toolCount: number +} +/** Context passed to custom slash command handlers. */ +export interface CommandContext { + /** Current session ID. */ + sessionId: string + /** Current workspace path. */ + workspace: string + /** Current active model identifier. */ + model: string + /** Number of messages in session history. */ + historyLen: number + /** Total tokens used in this session so far. */ + totalTokens: number + /** Estimated session cost in USD. */ + totalCost: number + /** Registered tool names (builtin + MCP). */ + toolNames: Array + /** Connected MCP servers and their tool counts. */ + mcpServers: Array +} +/** Metadata about a registered slash command. */ +export interface CommandInfo { + /** Command name without the leading `/` (e.g., `"help"`, `"model"`) */ + name: string + /** Short description shown in `/help` */ + description: string + /** Optional usage hint (e.g., `"/model "`) */ + usage?: string +} +/** Matcher for filtering which events trigger a hook. */ +export interface HookMatcherObject { + /** Match specific tool name (exact match) */ + tool?: string + /** Match file path pattern (glob) */ + pathPattern?: string + /** Match command pattern (regex for Bash commands) */ + commandPattern?: string + /** Match session ID (exact match) */ + sessionId?: string + /** Match skill name (supports glob patterns) */ + skill?: string +} +/** Configuration for a hook. */ +export interface HookConfigObject { + /** Priority (lower values = higher priority, default: 100) */ + priority?: number + /** Timeout in milliseconds (default: 30000) */ + timeoutMs?: number + /** Whether to execute asynchronously (fire-and-forget) */ + asyncExecution?: boolean + /** Maximum retry attempts */ + maxRetries?: number +} +/** Metadata about a built-in skill. */ +export interface SkillInfo { + name: string + description: string + /** Skill kind: "instruction", "tool", or "agent". */ + kind: string +} +/** + * Return a list of built-in skills compiled into the library. + * + * Each entry has `name`, `description`, and `kind` (instruction, tool, or agent). + */ +export declare function builtinSkills(): Array +/** Configuration for a search engine. */ +export interface SearchEngineConfig { + enabled: boolean + weight: number + timeout?: number +} +/** Browser backend for headless search. */ +export const enum BrowserBackend { + /** Chrome/Chromium headless. */ + Chrome = 0, + /** Lightpanda headless browser (Linux/macOS only). */ + Lightpanda = 1 +} +/** Headless browser configuration. */ +export interface HeadlessConfig { + backend: BrowserBackend + browserPath?: string + maxTabs?: number + launchArgs?: Array + proxyUrl?: string +} +/** Health monitor configuration for search engines. */ +export interface SearchHealthConfig { + maxFailures: number + suspendSeconds: number +} +/** Search engine configuration (a3s-search integration). */ +export interface SearchConfig { + timeout: number + health?: SearchHealthConfig + engines: Record + headless?: HeadlessConfig +} +/** Streaming event iterator. Use `for await (const event of stream)` or call `.next()` manually. */ +export declare class EventStream { + /** + * Get the next event from the stream. + * + * Returns `{ value: AgentEvent | null, done: boolean }`. + * When `done` is true, the stream is exhausted. + */ + next(): Promise +} +/** + * File-backed long-term memory store. + * + * ```js + * agent.session('.', { memoryStore: new FileMemoryStore('./memory') }); + * ``` + */ +export declare class FileMemoryStore { + backend: string + dir: string + /** Create a file-backed memory store at `dir`. */ + constructor(dir: string) +} +/** + * File-backed session store (persists sessions to disk for later resumption). + * + * ```js + * agent.session('.', { + * sessionStore: new FileSessionStore('./sessions'), + * sessionId: 'my-session', + * autoSave: true, + * }); + * ``` + */ +export declare class FileSessionStore { + backend: string + dir: string + /** Create a file-backed session store at `dir`. */ + constructor(dir: string) +} +/** + * In-memory (non-persistent) session store. + * + * Useful for testing, ephemeral runs, and CI pipelines where no disk state is needed. + * + * ```js + * agent.session('.', { sessionStore: new MemorySessionStore() }); + * ``` + */ +export declare class MemorySessionStore { + backend: string + constructor() +} +/** + * Default security provider: input taint tracking + output sanitisation. + * + * ```js + * agent.session('.', { securityProvider: new DefaultSecurityProvider() }); + * ``` + */ +export declare class DefaultSecurityProvider { + kind: string + constructor() +} +/** + * Local filesystem workspace backend. + * + * This is the explicit typed form of the default local workspace behavior. + * It is useful when callers want to pass workspace backends through the same + * option surface that remote/browser backends will use. + * + * ```js + * agent.session('/repo', { workspaceBackend: new LocalWorkspaceBackend('/repo') }); + * ``` + */ +export declare class LocalWorkspaceBackend { + kind: string + root: string + /** Create a local filesystem workspace backend rooted at `root`. */ + constructor(root: string) +} +/** + * S3-compatible object-storage workspace backend. + * + * Points built-in file tools (`read`, `write`, `edit`, `patch`, `ls`) at an + * S3-compatible bucket. Works with AWS S3, MinIO, RustFS, Cloudflare R2, + * Backblaze B2, and other S3-API-compatible services. + * + * `bash`, `git`, `grep`, and `glob` are intentionally **not** registered + * when this backend is in use — object storage cannot service them. + * + * ```js + * const backend = new S3WorkspaceBackend({ + * endpoint: 'https://minio.local:9000', + * region: 'us-east-1', + * accessKeyId: 'AKIA...', + * secretAccessKey: '...', + * bucket: 'workspace', + * prefix: 'users/u1/sessions/s1', + * forcePathStyle: true, + * }); + * agent.session('s3://workspace/users/u1/sessions/s1', { workspaceBackend: backend }); + * ``` + */ +export declare class S3WorkspaceBackend { + kind: string + s3: JsS3BackendConfig + /** Create an S3-compatible workspace backend. */ + constructor(config: JsS3BackendConfig) +} +/** + * Stdio transport for AHP (Agent Harness Protocol). + * + * Launches a child process and communicates via stdin/stdout using JSON-RPC 2.0. + * + * ```js + * agent.session('.', { + * ahpTransport: new StdioTransport('python', ['ahp_server.py']) + * }); + * ``` + */ +export declare class StdioTransport { + kind: string + program?: string + args?: Array + url?: string + authToken?: string + path?: string + constructor(program: string, args: Array) +} +/** + * HTTP transport for AHP (Agent Harness Protocol). + * + * Connects to a remote AHP harness server via HTTP. + * + * ```js + * agent.session('.', { + * ahpTransport: new HttpTransport('http://localhost:8080/ahp') + * }); + * ``` + */ +export declare class HttpTransport { + kind: string + program?: string + args?: Array + url?: string + authToken?: string + path?: string + constructor(url: string, authToken?: string | undefined | null) +} +/** + * WebSocket transport for AHP (Agent Harness Protocol). + * + * Connects to a remote AHP harness server via WebSocket for bidirectional streaming. + * + * ```js + * agent.session('.', { + * ahpTransport: new WebSocketTransport('ws://localhost:8080/ahp') + * }); + * ``` + */ +export declare class WebSocketTransport { + kind: string + program?: string + args?: Array + url?: string + authToken?: string + path?: string + constructor(url: string, authToken?: string | undefined | null) +} +/** + * Unix socket transport for AHP (Agent Harness Protocol). + * + * Connects to a local AHP harness server via Unix domain socket. + * + * ```js + * agent.session('.', { + * ahpTransport: new UnixSocketTransport('/tmp/ahp.sock') + * }); + * ``` + */ +export declare class UnixSocketTransport { + kind: string + program?: string + args?: Array + url?: string + authToken?: string + path?: string + constructor(path: string) +} +/** AI coding agent. Create with `Agent.create()`, then call `agent.session()`. */ +export declare class Agent { + /** + * Create an Agent from a config file path or inline config string. + * + * Accepts ACL-compatible config files (.acl) or inline config strings. + * JSON config is not supported. + * + * @param configSource - Path to a config file (.acl), or inline config string + */ + static create(configSource: string): Promise + /** + * Re-fetch tool definitions from all connected global MCP servers and + * update the agent-level cache. + * + * New sessions created after this call will see the refreshed tool list. + * Existing sessions are unaffected. + */ + refreshMcpTools(): Promise + /** + * Bind to a workspace directory, returning a Session. + * + * @param workspace - Path to the workspace directory + * @param options - Optional session overrides + */ + session(workspace: string, options?: SessionOptions | undefined | null): Session + /** + * Resume a previously saved session by ID. + * + * `options.sessionStore` must be set to a `FileSessionStore` (or `MemorySessionStore`) + * that points to the directory where the session was originally saved. + * + * ```js + * const session = agent.resumeSession('my-session', { + * sessionStore: new FileSessionStore('./sessions'), + * }); + * ``` + * + * @param sessionId - The session ID to resume + * @param options - Session options; `sessionStore` is required + */ + resumeSession(sessionId: string, options: SessionOptions): Session + /** + * Create a session pre-configured from a named agent definition. + * + * Loads the agent by name from built-in agents and optionally from + * additional directories, then creates a session with the agent's + * permissions, system prompt, model, and step limit applied. + * + * @param workspace - Path to the workspace directory + * @param agentName - Name of the agent to load (e.g. "explore", "general") + * @param agentDirs - Optional directories to scan for agent files + * @param options - Optional session overrides layered on top of the agent definition + */ + sessionForAgent(workspace: string, agentName: string, agentDirs?: Array | undefined | null, options?: SessionOptions | undefined | null): Session + /** + * Create a session pre-configured from a disposable worker spec. + * + * This avoids writing temporary agent files for one-off cattle workers. + * + * @param workspace - Path to the workspace directory + * @param worker - Worker spec to compile into an agent definition + * @param options - Optional session overrides layered on top of the worker definition + */ + sessionForWorker(workspace: string, worker: WorkerAgentSpec, options?: SessionOptions | undefined | null): Session +} +/** Workspace-bound session. All LLM and tool operations happen here. */ +export declare class Session { + /** + * Send a prompt or request and wait for the complete response. + * + * `send("prompt")` is the compact prompt-first form. `send({ prompt, + * history, attachments })` is the compact object-shaped form for growth. + */ + send(request: string | SessionRequestOptions, history?: Array | null): Promise + /** Alias for `send(...)` with a name that matches run/replay terminology. */ + run(request: string | SessionRequestOptions, history?: Array | null): Promise + /** + * Send a prompt or request and get a streaming event iterator. + * + * Returns an `EventStream`. Use `for await (const event of stream)` or call `.next()` manually. + * When `history` is omitted, the session history and verification evidence are + * updated after the stream completes. Supplying `history` keeps the stream isolated. + */ + stream(request: string | SessionRequestOptions, history?: Array | null): Promise + /** + * Send a request using the long-lived object-shaped API. + * + * Prefer this for new integrations when the call may need history, + * attachments, or future request options. + */ + sendRequest(request: SessionRequestOptions): Promise + /** Stream a request using the long-lived object-shaped API. */ + streamRequest(request: SessionRequestOptions): Promise + /** + * Send a prompt with image attachments and wait for the complete response. + * + * @param prompt - The prompt to send + * @param attachments - Array of `{ data: Buffer, mediaType: string }` + * @param history - Optional conversation history + */ + sendWithAttachments(prompt: string, attachments: Array, history?: Array | undefined | null): Promise + /** + * Stream a prompt with image attachments. + * + * When `history` is omitted, the session history and verification evidence are + * updated after the stream completes. Supplying `history` keeps the stream isolated. + * + * @param prompt - The prompt to send + * @param attachments - Array of `{ data: Buffer, mediaType: string }` + * @param history - Optional conversation history + */ + streamWithAttachments(prompt: string, attachments: Array, history?: Array | undefined | null): Promise + /** Return the session's conversation history. */ + history(): Array + /** Return run snapshots recorded by this session. */ + runs(): Promise + /** Return a run snapshot by ID, or null when it is unknown. */ + runSnapshot(runId: string): Promise + /** Return recorded runtime events for a run. */ + runEvents(runId: string): Promise + /** Return the currently running operation, or null when idle. */ + currentRun(): Promise + /** Return active tool calls observed for the currently running operation. */ + activeTools(): Promise + /** + * Look up a delegated subagent task by id. Resolves to `null` when no + * such task has been observed in this session. + */ + subagentTask(taskId: string): Promise + /** + * Return snapshots of every delegated subagent task observed in this + * session (including completed and failed ones), oldest first. + */ + subagentTasks(): Promise + /** Return snapshots of subagent tasks still in `running` state. */ + pendingSubagentTasks(): Promise + /** Cancel a specific run only if it is still the active run. */ + cancelRun(runId: string): Promise + /** Execute a tool by name, bypassing the LLM. */ + tool(name: string, args: any): Promise + /** Delegate a bounded task to a child agent through the built-in `task` tool. */ + task(options: DelegateTaskOptions): Promise + /** Delegate a bounded task to a child agent through the built-in `task` tool. */ + delegateTask(options: DelegateTaskOptions): Promise + /** Execute several delegated child-agent tasks concurrently through `parallel_task`. */ + tasks(tasks: DelegateTaskOptions[]): Promise + /** Execute several delegated child-agent tasks concurrently through `parallel_task`. */ + parallelTask(tasks: DelegateTaskOptions[]): Promise + /** Run a bounded JavaScript script through the embedded QuickJS `program` tool. */ + program(options: ProgramScriptOptions): Promise + /** Read a file from the workspace. */ + readFile(path: string): Promise + /** Write a file in the workspace. */ + writeFile(path: string, content: string): Promise + /** List a directory in the workspace. */ + ls(path?: string | undefined | null): Promise + /** Edit a file by replacing text in the workspace. */ + editFile(path: string, oldString: string, newString: string, replaceAll?: boolean | undefined | null): Promise + /** Apply a unified diff patch to a workspace file. */ + patchFile(path: string, diff: string): Promise + /** Execute a bash command in the workspace. */ + bash(command: string): Promise + /** Search for files matching a glob pattern. */ + glob(pattern: string): Promise> + /** Search file contents with a regex pattern. */ + grep(pattern: string): Promise + /** Search the web using multiple search engines. */ + webSearch(params: JsWebSearchParams): Promise + /** + * Execute a git command. + * + * Prefer `git({ command: "status" })`; positional arguments remain for + * compatibility. + */ + 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 + /** + * Execute a git command with an object-shaped API. + * + * Preferred over the positional `git(...)` overload for new callers. + * + * ```js + * await session.gitCommand({ command: 'status' }) + * await session.gitCommand({ command: 'worktree', subcommand: 'list' }) + * ``` + */ + gitCommand(args: GitCommandOptions): Promise + /** Check if this session has an advanced lane queue configured. */ + hasQueue(): boolean + /** + * Configure a lane's handler mode for explicit external/hybrid dispatch. + * + * @param lane - "control", "query", "execute", or "generate" + * @param config - { mode: "internal"|"external"|"hybrid", timeoutMs?: number } + */ + setLaneHandler(lane: string, config: LaneHandlerConfig): Promise + /** + * Complete an external queue task by ID. + * + * @param taskId - The task identifier + * @param result - { success: boolean, result?: any, error?: string } + * @returns true if found, false if not found + */ + completeExternalTask(taskId: string, result: ExternalTaskResult): Promise + /** Get pending external queue tasks. */ + pendingExternalTasks(): Promise + /** Return pending HITL tool confirmations for this session. */ + pendingConfirmations(): Promise> + /** + * Resolve a pending HITL tool confirmation. + * + * @param toolId - Tool call ID from a `confirmation_required` event. + * @param approved - Whether the tool execution should proceed. + * @param reason - Optional human-readable reason for audit/UI display. + * @returns true if a pending confirmation was found and completed. + */ + confirmToolUse(toolId: string, approved: boolean, reason?: string | undefined | null): Promise + /** Cancel all pending HITL confirmations for this session. */ + cancelConfirmations(): Promise + /** Get optional queue statistics. */ + queueStats(): Promise + /** Return compact execution trace events recorded for this session. */ + traceEvents(): any + /** Return structured verification reports recorded for this session. */ + verificationReports(): any + /** Add externally produced verification reports to this session. */ + recordVerificationReports(reports: any): void + /** Return a structured verification summary for this session. */ + verificationSummary(): any + /** Return a concise human-readable verification summary for this session. */ + verificationSummaryText(): string + /** Run verification commands and return a structured verification report. */ + verifyCommands(subject: string, commands: Array): Promise + /** Return project-aware verification command presets for this workspace. */ + verificationPresets(): any + /** Get dead letters from the optional queue's DLQ. */ + deadLetters(): Promise + /** + * Get a detailed metrics snapshot from the queue. + * + * Returns `null` if metrics are not enabled (queue not configured or + * `enable_metrics` was not set in `SessionQueueConfig`). + * + * @returns Object with `counters`, `gauges`, and `histograms` maps, or null + */ + queueMetrics(): Promise + /** + * Add an MCP server to this live session. + * + * Connects the server and registers all its tools immediately so the agent + * can call them. Tool names follow the convention `mcp____`. + * + * @param name - Server identifier (used as prefix in tool names) + * @param transport - Transport type: `"stdio"` (default), `"http"`, or `"streamable-http"` + * @param command - Executable to launch (stdio only, e.g. `"npx"`) + * @param args - Arguments for the command (stdio only) + * @param url - Server URL (http / streamable-http only) + * @param headers - HTTP headers (http / streamable-http only) + * @param env - Optional extra environment variables (stdio only) + * @returns Number of tools registered from the server + */ + addMcpServer(name: string, transport?: 'stdio' | 'http' | 'streamable-http', command?: string | undefined | null, args?: Array | undefined | null, url?: string | undefined | null, headers?: Record | undefined | null, env?: Record | undefined | null, timeoutMs?: number | undefined | null): Promise + /** + * Add an MCP server with a typed object config. + * + * Preferred over the positional overload for new SDK callers. + * + * ```js + * await session.addMcpServerConfig({ + * name: 'github', + * transport: { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] }, + * env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }, + * timeoutMs: 30000, + * }) + * ``` + */ + addMcpServerConfig(config: McpServerConfig): Promise + /** Add an MCP server with the compact object-shaped API. */ + addMcp(config: McpServerConfig): Promise + /** + * Dynamically register agent definitions from a directory into the live session. + * + * Scans the directory for `*.yaml`, `*.yml`, and `*.md` agent definition files + * and registers them into the shared AgentRegistry used by the `task` tool. + * New agents are immediately callable via `task({ agent: "…", … })` without + * restarting the session. + * + * @param path - Directory to scan for agent definition files + * @returns Number of agents successfully loaded + */ + registerAgentDir(path: string): number + /** + * Register a disposable worker agent into the live session. + * + * The worker is immediately callable through the model-visible `task` tool. + * + * @param worker - Worker spec to register + * @returns Compiled agent definition + */ + registerWorkerAgent(worker: WorkerAgentSpec): AgentDefinition + /** + * Register many disposable workers into the live session. + * + * @param workers - Worker specs to register + * @returns Compiled agent definitions + */ + registerWorkerAgents(workers: Array): Array + /** + * Disconnect and unregister an MCP server, removing its tools from the session. + * + * @param name - Server name (must match the name used in addMcpServer) + */ + removeMcpServer(name: string): Promise + /** Remove an MCP server with the compact API. */ + removeMcp(name: string): Promise + /** + * Return connection status for all MCP servers registered on this session. + * + * @returns Array of `{ name, connected, toolCount }` entries + */ + mcpStatus(): Promise> + /** Return MCP server status with the compact API. */ + mcps(): Promise> + /** + * Return the names of all tools currently registered on this session. + * + * @returns Array of tool name strings + */ + toolNames(): Array + /** Return full model-visible tool definitions currently registered on this session. */ + toolDefinitions(): any + /** Return a stored tool artifact by URI, or null if it is not retained. */ + getArtifact(artifactUri: string): any + /** + * Register a hook for lifecycle event interception. + * + * Hooks registered on a session are automatically propagated to all sub-agents + * spawned by the `task` tool, including grandchild agents at arbitrary depth. + * This ensures security hooks (e.g. a sentinel) apply across the full agent tree + * without requiring explicit registration on each sub-agent session. + * + * @param hookId - Unique hook identifier + * @param eventType - Event type: "pre_tool_use", "post_tool_use", "generate_start", + * "generate_end", "session_start", "session_end", "skill_load", "skill_unload", + * "pre_prompt", "post_response", "on_error" + * @param matcher - Optional matcher: { tool?, pathPattern?, commandPattern?, sessionId?, skill? } + * @param config - Optional config: { priority?, timeoutMs?, asyncExecution?, maxRetries? } + * @param handler - Optional callback `(event: any) => { action: 'continue' | 'block' | 'skip', + * reason?: string } | null`. When provided, the function is called for every matching event + * and its return value controls execution. Return `{ action: 'block', reason: '...' }` to + * cancel the operation, `{ action: 'skip' }` to skip remaining hooks, or `null`/`undefined` + * for continue. Hooks with no handler still fire (observable via stream events) but always + * continue. + */ + registerHook(hookId: string, eventType: string, matcher?: HookMatcherObject | undefined | null, config?: HookConfigObject | undefined | null, handler?: ((event: Record) => { action: string; reason?: string } | null | undefined) | null | undefined): void + /** + * Unregister a hook by ID. + * + * @param hookId - The hook identifier to remove + * @returns true if the hook was found and removed + */ + unregisterHook(hookId: string): boolean + /** Get the number of registered hooks. */ + hookCount(): number + /** Return the session ID. */ + get sessionId(): string + /** Return the workspace path. */ + get workspace(): string + /** Return any deferred init warning (e.g. memory store failed to initialize). */ + get initWarning(): string | null + /** Save the session to the configured store. */ + save(): Promise + /** Check if memory is configured for this session. */ + get hasMemory(): boolean + /** + * Remember a successful task execution. + * + * @param task - Description of the task + * @param tools - List of tool names used + * @param result - Summary of the result + */ + rememberSuccess(task: string, tools: Array, result: string): Promise + /** + * Remember a failed task execution. + * + * @param task - Description of the task + * @param error - Error message + * @param tools - List of tool names attempted + */ + rememberFailure(task: string, error: string, tools: Array): Promise + /** + * Recall memories similar to a query. + * + * @param query - Search query + * @param limit - Maximum number of results (default: 5) + * @returns Array of memory items + */ + recallSimilar(query: string, limit?: number | undefined | null): Promise + /** + * Recall memories by tags. + * + * @param tags - Tags to search for + * @param limit - Maximum number of results (default: 10) + * @returns Array of memory items + */ + recallByTags(tags: Array, limit?: number | undefined | null): Promise + /** + * Get recent memory items. + * + * @param limit - Maximum number of results (default: 10) + * @returns Array of memory items + */ + memoryRecent(limit?: number | undefined | null): Promise + /** + * Get memory statistics. + * + * @returns Object with longTermCount, shortTermCount, workingCount + */ + memoryStats(): Promise + /** + * Get current working memory items. + * + * Working memory holds the active context items for the current task. + * + * @returns Array of memory items currently in working memory + */ + getWorking(): Promise + /** + * Clear working memory. + * + * Removes all items from working memory without affecting short-term or long-term memory. + */ + clearWorking(): Promise + /** + * Get current short-term memory items. + * + * Short-term memory contains items stored during this session. + * + * @returns Array of memory items in short-term memory + */ + getShortTerm(): Promise + /** + * Clear short-term memory for this session. + * + * Removes all session-scoped memory items without affecting long-term or working memory. + */ + clearShortTerm(): Promise + /** + * Register a custom slash command. + * + * Slash commands are invoked via `session.send("/command args")` and execute + * before the LLM sees the input. The handler receives the command arguments + * and a context object with session metadata. + * + * @param name - Command name without the leading `/` (e.g., `"status"`) + * @param description - Short description shown in `/help` + * @param handler - Callback `(args: string, ctx: CommandContext) => string` + * + * @example + * ```typescript + * session.registerCommand("status", "Show session info", (args, ctx) => { + * return `Session ${ctx.sessionId} in ${ctx.workspace}`; + * }); + * await session.send("/status"); + * ``` + */ + registerCommand(name: string, description: string, handler: (args: string, ctx: CommandContext) => string): void + /** + * List all registered slash commands. + * + * Returns each command's name, description, and optional usage hint. + * Slash commands can be invoked via `session.send("/command args")`. + * + * @returns Array of CommandInfo objects sorted by name + */ + listCommands(): Array + /** + * Cancel the current ongoing operation (send/stream). + * + * If an operation is in progress, this will trigger cancellation of the LLM streaming + * and tool execution. The operation will terminate as soon as possible. + * + * @returns `true` if an operation was cancelled, `false` if no operation was in progress + */ + cancel(): boolean + /** + * Close the session and cancel any active operation. + * + * Call this when the session will no longer be used so Node.js can exit + * cleanly without waiting on session-scoped background workers. + */ + close(): void +} diff --git a/sdk/node/index.d.ts b/sdk/node/index.d.ts index d8dd9ed..6214736 100644 --- a/sdk/node/index.d.ts +++ b/sdk/node/index.d.ts @@ -1,1549 +1,13 @@ -/* tslint:disable */ -/* eslint-disable */ - -/* auto-generated by NAPI-RS */ - -/** AHP event type. */ -export interface AhpEventType { - /** Event type string: "handshake", "pre_action", "post_action", "pre_prompt", "post_response", "session_start", "session_end", "error", "query", "heartbeat", "idle" */ - eventType: string -} -/** A factual memory item. */ -export interface AhpFact { - content: string - source: string - confidence: number -} -/** Memory state summary. */ -export interface AhpMemorySummary { - memoryType: string - totalItems: number - recentTopics: Array -} -/** Session statistics. */ -export interface AhpSessionStats { - totalActions: number - totalTokens: number - durationMs: number - errorCount: number -} -/** Decision from harness for idle events. */ -export interface AhpIdleDecision { - /** Decision string: "allow" or "defer" */ - decision: string - /** Reason if deferred */ - reason?: string -} -/** Context passed with AHP events. */ -export interface AhpEventContext { - recentFacts?: Array - memorySummary?: AhpMemorySummary - sessionStats?: AhpSessionStats - currentTask?: string - capabilities?: Record -} -export interface AgentResult { - text: string - toolCallsCount: number - promptTokens: number - completionTokens: number - totalTokens: number - verificationStatus: string - pendingVerificationCount: number - failedVerificationCount: number - verificationReportCount: number - verificationSummaryJson: string - verificationSummaryText: string -} -export declare function formatVerificationSummary(summary: any): string -export interface AgentEvent { - type: string - text?: string - toolName?: string - toolId?: string - toolOutput?: string - exitCode?: number - turn?: number - prompt?: string - error?: string - totalTokens?: number - verificationSummaryJson?: string - verificationSummaryText?: string - /** Extra data for events that don't map to standard fields (JSON-encoded) */ - data?: string - /** - * Structured discriminant for tool failures on `tool_end` events - * (JSON-encoded with a `type` field). `None` on success or untyped - * failure. Lets streaming consumers branch on the failure kind - * without scanning `tool_output`. - */ - errorKindJson?: string -} -export interface VerificationCommand { - id: string - kind: string - description: string - command: string - required?: boolean - timeoutMs?: number -} -export type VerificationStatus = 'passed' | 'failed' | 'needs_review' | 'skipped' -export interface VerificationCheck { - id: string - kind: string - description: string - status: VerificationStatus - required?: boolean - suggested_tools?: Array - evidence_uris?: Array - residual_risk?: string -} -export interface VerificationReport { - schema: string - subject: string - status: VerificationStatus - checks: Array - residual_risks?: Array -} -export interface ToolArtifact { - artifact_id: string - artifact_uri: string - tool_name: string - content: string - original_bytes: number - shown_bytes: number -} -export interface ToolResult { - name: string - output: string - exitCode: number - /** Raw JSON-encoded tool metadata returned by the Rust core API. */ - metadataJson?: string - /** Convenience JSON view of `metadata.document_runtime` when present. */ - documentRuntimeJson?: string - /** - * Structured discriminant for tool failures, JSON-encoded with a - * `type` field on the top level — e.g. - * `{"type":"version_conflict","path":"doc.md","expected":"etag-1","actual":"etag-2"}`. - * `None` on success or untyped failure. SDK callers parse it to - * branch on the failure kind without scanning the `output` string. - */ - errorKindJson?: string -} - /** - * Parsed shape of `ToolResult.errorKindJson` / `AgentEvent.errorKindJson`. + * Entry point for `@a3s-lab/code` type declarations. * - * Use a discriminated union on the `type` field; new variants may be - * added in future minor releases — callers should match exhaustively on - * the kinds they care about and fall through to a default branch for - * unknown ones. - */ -export type ToolErrorKind = - | { type: 'version_conflict'; path: string; expected: string; actual: string | null } - | { type: 'remote_git_conflict'; code: string; message: string } - | { type: 'not_found'; path: string } - | { type: 'invalid_argument'; message: string } - | { type: 'unsupported'; message: string } - | { type: 'timeout'; op: string; duration_ms: number } - -/** Execution limits for `Session.program`. */ -export interface ProgramScriptLimits { - timeoutMs?: number - maxToolCalls?: number - maxOutputBytes?: number -} -/** Options for `Session.program`. */ -export interface ProgramScriptOptions { - source?: string - path?: string - inputs?: any - allowedTools?: Array - limits?: ProgramScriptLimits -} -/** Options for `Session.delegateTask`. */ -export interface DelegateTaskOptions { - agent: string - description: string - prompt: string - background?: boolean - maxSteps?: number -} -/** Object-shaped request for `Session.sendRequest` and `Session.streamRequest`. */ -export interface SessionRequestOptions { - prompt: string - history?: Array - attachments?: Array -} -export interface GitCommandOptions { - command: string - subcommand?: string - name?: string - path?: string - newBranch?: boolean - base?: string - force?: boolean - maxCount?: number - message?: string - includeUntracked?: boolean - target?: string - ref?: string - reference?: string -} -/** Parameters for the web_search tool. */ -export interface JsWebSearchParams { - /** The search query. */ - query: string - /** List of search engines to use. */ - engines?: Array - /** Maximum number of results to return (default: 10, max: 50). */ - limit?: number - /** Search timeout in seconds (default: 10, max: 60). */ - timeout?: number - /** Proxy URL (e.g., http://127.0.0.1:8080 or socks5://127.0.0.1:1080). */ - proxy?: string - /** Output format: "text" or "json". */ - format?: string -} -/** Result of a single `EventStream.next()` call. */ -export interface NextResult { - value?: AgentEvent - done: boolean -} -/** - * An inline skill registered programmatically (no file required). - * - * Use `kind: "instruction"` for prompt injections or `kind: "persona"` to - * replace the default role section of the system prompt. - */ -export interface InlineSkill { - /** Unique skill name (kebab-case recommended, e.g. "type-hints"). */ - name: string - /** Skill kind: `"instruction"` or `"persona"`. */ - kind: string - /** Markdown content for the skill. */ - content: string -} -export interface JsMemoryStore { - backend: string - dir?: string -} -export interface JsSessionStore { - backend: string - dir?: string -} -export interface JsSecurityProvider { - kind: string -} -export interface JsWorkspaceBackend { - kind: string - root?: string - s3?: JsS3BackendConfig -} -/** - * Configuration for an S3-compatible workspace backend. - * - * Use this with [`S3WorkspaceBackend`] to point a session's built-in file - * tools at any S3-compatible endpoint (AWS S3, MinIO, RustFS, R2, etc.). - * `endpoint` is optional — omit it to use the AWS default. `prefix` is - * the logical workspace root inside the bucket; every workspace path - * becomes `/` when sent to S3. - */ -export interface JsS3BackendConfig { - /** - * Optional S3 endpoint URL. Omit for AWS S3 (the SDK will compute it - * from `region`). Set to `https://...` for MinIO / RustFS / R2 / etc. - */ - endpoint?: string - /** AWS region. Defaults to `us-east-1` when omitted. */ - region?: string - /** Static access key. Use `sessionToken` together when STS-issued. */ - accessKeyId: string - secretAccessKey: string - sessionToken?: string - /** Bucket name. */ - bucket: string - /** - * Logical workspace prefix inside the bucket (without leading/trailing - * slashes). Use `""` to make the bucket root the workspace. - */ - prefix: string - /** `true` for MinIO / RustFS / most non-AWS endpoints; `false` for AWS S3. */ - forcePathStyle?: boolean - /** - * Maximum bytes a single `read` may return. The backend rejects any - * response with `Content-Length` greater than this without buffering - * the body. Defaults to 10 MiB on the Rust side when omitted. - */ - maxReadBytes?: number - /** - * Enable degraded `grep` / `glob` against this S3 backend. Off by - * default — object storage has no native search, so the only viable - * strategy is `LIST` + `GET` + regex, which can be slow and expensive. - */ - searchEnabled?: boolean - /** - * Upper bound on objects considered per `grep` / `glob` call. Defaults - * to 500 on the Rust side. Ignored when `searchEnabled` is `false`. - */ - maxObjectsScanned?: number - /** - * Per-object body-size ceiling for `grep` downloads. Larger objects are - * skipped (debug-traced). Defaults to 1 MiB on the Rust side. Ignored - * when `searchEnabled` is `false`. - */ - maxGrepBytesPerObject?: number - /** - * Concurrent object downloads during `grep`. Defaults to 8 on the - * Rust side. Set lower when the gitserver / S3 endpoint rate-limits - * aggressively; set higher when latency dominates. Ignored when - * `searchEnabled` is `false`. - */ - searchConcurrency?: number -} -/** - * Configuration for a [`RemoteGitBackend`] — an HTTP/JSON client that - * brings the `git` tool to non-local workspaces (S3, future container / - * DFS). - * - * Pass alongside `workspaceBackend` on a session to attach remote git - * on top of any filesystem backend. The protocol is specified in the - * repository RFC `apps/docs/content/docs/en/code/rfcs/workspace-remote-git.mdx`. - */ -export interface JsRemoteGitBackendConfig { - /** - * Base URL of the gitserver, no trailing slash. The client builds - * `{baseUrl}/v1/repos/{repoId}/git/{op}` per the RFC. - */ - baseUrl: string - /** - * Opaque repository identifier, URL-safe. Negotiated out of band - * with the gitserver operator. - */ - repoId: string - /** - * Bearer token sent as `Authorization: Bearer `. Required in - * production; omitting it emits a `tracing::warn!` and is only safe - * on a trusted localhost gitserver. - */ - bearerToken?: string - /** - * mTLS client certificate path (PEM). When set together with - * `clientKeyPem`, the backend reads both files at construction and - * configures mTLS on the HTTP client. Setting only one of the pair - * errors at construction. - */ - clientCertPem?: string - /** - * mTLS client private key path (PEM). PKCS#8 format expected for the - * `rustls-tls` backend. See `clientCertPem`. - */ - clientKeyPem?: string - /** Per-call HTTP timeout in milliseconds. Defaults to 30 000. */ - requestTimeoutMs?: number - /** Client-side cap on `diff` response bytes. Defaults to 1 MiB. */ - maxDiffBytes?: number - /** Client-side cap on `log` `max_count`. Defaults to 200. */ - maxLogEntries?: number -} -/** - * Union type for AHP transport configuration. - * Accepts any of: StdioTransport, HttpTransport, WebSocketTransport, UnixSocketTransport. - */ -export interface JsAhpTransport { - kind: string - program?: string - args?: Array - url?: string - authToken?: string - path?: string -} -export interface PermissionPolicy { - /** Tool invocation patterns that are always denied first. */ - deny?: Array - /** Tool invocation patterns that are auto-approved. */ - allow?: Array - /** Tool invocation patterns that always require confirmation. */ - ask?: Array - /** Default decision when no rule matches: "allow", "deny", or "ask". */ - defaultDecision?: string - /** Whether this policy is enabled. Defaults to true. */ - enabled?: boolean -} -/** - * Reproducible recipe for a disposable worker/subagent. - * - * This is the Node.js cattle-mode interface: define workers in data, pass them - * to SessionOptions.workerAgents, Agent.sessionForWorker(), or - * Session.registerWorkerAgent(). The Rust core compiles each spec into the - * normal delegated-agent runtime definition. - */ -export interface WorkerAgentSpec { - /** Stable worker name used by task delegation. */ - name: string - /** Human-readable worker purpose. */ - description: string - /** Preset role: "read_only", "planner", "implementer", "verifier", "reviewer", or "custom". */ - kind?: string - /** Hide from UI lists while allowing explicit delegation. */ - hidden?: boolean - /** Optional permission policy override. */ - permissions?: PermissionPolicy - /** Optional model override in "provider/model" format. */ - model?: string - /** Optional worker-specific prompt. */ - prompt?: string - /** Maximum execution steps/tool rounds. */ - maxSteps?: number - /** How child runs resolve Ask decisions: "auto_approve" (default), "deny_on_ask", or "inherit_parent". */ - confirmationInheritance?: string -} -export interface AgentDefinition { - name: string - description: string - native: boolean - hidden: boolean - model?: string - prompt?: string - maxSteps?: number - /** How child runs resolve Ask decisions: "auto_approve", "deny_on_ask", or "inherit_parent". */ - confirmationInheritance?: string -} -/** - * HITL confirmation policy configuration. - * - * Controls the runtime behavior of Human-in-the-Loop confirmation flow. - */ -export interface ConfirmationPolicy { - /** Whether HITL is enabled (default: false, all tools auto-approved). */ - enabled?: boolean - /** Default timeout in milliseconds (default: 30000 = 30s). */ - defaultTimeoutMs?: number - /** Action to take on timeout: "reject" or "auto_approve" (default: "reject"). */ - timeoutAction?: string - /** Lanes that should auto-approve without confirmation: "control", "query", "execute", or "generate". */ - yoloLanes?: Array -} -/** Snapshot of a pending HITL tool confirmation. */ -export interface PendingConfirmation { - /** Tool call ID to pass to `confirmToolUse`. */ - toolId: string - /** Tool name awaiting confirmation. */ - toolName: string - /** Tool arguments for display in a confirmation UI. */ - args: any - /** Milliseconds remaining before the confirmation times out. */ - remainingMs: number -} -export interface AutoDelegationOptions { - /** Enable runtime-driven automatic child-agent delegation. */ - enabled?: boolean - /** - * Allow automatic delegation to launch multiple child agents in parallel. - * - * Manual `parallel_task` calls remain available when this is false. - */ - autoParallel?: boolean - /** Minimum local confidence required to auto-delegate a child task. */ - minConfidence?: number - /** Maximum number of automatic child tasks per user request. */ - maxTasks?: number -} -export interface SessionOptions { - /** Override the default model. Format: "provider/model" (e.g., "openai/gpt-4o"). */ - model?: string - /** Enable built-in skills (4 skills: code-search, code-review, explain-code, find-bugs). */ - builtinSkills?: boolean - /** Extra directories to scan for skill files (.md with YAML frontmatter). */ - skillDirs?: Array - /** Extra directories to scan for agent files. */ - agentDirs?: Array - /** Reproducible disposable workers to register for task delegation. */ - workerAgents?: Array - /** - * Optional advanced queue configuration for explicit external/hybrid lane dispatch. - * - * Ordinary sessions are queue-free unless this is provided. - */ - queueConfig?: SessionQueueConfig - /** Explicit permission policy for tool execution. */ - permissionPolicy?: PermissionPolicy - /** - * Explicit planning mode: "auto", "enabled", or "disabled". - * - * Prefer this over `planning` when the caller needs an unambiguous SDK contract. - * If both are set, `planningMode` wins. - */ - planningMode?: string - /** Legacy planning shortcut. Omit for auto planning, true to force planning, false to disable. */ - planning?: boolean - /** Enable goal tracking (default: false). */ - goalTracking?: boolean - /** Max consecutive parse errors before abort. */ - maxParseRetries?: number - /** Per-tool execution timeout in milliseconds. */ - toolTimeoutMs?: number - /** Max LLM API failures before abort. */ - circuitBreakerThreshold?: number - /** Enable auto-compaction when context window fills up (default: false). */ - autoCompact?: boolean - /** Context usage threshold (0.0–1.0) to trigger auto-compaction (default: 0.8). */ - autoCompactThreshold?: number - /** Retention limits for large tool/program artifacts. */ - artifactStoreLimits?: ArtifactStoreLimits - /** - * Long-term memory store backend. - * - * Pass `new FileMemoryStore("./memory")` for file-based persistence. - * ```js - * agent.session('.', { memoryStore: new FileMemoryStore('./memory') }); - * ``` - */ - memoryStore?: JsMemoryStore - /** - * Session persistence store backend. - * - * Pass `new FileSessionStore("./sessions")` to persist sessions to disk, - * or `new MemorySessionStore()` for an ephemeral in-process store. - * ```js - * agent.session('.', { - * sessionStore: new FileSessionStore('./sessions'), - * sessionId: 'my-session', - * autoSave: true, - * }); - * ``` - */ - sessionStore?: JsSessionStore - /** - * Security provider. - * - * Pass `new DefaultSecurityProvider()` to enable input taint tracking and - * output sanitisation. Omit to disable security (default: no security). - * ```js - * agent.session('.', { securityProvider: new DefaultSecurityProvider() }); - * ``` - */ - securityProvider?: JsSecurityProvider - /** - * Workspace backend used by built-in tools. - * - * Pass `new LocalWorkspaceBackend("/repo")` to explicitly use the local - * filesystem backend. This option is the SDK surface for future remote, - * browser, DFS, and container-backed workspace implementations. - * ```js - * agent.session('/repo', { workspaceBackend: new LocalWorkspaceBackend('/repo') }); - * ``` - */ - workspaceBackend?: JsWorkspaceBackend - /** - * Optional remote git provider. When set, the resulting session attaches - * a `RemoteGitBackend` on top of `workspaceBackend` so the built-in - * `git` tool is available even on object-storage workspaces. - * - * ```js - * agent.session('s3://workspace/u1/s1', { - * workspaceBackend: new S3WorkspaceBackend({ ... }), - * remoteGit: { - * baseUrl: 'https://gitserver.internal', - * repoId: 'u1/s1', - * bearerToken: token, - * }, - * }); - * ``` - */ - remoteGit?: JsRemoteGitBackendConfig - /** - * Custom role/identity prepended before the core agentic prompt. - * Example: "You are a senior Python developer specializing in FastAPI." - */ - role?: string - /** - * Custom coding guidelines appended after the core prompt. - * Example: "Always use type hints. Follow PEP 8." - */ - guidelines?: string - /** Custom response style (replaces default Response Format section). */ - responseStyle?: string - /** Freeform extra instructions appended at the end. */ - extra?: string - /** - * Inline skills registered programmatically without needing skill files on disk. - * Each entry defines an instruction or persona skill injected into the system prompt. - */ - inlineSkills?: Array - /** Override maximum number of tool-call rounds for this session. */ - maxToolRounds?: number - /** Override maximum sibling parallel branches for this session. */ - maxParallelTasks?: number - /** Override automatic child-agent delegation for this session. */ - autoDelegation?: AutoDelegationOptions - /** - * Global session-level kill switch for automatic parallel child-agent fan-out. - * - * Manual `parallel_task` calls remain available when this is false. - */ - autoParallel?: boolean - /** - * Sampling temperature (0.0–1.0). Overrides the provider default. - * Only applied when `model` is also set. - */ - temperature?: number - /** - * Extended thinking token budget (e.g. 10_000). Enables chain-of-thought reasoning. - * Only applied when `model` is also set. Provider must support extended thinking. - */ - thinkingBudget?: number - /** - * Enable continuation injection (default: true). - * When enabled, the loop injects a follow-up prompt when the LLM stops without completing. - */ - continuationEnabled?: boolean - /** Maximum continuation injections per execution (default: 3). */ - maxContinuationTurns?: number - /** - * Session ID (auto-generated if not set). - * - * Set a stable ID so the session can be saved and resumed later: - * ```js - * agent.session('.', { sessionId: 'my-session', sessionStore: new FileSessionStore('./sessions'), autoSave: true }); - * // Later: - * agent.resumeSession('my-session', { sessionStore: new FileSessionStore('./sessions') }); - * ``` - */ - sessionId?: string - /** Automatically save the session to the configured store after each turn (default: false). */ - autoSave?: boolean - /** - * AHP transport configuration for external agent supervision. - * - * Pass an AHP transport instance to enable Agent Harness Protocol supervision. - * All agent lifecycle events will be forwarded to the harness server. - * - * ```js - * // Stdio transport (local child process) - * agent.session('.', { ahpTransport: new StdioTransport('python', ['ahp_server.py']) }); - * - * // HTTP transport (remote server) - * agent.session('.', { ahpTransport: new HttpTransport('http://localhost:8080/ahp') }); - * - * // WebSocket transport (bidirectional streaming) - * agent.session('.', { ahpTransport: new WebSocketTransport('ws://localhost:8080/ahp') }); - * - * // Unix socket transport (local IPC) - * agent.session('.', { ahpTransport: new UnixSocketTransport('/tmp/ahp.sock') }); - * ``` - */ - ahpTransport?: JsAhpTransport - /** - * HITL confirmation policy configuration. - * - * Pass a confirmation policy to enable Human-in-the-Loop confirmation for tool execution. - * When enabled, tools that require confirmation will emit ConfirmationRequired events - * and wait for user approval before executing. - * - * ```js - * agent.session('.', { - * confirmationPolicy: { - * enabled: true, - * defaultTimeoutMs: 30000, - * timeoutAction: 'reject' - * } - * }); - * ``` - */ - confirmationPolicy?: ConfirmationPolicy - /** - * Maximum execution time in milliseconds. - * - * When set, the execution loop will abort if it exceeds this duration. - * This prevents runaway executions and excessive API costs. - * - * ```js - * agent.session('.', { - * maxExecutionTimeMs: 300000 // 5 minutes - * }); - * ``` - */ - maxExecutionTimeMs?: number -} -/** Retention limits for large tool/program artifacts. */ -export interface ArtifactStoreLimits { - /** Maximum number of artifacts retained by a session. */ - maxArtifacts?: number - /** Maximum total artifact content bytes retained by a session. */ - maxBytes?: number -} -/** A single message in conversation history. */ -export interface MessageObject { - role: string - content: Array -} -/** A content block within a message. */ -export interface ContentBlockObject { - type: string - /** Text content (for "text" blocks). */ - text?: string - /** Tool use ID (for "tool_use" blocks). */ - id?: string - /** Tool name (for "tool_use" blocks). */ - name?: string - /** Tool input (for "tool_use" blocks). */ - input?: any - /** Tool use ID reference (for "tool_result" blocks). */ - toolUseId?: string - /** Tool result content (for "tool_result" blocks). */ - resultContent?: string - /** Whether this is an error result (for "tool_result" blocks). */ - isError?: boolean -} -/** An image attachment for multi-modal prompts. */ -export interface AttachmentObject { - /** Raw image bytes. */ - data: Buffer - /** MIME type (e.g., "image/jpeg", "image/png"). */ - mediaType: string -} -/** - * Configuration for the optional advanced session lane queue. - * - * Ordinary sessions do not initialize queue infrastructure. Use this only for - * explicit external/hybrid dispatch, priority experiments, or operational integrations. - */ -export interface SessionQueueConfig { - /** Max concurrency for Query lane (default: 4). */ - queryConcurrency?: number - /** Max concurrency for Execute lane (default: 2). */ - executeConcurrency?: number - /** Max concurrency for Generate lane (default: 1). */ - generateConcurrency?: number - /** Enable dead letter queue. */ - enableDlq?: boolean - /** Max DLQ size (default: 1000). */ - dlqMaxSize?: number - /** Enable metrics collection. */ - enableMetrics?: boolean - /** Enable queue alerts. */ - enableAlerts?: boolean - /** Default command timeout (ms). */ - timeoutMs?: number - /** Enable all features with sensible defaults. */ - enableAllFeatures?: boolean - /** - * Per-lane handler config. Keys: "control", "query", "execute", "generate". - * Values: LaneHandlerConfig with mode ("internal"/"external"/"hybrid") and timeoutMs. - */ - laneHandlers?: Record -} -/** Result of an external task completion. */ -export interface ExternalTaskResult { - success: boolean - result?: any - error?: string -} -/** Lane handler configuration. */ -export interface LaneHandlerConfig { - /** "internal", "external", or "hybrid" */ - mode: string - /** Timeout for external processing (ms). */ - timeoutMs?: number -} -/** Queue statistics. */ -export interface QueueStats { - totalPending: number - totalActive: number - externalPending: number -} -export interface McpServerStatusEntry { - name: string - connected: boolean - toolCount: number - error?: string -} -/** MCP server metadata exposed to slash command handlers. */ -export interface CommandMcpServerInfo { - /** MCP server name. */ - name: string - /** Number of tools currently exposed by the server. */ - toolCount: number -} -/** Context passed to custom slash command handlers. */ -export interface CommandContext { - /** Current session ID. */ - sessionId: string - /** Current workspace path. */ - workspace: string - /** Current active model identifier. */ - model: string - /** Number of messages in session history. */ - historyLen: number - /** Total tokens used in this session so far. */ - totalTokens: number - /** Estimated session cost in USD. */ - totalCost: number - /** Registered tool names (builtin + MCP). */ - toolNames: Array - /** Connected MCP servers and their tool counts. */ - mcpServers: Array -} -/** Metadata about a registered slash command. */ -export interface CommandInfo { - /** Command name without the leading `/` (e.g., `"help"`, `"model"`) */ - name: string - /** Short description shown in `/help` */ - description: string - /** Optional usage hint (e.g., `"/model "`) */ - usage?: string -} -/** Matcher for filtering which events trigger a hook. */ -export interface HookMatcherObject { - /** Match specific tool name (exact match) */ - tool?: string - /** Match file path pattern (glob) */ - pathPattern?: string - /** Match command pattern (regex for Bash commands) */ - commandPattern?: string - /** Match session ID (exact match) */ - sessionId?: string - /** Match skill name (supports glob patterns) */ - skill?: string -} -/** Configuration for a hook. */ -export interface HookConfigObject { - /** Priority (lower values = higher priority, default: 100) */ - priority?: number - /** Timeout in milliseconds (default: 30000) */ - timeoutMs?: number - /** Whether to execute asynchronously (fire-and-forget) */ - asyncExecution?: boolean - /** Maximum retry attempts */ - maxRetries?: number -} -/** Metadata about a built-in skill. */ -export interface SkillInfo { - name: string - description: string - /** Skill kind: "instruction", "tool", or "agent". */ - kind: string -} -/** - * Return a list of built-in skills compiled into the library. - * - * Each entry has `name`, `description`, and `kind` (instruction, tool, or agent). - */ -export declare function builtinSkills(): Array -/** Configuration for a search engine. */ -export interface SearchEngineConfig { - enabled: boolean - weight: number - timeout?: number -} -/** Browser backend for headless search. */ -export const enum BrowserBackend { - /** Chrome/Chromium headless. */ - Chrome = 0, - /** Lightpanda headless browser (Linux/macOS only). */ - Lightpanda = 1 -} -/** Headless browser configuration. */ -export interface HeadlessConfig { - backend: BrowserBackend - browserPath?: string - maxTabs?: number - launchArgs?: Array - proxyUrl?: string -} -/** Health monitor configuration for search engines. */ -export interface SearchHealthConfig { - maxFailures: number - suspendSeconds: number -} -/** Search engine configuration (a3s-search integration). */ -export interface SearchConfig { - timeout: number - health?: SearchHealthConfig - engines: Record - headless?: HeadlessConfig -} -/** Streaming event iterator. Use `for await (const event of stream)` or call `.next()` manually. */ -export declare class EventStream { - /** - * Get the next event from the stream. - * - * Returns `{ value: AgentEvent | null, done: boolean }`. - * When `done` is true, the stream is exhausted. - */ - next(): Promise -} -/** - * File-backed long-term memory store. - * - * ```js - * agent.session('.', { memoryStore: new FileMemoryStore('./memory') }); - * ``` - */ -export declare class FileMemoryStore { - backend: string - dir: string - /** Create a file-backed memory store at `dir`. */ - constructor(dir: string) -} -/** - * File-backed session store (persists sessions to disk for later resumption). - * - * ```js - * agent.session('.', { - * sessionStore: new FileSessionStore('./sessions'), - * sessionId: 'my-session', - * autoSave: true, - * }); - * ``` - */ -export declare class FileSessionStore { - backend: string - dir: string - /** Create a file-backed session store at `dir`. */ - constructor(dir: string) -} -/** - * In-memory (non-persistent) session store. - * - * Useful for testing, ephemeral runs, and CI pipelines where no disk state is needed. - * - * ```js - * agent.session('.', { sessionStore: new MemorySessionStore() }); - * ``` - */ -export declare class MemorySessionStore { - backend: string - constructor() -} -/** - * Default security provider: input taint tracking + output sanitisation. - * - * ```js - * agent.session('.', { securityProvider: new DefaultSecurityProvider() }); - * ``` - */ -export declare class DefaultSecurityProvider { - kind: string - constructor() -} -/** - * Local filesystem workspace backend. - * - * This is the explicit typed form of the default local workspace behavior. - * It is useful when callers want to pass workspace backends through the same - * option surface that remote/browser backends will use. - * - * ```js - * agent.session('/repo', { workspaceBackend: new LocalWorkspaceBackend('/repo') }); - * ``` - */ -export declare class LocalWorkspaceBackend { - kind: string - root: string - /** Create a local filesystem workspace backend rooted at `root`. */ - constructor(root: string) -} -/** - * S3-compatible object-storage workspace backend. - * - * Points built-in file tools (`read`, `write`, `edit`, `patch`, `ls`) at an - * S3-compatible bucket. Works with AWS S3, MinIO, RustFS, Cloudflare R2, - * Backblaze B2, and other S3-API-compatible services. - * - * `bash`, `git`, `grep`, and `glob` are intentionally **not** registered - * when this backend is in use — object storage cannot service them. - * - * ```js - * const backend = new S3WorkspaceBackend({ - * endpoint: 'https://minio.local:9000', - * region: 'us-east-1', - * accessKeyId: 'AKIA...', - * secretAccessKey: '...', - * bucket: 'workspace', - * prefix: 'users/u1/sessions/s1', - * forcePathStyle: true, - * }); - * agent.session('s3://workspace/users/u1/sessions/s1', { workspaceBackend: backend }); - * ``` - */ -export declare class S3WorkspaceBackend { - kind: string - s3: JsS3BackendConfig - /** Create an S3-compatible workspace backend. */ - constructor(config: JsS3BackendConfig) -} -/** - * Stdio transport for AHP (Agent Harness Protocol). - * - * Launches a child process and communicates via stdin/stdout using JSON-RPC 2.0. - * - * ```js - * agent.session('.', { - * ahpTransport: new StdioTransport('python', ['ahp_server.py']) - * }); - * ``` - */ -export declare class StdioTransport { - kind: string - program?: string - args?: Array - url?: string - authToken?: string - path?: string - constructor(program: string, args: Array) -} -/** - * HTTP transport for AHP (Agent Harness Protocol). - * - * Connects to a remote AHP harness server via HTTP. - * - * ```js - * agent.session('.', { - * ahpTransport: new HttpTransport('http://localhost:8080/ahp') - * }); - * ``` - */ -export declare class HttpTransport { - kind: string - program?: string - args?: Array - url?: string - authToken?: string - path?: string - constructor(url: string, authToken?: string | undefined | null) -} -/** - * WebSocket transport for AHP (Agent Harness Protocol). - * - * Connects to a remote AHP harness server via WebSocket for bidirectional streaming. - * - * ```js - * agent.session('.', { - * ahpTransport: new WebSocketTransport('ws://localhost:8080/ahp') - * }); - * ``` - */ -export declare class WebSocketTransport { - kind: string - program?: string - args?: Array - url?: string - authToken?: string - path?: string - constructor(url: string, authToken?: string | undefined | null) -} -/** - * Unix socket transport for AHP (Agent Harness Protocol). - * - * Connects to a local AHP harness server via Unix domain socket. + * This file is hand-authored. The napi-rs build writes to `generated.d.ts`, + * which this aggregator re-exports. Cross-boundary types that aren't + * generated from Rust (because napi-derive would camelCase fields that + * need to mirror the wire JSON, or because they describe discriminated + * unions napi can't express) live in `extra-types.d.ts`. * - * ```js - * agent.session('.', { - * ahpTransport: new UnixSocketTransport('/tmp/ahp.sock') - * }); - * ``` + * Edit those two files, not this one. */ -export declare class UnixSocketTransport { - kind: string - program?: string - args?: Array - url?: string - authToken?: string - path?: string - constructor(path: string) -} -/** AI coding agent. Create with `Agent.create()`, then call `agent.session()`. */ -export declare class Agent { - /** - * Create an Agent from a config file path or inline config string. - * - * Accepts ACL-compatible config files (.acl) or inline config strings. - * JSON config is not supported. - * - * @param configSource - Path to a config file (.acl), or inline config string - */ - static create(configSource: string): Promise - /** - * Re-fetch tool definitions from all connected global MCP servers and - * update the agent-level cache. - * - * New sessions created after this call will see the refreshed tool list. - * Existing sessions are unaffected. - */ - refreshMcpTools(): Promise - /** - * Bind to a workspace directory, returning a Session. - * - * @param workspace - Path to the workspace directory - * @param options - Optional session overrides - */ - session(workspace: string, options?: SessionOptions | undefined | null): Session - /** - * Resume a previously saved session by ID. - * - * `options.sessionStore` must be set to a `FileSessionStore` (or `MemorySessionStore`) - * that points to the directory where the session was originally saved. - * - * ```js - * const session = agent.resumeSession('my-session', { - * sessionStore: new FileSessionStore('./sessions'), - * }); - * ``` - * - * @param sessionId - The session ID to resume - * @param options - Session options; `sessionStore` is required - */ - resumeSession(sessionId: string, options: SessionOptions): Session - /** - * Create a session pre-configured from a named agent definition. - * - * Loads the agent by name from built-in agents and optionally from - * additional directories, then creates a session with the agent's - * permissions, system prompt, model, and step limit applied. - * - * @param workspace - Path to the workspace directory - * @param agentName - Name of the agent to load (e.g. "explore", "general") - * @param agentDirs - Optional directories to scan for agent files - * @param options - Optional session overrides layered on top of the agent definition - */ - sessionForAgent(workspace: string, agentName: string, agentDirs?: Array | undefined | null, options?: SessionOptions | undefined | null): Session - /** - * Create a session pre-configured from a disposable worker spec. - * - * This avoids writing temporary agent files for one-off cattle workers. - * - * @param workspace - Path to the workspace directory - * @param worker - Worker spec to compile into an agent definition - * @param options - Optional session overrides layered on top of the worker definition - */ - sessionForWorker(workspace: string, worker: WorkerAgentSpec, options?: SessionOptions | undefined | null): Session -} -/** Workspace-bound session. All LLM and tool operations happen here. */ -export declare class Session { - /** - * Send a prompt or request and wait for the complete response. - * - * `send("prompt")` is the compact prompt-first form. `send({ prompt, - * history, attachments })` is the compact object-shaped form for growth. - */ - send(request: string | SessionRequestOptions, history?: Array | null): Promise - /** Alias for `send(...)` with a name that matches run/replay terminology. */ - run(request: string | SessionRequestOptions, history?: Array | null): Promise - /** - * Send a prompt or request and get a streaming event iterator. - * - * Returns an `EventStream`. Use `for await (const event of stream)` or call `.next()` manually. - * When `history` is omitted, the session history and verification evidence are - * updated after the stream completes. Supplying `history` keeps the stream isolated. - */ - stream(request: string | SessionRequestOptions, history?: Array | null): Promise - /** - * Send a request using the long-lived object-shaped API. - * - * Prefer this for new integrations when the call may need history, - * attachments, or future request options. - */ - sendRequest(request: SessionRequestOptions): Promise - /** Stream a request using the long-lived object-shaped API. */ - streamRequest(request: SessionRequestOptions): Promise - /** - * Send a prompt with image attachments and wait for the complete response. - * - * @param prompt - The prompt to send - * @param attachments - Array of `{ data: Buffer, mediaType: string }` - * @param history - Optional conversation history - */ - sendWithAttachments(prompt: string, attachments: Array, history?: Array | undefined | null): Promise - /** - * Stream a prompt with image attachments. - * - * When `history` is omitted, the session history and verification evidence are - * updated after the stream completes. Supplying `history` keeps the stream isolated. - * - * @param prompt - The prompt to send - * @param attachments - Array of `{ data: Buffer, mediaType: string }` - * @param history - Optional conversation history - */ - streamWithAttachments(prompt: string, attachments: Array, history?: Array | undefined | null): Promise - /** Return the session's conversation history. */ - history(): Array - /** Return run snapshots recorded by this session. */ - runs(): Promise - /** Return a run snapshot by ID, or null when it is unknown. */ - runSnapshot(runId: string): Promise - /** Return recorded runtime events for a run. */ - runEvents(runId: string): Promise - /** Return the currently running operation, or null when idle. */ - currentRun(): Promise - /** Return active tool calls observed for the currently running operation. */ - activeTools(): Promise - /** - * Look up a delegated subagent task by id. Resolves to `null` when no - * such task has been observed in this session. - */ - subagentTask(taskId: string): Promise - /** - * Return snapshots of every delegated subagent task observed in this - * session (including completed and failed ones), oldest first. - */ - subagentTasks(): Promise - /** Return snapshots of subagent tasks still in `running` state. */ - pendingSubagentTasks(): Promise - /** Cancel a specific run only if it is still the active run. */ - cancelRun(runId: string): Promise - /** Execute a tool by name, bypassing the LLM. */ - tool(name: string, args: any): Promise - /** Delegate a bounded task to a child agent through the built-in `task` tool. */ - task(options: DelegateTaskOptions): Promise - /** Delegate a bounded task to a child agent through the built-in `task` tool. */ - delegateTask(options: DelegateTaskOptions): Promise - /** Execute several delegated child-agent tasks concurrently through `parallel_task`. */ - tasks(tasks: DelegateTaskOptions[]): Promise - /** Execute several delegated child-agent tasks concurrently through `parallel_task`. */ - parallelTask(tasks: DelegateTaskOptions[]): Promise - /** Run a bounded JavaScript script through the embedded QuickJS `program` tool. */ - program(options: ProgramScriptOptions): Promise - /** Read a file from the workspace. */ - readFile(path: string): Promise - /** Write a file in the workspace. */ - writeFile(path: string, content: string): Promise - /** List a directory in the workspace. */ - ls(path?: string | undefined | null): Promise - /** Edit a file by replacing text in the workspace. */ - editFile(path: string, oldString: string, newString: string, replaceAll?: boolean | undefined | null): Promise - /** Apply a unified diff patch to a workspace file. */ - patchFile(path: string, diff: string): Promise - /** Execute a bash command in the workspace. */ - bash(command: string): Promise - /** Search for files matching a glob pattern. */ - glob(pattern: string): Promise> - /** Search file contents with a regex pattern. */ - grep(pattern: string): Promise - /** Search the web using multiple search engines. */ - webSearch(params: JsWebSearchParams): Promise - /** - * Execute a git command. - * - * Prefer `git({ command: "status" })`; positional arguments remain for - * compatibility. - */ - 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 - /** - * Execute a git command with an object-shaped API. - * - * Preferred over the positional `git(...)` overload for new callers. - * - * ```js - * await session.gitCommand({ command: 'status' }) - * await session.gitCommand({ command: 'worktree', subcommand: 'list' }) - * ``` - */ - gitCommand(args: GitCommandOptions): Promise - /** Check if this session has an advanced lane queue configured. */ - hasQueue(): boolean - /** - * Configure a lane's handler mode for explicit external/hybrid dispatch. - * - * @param lane - "control", "query", "execute", or "generate" - * @param config - { mode: "internal"|"external"|"hybrid", timeoutMs?: number } - */ - setLaneHandler(lane: string, config: LaneHandlerConfig): Promise - /** - * Complete an external queue task by ID. - * - * @param taskId - The task identifier - * @param result - { success: boolean, result?: any, error?: string } - * @returns true if found, false if not found - */ - completeExternalTask(taskId: string, result: ExternalTaskResult): Promise - /** Get pending external queue tasks. */ - pendingExternalTasks(): Promise - /** Return pending HITL tool confirmations for this session. */ - pendingConfirmations(): Promise> - /** - * Resolve a pending HITL tool confirmation. - * - * @param toolId - Tool call ID from a `confirmation_required` event. - * @param approved - Whether the tool execution should proceed. - * @param reason - Optional human-readable reason for audit/UI display. - * @returns true if a pending confirmation was found and completed. - */ - confirmToolUse(toolId: string, approved: boolean, reason?: string | undefined | null): Promise - /** Cancel all pending HITL confirmations for this session. */ - cancelConfirmations(): Promise - /** Get optional queue statistics. */ - queueStats(): Promise - /** Return compact execution trace events recorded for this session. */ - traceEvents(): any - /** Return structured verification reports recorded for this session. */ - verificationReports(): any - /** Add externally produced verification reports to this session. */ - recordVerificationReports(reports: any): void - /** Return a structured verification summary for this session. */ - verificationSummary(): any - /** Return a concise human-readable verification summary for this session. */ - verificationSummaryText(): string - /** Run verification commands and return a structured verification report. */ - verifyCommands(subject: string, commands: Array): Promise - /** Return project-aware verification command presets for this workspace. */ - verificationPresets(): any - /** Get dead letters from the optional queue's DLQ. */ - deadLetters(): Promise - /** - * Get a detailed metrics snapshot from the queue. - * - * Returns `null` if metrics are not enabled (queue not configured or - * `enable_metrics` was not set in `SessionQueueConfig`). - * - * @returns Object with `counters`, `gauges`, and `histograms` maps, or null - */ - queueMetrics(): Promise - /** - * Add an MCP server to this live session. - * - * Connects the server and registers all its tools immediately so the agent - * can call them. Tool names follow the convention `mcp____`. - * - * @param name - Server identifier (used as prefix in tool names) - * @param transport - Transport type: `"stdio"` (default), `"http"`, or `"streamable-http"` - * @param command - Executable to launch (stdio only, e.g. `"npx"`) - * @param args - Arguments for the command (stdio only) - * @param url - Server URL (http / streamable-http only) - * @param headers - HTTP headers (http / streamable-http only) - * @param env - Optional extra environment variables (stdio only) - * @returns Number of tools registered from the server - */ - addMcpServer(name: string, transport?: 'stdio' | 'http' | 'streamable-http', command?: string | undefined | null, args?: Array | undefined | null, url?: string | undefined | null, headers?: Record | undefined | null, env?: Record | undefined | null, timeoutMs?: number | undefined | null): Promise - /** - * Add an MCP server with a typed object config. - * - * Preferred over the positional overload for new SDK callers. - * - * ```js - * await session.addMcpServerConfig({ - * name: 'github', - * transport: { type: 'stdio', command: 'npx', args: ['-y', '@modelcontextprotocol/server-github'] }, - * env: { GITHUB_TOKEN: process.env.GITHUB_TOKEN }, - * timeoutMs: 30000, - * }) - * ``` - */ - addMcpServerConfig(config: McpServerConfig): Promise - /** Add an MCP server with the compact object-shaped API. */ - addMcp(config: McpServerConfig): Promise - /** - * Dynamically register agent definitions from a directory into the live session. - * - * Scans the directory for `*.yaml`, `*.yml`, and `*.md` agent definition files - * and registers them into the shared AgentRegistry used by the `task` tool. - * New agents are immediately callable via `task({ agent: "…", … })` without - * restarting the session. - * - * @param path - Directory to scan for agent definition files - * @returns Number of agents successfully loaded - */ - registerAgentDir(path: string): number - /** - * Register a disposable worker agent into the live session. - * - * The worker is immediately callable through the model-visible `task` tool. - * - * @param worker - Worker spec to register - * @returns Compiled agent definition - */ - registerWorkerAgent(worker: WorkerAgentSpec): AgentDefinition - /** - * Register many disposable workers into the live session. - * - * @param workers - Worker specs to register - * @returns Compiled agent definitions - */ - registerWorkerAgents(workers: Array): Array - /** - * Disconnect and unregister an MCP server, removing its tools from the session. - * - * @param name - Server name (must match the name used in addMcpServer) - */ - removeMcpServer(name: string): Promise - /** Remove an MCP server with the compact API. */ - removeMcp(name: string): Promise - /** - * Return connection status for all MCP servers registered on this session. - * - * @returns Array of `{ name, connected, toolCount }` entries - */ - mcpStatus(): Promise> - /** Return MCP server status with the compact API. */ - mcps(): Promise> - /** - * Return the names of all tools currently registered on this session. - * - * @returns Array of tool name strings - */ - toolNames(): Array - /** Return full model-visible tool definitions currently registered on this session. */ - toolDefinitions(): any - /** Return a stored tool artifact by URI, or null if it is not retained. */ - getArtifact(artifactUri: string): any - /** - * Register a hook for lifecycle event interception. - * - * Hooks registered on a session are automatically propagated to all sub-agents - * spawned by the `task` tool, including grandchild agents at arbitrary depth. - * This ensures security hooks (e.g. a sentinel) apply across the full agent tree - * without requiring explicit registration on each sub-agent session. - * - * @param hookId - Unique hook identifier - * @param eventType - Event type: "pre_tool_use", "post_tool_use", "generate_start", - * "generate_end", "session_start", "session_end", "skill_load", "skill_unload", - * "pre_prompt", "post_response", "on_error" - * @param matcher - Optional matcher: { tool?, pathPattern?, commandPattern?, sessionId?, skill? } - * @param config - Optional config: { priority?, timeoutMs?, asyncExecution?, maxRetries? } - * @param handler - Optional callback `(event: any) => { action: 'continue' | 'block' | 'skip', - * reason?: string } | null`. When provided, the function is called for every matching event - * and its return value controls execution. Return `{ action: 'block', reason: '...' }` to - * cancel the operation, `{ action: 'skip' }` to skip remaining hooks, or `null`/`undefined` - * for continue. Hooks with no handler still fire (observable via stream events) but always - * continue. - */ - registerHook(hookId: string, eventType: string, matcher?: HookMatcherObject | undefined | null, config?: HookConfigObject | undefined | null, handler?: ((event: Record) => { action: string; reason?: string } | null | undefined) | null | undefined): void - /** - * Unregister a hook by ID. - * - * @param hookId - The hook identifier to remove - * @returns true if the hook was found and removed - */ - unregisterHook(hookId: string): boolean - /** Get the number of registered hooks. */ - hookCount(): number - /** Return the session ID. */ - get sessionId(): string - /** Return the workspace path. */ - get workspace(): string - /** Return any deferred init warning (e.g. memory store failed to initialize). */ - get initWarning(): string | null - /** Save the session to the configured store. */ - save(): Promise - /** Check if memory is configured for this session. */ - get hasMemory(): boolean - /** - * Remember a successful task execution. - * - * @param task - Description of the task - * @param tools - List of tool names used - * @param result - Summary of the result - */ - rememberSuccess(task: string, tools: Array, result: string): Promise - /** - * Remember a failed task execution. - * - * @param task - Description of the task - * @param error - Error message - * @param tools - List of tool names attempted - */ - rememberFailure(task: string, error: string, tools: Array): Promise - /** - * Recall memories similar to a query. - * - * @param query - Search query - * @param limit - Maximum number of results (default: 5) - * @returns Array of memory items - */ - recallSimilar(query: string, limit?: number | undefined | null): Promise - /** - * Recall memories by tags. - * - * @param tags - Tags to search for - * @param limit - Maximum number of results (default: 10) - * @returns Array of memory items - */ - recallByTags(tags: Array, limit?: number | undefined | null): Promise - /** - * Get recent memory items. - * - * @param limit - Maximum number of results (default: 10) - * @returns Array of memory items - */ - memoryRecent(limit?: number | undefined | null): Promise - /** - * Get memory statistics. - * - * @returns Object with longTermCount, shortTermCount, workingCount - */ - memoryStats(): Promise - /** - * Get current working memory items. - * - * Working memory holds the active context items for the current task. - * - * @returns Array of memory items currently in working memory - */ - getWorking(): Promise - /** - * Clear working memory. - * - * Removes all items from working memory without affecting short-term or long-term memory. - */ - clearWorking(): Promise - /** - * Get current short-term memory items. - * - * Short-term memory contains items stored during this session. - * - * @returns Array of memory items in short-term memory - */ - getShortTerm(): Promise - /** - * Clear short-term memory for this session. - * - * Removes all session-scoped memory items without affecting long-term or working memory. - */ - clearShortTerm(): Promise - /** - * Register a custom slash command. - * - * Slash commands are invoked via `session.send("/command args")` and execute - * before the LLM sees the input. The handler receives the command arguments - * and a context object with session metadata. - * - * @param name - Command name without the leading `/` (e.g., `"status"`) - * @param description - Short description shown in `/help` - * @param handler - Callback `(args: string, ctx: CommandContext) => string` - * - * @example - * ```typescript - * session.registerCommand("status", "Show session info", (args, ctx) => { - * return `Session ${ctx.sessionId} in ${ctx.workspace}`; - * }); - * await session.send("/status"); - * ``` - */ - registerCommand(name: string, description: string, handler: (args: string, ctx: CommandContext) => string): void - /** - * List all registered slash commands. - * - * Returns each command's name, description, and optional usage hint. - * Slash commands can be invoked via `session.send("/command args")`. - * - * @returns Array of CommandInfo objects sorted by name - */ - listCommands(): Array - /** - * Cancel the current ongoing operation (send/stream). - * - * If an operation is in progress, this will trigger cancellation of the LLM streaming - * and tool execution. The operation will terminate as soon as possible. - * - * @returns `true` if an operation was cancelled, `false` if no operation was in progress - */ - cancel(): boolean - /** - * Close the session and cancel any active operation. - * - * Call this when the session will no longer be used so Node.js can exit - * cleanly without waiting on session-scoped background workers. - */ - close(): void -} +export * from './generated' +export * from './extra-types' diff --git a/sdk/node/package.json b/sdk/node/package.json index 294b2ff..14c229c 100644 --- a/sdk/node/package.json +++ b/sdk/node/package.json @@ -23,6 +23,8 @@ "files": [ "index.js", "index.d.ts", + "generated.d.ts", + "extra-types.d.ts", "*.node" ], "devDependencies": { @@ -33,10 +35,11 @@ }, "scripts": { "artifacts": "napi artifacts", - "build": "napi build --platform --release --js index.js --dts index.d.ts", - "build:debug": "napi build --platform --js index.js --dts index.d.ts", + "build": "napi build --platform --release --js index.js --dts generated.d.ts", + "build:debug": "napi build --platform --js index.js --dts generated.d.ts", "prepublishOnly": "napi prepublish -t npm", "test": "node test.mjs", + "test:types": "tsc --noEmit --module nodenext --moduleResolution nodenext --target es2022 --strict --skipLibCheck test-types.ts", "test:helpers": "node test-helpers.mjs" }, "optionalDependencies": { diff --git a/sdk/node/test-types.ts b/sdk/node/test-types.ts new file mode 100644 index 0000000..7caa9c5 --- /dev/null +++ b/sdk/node/test-types.ts @@ -0,0 +1,48 @@ +// Compile-only check that both generated and hand-authored types resolve +// from the package entry. If the napi-rs build ever overwrites index.d.ts +// (i.e. the aggregator was lost), this file will fail to type-check. +// +// Run with: npx tsc --noEmit --module nodenext --moduleResolution nodenext test-types.ts + +import type { + // From generated.d.ts (napi-rs): + Session, + Agent, + AgentEvent, + ToolResult, + // From extra-types.d.ts (hand-authored): + ToolErrorKind, + VerificationStatus, + VerificationCheck, + VerificationReport, + ToolArtifact, +} from './index.js' + +// Forced uses so unused-import lint stays quiet. +declare const _session: Session +declare const _agent: Agent +declare const _event: AgentEvent +declare const _result: ToolResult +declare const _err: ToolErrorKind +declare const _status: VerificationStatus +declare const _check: VerificationCheck +declare const _report: VerificationReport +declare const _artifact: ToolArtifact + +// Exhaustive narrowing on the discriminated union — confirms the union +// shape survives a regenerate. +function _describe(err: ToolErrorKind): string { + switch (err.type) { + case 'version_conflict': + return `${err.path} expected=${err.expected}` + case 'remote_git_conflict': + return err.message + case 'not_found': + return err.path + case 'invalid_argument': + case 'unsupported': + return err.message + case 'timeout': + return `${err.op} after ${err.duration_ms}ms` + } +}