ClineCore API 参考:构建可持久化、可审批、可自动化的 Cline SDK 会话
本篇基于 Cline 仓库中的 ClineCore API 参考文档,系统讲解 @cline/sdk 提供的 ClineCore 运行时的完整 API 面:实例创建与后端模式选择、会话启动配置(ClineCoreOptions / CoreSessionConfig 全字段)、事件订阅类型、工具策略与交互式审批、自动化(automation)与设置(settings)子 API。读完后,你可以独立编写一个具备会话持久化、token 用量统计、工具权限控制和定时任务能力的 Cline 嵌入式应用。
一、ClineCore 是什么
ClineCore 是 @cline/core 包导出的全功能运行时,它包装了底层的 Agent 循环,并叠加了会话持久化、内置工具(bash、editor、文件读取、搜索、web 抓取)、.cline/ 配置发现、插件加载,以及可选的 hub 多进程支持。源码主类位于 ClineCore 实现,其 JSDoc 明确将其标注为 "The primary entry point for the Cline Core SDK"。
在什么场景下应该选择 ClineCore 而不是更轻量的 Agent?参考文档 clinecore REFERENCE 给出的对照:
| 使用 ClineCore 的场景 | 改用 Agent 的场景 |
|---|---|
| 需要内置工具(bash、editor 等) | 只用自定义工具 |
| 需要会话持久化到磁盘 | 无状态即可 |
需要从 .cline/ 目录做配置发现 |
自己管理配置 |
| 需要定时/自动化 agent | 不需要调度 |
| 需要多客户端共享会话 | 单进程即可 |
| 正在构建完整应用 | 希望依赖最小化 |
最小可用示例(摘自 REFERENCE.md,已验证与源码签名一致):
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create({ clientName: "my-app" })
const session = await cline.start({
prompt: "Set up CI with GitHub Actions",
config: {
providerId: "anthropic",
modelId: "claude-sonnet-4-6",
apiKey: process.env.ANTHROPIC_API_KEY,
cwd: "/path/to/project",
enableTools: true,
},
})
console.log(session.result?.text)
await cline.dispose()
从源码结构看,ClineCore 实例通过私有构造函数接收一个 RuntimeHost,对外暴露的 start / send / abort / stop / dispose / get / delete / update / readMessages 等方法几乎全部是 host 对应方法的转发(见 ClineCore.ts),真正的执行与持久化由 host 层完成。
二、创建实例:ClineCore.create(options)
import { ClineCore } from "@cline/sdk"
const cline = await ClineCore.create(options: ClineCoreOptions)
ClineCore.create 是工厂方法。对照 ClineCore.ts 的 create 实现,其内部流程为:解析 distinctId → 规范化 capabilities → 通过 createRuntimeHost(normalizedOptions) 按 backendMode 选择运行时 → 若开启了 automation 且 autoStart !== false,自动调用 core.automation.start()。
ClineCoreOptions 全字段
参考文档中给出的最小接口如下:
interface ClineCoreOptions {
clientName: string // identifies your app
distinctId?: string // user/instance identifier
backendMode?: "auto" | "local" | "hub" | "remote"
hub?: HubOptions
remote?: RemoteOptions
capabilities?: RuntimeCapabilities
toolPolicies?: Record<string, ToolPolicy>
automation?: boolean | ClineCoreAutomationOptions
fetch?: typeof fetch
}
结合源码中的完整定义 ClineCoreOptions,还可以补充以下文档未展开的字段与实际语义:
clientName(源码中为可选,类型string | undefined):人类可读的客户端名称,用于遥测与日志中识别消费者,如"my-app"、"acme-bot"。distinctId:稳定的机器/用户标识,用于遥测归因。源码注释说明:缺省时默认使用系统 machine ID,再退回到生成并持久化在~/.cline/data/machine-id的cl-<nanoid>。telemetry?: ITelemetryService、logger?: BasicLogger、featureFlags?: FeatureFlagsService:缺省时分别使用 no-op 遥测、无日志和 no-op 特性标志,即默认不产生任何外部副作用。messagesArtifactUploader?: SessionMessagesArtifactUploader:可选 hook,在messages.json落盘后被调用,可用于将会话转录镜像到远端存储。prepare?: (input: ClineCoreStartInput) => StartSessionBootstrap | undefined:每次会话启动前的准备 hook,返回的 bootstrap 可以在 core 启动运行前改写会话输入(见下文start的实现说明)。fetch:自定义fetch实现会被注入到本地会话使用的每个ProviderConfig.fetch,进而填充GatewayProviderSettings.fetch与顶层GatewayConfig.fetch,用于注入代理、重试、追踪或测试替身。源码注释强调优先级:会话级config.fetch或 provider 级存储的fetch会覆盖此默认值;且该设置只对"本进程内执行"的会话(local 与 auto 回退 local)生效——hub / remote 模式下 HTTP 调用发生在持有 gateway 的进程内,应在startHubServer({ fetch })处配置。automation:布尔或ClineCoreAutomationOptions,启用后可通过cline.automation.*访问文件驱动与事件驱动的自动化能力,无需自行构造 cron 服务。
后端模式(backendMode)
| 模式 | 行为 |
|---|---|
"auto"(默认) |
优先连接本地 hub;不可用时回退到进程内本地执行 |
"local" |
进程内执行 + 本地 SQLite/文件存储,不依赖 hub |
"hub" |
要求存在兼容的本地 WebSocket hub,不可达时抛错 |
"remote" |
连接显式指定的远端 hub endpoint |
对应结构体同样定义在 cline-core/types.ts:HubOptions 支持 endpoint、authToken、strategy: "prefer-hub" | "require-hub"、clientType、displayName、workspaceRoot、cwd;RemoteOptions 则要求必填 endpoint,其余字段与 hub 类似。对简单脚本与 CLI 工具,推荐显式使用 "local" 以避免 hub 发现开销;需要多客户端共享会话(例如 dashboard 从另一进程观察正在运行的会话)时使用 hub 模式。
capabilities:RuntimeCapabilities
interface RuntimeCapabilities {
requestToolApproval?: (request: ToolApprovalRequest) => Promise<ToolApprovalResult>
// ... other capability callbacks
}
源码中的完整定义比文档更精确,除了 requestToolApproval 还包含 toolExecutors(允许宿主接管内置工具的底层执行),见 runtime-capabilities.ts:
export interface RuntimeCapabilities {
toolExecutors?: Partial<ToolExecutors>
requestToolApproval?: (
request: ToolApprovalRequest,
) => Promise<ToolApprovalResult> | ToolApprovalResult
}
三、启动会话:start(input)
const session = await cline.start(input: ClineCoreStartInput)
start 返回 StartSessionResult:
interface StartSessionResult {
sessionId: string
manifest: SessionManifest
manifestPath: string
messagesPath: string
result?: AgentResult
}
会话消息与元数据会被持久化到 SQLite。从 REFERENCE.md 与 host 层实现看,本地模式下会话存储于:
~/.cline/data/sessions/
sessions.db # SQLite 数据库
[session-id].json # 消息历史
从源码结构看,ClineCore.start 有两个重载(ClineCore.ts):通用 StartSessionInput 与 core 专属的 ClineCoreStartInput。实际执行时,若配置了 prepare hook,会先拿到 StartSessionBootstrap 并用其 applyToStartSessionInput 改写输入;成功启动且会话仍处于活跃状态时,该 bootstrap 会被登记进 activeSessionBootstraps,在会话 ended 或出错时自动 dispose,实现工作区级运行时状态与会话生命周期的绑定。启动成功后还会经 emitSessionStartedTelemetry 发出遥测(仅在提供了 telemetry 服务时生效)。
ClineCoreStartInput
interface ClineCoreStartInput {
prompt: string
config: CoreSessionConfig
source?: string
interactive?: boolean
sessionMetadata?: Record<string, unknown>
initialMessages?: AgentMessage[]
toolPolicies?: Record<string, ToolPolicy>
capabilities?: RuntimeCapabilities
}
源码中该类型继承自 StartSessionInput 并替换了 config 字段为 ClineCoreStartConfig,另允许 localRuntime 本地运行时选项(types.ts)。
CoreSessionConfig
参考文档给出的字段(与源码 CoreSessionConfig 对照):
interface CoreSessionConfig {
cwd?: string // working directory
providerId: string // LLM provider
modelId: string // model identifier
apiKey?: string // provider API key
systemPrompt?: string // custom system prompt
tools?: readonly AgentTool[] // additional custom tools
enableTools?: boolean // enable built-in tools
hooks?: Partial<AgentRuntimeHooks> // runtime hooks
extensions?: AgentPlugin[] // plugins loaded inline
pluginPaths?: string[] // paths to plugin packages
extensionLoading?: "isolated" | "direct"
extensionContext?: { // context passed to plugin setup()
workspace?: { rootPath: string; cwd: string }
}
checkpointConfig?: CoreCheckpointConfig
compactionConfig?: CoreCompactionConfig
telemetry?: ITelemetryService
logger?: BasicLogger
enableSpawnAgent?: boolean // enable sub-agent spawning
enableAgentTeams?: boolean // enable team coordination
teamName?: string // team identifier
}
结合源码,有几点值得注意:
- 模型配置面比文档更宽。
CoreSessionConfig继承自CoreModelConfig,后者还包含baseUrl、headers、providerConfig、knownModels,以及推理控制字段thinking/reasoningEffort/thinkingBudgetTokens,采样参数maxTokensPerTurn、temperature(config.ts)。 - 插件加载。文档特别说明:
extensions直接传递插件对象;pluginPaths指向包含package.json且其中有cline.plugins字段的目录;务必设置extensionContext.workspace,否则插件setup()中拿到的ctx.workspaceInfo为undefined。 - checkpoints(检查点)默认关闭。源码中
CoreCheckpointConfig.enabled默认false——检查点是显式开启的功能,启用后每次 root-agent 运行开始时会用 git stash/ref 机制对工作区做可回滚快照;也可以传入自定义createCheckpoint(context: { cwd, sessionId, runCount })实现来替换内置 git 逻辑,返回{ ref, createdAt, runCount, kind? }即记入会话元数据(config.ts)。 - compaction(压缩)策略。
CoreCompactionConfig支持strategy: "basic" | "agentic"、preserveRecentTokens、独立 summarizer 模型配置,甚至完全自定义的compact(context)函数;context.abortSignal允许自定义压缩实现响应取消信号,避免被取消的回合卡在慢速压缩上(config.ts)。 - 执行控制。除文档字段外,源码还暴露
missionLogIntervalSteps/missionLogIntervalMs、onTeamEvent、onConsecutiveMistakeLimitReached、toolRoutingRules、skills(skills 工具的允许名单)等,用于精细控制多智能体与错误恢复行为。
enableTools: true 时,ClineCore 自动提供的内置工具为:bash(执行 shell 命令)、editor(编辑文件)、read_files(读取文件)、apply_patch(应用统一 diff)、search(搜索文件内容与结构)、fetch_web(HTTP 请求与网页内容)。
四、后续消息与事件订阅
send({ sessionId, prompt })
向已有会话发送后续消息:
const result = await cline.send({
sessionId: session.sessionId,
prompt: "Now add authentication",
})
返回 AgentResult | undefined。源码中 send 直接绑定到 RuntimeHost 的 runTurn(ClineCore.ts)。
subscribe(listener, options?)
const unsubscribe = cline.subscribe(
(event: CoreSessionEvent) => {
// handle events
},
{ sessionId: "optional-filter" }
)
CoreSessionEvent
type CoreSessionEvent =
| { type: "chunk"; payload: SessionChunkEvent }
| { type: "agent_event"; payload: { sessionId: string, event: AgentEvent } }
| { type: "ended"; payload: SessionEndedEvent }
| { type: "team_progress"; payload: SessionTeamProgressEvent }
| { type: "status"; payload: { sessionId: string, status: string } }
| { type: "hook"; payload: SessionToolEvent }
一个实用的流式输出订阅示例:
cline.subscribe((event) => {
switch (event.type) {
case "chunk":
if (event.payload.type === "text") {
process.stdout.write(event.payload.text)
}
break
case "ended":
console.log(`Session ended: ${event.payload.finishReason}`)
break
}
})
注意区分:CoreSessionEvent 是 ClineCore 层的事件,与独立 Agent 类发出的 AgentRuntimeEvent 不同;ClineCore 的结果对象用 AgentResult.text(而非独立 Agent 的 AgentRunResult.outputText)。subscribe 返回的函数即退订函数,cline.dispose() 内部也会用退订清理机制回收自己的内部监听。
五、会话管理:列举、读取、用量、恢复与清理
list / get / readMessages
const sessions: SessionRecord[] = await cline.list(50) // limit 默认 200
const session: SessionRecord = await cline.get(sessionId)
const messages: AgentMessage[] = await cline.readMessages(sessionId)
源码中 list 的默认 limit 确为 200(ClineCore.ts)。此外源码还区分了三种消息读取路径:readMessages(规范转录,供 resume/fork/compaction/模型回放使用)、readDisplayMessages(将 provider 侧的观测性 model-tool 活动投影成普通工具块,适合 UI 展示)和 readLiveMessages(会话仍在本进程内存中时优先读活动转录,避免持久化转录在回合边界才更新导致丢失进行中回合)。
getAccumulatedUsage(sessionId)
const usage = await cline.getAccumulatedUsage(sessionId)
// usage.usage - root agent only
// usage.aggregateUsage - root + subagents/teammates
即 usage 只统计 root/lead agent 的 token 与成本,aggregateUsage 还包含 teammates 与 subagents 的总和——多智能体场景下做成本核算应使用后者。
update / abort / stop / delete / restore / dispose
await cline.update(sessionId, { title: "New title" })
// abort:中断当前 in-flight 工具执行,会话保持存活
await cline.abort(sessionId, "User cancelled")
// stop:优雅终止会话并清理资源(不可恢复)
await cline.stop(sessionId)
// delete:永久删除会话及其数据(不可撤销,返回 boolean)
await cline.delete(sessionId)
// restore:从 checkpoint 恢复会话
await cline.restore({ sessionId, checkpointId })
// dispose:清理全部资源,用完务必调用
await cline.dispose("Shutting down")
源码对 abort 与 stop 的语义注释值得强调:abort 只中断当前工具操作(如长耗时 shell 命令),会话可以继续;stop 则彻底结束会话且不可 resume(ClineCore.ts)。
restore 在源码中的签名比文档更完整(types.ts):RestoreInput 含 checkpointRunCount、可选 cwd、restore 选项(messages / workspace / omitCheckpointMessageFromSession,均可选,默认均为恢复消息与恢复 git 快照)以及可选的 start 输入用于同时拉起一个 fork 会话;返回的 RestoreResult 携带 checkpoint: CheckpointEntry 与可选的新 startResult。配套的 compareCheckpoint({ sessionId, checkpointRunCount, cwd? }) 可将 checkpoint 与工作区做差异比对(ClineCore.ts)。
dispose 的完整清理链(源码可见):先 automationService.dispose() 再 host.dispose(),finally 中退订内部事件监听并并行 allSettled 地释放所有活跃 bootstrap。调用后实例不可复用。
六、AgentResult
会话操作返回的结果对象:
interface AgentResult {
text: string
usage: LegacyAgentUsage
messages: MessageWithMetadata[]
toolCalls: ToolCallRecord[]
iterations: number
finishReason: "completed" | "max_iterations" | "aborted" | "mistake_limit" | "error"
model: { id: string; provider: string; info?: ModelInfo }
startedAt: Date
endedAt: Date
durationMs: number
}
finishReason 的五种取值覆盖了正常完成、迭代上限、外部中止、连续错误超限与运行错误——在自动化流水线中应根据该字段分支处理(例如 mistake_limit 适合触发人工介入)。
七、工具策略:ToolPolicy 与交互式审批
会话级工具策略
const session = await cline.start({
prompt: "Review the code",
config: { ... },
toolPolicies: {
read_files: { autoApprove: true },
bash: { autoApprove: false },
editor: { enabled: false },
},
})
interface ToolPolicy {
enabled?: boolean // false = tool is hidden from the model
autoApprove?: boolean // false = requires approval callback
}
两个维度含义明确:enabled: false 直接让模型"看不见"该工具;autoApprove: false 则保留工具可见但在执行前必须通过审批回调。从源码结构看,策略在 Agent 运行时逐工具求值,例如 agent-runtime.ts 中 policy.autoApprove === false 分支会进入审批路径;同时支持 "*" 通配符策略(可参考 agent-runtime 测试 中 toolPolicies: { "*": { autoApprove: false } } 的用法)。ClineCore 自动化(cron)运行时在无人值守场景下的默认策略是 { "*": { autoApprove: true } },即默认自动批准(cron-runner.ts),这提示你:交互式应用不要依赖默认策略,应显式收紧。
交互式审批:requestToolApproval
const cline = await ClineCore.create({
clientName: "my-app",
capabilities: {
requestToolApproval: async (request) => {
console.log(`Tool: ${request.toolName}, Input: ${JSON.stringify(request.input)}`)
const approved = await askUser(`Allow ${request.toolName}?`)
return { approved }
},
},
})
request 为 ToolApprovalRequest(含 toolName、input 等),返回 { approved }。capabilities 在 create 时经 normalizeRuntimeCapabilities 规范化一次,之后在每次 start 时作为 defaultCapabilities 注入会话输入(ClineCore.ts)——这意味着实例级回调是全局兜底,单会话仍可用 start({ capabilities }) 覆盖。
八、Automation API 与 Settings API
Automation
在 ClineCore.create() 中开启 automation 后:
const cline = await ClineCore.create({
clientName: "my-app",
automation: true,
})
// Access automation methods
cline.automation.start()
cline.automation.stop()
cline.automation.reconcile(specs)
cline.automation.ingestEvent(event)
cline.automation.listEvents()
cline.automation.listSpecs()
cline.automation.listRuns()
源码侧的对应关系(ClineCore.ts):cline.automation 是一个 ClineCoreAutomationController,其内部惰性持有 CronService;未开启 automation 时调用任一方法会抛出明确错误 "ClineCore automation is not enabled. Pass \automation: true` or automation options to ClineCore.create()."。automation也可以传ClineCoreAutomationOptions对象,常用选项包括cronSpecsDir(旧字段 cronDir 已废弃)、cronScope: "global" | "user" | "workspace"、workspaceRoot、dbPath、pollIntervalMs、claimLeaseSeconds、globalMaxConcurrency、watcherDebounceMs、autoStart([types.ts](https://gitcode.com/GitHub_Trending/cl/cline/blob/be59305d7a632759e163012eeecddda59bc02cfe/sdk/packages/core/src/cline-core/types.ts?utm_source=gitcode_repo_files#L51-L65))。完整的控制器接口见 [ClineCoreAutomationApi](https://gitcode.com/GitHub_Trending/cl/cline/blob/be59305d7a632759e163012eeecddda59bc02cfe/sdk/packages/core/src/cline-core/types.ts?utm_source=gitcode_repo_files#L112-L125),另含 reconcileNow()、getEvent(eventId);listSpecs/listRuns/listEvents支持按triggerKind、status("queued" | "running" | "done" | "failed" | "cancelled")、processingStatus` 等过滤。
Settings
// Read settings
const settings = await cline.settings.list()
// Toggle tools, plugins, MCP servers
await cline.settings.toggle({ type: "tool", name: "bash", enabled: true })
cline.settings 由 createClineCoreSettingsApi(host) 构造(ClineCore.ts),类型 ClineCoreSettingsApi 从 settings 模块 导出,用于程序化读取与切换工具、插件、MCP server 的启用状态。
九、生命周期检查清单
把上述 API 组合起来,一个健壮的 ClineCore 应用应满足:
- 创建:按部署形态选择
backendMode(脚本/CLI 用"local",多进程共享用"hub"); - 启动:在
CoreSessionConfig中显式给出providerId/modelId/cwd/enableTools,敏感场景显式声明toolPolicies并提供requestToolApproval; - 观察:
subscribe处理chunk/ended等事件做流式输出与状态同步; - 核算:用
getAccumulatedUsage区分 root 与聚合用量; - 回收:
stop/abort区分"结束会话"与"打断操作",结束时await cline.dispose()释放 host、cron 服务与全部会话 bootstrap。
延伸阅读(仓库内文档)
- ClineCore 运行时总览与快速上手:.agents/skills/cline-sdk/references/clinecore/REFERENCE.md
- 常见模式与最佳实践:.agents/skills/cline-sdk/references/clinecore/patterns.md
- 陷阱与调试:.agents/skills/cline-sdk/references/clinecore/gotchas.md
- 工具创建:.agents/skills/cline-sdk/references/tools/REFERENCE.md
- 插件系统:.agents/skills/cline-sdk/references/plugins/REFERENCE.md
- 核心源码:ClineCore 主类、ClineCoreOptions 等类型定义、CoreSessionConfig 模型与会话配置、RuntimeCapabilities
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0624
Hy4-previewHy4 preview 是由腾讯混元团队研发的新一代混合专家(MoE)旗舰模型。模型总参数量 770B,每个 token 激活 49B,主干共包含78层,第一层采用标准 FFN,其余 77 层均为 MoE 结构,每层包含 256 个路由专家与 1 个共享专家,每个 token 激活 top-8 路由专家及共享专家。主干之外原生内置 1 层 MTP(总参数量 10B,激活 0.7B)以支持投机解码。Python00
GLM-5.3GLM-5.3 与 GLM-5.2 使用相同的基座模型——所有提升均来自后训练。与 GLM-5.2 相比,它在复杂编程和长程任务上的表现显著提升。Jinja00
GLM-5.3-FlashGLM-5.3-Flash (320B-A18B),是GLM-5系列的首个原生多模态模型。320B总参数,能力超过GLM-5.2Jinja00
Spark-X2.5-4BSpark-X2.5-4B 旨在让强大的 AI 更实用、更高效、更易获得。在广泛日常任务中表现强劲,涵盖对话、写作、翻译、推理、编码、工具调用以及智能体工作流,并在同等规模的开源模型中取得领先成绩。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00