Skip to content

SDK API Reference ​

Complete API reference for @protolabsai/sdk. For a guided introduction, see Contributing → TypeScript SDK.

Installation ​

bash
npm install @protolabsai/sdk

Requires Node.js ≥ 20.0.0 and proto installed in PATH.

query() ​

Creates a new agentic session with the proto CLI.

typescript
import { query } from '@protolabsai/sdk';

const conversation = query({
  prompt: 'What files are in the current directory?',
  options: { cwd: '/path/to/project' },
});

for await (const message of conversation) {
  console.log(message);
}

Parameters ​

ParameterTypeDescription
promptstring | AsyncIterable<SDKUserMessage>Single-turn string or multi-turn async iterable
optionsQueryOptionsSession configuration (all optional)

Returns a Query instance (implements AsyncIterable<SDKMessage>).

QueryOptions ​

Core ​

OptionTypeDefaultDescription
cwdstringprocess.cwd()Working directory
modelstring—Model ID
envobject—Environment variables merged into CLI process
systemPromptstring—Override or extend the built-in system prompt
maxSessionTurnsnumber-1Max turns before auto-termination
debugbooleanfalseVerbose CLI logging
logLevelstringerrorSDK log verbosity (debug, info, warn, error)
abortControllerAbortControllerautoCall .abort() to terminate
includePartialMessagesbooleanfalseEmit streaming events as they arrive

Permissions ​

OptionTypeDefaultDescription
permissionModestringdefaultdefault, plan, auto-edit, yolo
canUseToolCanUseTool—Custom per-tool permission callback
timeout{ canUseTool?: number }—Per-operation timeouts (ms). See note below.
allowedToolsstring[]—Auto-approved tools
excludeToolsstring[]—Blocked tools (highest priority)
coreToolsstring[]—If set, only these tools are available
authTypeAuthTypeopenaiopenai, anthropic, gemini

timeout.canUseTool bounds how long a canUseTool permission request may stay pending before it is rejected. The SDK forwards this value to the CLI at session initialization, so the CLI's control-plane timeout matches your callback's — a long-running approval handler is no longer cut short by the CLI's default (60s) before your own timeout elapses. Capped at 10 minutes. When unset, the CLI default applies.

Session ​

OptionTypeDefaultDescription
resumestring—Session ID to resume
sessionIdstringautoExplicit session ID
chatRecordingbooleantrueSet false to disable session persistence

MCP & agents ​

OptionTypeDescription
mcpServersobjectMCP server configurations (same schema as settings.json)
agentsSubagentConfig[]Sub-agent configurations

LSP ​

OptionTypeDefaultDescription
lspbooleanfalseEnable LSP code intelligence

Hooks ​

OptionTypeDescription
hookCallbacksobjectMap of event name → HookCallback or HookCallback[]

Message types ​

All messages from query() implement SDKMessage with type and session_id.

typeDescription
system + subtype: session_startSession started
assistantModel response with message.content array
tool_useTool call request
tool_resultTool execution result
result + subtype: success/errorSession completed

Helper functions ​

typescript
import {
  isTextMessage,
  isToolUseMessage,
  isResultMessage,
  isLspDiagnosticEvent,
  abortQuery,
} from '@protolabsai/sdk';

Multi-turn conversations ​

Pass an async iterable as prompt to drive a multi-turn session programmatically:

typescript
async function* conversation() {
  yield { type: 'human', content: 'Analyse the project structure' };
  yield { type: 'human', content: 'Now write a summary to README.md' };
}

const session = query({ prompt: conversation() });
for await (const msg of session) { ... }

Abort a session ​

typescript
const controller = new AbortController();
const session = query({ prompt: '...', options: { abortController: controller } });

setTimeout(() => controller.abort(), 30_000);

for await (const msg of session) { ... }

Hook callbacks ​

typescript
import { query, type HookCallback } from '@protolabsai/sdk';

const gate: HookCallback = async (input) => {
  const data = input as {
    tool_name?: string;
    tool_input?: Record<string, unknown>;
  };
  if (data.tool_name === 'Bash') {
    const cmd = String(data.tool_input?.command ?? '');
    if (cmd.includes('rm -rf')) {
      return { shouldSkip: true, message: 'Blocked destructive command' };
    }
  }
  return {};
};

const session = query({
  prompt: 'Clean up old files',
  options: { hookCallbacks: { PreToolUse: [gate] } },
});

Supported events: PreToolUse, PostToolUse, Stop, Notification, SubagentStop.

Sub-agent configuration ​

typescript
import { query, type SubagentConfig } from '@protolabsai/sdk';

const reviewer: SubagentConfig = {
  name: 'code-reviewer',
  description: 'Reviews code for bugs, security, and performance',
  systemPrompt: 'You are a code reviewer...',
  level: 'session',
  tools: ['read_file', 'glob', 'grep_search'],
  modelConfig: { model: 'claude-sonnet-4-6' },
};

const session = query({
  prompt: 'Review the changes in the current branch',
  options: { agents: [reviewer] },
});

See Contributing → Examples → SDK Sub-Agents for more patterns.

Released under the Apache-2.0 License.