核心来源 SDK
从 TypeScript 创建并运行完整的 AI 代理 。 核心源管理执行, 证书、存储和流;您的应用程序提供了代理定义 快点.
安装
npm install @coresourceai/sdk
export CORESOURCE_API_KEY='your-api-key'
需要20号或更新的节点.
SDK使用过 https://api.coresource.ai/v1/ 默认。 再来一次,
通过 { baseUrl: 'https://api.example.com/v1/' } 改为 createAgent() 或者说
new CoreSource(),或设置 CORESOURCE_API_URL。 。 。 .
创建代理
import { createAgent } from '@coresourceai/sdk';
const agent = createAgent({
// A saga plans and executes durable, multi-step research.
type: 'saga',
// The system prompt defines the agent's research method and quality bar.
systemPrompt: `You are a rigorous deep-research agent. Decompose the question,
search broadly, prioritize primary sources, cross-check important claims, and
resolve conflicting evidence. Cite every material claim, distinguish established
facts from inference, state uncertainty explicitly, and deliver a clear,
evidence-backed final report.`,
// Select the hosted model and use its highest reasoning-effort setting.
model: 'deepseek/deepseek-v4-flash',
effort: 'xhigh',
// Declare the artifact the agent should produce and persist with the run.
outputs: ['report.md']
});
try {
const result = await agent.run('Validate the invoice-management benchmarks.');
console.log(result.text);
const report = result.artifacts.find((artifact) => artifact.name === 'report.md');
if (report) console.log(await report.text());
} finally {
await agent.close();
}
createAgent() 既同步又懒惰 它第一次发出网络请求时
你打电话 run() 或者说 start()。 。 。 .
开始一个 agent 或者说 saga 需要至少1 000美元的预付余额,除非
账户在企业计划中。 一个被拒绝的开始抛出
InsufficientFundsError 有代码 InsufficientFunds一发请求不
分配运行时间;它们使用正常的推算平衡检查.
Core Source有三种代理类型:
| 类型 | 用它来 |
|---|---|
one-shot | 一个没有工具的模型响应 |
agent | 具有工具、技能、文件或MCP的迭接工作 |
saga | 计划、持久的多步骤工作 |
数值与 AgentType.OneShot, (中文(简体) ), AgentType.Agent,以及
AgentType.Saga。 。 。 .
一发
const answerer = createAgent({
type: 'one-shot',
systemPrompt: 'Answer clearly and concisely.',
model: 'deepseek/deepseek-v4-flash'
});
const result = await answerer.run('Explain three-way invoice matching.');
console.log(result.text);
一发特工故意无用工具. run() 使一个同步
请求到 API 网关并直接返回模型响应 - 没有
管理运行时间、桥接会、运行投票或 $1 运行时间地板。 使用 agent
或者说 saga 当运行需要工具,文件,技能,MCP服务器,流出时
进步,或文物.
工具
主机能力,如网络搜索和主机MCP服务器完全执行 核心来源. 他们不需要回你的申请.
一个 SDK 托管的工具在您的进程中执行 。 模型称为普通工具 名称, 且 CoreSource 透明地将呼叫给注册处理器 :
const agent = createAgent({
type: 'agent',
systemPrompt: 'Use the available business data.',
tools: [{
name: 'lookup_invoice',
description: 'Look up an invoice by ID.',
inputSchema: {
type: 'object',
properties: { id: { type: 'string' } },
required: ['id'],
additionalProperties: false
},
handler: async (input, { signal }) => {
signal.throwIfAborted();
return lookupInvoice(String(input.id), { signal });
}
}]
});
const result = await agent.run('Summarize invoice INV-123.');
没有默认注册本地工具 。 当特工需要你的申请时 文件系统、 命令运行器或网络上下文, 明确添加基础目录 第一次运行前:
const codingAgent = createAgent({ type: 'agent' });
codingAgent.registerRuntimeTools();
目录包含 file_read, (中文(简体) ), file_write, (中文(简体) ), file_edit, (中文(简体) ), glob, (中文(简体) ), grep, (中文(简体) ),
web_fetch,以及 execute。一个明确提供的 SDK 工具获得确切名称
碰撞。 主机搜索保留为 web_search。 。 。 .
图像理解
启用主机 understand_image(image, prompt) 通过选择一个
代理定义中可视能一发模型:
const visualAgent = createAgent({
type: 'agent',
systemPrompt: 'Inspect supplied images before drawing conclusions.',
model: 'deepseek/deepseek-v4-pro',
imageModel: 'makora/kimi-2.7-code'
});
const result = await visualAgent.run({
prompt: 'Read the attached chart and explain its largest change.',
files: ['./quarterly-chart.png']
});
图像模型是通过配置固定的;它不是代理可以使用的参数 变化。 主机运行时间读取运行本地图像并单独执行 通过 Core Source 调制一发请求。 图像从不需要 绕过你的SDK过程.
技能和MCP
技能字符串可以安装名称, 公开 owner/repository/path 参考文献,
或完整 GitHub 树 URL :
import { CoreSource, createAgent } from '@coresourceai/sdk';
const coresource = new CoreSource();
// Save the remote credential once. It is encrypted by CoreSource and never
// placed in the agent runtime or returned by a read/list API.
const researchMcp = await coresource.mcp.connect({
name: 'Research',
url: 'https://mcp.example.com/rpc',
auth: { type: 'bearer', token: process.env.RESEARCH_MCP_TOKEN! }
});
const researcher = createAgent({
type: 'saga',
systemPrompt: 'Prefer primary sources and retain direct URLs.',
skills: [
'deep-research',
'anthropics/skills/skills/pdf',
'https://github.com/owner/repository/tree/COMMIT_SHA/path/to/skill'
],
mcpServers: [{
connectionId: researchMcp.id,
alias: 'research'
}],
outputs: ['research.md']
});
用 API 密钥创建的连接默认为账户范围 。 连接 从一个经认证的用户会话中创建的默认是该用户的私人; 组织所有人可以明确选择组织范围.
主机MCP条目使用不透明的连接ID. 核心源注入远程
仅在其外出中继器、代理定义、运行、事件和
运行时配置从不包含它. OAuth 连接返回一个
authorizationUrl 打开一次 旋转静态证书
coresource.mcp.connections.rotateCredential(...) 并重新启动 OAuth 以
coresource.mcp.connections.authorize(...)。 。 。 .
对于 GitHub, 使用 Core Source 管理的 OAuth app 并有一个字段:
const github = await coresource.mcp.connect({
name: 'GitHub',
url: 'https://api.githubcopilot.com/mcp/',
auth: { type: 'oauth', provider: 'github' }
});
// Send the user to GitHub once, then use github.id in mcpServers after the
// callback changes the connection status to "connected".
console.log(github.authorizationUrl);
一个组织可以自行注册GitHub App或OAuth App. 内容
客户端秘密是只写,并由CoreSource加密. 配置返回的内容
callbackUrl 在 GitHub 中,然后在创建连接时通过 ID 选择应用程序 :
const app = await coresource.mcp.oauthApps.create({
name: 'Acme GitHub',
provider: 'github',
clientId: process.env.GITHUB_CLIENT_ID!,
clientSecret: process.env.GITHUB_CLIENT_SECRET!
});
console.log(`Set the GitHub callback URL to ${app.callbackUrl}`);
const github = await coresource.mcp.connect({
name: 'Acme GitHub',
url: 'https://api.githubcopilot.com/mcp/',
auth: { type: 'oauth', appId: app.id }
});
OAuth应用简介是组织层面的资源,需要所有者访问.
旋转 coresource.mcp.oauthApps.rotateCredential(...) 更新客户端
用于每个引用的连接,而不将该秘密复制到运行中.
要在您的应用程序中运行 MCP 客户端, 请打电话
agent.registerMcpServer(...) 在第一次比赛之前 本地技能捆绑也是
支持通过 { name, content, files } 条目.
档案和文物
通过本地路径或内存文件运行 :
const result = await agent.run({
prompt: 'Analyze the supplied invoices and write findings.md.',
files: [
'./invoices.csv',
{
name: 'policy.txt',
path: 'references/policy.txt',
data: 'Escalate invoices above EUR 50,000.',
mimeType: 'text/plain'
}
],
input: { country: 'DE', currency: 'EUR' }
});
for (const artifact of result.artifacts) {
console.log(artifact.name, await artifact.text());
}
文件目的地是运行所管理输入区域内的相对名称. 储存 位置和运行时文件系统根不是公共 API 的一部分.
清流和取消
run() 等待最终结果. start() 立即返回为 agent 财务报告和审定财务报表
saga数字 :
const run = await agent.start('Validate the benchmarks.');
for await (const event of run.events()) {
console.log(event.type, event.data);
}
const result = await run.result();
// When needed:
await run.cancel();
事件流包括状态,进度,日志,消息,工具活性,用法,
输出和终端结果事件。 事件ID可用于安全恢复.
投票结果没有默认全面超时,因此长距离跑可以继续
几天时间 过 timeoutMs 只有在打电话者有意要求等待期限时;
它永远不会取消运行.
人力投入
当代理打电话 ask_user,运行会持续暂停状态
awaiting_input。 。 。 . run.result() 立即带回问题
run.resume() 继续从检查站逃出:
const run = await agent.start('Prepare the launch plan and ask before choosing a date.');
let result = await run.result();
while (result.status === 'awaiting_input') {
const action = result.requiredAction;
if (!action) throw new Error('The run paused without a question.');
console.log(action.question);
const answer = await readAnswerFromYourUser();
await run.resume(answer);
result = await run.result();
}
对于请求/答复申请, agent.run() 可以处理每次暂停通过
一个回话:
const result = await agent.run('Prepare the launch plan.', {
onInputRequired: async ({ question }) => {
return readAnswerFromYourUser(question);
}
});
无 onInputRequired, (中文(简体) ), agent.run() 返回已暂停的结果而不是
无限期等待。 运行可能要求输入不止一次;每个答案是
提交该运行和 执行恢复 从相同的持久状态.
编剧
以 composeAgents; 使用普通承诺进行平行
分支 :
import { composeAgents } from '@coresourceai/sdk';
const pipeline = composeAgents(researcher, {
agent: createAgent({
type: 'agent',
systemPrompt: 'Turn the upstream evidence into an executive brief.',
outputs: ['brief.md']
}),
prompt: ({ previous }) => ({
prompt: `Write the brief from this upstream summary:\n\n${previous.text}`,
inputs: previous.artifacts.map((artifact) => ({
type: 'artifact',
runId: previous.id,
artifactId: artifact.id,
path: `upstream/${artifact.name ?? artifact.id}`
}))
})
});
const { result, steps } = await pipeline.run('Research invoice automation.');
const [eu, us] = await Promise.all([
euResearcher.run('Research EU benchmarks.'),
usResearcher.run('Research US benchmarks.')
]);
人工交接可能时仍然是服务器侧. 如果下游剂使用 SDK托管工具,SDK透明地下载并重新将交接器装入 那个代理的 管理的输入集.
已保存的代理
使用 CoreSource 定义何时应可重新使用并在
服务器 :
import { CoreSource } from '@coresourceai/sdk';
const coresource = new CoreSource();
const saved = await coresource.agents.create({
name: 'invoice-researcher',
type: 'saga',
systemPrompt: 'Validate claims using primary sources.',
model: 'openai/gpt-5',
skills: ['anthropics/skills/skills/pdf'],
outputs: ['report.md']
});
const result = await saved.run('Validate these invoice-management benchmarks.');
const updated = await saved.update({ description: 'Primary-source invoice analyst' });
const versions = await updated.versions();
已保存定义支持创建、检索、列表、更新、删除、运行、永久
版本,以及版本被绑定的运行. 函数处理器和当地技能组合
进程本地化,因此无法保存; 使用 createAgent() 这些.
关于直接的 HTTP 示例和完整的请求计划,见 核心源代码 HTTP API 指南。 。 。 .