Cortex Code Agent SDK 참조 – TypeScript

Cortex Code Agent SDK 참조 – TypeScript

이 항목은 TypeScript용 Cortex Code Agent SDK의 전체 API 참조를 제공합니다 — 모든 함수, 유형, 인터페이스를 포함합니다.

출처: Cortex Code Agent SDK reference – TypeScript

본문

설치

npm install cortex-code-agent-sdk

Node.js 18 이상이 필요합니다. 패키지는 ESM 전용입니다. SDK는 Cortex Code CLI가 별도로 설치되어 있다고 기대합니다. PATH에 없으면 CORTEX_CODE_CLI_PATH=/path/to/cortex를 설정하거나 세션 옵션에서 cliPath를 전달하세요.

함수

query()

Cortex Code와 상호작용하는 기본 함수. 도착하는 대로 메시지를 스트리밍하는 async 생성기를 만듭니다.

function query({
  prompt,
  options,
}: {
  prompt: string | AsyncIterable<SDKUserMessage>;
  options?: CortexCodeSessionOptions;
}): Query;

매개변수

매개변수 유형 설명
prompt string | AsyncIterable 단일 사용자 프롬프트, 또는 스트리밍 입력용 SDK 사용자 메시지의 async iterable
options CortexCodeSessionOptions | undefined 선택적 구성 객체(Options 참고)

반환값

추가 제어 메서드가 있는 AsyncGenerator<CortexCodeEvent>를 확장하는 Query 객체.

예시

import { query } from "cortex-code-agent-sdk";

for await (const message of query({
  prompt: "Fix the bug in utils.py",
  options: { cwd: "/path/to/project" },
})) {
  if (message.type === "assistant") {
    for (const block of message.content) {
      if (block.type === "text") {
        process.stdout.write(block.text);
      }
    }
  }
  if (message.type === "result") {
    console.log("Done:", message.subtype);
  }
}

createCortexCodeSession()

다중 턴 대화를 위한 지속 세션을 만듭니다.

function createCortexCodeSession(
  options: CortexCodeSessionOptions
): Promise<CortexCodeSession>;

예시

import { createCortexCodeSession } from "cortex-code-agent-sdk";

const session = await createCortexCodeSession({
  cwd: process.cwd(),
  model: "claude-sonnet-4-6",
  permissionMode: "bypassPermissions",
  allowDangerouslySkipPermissions: true,
});

await session.send("What files are here?");
for await (const event of session.stream()) {
  if (event.type === "assistant") { /* handle */ }
  if (event.type === "result") break;
}

// Send another prompt (same context)
await session.send("Now refactor the main function");
for await (const event of session.stream()) {
  if (event.type === "result") break;
}

await session.close();

Query 객체

query()가 반환합니다. AsyncGenerator<CortexCodeEvent>를 확장합니다.

메서드 설명
interrupt(): Promise<void> 기본 프로세스에 SIGINT 전송
setPermissionMode(mode: PermissionMode): Promise<void> 활성 쿼리의 이후 턴에 대한 권한 모드 변경
setModel(model: string): Promise<void> 후속 턴의 모델 변경
initializationResult(): Promise<QueryInitializationResult> CLI에서 초기화 핸드셰이크 메타데이터 반환
supportedCommands(): Promise<SlashCommand[]> CLI가 알릴 때 초기화 응답에서 슬래시 명령 메타데이터 반환
supportedModels(): Promise<ModelInfo[]> CLI가 알릴 때 초기화 응답에서 모델 메타데이터 반환
supportedAgents(): Promise<AgentInfo[]> CLI가 알릴 때 초기화 응답에서 사용자 정의 에이전트 메타데이터 반환
accountInfo(): Promise<AccountInfo> CLI가 알릴 때 초기화 응답에서 계정 메타데이터 반환
streamInput(stream: AsyncIterable<SDKUserMessage>): Promise<void> 활성 쿼리에 추가 SDK 사용자 메시지 스트리밍
stopTask(taskId: string): Promise<void> ID로 실행 중인 백그라운드 작업 취소
close(): void 세션을 닫고 프로세스 종료

CortexCodeSession 인터페이스

createCortexCodeSession()이 반환합니다. 다중 턴 대화를 지원하며 await using(Node.js 24+)과 함께 사용할 AsyncDisposable을 구현합니다.

속성 / 메서드 설명
pid: number | undefined 기본 CLI 프로세스의 PID
send(message: string | SDKUserMessage): Promise<void> 일반 텍스트 또는 구조화된 SDK 사용자 메시지 전송
stream(): AsyncGenerator<CortexCodeEvent> 에이전트의 이벤트 스트리밍
initializationResult(): Promise<QueryInitializationResult> 초기화 핸드셰이크 메타데이터 반환
interrupt(): Promise<void> 인터럽트 신호 전송
setPermissionMode(mode: PermissionMode): Promise<void> 세션의 이후 턴에 대한 권한 모드 변경
setModel(model: string): Promise<void> 세션 중간에 모델 변경
stopTask(taskId: string): Promise<void> ID로 실행 중인 백그라운드 작업 취소
close(): Promise<void> 세션 종료 및 프로세스 종료
[Symbol.asyncDispose](): Promise<void> close() 호출. await using session = ... 구문 활성화

옵션

query() 또는 createCortexCodeSession()에 전달되는 구성.

옵션 유형 기본값 설명
cwd string 현재 프로세스 작업 디렉터리 세션의 작업 디렉터리. 생략하면 SDK가 현재 프로세스 작업 디렉터리를 상속합니다.
model string CLI 기본값 사용할 모델. 자동 선택에는 "auto", 또는 "claude-sonnet-4-6" 같은 특정 식별자.
connection string CLI 기본값 Snowflake CLI 연결 설정의 Snowflake 연결 이름, 일반적으로 ~/.snowflake/connections.toml, 기존 설정에 ~/.snowflake/config.toml도 지원. 생략하면 CLI가 TOML 파일의 default_connection_name을 사용.
profile string undefined 프로필 이름(~/.snowflake/cortex/profiles/에서 로드)
resume string undefined 이전 대화를 재개할 세션 ID
continue boolean false 가장 최근 대화 계속. 세션 ID 없이 마지막 세션을 재개합니다.
forkSession boolean false 재개된 세션을 제자리에서 계속하는 대신 새 세션 ID로 포크. resume과 함께 사용.
sessionId string undefined 대화의 명시적 세션 ID. 생략하면 CLI가 자동으로 생성.
permissionMode string "default" "default" | "autoAcceptPlans" | "plan" | "bypassPermissions". 참고: "bypassPermissions"는 allowDangerouslySkipPermissions: true 필요. "plan" 모드에서 AskUserQuestion과 ExitPlanMode를 canUseTool로 라우팅할 수 있고, ExitPlanMode 거부는 계획을 활성 상태로 유지하며 승인하면 플랜 모드를 종료해 이후 턴이 정상 권한을 재개합니다.
allowDangerouslySkipPermissions boolean false permissionMode: "bypassPermissions" 사용 시 필요한 안전 플래그. 이 플래그만으로는 권한을 우회하지 않으며 permissionMode를 통해 명시적으로 요청할 때만 바이패스를 허용합니다.
allowedTools string[] undefined 프롬프트 없이 자동 승인할 도구
disallowedTools string[] undefined 항상 거부할 도구
canUseTool CanUseTool undefined 각 도구 실행 전에 호출되는 사용자 정의 권한 핸들러. canUseTool 콜백 참고.
permissionPromptToolName string undefined 권한 프롬프트에 사용되는 MCP 도구 이름. canUseTool이 제공되면 SDK가 자동으로 "stdio"를 사용.
maxTurns number undefined 중지 전 최대 에이전트 턴 수. 도달하면 세션이 error_max_turns 결과를 발생.
effort string undefined 모델의 추론 노력 수준. "minimal", "low", "medium", "high", "max" 중 하나.
additionalDirectories string[] undefined 세션에 제공할 추가 작업 디렉터리
plugins Array<string | { type: "local"; path: string }> undefined 로드할 플러그인 디렉터리. 문자열 또는 { type: "local", path: "..." } 객체를 받음.
env Record<string, string | undefined> undefined 생성된 프로세스 환경에 병합되는 환경 변수. 키를 undefined로 설정하면 상속된 변수를 제거.
abortController AbortController undefined 컨트롤러에서 abort() 호출로 인터럽트 신호 전송. 추가 프롬프트를 위해 세션은 유지됩니다. CLI에서 ESC 누르기와 동일.
systemPrompt string | SystemPromptPreset undefined 사용자 정의 시스템 프롬프트. 완전히 교체하려면 문자열, 확장하려면 SystemPromptPreset을 전달.
appendSystemPrompt string undefined 기본 시스템 프롬프트에 추가되는 텍스트. 내장 프롬프트를 교체하지 않고 지침을 추가하는 데 사용.
hooks Partial<Record<HookEvent, HookMatcher[]>> undefined 도구 실행 및 기타 에이전트 이벤트를 가로채는 훅 콜백. Hooks 참고.
settingSources SettingSource[] undefined 로드할 설정 소스. "user", "project", "local"의 배열.
includePartialMessages boolean false 토큰 수준 스트리밍 이벤트 포함
mcpServers Record<string, Record<string, unknown>> undefined 외부 MCP 서버 구성. 키는 서버 이름, 값은 서버 구성(예: { command: "node", args: ["server.js"] }). MCP servers 참고.
noMcp boolean false MCP 서버 비활성화
outputFormat { type: "json_schema"; schema: object } undefined 구조화된 출력 – JSON Schema에 대해 최종 응답 검증
cliPath string process.env.CORTEX_CODE_CLI_PATH ?? "cortex" 사용자 정의 CLI 바이너리 경로. 생략하면 SDK가 먼저 CORTEX_CODE_CLI_PATH를 확인하고 아니면 PATH의 cortex로 폴백.
extraArgs Record<string, string | null> undefined 키-값 쌍의 추가 CLI 인자

canUseTool 콜백

각 도구 실행 전에 호출되는 사용자 정의 권한 핸들러. 도구 호출이 진행되는지 제어하려면 allow 또는 deny 결과를 반환하세요.

많은 일반 도구 권한 확인에서 콜백 입력에는 { action, resource } 같은 필드가 포함됩니다. 허용/거부 결과와 선택적 거부 메시지가 이러한 확인에 사용됩니다. updatedInput은 AskUserQuestion, ExitPlanMode 같은 SDK 라우팅 의사 도구에 사용되며, 이들은 도구 특화 필드를 포함합니다.

type CanUseTool = (
  toolName: string,
  input: Record<string, unknown>,
  context: ToolPermissionContext,
) => Promise<PermissionResult>;

type ToolPermissionContext = {
  signal: AbortSignal;
  blockedPath?: string;
  decisionReason?: string;
  toolUseID: string;
  agentID?: string;
};

type PermissionResult = PermissionResultAllow | PermissionResultDeny;

type PermissionResultAllow = {
  behavior: "allow";
  updatedInput?: Record<string, unknown>;
  toolUseID?: string;
};

type PermissionResultDeny = {
  behavior: "deny";
  message?: string;
  interrupt?: boolean;
  toolUseID?: string;
};

예시

const session = await createCortexCodeSession({
  cwd: process.cwd(),
 canUseTool: async (toolName, input, context) => {
   if (toolName === "Write" && String(input.resource).endsWith(".env")) {
     return { behavior: "deny", message: "Destructive commands not allowed" };
   }
   return { behavior: "allow" };
  },
});

SystemPromptPreset

시스템 프롬프트를 완전히 교체하는 대신 preset 객체를 사용해 내장 프롬프트를 확장하세요.

type SystemPrompt = string | SystemPromptPreset;

type SystemPromptPreset = {
  type: "preset";
  append?: string;
};

예시

// Replace the system prompt entirely
const session1 = await createCortexCodeSession({
  cwd: process.cwd(),
  systemPrompt: "You are a code reviewer. Prioritize finding issues and suggesting fixes.",
});

// Extend the default prompt
const session2 = await createCortexCodeSession({
  cwd: process.cwd(),
  systemPrompt: {
    type: "preset",
    append: "Always write tests for any code you create.",
  },
});

Hooks

훅을 사용하면 도구 실행 같은 에이전트 이벤트를 가로챌 수 있습니다. 각 훅 이벤트는 매처 배열에 매핑되고, 각 매처는 선택적 패턴과 하나 이상의 콜백을 포함합니다.

type HookEvent =
  | "PreToolUse" | "PostToolUse" | "UserPromptSubmit"
  | "Stop" | "SubagentStop" | "PreCompact"
  | "Notification" | "PermissionRequest";

type HookMatcher = {
  matcher?: string;       // Match value pattern (optional)
  hooks: HookCallback[];
  timeout?: number;       // Timeout in seconds
};

type HookCallback = (
  input: HookInput,
  toolUseId: string | null,
  context: HookContext,
) => Promise<HookOutput>;

예시

const session = await createCortexCodeSession({
  cwd: process.cwd(),
  hooks: {
    PostToolUse: [
      {
        matcher: "Write",
        hooks: [
          async (input, toolUseId, context) => {
            console.log("File written:", input.tool_input?.file_path);
            return { continue: true };
          },
        ],
      },
    ],
  },
});

메시지 유형

query()와 session.stream()이 생성하는 이벤트:

SDKAssistantMessage

에이전트가 응답을 만들 때 발생. 하나 이상의 콘텐츠 블록을 포함.

type SDKAssistantMessage = {
  type: "assistant";
  content: ContentBlock[];
  message: {
    role: "assistant";
    content: ContentBlock[];
    model: string;
  };
  session_id: string;
}

SDKResultMessage

에이전트가 턴을 끝낼 때 발생. 성공/오류는 subtype으로 확인.

type SDKResultMessage =
  | { type: "result"; subtype: "success"; is_error: false; result: string; session_id: string; }
  | { type: "result"; subtype: "error_during_execution" | "error_max_turns" | "error_max_budget_usd";
      is_error: true; errors: string[]; session_id: string; }

SDKUserMessage

사용자 메시지가 처리될 때 다시 에코.

type SDKUserMessage = {
  type: "user";
  message: { role: "user"; content: ContentBlock[]; };
  session_id: string;
}

SDKSystemMessage

세션 초기화 같은 시스템 이벤트.

type SDKSystemMessage = {
  type: "system";
  subtype: string;  // e.g. "init"
  session_id: string;
}

콘텐츠 블록

유형 필드
TextBlock { type: "text", text: string }
ThinkingBlock { type: "thinking", thinking: string }
ToolUseBlock { type: "tool_use", id: string, name: string, input: object }
ToolResultBlock { type: "tool_result", tool_use_id: string, content: string }

스트리밍 이벤트

유형 설명
SDKPartialAssistantMessage 부분 텍스트/추론 스트리밍(includePartialMessages: true 필요)
StdErrEvent { type: "stderr", data: string } – CLI의 stderr
ParseErrorEvent { type: "parse_error", raw: string, error: string }

SDKPartialAssistantMessage는 부분 텍스트 및 추론 블록에 대해 발생합니다. 완전한 도구 호출은 여전히 AssistantMessage 블록으로, 도구 결과는 여전히 UserMessage 블록으로 도착합니다.

구조화된 출력

JSON Schema와 일치하는 응답을 반환하도록 에이전트를 강제합니다:

const result = query({
  prompt: "Analyze the codebase and return a summary",
  options: {
    cwd: process.cwd(),
    outputFormat: {
      type: "json_schema",
      schema: {
        type: "object",
        properties: {
          languages: { type: "array", items: { type: "string" } },
          file_count: { type: "number" },
          summary: { type: "string" },
        },
        required: ["languages", "file_count", "summary"],
      },
    },
  },
});

for await (const msg of result) {
  if (msg.type === "result" && msg.subtype === "success") {
    // The final text content will be valid JSON matching the schema
  }
}

자세한 내용은 구조화된 출력을 참고하세요.

오류 처리

try {
  for await (const message of query({ prompt: "...", options: { cwd: "." } })) {
    if (message.type === "result" && message.is_error) {
      console.error("Agent error:", message.errors.join(", "));
    }
  }
} catch (err) {
  // Thrown if the CLI binary is not found, session fails to start, etc.
  console.error("SDK error:", err.message);
}

더 알아보기