이 페이지는 영어 문서의 번역입니다. 명령, 식별자, 예제는 그대로입니다. 런타임 7.24.4 · SDK 2.6.7. 영어 원문
@defai-digital/ax-code-sdk 안내
AX Code 코딩 에이전트 런타임을 자신의 애플리케이션에 통합하는 TypeScript SDK입니다.
호환되는 서명된 AX Code 런타임을 형식 있는 헤드리스 또는 gRPC 경계로 감독하고, 스트리밍 이벤트를 소비하고, 세션 상태를 투영하고, 애플리케이션 통합을 시험하는 데 사용합니다. 비공개 런타임 패키지를 의도적으로 제공하는 소스 호스트는 프로세스 안의 createAgent() 어댑터도 사용할 수 있습니다.
설치
pnpm add jsr:@defai-digital/ax-code-sdk@2.6.7
deno add jsr:@defai-digital/ax-code-sdk@2.6.7
npx jsr add @defai-digital/ax-code-sdk@2.6.7
Node.js 26+(또는 Node 호환이 있는 Deno)가 필요합니다. 더 이전 Node.js 버전은 지원하지 않습니다. 헤드리스와 gRPC 수명 주기 도우미는 서명된 ax-code 실행 파일이 PATH에 있거나, 절대 경로를 binary으로 전달받기를 기대합니다. SDK 버전과 런타임 버전은 독립입니다. 앱 기능을 켜기 전에 런타임 기능 프로토콜을 확인합니다. SDK 버전 확인만으로는 런타임 호환이 확립되지 않습니다.
작업 공간 패키지 이름 @ax-code/sdk는 이 모노레포 전용입니다. 공개 사용자는 항상 JSR에서 @defai-digital/ax-code-sdk를 설치합니다.
보고서 API 이전
AX Code 7.24.1은 DRE 그래프 보고서를 Run Report로 바꿉니다. 보고서 통합은 ax-code run-report과 /run-report HTTP 경로를 사용해야 합니다. 이전 dre-graph 명령과 /dre-graph 경로는 제거되었습니다. 생성된 SDK 연산은 이제 getRunReportSessionSessionId과 getRunReportSessionSessionIdFingerprint이며, 대응하는 getDreGraph 연산을 대체합니다.
보고서 통합과 런타임을 함께 업그레이드합니다. 다른 통합 표면은 여전히 각자의 런타임 기능 확인이 필요합니다.
통합 표면을 고릅니다
| 필요 | 사용 | 이유 |
|---|---|---|
| 대화형 저장소 작업 | ax-code TUI 또는 ax-code run |
checkout에서 일하는 사람에게 가장 빠른 경로 |
| 앱 셸이나 GUI 백엔드 | @defai-digital/ax-code-sdk/headless |
형식 있는 이벤트와 투영된 상태로 로컬 백엔드를 시작하거나 붙임 |
| 네이티브 데스크톱 경계 | @defai-digital/ax-code-sdk/grpc |
안정적인 명령/이벤트 계약, 스트리밍, 메타데이터, 기한, 네이티브 호스트 어댑터 |
| 공유 작업 모드 계약 | @defai-digital/ax-code-sdk/mode |
TUI와 앱 클라이언트가 공유하는 모드 ID와 도우미 |
| 공급자 연결 선택기 | @defai-digital/ax-code-sdk/provider-connect |
런타임 소스를 가져오지 않는 공급자 분류 체계 |
| 프로세스 안 소스 임베딩 | @defai-digital/ax-code-sdk createAgent() |
비공개 런타임 패키지를 해석할 수 있을 때 오버헤드가 가장 낮고 사용자 정의 도구 가능 |
| 편집기 네이티브 작업 흐름 | VS Code 통합 | 편집기 안에서 설치된 CLI/런타임을 사용 |
공개 애플리케이션은 호환되는 서명된 AX Code 런타임과 함께 headless 또는 grpc를 사용해야 합니다. HTTP/OpenAPI는 그 SDK 뒤에서 폴백과 진단 계층으로 남습니다. 이전 @defai-digital/ax-code-sdk/v2 하위 경로는 런타임 호환을 위해 남아 있습니다. 새 통합은 거기서 시작하지 마십시오.
createAgent()는 호출 시점에 비공개 ax-code 소스 패키지를 불러옵니다. 런타임은 JSR에 게시되지 않습니다.
빠른 시작(헤드리스)
import { createHeadlessClient, startHeadlessBackend } from "@defai-digital/ax-code-sdk/headless"
const directory = process.cwd()
const backend = await startHeadlessBackend({ directory })
try {
const client = createHeadlessClient({
baseUrl: backend.url,
directory,
headers: backend.headers,
})
const session = await client.createSession({ title: "SDK example" })
await client.sendPrompt(session.id, {
parts: [{ type: "text", text: "Summarize this project." }],
})
} finally {
await backend.close()
}
데스크톱 호스트는 검증된 절대 경로를 binary으로 전달할 수 있습니다. 투영 기반 앱 루프는 example/headless-app.ts를 보십시오.
헤드리스 백엔드
startHeadlessBackend은 임의의 루프백 포트에서 ax-code serve을 띄우고, 일회용 자격 증명을 만들고, /global/health를 기다린 뒤 핸들을 반환합니다. close()은 SIGTERM을 보낸 다음 SIGKILL을 보냅니다.
import {
startHeadlessBackend,
createHeadlessClient,
createHeadlessProjectionState,
applyHeadlessProjectionEvent,
} from "@defai-digital/ax-code-sdk/headless"
const backend = await startHeadlessBackend({ directory: "/path/to/workspace" })
try {
const client = createHeadlessClient({ baseUrl: backend.url, headers: backend.headers })
const state = createHeadlessProjectionState()
const session = await client.createSession({ title: "My session" })
await client.sendPrompt(session.id, { parts: [{ type: "text", text: "Review this project" }] })
for await (const event of client.subscribe()) {
applyHeadlessProjectionEvent(state, event)
if (state.session_status[session.id]?.type === "idle") break
}
} finally {
await backend.close()
}
createHeadlessProjectionState과 applyHeadlessProjectionEvent는 순수 TypeScript입니다. 앱 UI는 permission, question, session_diff, todo, session_status, session_error을 주 상태로 취급해야 합니다. 자율 응답은 선택입니다. 감독되는 앱은 대기 중인 권한과 질문 요청을 렌더링해야 합니다.
자율 투영은 isolation_escalation, bash_destructive, ops_approve, webmcp, hook, computer 권한과, 메타데이터가 requireInteractive: true를 설정한 모든 요청을 대기 상태로 둡니다. 소비자는 이 요청에 대해 명시적인 사람 응답을 받아야 합니다.
gRPC / 네이티브 데스크톱
네이티브 호스트가 이미 전송을 소유할 때(Electron preload, Tauri, Rust, HTTP/2) @defai-digital/ax-code-sdk/grpc을 사용합니다.
import {
createAxCodeGrpcClientFromNativeIpc,
resolveAxCodeGrpcProtoUrl,
startAxCodeGrpcHeadlessBackend,
} from "@defai-digital/ax-code-sdk/grpc"
const backend = await startAxCodeGrpcHeadlessBackend({ directory: "/path/to/workspace" })
try {
const client = backend.client
await client.bootstrap.load({
include: { sessions: true, providers: true, path: true, vcs: true },
})
const session = (await client.createSession({ title: "Desktop session" })) as { id: string }
await client.sendPrompt(session.id, { parts: [{ type: "text", text: "Review this project" }] })
const protoUrl = resolveAxCodeGrpcProtoUrl()
} finally {
await backend.close()
}
createAxCodeGrpcClientFromNativeIpc()— 구조화 복제 IPC(preload / Tauri).createAxCodeGrpcClientFromNativeBridge()— 같은 JavaScript 영역,AbortSignal와 비동기 이터러블.createAxCodeGrpcClientFromNativeHandlers()— 메서드 이름을 형식 있는 핸들러에 묶습니다.requireHandlers은 빈틈이 있으면 즉시 실패합니다.startAxCodeGrpcNodeHttp2Server(), 출처는@defai-digital/ax-code-sdk/grpc/node— 같은 브리지를 로컬 HTTP/2 gRPC 엔드포인트로 노출합니다.AX_CODE_GRPC_METHOD_DESCRIPTORS/listAxCodeGrpcMethods()— 허용 목록과 proto 이름을 위한 기준 메서드 카탈로그.
createAxCodeGrpcClientFromHttp()은 루프백 전용입니다. proto 자산은 packages/sdk/proto/ax_code/v1/headless.proto이며 런타임에 resolveAxCodeGrpcProtoUrl()로 해석됩니다.
프로세스 안 에이전트(소스 호스트만)
이 경로는 비공개 ax-code 런타임 패키지가 필요합니다. 공개 앱 통합 경계가 아닙니다.
import { createAgent, tool } from "@defai-digital/ax-code-sdk"
import { z } from "zod"
const deploy = tool({
name: "deploy_staging",
description: "Deploy the current branch to staging",
parameters: z.object({
service: z.enum(["api", "web", "worker"]),
skipTests: z.boolean().default(false),
}),
execute: async ({ service }) => ({ url: `https://staging.example.com/${service}` }),
})
const agent = await createAgent({ directory: "/repo", tools: [deploy] })
const result = await agent.run("Fix the login bug")
for await (const event of agent.stream("Explain this codebase")) {
if (event.type === "text") process.stdout.write(event.text)
}
const session = await agent.session()
await session.run("Read src/auth/index.ts")
await agent.dispose()
인증은 환경 변수에서 자동 감지되거나, auth: { provider, apiKey }로 주입되거나, ax-code providers login에서 가져옵니다.
import { ProviderError, ToolError, TimeoutError } from "@defai-digital/ax-code-sdk"
try {
await agent.run("Deploy to prod")
} catch (e) {
if (e instanceof ProviderError && e.isRetryable) console.log("Rate limited, retry later")
else if (e instanceof ToolError) console.log(`Tool "${e.tool}" failed: ${e.message}`)
else if (e instanceof TimeoutError) console.log(`Timed out after ${e.timeout}ms`)
}
더 많은 예: example/programmatic.ts.
시험
import { createMockAgent, assertToolSuccess } from "@defai-digital/ax-code-sdk/testing"
test("CI bot scans for CVEs", async () => {
const agent = createMockAgent({
replies: ["Found 2 CVEs. Opening PR to bump versions."],
toolCalls: [{ tool: "grep", input: { pattern: "CVE-" }, output: "CVE-2025-1234" }],
})
const result = await agent.run("scan for CVEs")
expect(result.text).toContain("2 CVEs")
assertToolSuccess(result, "grep")
})
버전 호환
import { SDK_VERSION, isSDKVersionCompatible } from "@defai-digital/ax-code-sdk"
console.log(SDK_VERSION)
if (!isSDKVersionCompatible("^2.0.0")) {
throw new Error("Incompatible SDK version")
}
요청 제어와 조향
SDK 2.6은 헤드리스 요청에 선택적 제어를 더합니다. 기존 호출은 동작을 유지합니다. 기본 기한은 두지 않습니다.
import { createHeadlessClient, HeadlessRequestError } from "@defai-digital/ax-code-sdk/headless"
const client = createHeadlessClient({
baseUrl: backend.url,
headers: backend.headers,
directory,
requestOptions: { timeoutMs: 30_000 },
})
const compatibility = await client.checkCompatibility({ requiredFeatures: ["sessions", "asyncPrompt"] })
if (!compatibility.compatible) throw new Error(compatibility.issues.join("; "))
const controller = new AbortController()
const state = await client.steering(sessionID, { signal: controller.signal, timeoutMs: 5_000 })
if (state.generation) {
try {
const receipt = await client.steer(
sessionID,
{
expectedGeneration: state.generation,
clientID, // Keep this id with the correction so uncertain outcomes can be reconciled.
text: "Use the existing session contract.",
},
{ signal: controller.signal },
)
console.log(receipt.status)
} catch (error) {
if (error instanceof HeadlessRequestError && error.status === 409) {
console.log("Correction conflicts with a prior request; reconcile the steering state.")
} else {
throw error
}
}
}
client.taskQueue.steer(taskID)은 원자적인 대기 후속 엔드포인트를 노출합니다. 그 generation_not_active 결과는 행을 바꾸지 않습니다. SDK는 영수증과 거부 이유를 그대로 반환합니다. accepted은 이후 루프 경계에 받아들여졌다는 뜻입니다. applied는 그 경계에서 지속되게 받아들여졌다는 뜻이며, 공급자 완료는 여전히 별개입니다. 영수증은 프로세스 로컬이고 크기가 제한되므로, 다시 시작한 뒤 없다고 교정이 적용되지 않았다는 증명은 아닙니다.
requestOptions는 워크플로와 작업 대기열 연산을 포함해 모든 헤드리스 편의 요청과 명령의 기본값을 제공합니다. 핵심 세션/명령 메서드와 조향은 호출별 재정의를 받습니다. timeoutMs: 0은 기본 기한을 끕니다. 구독은 자신의 signal을 사용하고, client.client은 생성된 클라이언트의 제어를 유지합니다. 사용자 정의 HeadlessTransport는 신호를 받으며, 중단되면 대기 중인 자원을 놓아야 합니다.
HTTP와 IPC 취소는 로컬 대기를 멈춥니다. 이미 보낸 변경은 여전히 실행될 수 있습니다. 더 나아가기 전에 세션/대기열 상태를 맞춥니다. 어느 전송도 변경을 재시도하지 않습니다. 기한은 TimeoutError을 일으킵니다. 호출자 중단은 신호의 이유를 보존합니다. 성공이 아닌 HTTP와 IPC 응답은 HeadlessRequestError을 일으키며, 함께 status, body, method, path를 담습니다. IPC 프로토콜 오류 프레임은 IpcTransportError을 유지합니다.
런타임 호환과 SDK 2.5에서 업그레이드
| 확인 | 확립하는 것 |
|---|---|
isSDKVersionCompatible(range) |
설치된 SDK 버전이 지원되는 SDK 범위 문법을 만족함 |
client.checkCompatibility({ requiredFeatures }) |
런타임이 기능 스키마 1, 헤드리스 스키마 1, 요청된 기능 플래그를 알림 |
client.steering(sessionID) |
이 런타임이 세션 조향 엔드포인트와 현재 세대를 노출함 |
| 서명된 런타임 검증 | 기능 응답과 독립된 바이너리 신원과 출처 |
현재 생성된 계약 기준선은 AX Code 소스 v7.23.0입니다. SDK 2.6은 런타임 버전에서 알리지 않은 기능을 추론하지 않습니다. 현재 기능 카탈로그는 조향을 따로 알리지 않습니다. 조향을 제공하기 전에 읽기 엔드포인트를 확인하고, 지원하지 않는 경로 오류를 처리합니다. SDK 2.6은 기존 생성 진입점과 헤드리스 진입점을 유지합니다. 새 응답 오류 메타데이터와 요청 제어는 추가입니다. Error을 잡는 코드는 계속 동작합니다.
더 오래된 고정을 올리는 애플리케이션은 먼저 서명된 런타임을 검증한 다음, 기능 협상, 이벤트 투영, 대기 중인 권한/질문, 취소, 백엔드 종료를 시험해야 합니다. 소비자 고정 변경은 대상 SDK가 게시된 뒤 소비하는 저장소에 둡니다. 컴파일된 패키지는 pnpm --dir packages/sdk/js run test:consumer로 로컬에서 검증합니다. 이것은 비공개 런타임 소스 패키지 없이, 격리된 픽스처에서 공개 import, 선언, proto 자산을 확인합니다.
언어를 넘는 통합
이 패키지는 자사 TypeScript/JavaScript SDK입니다. Python, Go, Java, Rust나 다른 런타임은 저장소 gRPC proto에서 생성하거나, 그 통합이 소유한 CLI/런타임 경계를 사용합니다.
@ax-code/sdk 1.4.0에서 이전
이전 (@ax-code/sdk 1.4.0) |
이후 (@defai-digital/ax-code-sdk 2.6.7) |
|---|---|
import { createAxCode } from "@ax-code/sdk" |
import { startHeadlessBackend } from "@defai-digital/ax-code-sdk/headless" |
import { createAxCodeClient } from "@ax-code/sdk" |
import { createHeadlessClient } from "@defai-digital/ax-code-sdk/headless" |
import { createAxCodeServer } from "@ax-code/sdk" |
import { startHeadlessBackend } from "@defai-digital/ax-code-sdk/headless" |
import { createAgent } from "@ax-code/sdk/programmatic" |
import { createAgent } from "@defai-digital/ax-code-sdk" |
| 사용자 정의 도구 없음 | import { tool } from "@defai-digital/ax-code-sdk" |
| 시험 유틸리티 없음 | import { createMockAgent } from "@defai-digital/ax-code-sdk/testing" |
./programmatic 하위 경로는 여전히 기본 진입점을 다시 내보냅니다. 폐기된 것으로 취급합니다.
라이선스
Apache-2.0