ドキュメント
各 Package の使い方
ドキュメントデータは pnpm run docs:update により LienJack/guga-agent リポジトリから生成され、package ごとに用途、import、主要 API、利用例、パラメータ、注意点を整理しています。
CLI
@guga-agent/cli
@guga-agent/cli 提供面向最终用户的 guga 命令。它支持交互式 Ink workbench、headless runs、provider login/auth/config、model listing,以及基于 local host 的执行。
用途
@guga-agent/cli 提供面向最终用户的 guga 命令。它支持交互式 Ink workbench、headless runs、provider login/auth/config、model listing,以及基于 local host 的执行。
此包是 CLI 入口点,不是可复用的 library API。导入包根入口会执行 CLI 顶层入口。
本地开发安装
从仓库根目录:
pnpm dev:cli --install
source ~/.zshrc
guga包的 bin 将 guga 映射到 ./dist/index.js。
导入
不要将此包作为 library 导入。包根入口是可执行入口点,会运行 CLI 顶层代码。
guga --help 主要 API
- CLI binary:
guga。 - Internal executable entry:
src/index.ts。 - Internal command dispatcher:
commands/run.ts中的runCli(argv, io),由 tests 和 binary 使用。 - Workbench internals:
ink-workbench/下的 Ink UI、tui/下的 terminal compatibility helpers、host-factory.ts下的 host creation,以及render/下的 event rendering。
命令
guga:当 stdin/stdout 是 TTY 时启动交互式 workbench。guga chat或guga interactive:显式交互别名。guga run "<prompt>":运行一次 headless prompt。guga -p "<prompt>":headless mode 的短 one-shot 别名。guga init:初始化用户或项目 config。guga login <provider>:配置 provider credentials 或受支持的 OAuth flows。guga logout <provider>:移除本地 Guga-owned provider credentials。guga auth status [provider]:检查已脱敏的 provider auth state。guga --list-models:打印 model aliases 和 defaults。
常见 run flags 包括 --mock、--debug-events、--ops、--profile、--provider 和 --model。
常见用法
guga
guga run "summarize the repo" --mock --debug-events
guga -p "summarize the repo"
guga login openai --api-key-env OPENAI_API_KEY
guga auth status
guga --list-models 参数说明
guga run "<prompt>"和guga -p "<prompt>":<prompt>必填,多个非 flag 参数会用空格拼接;--mock使用 mock runtime;--debug-events输出调试事件渲染;--ops在 run 后打印 operational status;--profile <id>选择 CLI profile;--provider <id>指定 provider;--model <id>指定 model selector;--headless可被解析,但run本身已经是 headless 路径。guga、guga chat、guga interactive:进入交互式 workbench;可使用与 run 共用的--mock、--debug-events、--ops、--profile、--provider、--model。交互模式要求 stdin/stdout 都是 TTY。guga init:默认写 user config;--user或--project选择 scope;--force允许覆盖;--provider <id>、--provider-mode <mode>、--model <id>、--base-url <url>、--api-key-env <env>可初始化 provider/model 配置。guga login <provider>:<provider>必填;--mode <mode>或--provider-mode <mode>选择 provider mode;--api-key <value>直接写入 secret;--api-key-env <env>引用环境变量;--model <id>绑定默认模型;--static表示保存 static secret。未提供 API key 时,只有受支持 OAuth provider 会尝试 OAuth。guga logout <provider>:<provider>必填,用于移除 Guga 管理的本地 provider credentials。guga auth status [provider]:provider可选;省略时展示全部已知 provider 的脱敏 auth state。guga --list-models:无额外参数,列出已配置 model aliases、默认标记和不可用原因。runCli(argv, io):内部测试/入口函数;argv不包含 node/bin 前缀;io.stdout和io.stderr需要提供write(),stdin与isTTY决定是否允许交互模式,env可覆盖环境变量,oauthLoginRunner可注入 OAuth 登录实现。
内部入口点
src/index.ts:调用runCli(process.argv.slice(2), io)的可执行入口。runCli(argv, io):由 tests 和 executable 使用的 command parser 和 dispatcher。- Host construction 位于
host-factory.ts;rendering 位于render/下;Ink workbench code 位于ink-workbench/下。
注意事项
- 在 TTY 中运行裸
guga会打开 Ink workbench。非 TTY headless commands 会流式输出 host events,并在 run 结束后关闭 local host。 - Codex OAuth support 作为 pending/injected-runner path 存在,除非 host 提供 runner,否则可能被禁用。
- Runtime state 默认位于 Guga Home,通常是
~/.guga,除非 config 或GUGA_HOME覆盖它。
相关包
@guga-agent/host-sdk、@guga-agent/host-runtime和@guga-agent/host-protocol提供 host bridge。- Profile 和 plugin packages 提供 code、research、review、storage、ops、memory、eval 和 web-search capabilities。
Core
@guga-agent/core
@guga-agent/core 是与 provider 无关的运行时内核。它负责契约、agent loop、运行时 facade、provider 路由、能力注册、hooks、权限、事件发布、上下文投影、持久化契约,以及工具执行授权。
用途
@guga-agent/core 是与 provider 无关的运行时内核。它负责契约、agent loop、运行时 facade、provider 路由、能力注册、hooks、权限、事件发布、上下文投影、持久化契约,以及工具执行授权。
当你在构建 host、plugin、测试 fixture 或集成,并且需要在不依赖 CLI、HTTP、UI 或可选生态包的情况下运行 Guga 时,请使用此包。
导入
import { createAgentRuntime, HookEffect, HookPhase } from "@guga-agent/core";
import { createDefaultCoreCapabilities } from "@guga-agent/core/builtins";根入口点暴露契约和运行时原语。内置的文件系统、git、shell 和 AI SDK bridge 辅助能力通过 @guga-agent/core/builtins 暴露,这样常规 core 导入不会提前加载可选的 provider SDK。
主要 API
createAgentRuntime()和DefaultAgentRuntime:面向 host 的运行时创建与执行。AgentLoop:最小模型/工具 turn loop。ProviderRouter:模型选择、重试、fallback,以及 provider 失败归一化。CapabilityRegistry:provider、model、tool、skill、hook、context-policy、store、replay 和 operation 发现。PluginHost和LocalPlugin:可信的进程内 plugin 生命周期。ExecutionPipeline、ToolScheduler和ResultPolicy:schema 校验、感知权限的工具执行、调度和输出预算控制。PermissionKernel:对具有副作用的工具进行 allow/ask/deny 解析。HookKernel、HookPhase和HookEffect:生命周期、模型、上下文和工具 hook 执行。- 上下文辅助能力,例如压缩、投影、工具结果视图、重新注入、预算、压力和截断服务。
- 持久化 session、event、artifact、resume、fork、replay 和 corruption 契约。
- 测试 fixture,例如
createMockProvider()、createTestTool()和createExamplePlugin()。
常见用法
const runtime = createAgentRuntime({
plugins: [myPlugin],
builtIns: {
capabilities: createDefaultCoreCapabilities({ workspaceRoot: process.cwd() })
}
});
runtime.onEvent((event) => {
console.log(event.type);
});
const result = await runtime.run({
input: "summarize this repository",
providerId: "mock",
modelId: "primary"
}); 参数说明
createAgentRuntime(options?: AgentRuntimeOptions):options可省略;model用于传入旧式本地模型插件;plugins注册进程内LocalPlugin;builtIns可设为false禁用内置能力,或传入capabilities.providers、capabilities.models、capabilities.tools;permissions配置PermissionPolicy,包括profile、timeoutMs和resolver;routerPolicy指定 primary model、按purpose的候选模型和maxRetries;session提供默认sessionId、branchId等身份;stores可接入 events、sessions、artifacts 持久化;replay接入 replay 能力。runtime.run(options: AgentRunOptions):input为必填 prompt;providerId、modelId可显式选择模型;purpose用于 provider router 的用途路由;maxTurns限制 turn 数;signal用于取消;runId可由 host 指定;session可覆盖运行时默认 session 身份。createDefaultCoreCapabilities(options?: DefaultCoreCapabilitiesOptions):workspaceRoot默认为process.cwd();filesystem、git、shell可传入各自配置或设为false禁用;aiSdk需要config,可选factory,启用后会懒加载 AI SDK provider 能力。runtime.invokeTool(options: RuntimeToolInvokeOptions):通过 core 权限与执行管线调用工具;调用方应传入工具名、输入、运行上下文和可选signal,不要绕过 runtime 直接执行模型产出的 tool intents。
注意事项
- Core 不以内置形式实现 CLI、HTTP、UI、MCP、skills、memory、artifact storage、replay storage、evals 或 delegation。
- Provider SDK 类型不得泄漏到公共契约、loop、registry、hooks、permissions 或 execution pipeline 模块中。
- 模型生成的工具意图必须通过 core pipeline 进入;provider bridge 不应直接执行工具。
- 导出的测试 fixture 对验证很有用,但它们不是生产默认值。
相关包
@guga-agent/extension-sdk使用扩展元数据封装 core plugins。@guga-agent/host-runtime将 core runs 投影为 host resources 和 events。- Plugin packages 添加可选的 stores、MCP、skills、memory、replay、eval 和 operational capabilities。
Package
@guga-agent/eval-fixtures
@guga-agent/eval-fixtures 为 Guga 提供与路线图对齐的 hermetic eval fixtures。它是种子回归套件,不是基准测试平台。
用途
@guga-agent/eval-fixtures 为 Guga 提供与路线图对齐的 hermetic eval fixtures。它是种子回归套件,不是基准测试平台。
导入
import {
createFlywheelEvalManifest,
flywheelEvalFixtures,
getFlywheelFixturesByCategory,
validateFlywheelEvalFixtures
} from "@guga-agent/eval-fixtures"; 主要 API
flywheelEvalFixtures:用于路线图飞轮覆盖的 fixture 集合。createFlywheelEvalManifest(fixtures):构建按元数据分组的 manifest。getFlywheelFixturesByCategory(fixtures, category):按类别过滤 fixtures。validateFlywheelEvalFixtures(fixtures):验证 fixture 元数据和结构。- 类型:
EvalFixtureCategory、EvalFixtureLayer、FlywheelEvalFixture、FlywheelEvalManifest和FlywheelEvalManifestCategory。
常见用法
import { flywheelEvalFixtures } from "@guga-agent/eval-fixtures";
import { runEvalSuite } from "@guga-agent/plugin-eval-runner";
const result = await runEvalSuite([...flywheelEvalFixtures]); 参数说明
flywheelEvalFixtures是只读 fixture 集合,元素满足FlywheelEvalFixture。每个 fixture 继承EvalFixture,并增加module、category、layer、covers和tags元数据;runId必须稳定,便于回归对比。getFlywheelFixturesByCategory(fixtures, category)的fixtures是readonly FlywheelEvalFixture[],category必须是EvalFixtureCategory之一:"capability-discovery"、"host-protocol"、"production-ops"、"code-agent"或"deep-research"。createFlywheelEvalManifest(fixtures)接收 fixture 列表并返回FlywheelEvalManifest,包含fixtureCount、按固定 category 顺序生成的categories,以及去重排序后的modules。validateFlywheelEvalFixtures(fixtures)检查重复 id、空tags、空covers、缺少稳定runId,以及每个EvalFixtureCategory是否至少有一个 fixture;返回字符串诊断数组,空数组表示通过。FlywheelEvalFixture.module目前限定为"M6"、"M7/M11"、"M8"、"M9"或"M10";layer使用EvalFixtureLayer,可为 provider、tool、context、permission、session、protocol 或 profile。
注意事项
- Fixtures 包含类别、模块、层级、覆盖风险和标签的元数据。
- 该包依赖 eval runner 包执行。
- 保持 fixtures 小巧且 hermetic,使其无需 provider 凭据即可运行。
相关包
@guga-agent/plugin-eval-runner执行这些 fixtures。@guga-agent/core提供 eval 使用的运行时契约。
Extension
@guga-agent/extension-sdk
@guga-agent/extension-sdk 是可信 Guga extensions 的编写 facade。它会把 extension definition 转换成普通 core LocalPlugin,同时把 extension metadata 附加到每个已注册的 capability 上。
用途
@guga-agent/extension-sdk 是可信 Guga extensions 的编写 facade。它会把 extension definition 转换成普通 core LocalPlugin,同时把 extension metadata 附加到每个已注册的 capability 上。
当某个包提供可选运行时能力时使用它,例如 tools、providers、skills、hooks、context policies 或 operations。
导入
import { defineExtension, ExtensionSdkError } from "@guga-agent/extension-sdk"; 主要 API
defineExtension(definition):返回与 core 兼容的LocalPlugin。ExtensionDefinition:extension metadata,加上setup()和可选的shutdown()。ExtensionSetupContext:注册 facade,带有provider()、model()、tool()、skill()、hook()、contextPolicy()和operation()别名。ExtensionShutdownContext:传给shutdown()的生命周期上下文。ExtensionSdkError:在上下文已失效或注册特性不受支持时抛出。
常见用法
export const extension = defineExtension({
id: "example-extension",
source: { kind: "first-party", packageName: "@guga-agent/example-extension" },
namespace: "example",
declaredEffects: ["hook.observe"],
setup(context) {
context.tool(exampleTool, { source: "plugin" });
context.operation("example.health", { source: "plugin" });
},
shutdown() {
// Release extension-scoped resources here.
}
});将返回值传给 createAgentRuntime({ plugins: [extension] })。
参数说明
defineExtension(definition: ExtensionDefinition):id、source和setup(context)为必填;source.kind描述来源,source.packageName或source.location可补充包或位置;owner可省略,默认按 extensionid推导;name、version、namespace、declaredEffects、permissionRequirements、dependencies、lifecycle和shutdown(context)均为可选元数据或生命周期钩子。setup(context: ExtensionSetupContext):context.provider()、model()、tool()、skill()、hook()、contextPolicy()和operation()的第一个参数是要注册的能力对象或 operation name;第二个参数是 options,常用字段包括source、namespace、trust、declaredEffects、permissionRequirements、dependencies和lifecycle。ExtensionCapabilityOptions:source只能是"plugin"或"mcp",省略时默认为"plugin";namespace省略时继承 extension 的namespace;declaredEffects、permissionRequirements、dependencies、lifecycle省略时继承 extension 元数据。ExtensionToolOptions:除通用 capability options 外,还支持override,用于声明工具覆盖关系;其他能力注册不会开放override。ExtensionShutdownContext:提供pluginId、extension、isActive()和assertActive();生命周期方法返回后上下文会失效,因此不要在延迟异步任务中继续注册能力。
注意事项
- Extension capability 的
source可以是"plugin"或"mcp";它不能声明为"host"或"built-in"。 - Setup 和 shutdown 上下文会在其生命周期方法返回后失效。延迟的异步注册会抛出
ExtensionSdkError。 - SDK 会用
layer: "extension"、owner metadata、namespace、lifecycle metadata、declared effects、permission requirements 和 dependencies 丰富注册信息。
相关包
@guga-agent/core提供 plugin context 和 capability contracts。@guga-agent/plugin-mcp和@guga-agent/plugin-web-search使用这种形态提供可选 extensions。
Host
@guga-agent/host-local-server
@guga-agent/host-local-server 是覆盖 @guga-agent/host-runtime 的 Node HTTP 和 SSE adapter。它负责 transport 相关事项,并向 clients 暴露本地 host protocol。
用途
@guga-agent/host-local-server 是覆盖 @guga-agent/host-runtime 的 Node HTTP 和 SSE adapter。它负责 transport 相关事项,并向 clients 暴露本地 host protocol。
导入
import { HostLocalServer, createHostLocalServer } from "@guga-agent/host-local-server"; 主要 API
HostLocalServer:HTTP server wrapper,带有listen()、url、hostRuntime、bridgeToken和close()。createHostLocalServer(options):HostLocalServer的 factory。createHostRequestHandler(hostRuntime, options):用于自定义 Node servers 的更底层 request handler。streamRunEvents(options):run events 的 SSE streaming helper。- Types:
HostLocalServerOptions、HostLocalServerListenOptions、HostRequestHandlerOptions和StreamRunEventsOptions。
常见用法
const server = createHostLocalServer({
runtimeOptions: {
plugins: [myPlugin]
}
});
const baseUrl = await server.listen({ host: "127.0.0.1", port: 0 });
try {
console.log(baseUrl, server.bridgeToken);
} finally {
await server.close();
} 参数说明
createHostLocalServer(options?: HostLocalServerOptions):hostRuntime可传入已有HostRuntime;runtimeOptions用于创建内部HostRuntime;pollIntervalMs控制 SSE 轮询间隔;disposeRuntimeOnClose默认为true,关闭 server 时释放 runtime;bridgeToken可显式指定,否则自动生成。server.listen(options?: HostLocalServerListenOptions):host默认"127.0.0.1";port默认0,表示让系统分配可用端口。返回值是 base URL。createHostRequestHandler(hostRuntime, options?: HostRequestHandlerOptions):hostRuntime必填;options.bridgeToken用于校验非 GET mutating requests;options.pollIntervalMs传给 run event SSE streaming。streamRunEvents(options: StreamRunEventsOptions):hostRuntime、runId、request、response必填;afterSeq可用于从指定事件序号之后恢复;pollIntervalMs可覆盖默认轮询间隔。- HTTP request bodies:创建 session 使用可选
title;启动 run 需要input,可选providerId、modelId、maxTurns;队列输入需要mode为"steer"或"follow_up"且text非空;权限响应需要decision为"allow"或"deny"。
注意事项
- Mutating requests 需要 server 创建的 bridge token,除非调用方显式提供一个。
- GET routes 会进行 origin check。普通 client 访问应使用 SDK,而不是手写 requests。
/runs/:id/abort目前委托给与 cancel 相同的 runtime cancellation path。
相关包
@guga-agent/host-runtime提供进程内 host service。@guga-agent/host-protocol提供 DTOs 和 SSE event names。@guga-agent/host-sdk启动并连接此 server。
Host
@guga-agent/host-protocol
@guga-agent/host-protocol 定义 runtime、local server、SDK、CLI 和未来 UI clients 共享的可序列化 host protocol。它只包含 DTO 和辅助函数;不运行 agents、不提供 HTTP 服务,也不渲染 UI。
用途
@guga-agent/host-protocol 定义 runtime、local server、SDK、CLI 和未来 UI clients 共享的可序列化 host protocol。它只包含 DTO 和辅助函数;不运行 agents、不提供 HTTP 服务,也不渲染 UI。
导入
import {
HOST_PROTOCOL_VERSION,
createHostEventSequencer,
createSseEnvelope,
type HostEvent,
type RunResource
} from "@guga-agent/host-protocol"; 主要 API
- Host events:
HostEvent、HostEventInput,以及带类型的 run、message、tool、permission、interaction、queue、task、verification、artifact、usage 和 operational event 形态。 - Event helpers:
createHostEventSequencer()、hostEventSseName()、isTerminalHostEvent()和HOST_EVENT_SSE_NAME。 - Resource DTOs:sessions、branches、runs、queued input、interactions、permissions、capabilities、provider health、audit summaries、metrics、operations、tasks、verification attempts、artifacts 和 usage。
- Protocol constants:
HOST_PROTOCOL_VERSION和HOST_PROTOCOL_FEATURES。 - SSE helpers:
createSseEnvelope()和encodeSseEnvelope()。
常见用法
const sequencer = createHostEventSequencer();
const event = sequencer({
type: "run.started",
sessionId: "session-1",
runId: "run-1",
input: "hello"
});
const frame = encodeSseEnvelope(createSseEnvelope(event)); 参数说明
createHostEventSequencer(options?: { startSeq?: number; now?: () => Date }):startSeq指定已有事件序号的起点,省略时从0开始;now可注入时间源,省略时使用当前时间。返回的next(event)接收HostEventInput,会自动补齐递增seq和默认occurredAt。HostEventInput:是HostEvent去掉seq与occurredAt后的输入形态;run 范围事件通常需要type、sessionId、runId,再加各事件自身字段,例如run.started需要input,permission.resolved需要requestId、callId和decision。createSseEnvelope(event: HostEvent):event必须已经带有seq;返回的 envelope 使用String(event.seq)作为id,并使用 host event SSE 名称作为event。encodeSseEnvelope(envelope: SseEnvelope):将id、event和 JSON 序列化的data编码为 SSE frame 字符串;传入的data应保持 JSON-serializable。PermissionResolution:decision为必填,取"allow"或"deny";remember可选,取"once"、"session"或"always";reason和updatedInput可选,用于说明决策或替换工具输入。
注意事项
- 公共消费者应从包根入口导入。
events.ts中的一些内部 event type aliases 会体现在HostEventunion 内,但不会逐个重新导出。 - 保持 protocol objects 可 JSON 序列化。Runtime objects、functions、AbortSignals、child processes 和原始 provider clients 不属于 protocol resources。
相关包
@guga-agent/host-runtime发出这些 resources 和 events。@guga-agent/host-local-server通过 HTTP 和 SSE 暴露它们。@guga-agent/host-sdk、@guga-agent/host-stdio和@guga-agent/cli消费它们。
Host
@guga-agent/host-runtime
@guga-agent/host-runtime 将 @guga-agent/core 封装成进程内 host service。它负责 session 和 run state projection、canonical host events、queued run input、permissions、interactions、task projection 和 operational views。
用途
@guga-agent/host-runtime 将 @guga-agent/core 封装成进程内 host service。它负责 session 和 run state projection、canonical host events、queued run input、permissions、interactions、task projection 和 operational views。
当 host 需要运行时行为但还不想选择 transport 时,请使用它。
导入
import { HostRuntime, createHostRuntime, projectAgentEvent } from "@guga-agent/host-runtime"; 主要 API
HostRuntime:用于 sessions、runs、event streams、permissions、interactions、capabilities、operational status 和 task resources 的进程内 service。createHostRuntime(options):HostRuntime的 factory wrapper。projectAgentEvent(event, context):将 coreAgentEventfacts 映射为 host protocol events。- Types:
HostRuntimeOptions、StartRunOptions、EnqueueRunInputOptions、PermissionResponseResult和RequestInteractionOptions。
常见用法
const hostRuntime = createHostRuntime({
runtimeOptions: {
plugins: [myPlugin]
}
});
const session = await hostRuntime.createSession({ title: "Local work" });
const run = await hostRuntime.startRun({
sessionId: session.id,
input: "summarize the current project",
providerId: "mock",
modelId: "primary"
});
const events = await hostRuntime.listRunEvents(run.id); 参数说明
createHostRuntime(options?: HostRuntimeOptions):runtime可传入已有AgentRuntime;runtimeOptions用于创建内部 runtime;now和idFactory便于测试中固定时间与 ID;profileId和cwd传给 code task 分类;codeTasks提供可选的 code-task runtime。hostRuntime.createSession(options?: { title?: string }):title可选;省略时创建无标题 session,并默认建立mainbranch。hostRuntime.startRun(options: StartRunOptions):sessionId和input必填;providerId、modelId可选,用于显式模型选择;maxTurns可选,用于限制 agent loop turn 数。startRun()等待运行完成;startRunDetached()使用同一 options 但立即返回初始RunResource。hostRuntime.enqueueRunInput(runId, options: EnqueueRunInputOptions):runId必填;options.mode为"steer"或"follow_up";text必填且会进入队列预览。terminal run 会返回undefined。hostRuntime.requestInteraction(options: RequestInteractionOptions):sessionId和request必填;runId可选,传入时会验证该 run 属于 session,并发出 interaction event。hostRuntime.respondPermission(permissionId, resolution: PermissionResolution):permissionId必填;resolution.decision为"allow"或"deny";remember、reason、updatedInput可选,非法或非 pending 权限会返回结构化失败结果。
注意事项
- 此包不实现 HTTP、CLI、Web UI 或 desktop UI。
HostRuntimeOptions包含 code-task 集成点,但若干相关内部 helper types 不会从包根入口重新导出。- 配置 durable stores 后,host-sourced task 和 verification facts 可以作为 durable event envelopes flush。
相关包
@guga-agent/core运行 model/tool turns。@guga-agent/host-protocol定义发出的 DTOs。@guga-agent/host-local-server提供 HTTP/SSE transport。
Host
@guga-agent/host-sdk
@guga-agent/host-sdk 是本地 Guga host protocol 的带类型 client。它也提供用于启动进程内 local host server 的 helper,适合 tests、local apps 或 CLI 风格集成。
用途
@guga-agent/host-sdk 是本地 Guga host protocol 的带类型 client。它也提供用于启动进程内 local host server 的 helper,适合 tests、local apps 或 CLI 风格集成。
导入
import { connectHost, createLocalGugaHost, HostClientError } from "@guga-agent/host-sdk"; 主要 API
connectHost({ baseUrl, bridgeToken, fetch }):创建带类型的HostClient。HostClient:protocol、session、run、event stream、queued input、permission、interaction、task、capability、provider health、audit、metrics 和 operational status 方法。createLocalGugaHost(options):启动 local host server,并返回 client 和 close handle。streamHostEvents()和parseSsePayload():底层 SSE helpers。HostClientError:结构化 HTTP/protocol error。- Types:
ConnectHostOptions、CreateSessionRequest、StartRunRequest、SendRunInputRequest、RequestInteractionRequest、LocalGugaHostOptions和StreamHostEventsOptions。
常见用法
const host = await createLocalGugaHost({
runtimeOptions: {
plugins: [myPlugin]
}
});
try {
const session = await host.client.createSession({ title: "SDK run" });
const run = await host.client.startRun(session.id, { input: "hello" });
for await (const event of host.client.streamRunEvents(run.id)) {
console.log(event.type);
}
} finally {
await host.close();
} 参数说明
connectHost(options: ConnectHostOptions):baseUrl必填,末尾斜杠会被规整;bridgeToken可选,调用 mutating routes 时通常必需;fetch可选,用于注入测试或非默认 fetch 实现。createLocalGugaHost(options?: LocalGugaHostOptions):继承HostLocalServerOptions,可配置hostRuntime、runtimeOptions、bridgeToken、pollIntervalMs和disposeRuntimeOnClose;额外的listen可传host、port。返回baseUrl、client、server和close()。client.createSession(request?: CreateSessionRequest):title可选。client.startRun(sessionId, request: StartRunRequest):sessionId和request.input必填;providerId、modelId、maxTurns可选。client.streamRunEvents(runId, options?):runId必填;afterSeq可从指定序号之后继续消费;signal可取消 SSE 读取。client.sendRunInput(runId, request: SendRunInputRequest):runId必填;request.mode为"steer"或"follow_up";text必填。client.requestInteraction(sessionId, request: RequestInteractionRequest):sessionId和request.request必填;runId可选。client.respondPermission(permissionId, resolution)使用PermissionResolution,其中decision必填,remember、reason、updatedInput可选。
注意事项
- 包根入口不会从
client.ts重新导出每个内部 request type;请使用上方列出的 root API types 作为公共表面。 - 调用 mutating routes 时,始终传入 local server 返回的 bridge token。
相关包
@guga-agent/host-local-server由createLocalGugaHost()启动。@guga-agent/host-protocol定义 client resource 和 event types。
Host
@guga-agent/host-stdio
@guga-agent/host-stdio 为基于 HostClient 的 Pi-compatible stdio 风格集成提供 JSONL command 和 event adapter helpers。
用途
@guga-agent/host-stdio 为基于 HostClient 的 Pi-compatible stdio 风格集成提供 JSONL command 和 event adapter helpers。
它是 adapter library,不是独立进程:该包没有 bin 入口,也不自行拥有 read loop。
导入
import {
encodeJsonLine,
handleStdioCommand,
hostEventToPiCompatibleEvents,
parseJsonLine
} from "@guga-agent/host-stdio"; 主要 API
parseJsonLine(line):将一行 JSON command 解析为StdioCommand。encodeJsonLine(value):将 result 或 event 序列化为以换行结尾的 JSON 字符串。handleStdioCommand(client, command):通过注入的HostClient分发 commands。hostEventToPiCompatibleEvents(event):将 host protocol events 映射为 Pi-compatible event names。- Types:
StdioCommand、StdioCommandResult和PiCompatibleEvent。
常见用法
const command = parseJsonLine(line);
const result = await handleStdioCommand(hostClient, command);
stdout.write(encodeJsonLine(result));支持的 command types 包括 new_session、prompt、steer、follow_up、abort、get_state、get_messages、switch_session、fork、respond_interaction、extension_ui_response 和 get_last_assistant_text。
参数说明
parseJsonLine(line: string):line必须是一个 JSON 字符串,解析结果按StdioCommand处理;此函数不做 schema 校验,调用方应保证 command shape 正确。encodeJsonLine(value: unknown):value可以是 result 或 event;返回值总是 JSON 字符串加一个换行,适合直接写入 stdout。handleStdioCommand(client, command):client必须实现HostClient;command.type决定分发路径,返回StdioCommandResult,成功时为{ ok: true, data },失败时为{ ok: false, error }。StdioCommand:new_session可带title;prompt需要sessionId和input,可带providerId、modelId、maxTurns;steer和follow_up需要runId、text;abort、get_messages、get_last_assistant_text需要runId;get_state需要sessionId或runId;switch_session需要sessionId,可带branchId;fork需要sessionId,可带parentBranchId、createdFromRunId、summary。- Interaction commands:
respond_interaction使用requestId和可选response;extension_ui_response使用 Pi-compatible 的request_id和可选response。 hostEventToPiCompatibleEvents(event: HostEvent):event必须是 host protocol event;无法映射到 Pi-compatible vocabulary 的事件会返回空数组。
注意事项
compact在 command type 中保留,但目前返回UNSUPPORTED_COMMAND。abort委托给 host client 的 abort path。- Event mapping 按设计是有损的,因为它面向 Pi-compatible event vocabulary。
相关包
@guga-agent/host-sdk提供HostClient。@guga-agent/host-protocol提供 host event types。
Plugin
@guga-agent/plugin-artifact-filesystem
@guga-agent/plugin-artifact-filesystem 为 Guga 运行时提供基于文件系统的 ArtifactStore。它将 artifact 内容存储到磁盘,记录 manifest,在读取时校验哈希,并支持 tombstone 状态转换。
用途
@guga-agent/plugin-artifact-filesystem 为 Guga 运行时提供基于文件系统的 ArtifactStore。它将 artifact 内容存储到磁盘,记录 manifest,在读取时校验哈希,并支持 tombstone 状态转换。
导入
import {
FilesystemArtifactStore,
createFilesystemArtifactPlugin
} from "@guga-agent/plugin-artifact-filesystem"; 主要 API
createFilesystemArtifactPlugin(options): 将文件系统 artifact store 注册到核心插件上下文。FilesystemArtifactStore: 供希望自行管理注册流程的 host 直接使用的 store 实现。- 类型:
FilesystemArtifactPluginOptions、FilesystemArtifactStoreOptions、ArtifactManifest和ArtifactManifestTransitionRecord。
常见用法
const runtime = createAgentRuntime({
plugins: [
createFilesystemArtifactPlugin({
rootDir: ".guga/artifacts"
})
]
});高级 host 可以实例化 new FilesystemArtifactStore({ rootDir }),并通过自定义插件注册它。
参数说明
createFilesystemArtifactPlugin(options)使用FilesystemArtifactPluginOptions。rootDir为必填字段,指定 artifact 内容和 manifest 的落盘根目录;pluginId为可选字段,用于覆盖默认插件 id;now为可选时间函数,主要用于测试或可重复时间戳。new FilesystemArtifactStore(options)使用FilesystemArtifactStoreOptions。rootDir必填;now可选,默认返回当前 ISO 时间字符串。FilesystemArtifactStore.putArtifact(options)使用 core 的PutArtifactOptions。常见字段包括data(要写入的内容,必填)、artifactId(可选,缺省生成随机 id)、mimeType、label、privacyTags、retention、actor和metadata。
注意事项
- Artifact 内容和 manifest 会分开存储;读取时会校验记录的 SHA-256 哈希。
- 缺失、已 tombstone 和哈希不匹配的 artifact 会返回结构化诊断。
- 当前公共 API 暴露 tombstone 行为,而不是单独的公共 redaction helper。
- 该包不会自动持久化原始 provider payload;host 必须决定要写入哪些 artifact。
相关包
@guga-agent/core定义ArtifactStore契约。@guga-agent/plugin-replay-audit可以在 replay 期间读取 artifact 引用。@guga-agent/plugin-session-jsonl存储可能指向 artifact 的持久事件引用。
Plugin
@guga-agent/plugin-audit-export
@guga-agent/plugin-audit-export 将 agent 事件流投影为安全的运维摘要和指标快照。它面向需要计数、状态、用量、失败和权限结果的审计与健康状态界面,同时避免复制 prompt、工具输入或原始工具输出。
用途
@guga-agent/plugin-audit-export 将 agent 事件流投影为安全的运维摘要和指标快照。它面向需要计数、状态、用量、失败和权限结果的审计与健康状态界面,同时避免复制 prompt、工具输入或原始工具输出。
导入
import {
createAuditExportPlugin,
createAuditSummary,
createMetricsSnapshot
} from "@guga-agent/plugin-audit-export"; 主要 API
createAuditSummary(options): 从AgentEvent[]聚合 run、tool、permission、usage 和 failure 事实。createMetricsSnapshot(options): 从事件流派生高层运行时指标。createAuditExportPlugin(options): 注册可发现的audit.summary和metrics.snapshot操作。- 类型:
CreateAuditSummaryOptions、CreateMetricsSnapshotOptions和AuditExportPluginOptions。
常见用法
const summary = createAuditSummary({
runId: "run-1",
events,
startedAt: "2026-06-01T00:00:00.000Z",
completedAt: "2026-06-01T00:00:05.000Z"
});
const runtime = createAgentRuntime({
plugins: [createAuditExportPlugin()]
}); 参数说明
createAuditSummary(options)使用CreateAuditSummaryOptions。runId和events为必填字段,分别用于限定目标 run 和传入AgentEvent[];startedAt、completedAt可选,用于显式覆盖摘要中的开始/完成时间。createMetricsSnapshot(options)使用CreateMetricsSnapshotOptions。events必填;runId可选,传入后只统计对应 run;updatedAt可选,缺省使用当前时间。createAuditExportPlugin(options)使用AuditExportPluginOptions。pluginId可选,用于覆盖默认插件 id;该 factory 不接收事件数据,只注册audit.summary和metrics.snapshotoperation descriptor。
注意事项
- 该插件只注册 operation descriptor;它本身不会暴露模型可见工具或 HTTP route。
- 摘要中会包含失败消息,因此调用方应避免在错误消息中放入 secret。
- 需要有意义的 duration 字段时,请传入显式时间戳。
相关包
@guga-agent/core提供AgentEvent和运维契约。@guga-agent/profile-code-agent和@guga-agent/cli可以在组合运行时中包含 audit 操作。
Plugin
@guga-agent/plugin-context-default
@guga-agent/plugin-context-default 为 Guga 运行时提供默认 context policy 和 context 生命周期 hook。它覆盖资源发现、context 组装、预算决策、截断、压缩、重新注入以及相关 context 阶段。
用途
@guga-agent/plugin-context-default 为 Guga 运行时提供默认 context policy 和 context 生命周期 hook。它覆盖资源发现、context 组装、预算决策、截断、压缩、重新注入以及相关 context 阶段。
导入
import {
DEFAULT_CONTEXT_POLICY_ID,
createDefaultContextPlugin,
defaultContextHooks,
defaultContextPolicy
} from "@guga-agent/plugin-context-default"; 主要 API
createDefaultContextPlugin(options): 注册默认 context policy 和 hook。defaultContextPolicy(pluginId): 直接创建 policy 对象。defaultContextHooks(pluginId): 直接创建 hook 注册项。DEFAULT_CONTEXT_POLICY_ID: 稳定的 policy id。- 类型:
DefaultContextPluginOptions。
常见用法
const runtime = createAgentRuntime({
plugins: [createDefaultContextPlugin()]
});高级测试可以在需要独立检查或注册这些部分时,直接调用 defaultContextPolicy() 或 defaultContextHooks()。
参数说明
createDefaultContextPlugin(options)使用DefaultContextPluginOptions。pluginId可选,用于覆盖默认插件 id;该 id 也会传给默认 policy 和 hook,便于诊断与归属。defaultContextPolicy(pluginId)接收 policy 的pluginId字符串,返回可直接注册的 context policy 对象。defaultContextHooks(pluginId)接收 hook 的pluginId字符串,返回一组可直接注册的 hook 定义。DEFAULT_CONTEXT_POLICY_ID是稳定常量,不需要参数,适合 host 或测试引用默认 policy id。
注意事项
- 该插件会在可用时使用
registerContextPolicy,并通过常规 hook 路径注册 hook。 - 使用该插件的 host 必须支持 hook 注册。
- 该包不存储 context 历史;它只为运行时贡献 policy 和 hook 行为。
相关包
@guga-agent/core定义 context policy 和 hook 契约。- Host/profile 包可以在需要第一方默认 context 行为时安装该插件。
Plugin
@guga-agent/plugin-eval-runner
@guga-agent/plugin-eval-runner 针对 Guga 运行时运行 hermetic 本地 eval fixture。Fixture 使用 mock provider response 和预期结果,因此不需要 provider 凭据。
用途
@guga-agent/plugin-eval-runner 针对 Guga 运行时运行 hermetic 本地 eval fixture。Fixture 使用 mock provider response 和预期结果,因此不需要 provider 凭据。
导入
import {
createEvalRunnerPlugin,
passingMockFixture,
runEvalFixture,
runEvalSuite
} from "@guga-agent/plugin-eval-runner"; 主要 API
runEvalFixture(fixture, options): 运行单个 fixture 并返回结构化诊断。runEvalSuite(fixtures, options): 运行多个 fixture 并聚合结果。passingMockFixture和failingMockFixture: 小型示例 fixture。createEvalRunnerPlugin(options): 注册可发现的eval.run操作。- 类型:
EvalExpectation、EvalFixture、EvalResult、EvalRunnerOptions、EvalSuiteResult和EvalRunnerPluginOptions。
常见用法
const result = await runEvalSuite([passingMockFixture]);
if (!result.ok) {
console.error(result.failures);
}当某个运行时需要声明 eval 支持时,安装该插件:
const runtime = createAgentRuntime({
plugins: [createEvalRunnerPlugin()]
}); 参数说明
runEvalFixture(fixture, options)的fixture使用EvalFixture。id、input和mockResponses为必填字段;name、providerId、modelId、runId、maxTurns和expected可选,用于命名、选择 provider/model、固定 run id、限制 turn 数以及声明预期结果。EvalFixture.expected使用EvalExpectation。ok、finalAnswer、finalAnswerIncludes、errorCode和eventTypes均为可选字段,用于检查运行状态、最终回答、错误码和事件序列。runEvalSuite(fixtures, options)接收EvalFixture[];options使用EvalRunnerOptions,其中runtime可选,用于传入AgentRuntimeOptions并影响 fixture 创建的运行时。createEvalRunnerPlugin(options)使用EvalRunnerPluginOptions。pluginId可选;该 factory 只注册eval.runoperation descriptor,不接收 fixture。
注意事项
createEvalRunnerPlugin()不会执行 eval。实际执行使用导出的 runner helper。failingMockFixture有意用于 failure-path fixture。- 该包用于种子回归检查,而不是 benchmark scoring。
相关包
@guga-agent/core提供运行时和 mock provider 契约。@guga-agent/eval-fixtures提供与路线图对齐的 fixture 集合。
Plugin
@guga-agent/plugin-mcp
@guga-agent/plugin-mcp 是 Guga 的第一方 MCP 扩展。它连接到已配置的 stdio MCP server,列出它们的工具,并将每个 server tool 注册为常规 Guga ToolDefinition。
用途
@guga-agent/plugin-mcp 是 Guga 的第一方 MCP 扩展。它连接到已配置的 stdio MCP server,列出它们的工具,并将每个 server tool 注册为常规 Guga ToolDefinition。
导入
import {
McpStdioClient,
createMcpExtension,
createMcpPlugin,
mcpToolName
} from "@guga-agent/plugin-mcp"; 主要 API
createMcpExtension(options): MCP extension 注册的首选 factory。createMcpPlugin(options): 兼容性 alias。McpStdioClient: 低层 stdio MCP client。createMcpToolDefinition(options): 将 MCP tool metadata 和调用适配为 Guga tool。mcpToolName(serverName, toolName): 返回类似mcp__server__tool的规范化名称。stringifyMcpToolResult(result): 格式化 MCP tool output。- 类型:
McpPluginOptions、McpServerConfig、McpCallToolResult、McpClientInfo和McpToolInfo。
常见用法
const runtime = createAgentRuntime({
plugins: [
createMcpExtension({
servers: [
{
name: "filesystem",
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", process.cwd()]
}
]
})
]
}); 参数说明
createMcpExtension(options)和createMcpPlugin(options)都使用McpPluginOptions。servers为必填数组,列出要连接的 MCP server;pluginId可选,用于覆盖默认插件 id。McpServerConfig的name和command为必填字段。name用作工具 namespace 和依赖名称;command是要启动的 stdio server 命令;args、cwd和env可选,分别用于命令参数、工作目录和环境变量覆盖。new McpStdioClient(options)使用与 server 配置相同的 stdio 字段,并额外支持可选clientInfo,用于初始化握手中的 client 名称与版本。createMcpToolDefinition(options)需要serverName、tool和client。tool使用McpToolInfo,其中name必填,description和inputSchema可选。mcpToolName(serverName, toolName)接收原始 server/tool 名称并返回规范化工具名;stringifyMcpToolResult(result)接收McpCallToolResult并输出字符串内容。
注意事项
- 该包目前只支持 stdio transport。SSE、HTTP、OAuth 和 remote auth cache 尚未在这里实现。
- 注册的 MCP tool 使用
source: "mcp"、layer: "extension",并将 MCP server name 作为 namespace。 - Shutdown 会关闭已连接的 client,并移除 extension 拥有的 tool。
- 一些低层 client option 类型有意不从 package root 导出。
相关包
@guga-agent/core会通过与常规 tool 相同的 permission、hook、event 和 result-policy 路径执行 MCP tool。@guga-agent/extension-sdk提供 extension 生命周期 facade。
Plugin
@guga-agent/plugin-memory-candidates
@guga-agent/plugin-memory-candidates 包含纯内存候选项、治理、检索、Markdown 渲染和评审报告辅助能力。它还为一方记忆界面暴露小型操作注册插件。
用途
@guga-agent/plugin-memory-candidates 包含纯内存候选项、治理、检索、Markdown 渲染和评审报告辅助能力。它还为一方记忆界面暴露小型操作注册插件。
将此包用于记忆逻辑和视图。它本身不提供持久化存储,也不提供模型可见的工具。
导入
import {
createMemoryCandidate,
createMemoryCandidateLedger,
createMemoryCandidatesPlugin,
createMemoryGovernanceLedger,
renderGovernedMemoryBlock,
searchGovernedMemoryItems
} from "@guga-agent/plugin-memory-candidates"; 主要 API
- 候选项辅助函数:
createMemoryCandidate()、createMemoryCandidateLedger()、scanMemoryCandidateContent()、validateMemoryCandidate()和renderMemoryContextBlock()。 - 治理辅助函数:
createMemoryGovernanceLedger()、validateMemoryDecision()、listMemoryItemsByScope()和renderGovernedMemoryBlock()。 - 检索辅助函数:
searchGovernedMemoryItems()和renderMemoryRetrievalBlock()。 - Markdown/评审辅助函数:
renderCuratedMemoryMarkdown()、createMemoryReviewHealth()、createMemoryReviewReport()、renderMemoryReviewHealthBlock()和renderMemoryReviewReport()。 - 插件:
createMemoryCandidatesPlugin()、createMemoryGovernancePlugin()和createMemoryReviewPlugin()。 - 用于候选项、治理决策、检索结果、评审报告和渲染选项的类型。
常见用法
const candidate = createMemoryCandidate({
id: "mem-1",
scope: "project",
kind: "workflow",
content: "Prefer package-root public APIs in docs.",
confidence: 0.9,
importance: 0.7,
status: "accepted",
createdAt: new Date().toISOString(),
sourceRefs: [{ eventId: "event-1" }]
});
const diagnostics = validateMemoryCandidate(candidate);
const block = renderMemoryContextBlock([candidate]);只有当某个运行时需要公开记忆操作时,才安装该插件:
const runtime = createAgentRuntime({
plugins: [createMemoryCandidatesPlugin()]
}); 参数说明
createMemoryCandidate(input)接收Omit<MemoryCandidate, "safety"> & { safety?: MemorySafetyVerdict }。id、scope、kind、content、confidence、importance、status、createdAt和非空sourceRefs是候选项的核心字段;confidence与importance必须是0到1之间的数字,createdAt使用 ISO 时间字符串。safety可省略,函数会用scanMemoryCandidateContent()自动生成并与显式值合并;tags可选。createMemoryGovernanceLedger(candidates, decisions)需要候选项数组和MemoryDecision数组。MemoryDecision的action为"accept"、"reject"或"supersede";supersede必须提供supersedesItemId,itemId可用于覆盖生成的记忆项 id。listMemoryItemsByScope(ledger, filter)的filter.scope必填;kind、tags和includeSuperseded可选,用于缩小返回的GovernedMemoryItem[]。searchGovernedMemoryItems(items, query, options)的query必须包含可检索词,options.scope必填;kind、tags、includeSuperseded和maxResults可选,默认只返回 active 且 safe 的结果。- 渲染函数的 options 只影响视图,不改变数据。
RenderMemoryContextOptions、RenderGovernedMemoryOptions和RenderMemoryRetrievalOptions常用字段包括maxItems、maxContentChars、includeSourceRefs与title;RenderMemoryRetrievalOptions.includeReasons会附加命中原因。RenderCuratedMemoryMarkdownOptions还支持scopes、kinds和includeTags。 renderMemoryReviewReport(report, options)使用RenderMemoryReviewReportOptions控制报告标题和各分区数量:maxActiveItems、maxSupersededItems、maxCandidateItems、maxDiagnostics、maxContentChars。createMemoryCandidatesPlugin(options)、createMemoryGovernancePlugin(options)和createMemoryReviewPlugin(options)都接收MemoryCandidatesPluginOptions;目前只有可选pluginId,省略时分别使用包内默认 id。
注意事项
- 插件工厂只注册操作描述符;它们不会持久化记忆记录。
- 需要 JSONL 持久化时,请使用
@guga-agent/plugin-memory-jsonl。 - 检索和渲染辅助函数作用于调用方传入的、经过治理的内存数据。
相关包
@guga-agent/core提供操作发现契约。@guga-agent/plugin-memory-jsonl基于这些辅助函数构建持久化 JSONL 工作流。
Plugin
@guga-agent/plugin-memory-jsonl
@guga-agent/plugin-memory-jsonl 将记忆候选项和决策作为 JSONL 记录持久化,然后派生出治理账本、评审报告、健康视图、检索结果、精选 Markdown 和审计快照。
用途
@guga-agent/plugin-memory-jsonl 将记忆候选项和决策作为 JSONL 记录持久化,然后派生出治理账本、评审报告、健康视图、检索结果、精选 Markdown 和审计快照。
导入
import {
JsonlMemoryStore,
MEMORY_JSONL_OPERATION_NAMES,
createMemoryJsonlPlugin
} from "@guga-agent/plugin-memory-jsonl"; 主要 API
JsonlMemoryStore:基于 JSONL 的记忆记录存储和派生视图读取器。createMemoryJsonlPlugin(options):注册可发现的记忆 JSONL 操作。MEMORY_JSONL_OPERATION_NAME、MEMORY_JSONL_OPERATION_NAMESPACE、MEMORY_JSONL_OPERATION_NAMES和MEMORY_JSONL_READ_OPERATION_NAMES:稳定的操作常量。- 用于追加、读取、审计快照、评审、健康、检索、精选 Markdown、诊断、记录和存储选项的类型。
常见用法
const store = new JsonlMemoryStore({
rootDir: ".guga/memory"
});
await store.appendCandidate(candidate);
await store.appendDecision(decision);
const ledger = await store.readGovernanceLedger();
const retrieval = await store.readRetrieval("package docs", {});当某个运行时需要公开操作命名空间时,安装该插件:
const runtime = createAgentRuntime({
plugins: [createMemoryJsonlPlugin()]
}); 参数说明
new JsonlMemoryStore(options)使用JsonlMemoryStoreOptions。rootDir必填,表示 JSONL 目录;fileName可选,默认是"memory.jsonl"。appendCandidate(candidate, options)与appendDecision(decision, options)会先验证MemoryCandidate或MemoryDecision。options.recordId可覆盖默认记录 id,options.recordedAt可覆盖写入时间;省略时分别使用候选项/决策 id 和当前 ISO 时间。readRecords()无参数,返回原始JsonlMemoryRecord[]、候选项、决策和可恢复诊断;遇到不可恢复 JSON 或记录损坏时返回status: "corrupt"。readGovernanceLedger()、readReviewReport()和readReviewHealth()无业务参数,都是从当前 JSONL 派生视图;它们不写入文件。readReviewMarkdown(options)与readAuditSnapshot(options)接收RenderMemoryReviewReportOptions,用于控制标题、条目数量和内容截断长度。readReviewHealthMarkdown(options)只支持可选title。readRetrieval(query, options)的query是检索文本,options使用MemoryRetrievalOptions;其中scope必填,kind、tags、includeSuperseded和maxResults可选。readCuratedMarkdown(options)接收RenderCuratedMemoryMarkdownOptions,可用scopes、kinds、maxItems、maxContentChars、includeSourceRefs、includeTags和title控制导出 Markdown。createMemoryJsonlPlugin(options)接收MemoryJsonlPluginOptions;目前只有可选pluginId,默认是"memory-jsonl"。插件只注册MEMORY_JSONL_OPERATION_NAMES描述符,不绑定具体JsonlMemoryStore实例。
注意事项
- 该插件注册操作描述符;调用方仍然决定实际持久化时使用哪个存储实例。
memory.jsonl可读写。评审、报告、健康、审计快照、检索和精选 Markdown 操作都是只读描述符。- 当 JSONL 文件存在阻塞性损坏或最终行不完整时,追加操作会拒绝继续。
相关包
@guga-agent/plugin-memory-candidates提供候选项、治理、检索和渲染逻辑。@guga-agent/core提供操作描述符契约。
Plugin
@guga-agent/plugin-ops-health
@guga-agent/plugin-ops-health 提供 provider health check 以及经过 redaction 的 credential/config 视图。它为运维状态界面而构建;除非 host 注入显式的网络 health checker,否则它是 hermetic 的。
用途
@guga-agent/plugin-ops-health 提供 provider health check 以及经过 redaction 的 credential/config 视图。它为运维状态界面而构建;除非 host 注入显式的网络 health checker,否则它是 hermetic 的。
导入
import {
checkProviderHealth,
createOpsHealthPlugin,
redactSecret,
resolveCredentialConfig
} from "@guga-agent/plugin-ops-health"; 主要 API
resolveCredentialConfig(options): 将 env 或 static credential configuration 解析为经过 redaction 的视图和诊断。redactSecret(value): 对看起来像 secret 的值进行 redaction 以便展示。checkProviderHealth(options): 调用注入的 health checker 并规范化 status。createOpsHealthPlugin(options): 注册provider.health和provider.configoperation descriptor。- 类型:
CredentialConfigInput、ResolveCredentialConfigOptions、ProviderHealthCheck、ProviderHealthCheckResult、ProviderHealthTarget和OpsHealthPluginOptions。
常见用法
const config = resolveCredentialConfig({
providerId: "openai",
source: "env",
env: process.env,
requiredKeys: ["OPENAI_API_KEY"]
});
const health = await checkProviderHealth({
target: { providerId: "openai", modelId: "gpt-5.4" },
check: async () => ({ status: "healthy" })
}); 参数说明
resolveCredentialConfig(options)使用ResolveCredentialConfigOptions。providerId和source必填;values可选,用于 static 或 managed 配置值;requiredKeys可选,用于声明必须存在的 key;env可选,仅在source: "env"时用于替代process.env。redactSecret(value)接收string | undefined。缺失值返回<missing>,短值完全 redaction,较长值只保留头尾片段。checkProviderHealth(options)的target必填,使用ProviderHealthTarget,其中providerId必填、modelId可选;check可选,使用ProviderHealthCheck,用于执行实际健康检查;now可选,用于提供检查时间。createOpsHealthPlugin(options)使用OpsHealthPluginOptions。pluginId可选;该 factory 只注册provider.health和provider.configoperation descriptor。
注意事项
- 没有注入
check函数时,provider health 会报告为unknown,而不是发起网络调用。 - Static secret 会被 redaction 并带 warning 报告。
- 该插件只注册 operation descriptor;host 决定如何暴露 operation data。
相关包
@guga-agent/core提供运维契约。@guga-agent/profile-code-agent和@guga-agent/cli可以在组合运行时中包含 ops health。
Plugin
@guga-agent/plugin-replay-audit
@guga-agent/plugin-replay-audit 从持久 session、event 和 artifact 事实派生 replay 与 audit 视图。它无需重新运行 provider、tool 或 hook,就能重建 conversation、model-input 和 audit 投影。
用途
@guga-agent/plugin-replay-audit 从持久 session、event 和 artifact 事实派生 replay 与 audit 视图。它无需重新运行 provider、tool 或 hook,就能重建 conversation、model-input 和 audit 投影。
导入
import {
ReplayAuditProjectionCapability,
buildAuditView,
buildConversationView,
buildModelInputView,
createReplayAuditPlugin
} from "@guga-agent/plugin-replay-audit"; 主要 API
createReplayAuditPlugin(options): 向运行时注册 replay capability。ReplayAuditProjectionCapability: 围绕 store 的直接 replay capability wrapper。buildConversationView(options): 重建 branch 可见的 conversation message。buildModelInputView(options): 从已提交事实重建 provider 可见的 model input。buildAuditView(options): 构建有序 audit timeline。- 类型:
ReplayAuditPluginOptions、ReplayAuditStores、ConversationViewResult、ModelInputViewResult、AuditViewResult和BranchReplayView。
常见用法
const runtime = createAgentRuntime({
plugins: [
createJsonlSessionPlugin({ rootDir: ".guga/sessions" }),
createFilesystemArtifactPlugin({ rootDir: ".guga/artifacts" }),
createReplayAuditPlugin()
]
});当高级 host 已经自行管理 store 时,可以直接构造 ReplayAuditProjectionCapability。
参数说明
createReplayAuditPlugin(options)使用ReplayAuditPluginOptions。pluginId可选;eventStore、sessionStore和artifactStore可选,未传入时会尝试从 plugin context 获取。eventStore是 replay 的关键依赖;缺失时 replay capability 会返回 unavailable。new ReplayAuditProjectionCapability(stores)接收Partial<ReplayAuditStores>。eventStore用于读取持久事件流;sessionStore用于解析 branch-aware 视图;artifactStore用于 audit 视图中的 artifact 校验。buildConversationView(events)接收DurableEventEnvelope[],用于重建对话消息和相关诊断。buildModelInputView(events, request)接收DurableEventEnvelope[];request.turn可选,用于选择特定 turn 的 provider input 投影。buildAuditView(options)的events必填;branch、artifactStore和readDiagnostics可选,分别用于附加 branch 信息、检查 artifact 引用和合并读取诊断。
注意事项
- Replay 不会修改状态,也不会模拟或重新运行 model/tool 行为。
- 没有 event store 时,replay 会报告 unavailable。
- 没有 session store 时,branch-aware view 会回退到 main/default branch 假设。
- Audit view 包含针对 open run、open tool、open model request、open permission、compaction、artifact verification 和相关持久事实的诊断。
相关包
@guga-agent/core定义 replay 契约。@guga-agent/plugin-session-jsonl提供本地持久 event/session store。@guga-agent/plugin-artifact-filesystem提供 audit view 使用的 artifact 读取能力。
Plugin
@guga-agent/plugin-session-jsonl
@guga-agent/plugin-session-jsonl 提供 local-first 的核心 EventStore 和 SessionStore JSONL 实现。它会在 host 提供的 root directory 下持久化 durable event envelope 和 session tree fact。
用途
@guga-agent/plugin-session-jsonl 提供 local-first 的核心 EventStore 和 SessionStore JSONL 实现。它会在 host 提供的 root directory 下持久化 durable event envelope 和 session tree fact。
导入
import {
JsonlEventStore,
JsonlSessionStore,
createJsonlSessionPlugin
} from "@guga-agent/plugin-session-jsonl"; 主要 API
createJsonlSessionPlugin(options): 同时注册 JSONL event store 和 session store。JsonlEventStore: append-only durable event stream store。JsonlSessionStore: session、branch 和 active-leaf fact store。- 类型:
JsonlSessionPluginOptions、JsonlEventStoreOptions和JsonlSessionStoreOptions。
常见用法
const runtime = createAgentRuntime({
plugins: [
createJsonlSessionPlugin({
rootDir: ".guga/sessions"
})
]
});高级 host 可以直接实例化 store:
const eventStore = new JsonlEventStore({ rootDir: ".guga/sessions/events" });
const sessionStore = new JsonlSessionStore({ rootDir: ".guga/sessions/sessions" }); 参数说明
createJsonlSessionPlugin(options)使用JsonlSessionPluginOptions。rootDir为必填字段,作为 JSONL event/session store 的根目录;pluginId可选;upcasters可选,用于事件读取时的 schema 升级;now可选,用于 session fact 时间戳。new JsonlEventStore(options)使用JsonlEventStoreOptions。rootDir必填;upcasters可选,传给 durable event upcast 流程。JsonlEventStore.append(event, options)的event为必填DurableEventEnvelope;options使用 core 的EventAppendOptions,常见用途是传入 expected revision 或 idempotency 信息。JsonlEventStore.readStream(streamId, options)的streamId必填;options使用 core 的EventStreamReadOptions,可用于限制读取范围或指定目标 schema version。new JsonlSessionStore(options)使用JsonlSessionStoreOptions。rootDir必填;now可选,默认返回当前 ISO 时间字符串。
注意事项
- Event record 是 append-only durable envelope,并支持 expected revision 和 idempotency。
- 读取会校验 revision order 和 hash-chain continuity。
- 部分最终行可以在读取时报告为可恢复的 tail diagnostic,但 append 会拒绝继续写入带 partial tail 的 stream。
- 进程内 append queue 不是跨进程 lock。
- 该包不实现 remote sync、search、multi-writer conflict resolution 或 curated memory。
相关包
@guga-agent/core定义持久化契约。@guga-agent/plugin-replay-audit读取这些 store 以进行 replay。
Plugin
@guga-agent/plugin-skills
@guga-agent/plugin-skills 从配置的 root 中发现 SKILL.md 文件,并向运行时注册 skill metadata。它只在需要时加载完整 skill body 和 asset,因此默认模型上下文会保持较小。
用途
@guga-agent/plugin-skills 从配置的 root 中发现 SKILL.md 文件,并向运行时注册 skill metadata。它只在需要时加载完整 skill body 和 asset,因此默认模型上下文会保持较小。
导入
import {
createSkillsPlugin,
discoverSkills,
loadSkillBody,
resolveSkillAssetPath
} from "@guga-agent/plugin-skills"; 主要 API
createSkillsPlugin(options): 发现 skill,并通过 plugin context 注册 metadata。discoverSkills(options): 返回已发现的 skill、无效 skill 和名称冲突。loadSkillBody(skill): 在需要时加载已发现的 skill body。resolveSkillAssetPath(skill, relativePath): 解析 skill asset,同时防止路径逃逸。parseSkillFileContent()、parseSkillFrontmatter()和parseSkillMetadataFrontmatter(): frontmatter parsing helper。- 类型:
SkillsPluginOptions、DiscoveredSkill、InvalidSkill、SkillDiscoveryResult、SkillNameConflict、SkillRoot和ParsedSkillFile。
常见用法
const runtime = createAgentRuntime({
plugins: [
createSkillsPlugin({
roots: [{ path: ".guga/skills", namespace: "project" }]
})
]
});只有当选中的 skill 将被使用时,才加载 body:
const result = await discoverSkills({
roots: [{ path: ".guga/skills", namespace: "project" }]
});
const body = await loadSkillBody(result.skills[0]); 参数说明
createSkillsPlugin(options)使用SkillsPluginOptions。roots为必填数组,列出要扫描的 skill 根目录;pluginId可选,用于覆盖默认插件 id。SkillRoot的path为必填字段,指向包含SKILL.md的目录树;namespace可选,会在 skill frontmatter 未声明 namespace 时作为默认 namespace。discoverSkills(roots)接收SkillRoot[],返回SkillDiscoveryResult,其中skills是有效 skill,invalid是无效文件记录,conflicts是重复名称冲突。loadSkillBody(skill)接收DiscoveredSkill,读取并返回去掉 frontmatter 后的正文。resolveSkillAssetPath(skill, relativePath)接收DiscoveredSkill和相对路径,返回解析后的 asset 路径,并阻止路径逃逸。parseSkillFileContent()、parseSkillFrontmatter()和parseSkillMetadataFrontmatter()接收字符串内容,用于解析 skill frontmatter 和 metadata。
注意事项
- Frontmatter parser 有意保持小型,并不是完整的 YAML parser。
- Discovery 只读取每个 skill file 的前部以获取 metadata。
- Duplicate skill name 会保留排序更早的 entry,并在
discoverSkills()结果中报告 conflict。 - 除非 host 传入这些 root,否则该插件不会扫描全局用户目录。
相关包
@guga-agent/core定义 skill metadata 和 plugin registration。@guga-agent/profile-code-agent可以在 coding-agent bundle 中包含该插件。
Plugin
@guga-agent/plugin-tools-delegation
@guga-agent/plugin-tools-delegation 为能够运行隔离子代理的宿主贡献 delegate_task 工具形态。它会验证委派输入,调用注入的子运行器,记录精简账本,并向父运行返回有界结果。
用途
@guga-agent/plugin-tools-delegation 为能够运行隔离子代理的宿主贡献 delegate_task 工具形态。它会验证委派输入,调用注入的子运行器,记录精简账本,并向父运行返回有界结果。
导入
import {
DEFAULT_DELEGATE_TASK_TOOL_NAME,
createDelegationPlugin,
createDelegateTaskTool
} from "@guga-agent/plugin-tools-delegation"; 主要 API
createDelegationPlugin(options):通过运行时插件注册委派工具。createDelegateTaskTool(options):直接创建工具定义。buildDelegationInput(input):规范化模型提供的输入。validateDelegationConfig(options):验证子运行器/工具目录配置。- 账本辅助函数:
createDelegationLedger()、renderDelegationResult()、sortEventCounts()和validateDelegationOutput()。 - 常量:
DEFAULT_DELEGATE_TASK_TOOL_NAME和LEGACY_DELEGATE_TASK_TOOL_NAME。 - 用于子运行器、请求、结果、账本记录、事件计数、状态、验证诊断和工具选项的类型。
常见用法
const runtime = createAgentRuntime({
plugins: [
createDelegationPlugin({
childRunner: async (request) => ({
status: "completed",
summary: `Completed: ${request.goal}`,
events: []
}),
toolCatalog: []
})
]
}); 参数说明
createDelegationPlugin(options)与createDelegateTaskTool(options)的核心参数是DelegateTaskToolOptions。childRunner必填,宿主通过它真正启动子代理;parentRunId可传字符串或函数;toolName、description、defaultAgentType、defaultMaxTurns、defaultTimeoutMs、defaultToolAllowlist和blockedToolNames都是可选覆盖项。DelegationPluginOptions在DelegateTaskToolOptions基础上增加可选pluginId,默认是"agent-delegation"。toolCatalog是DelegationToolCatalogItem[],每项至少包含name。模型传入的toolAllowlist和defaultToolAllowlist必须都存在于toolCatalog,并且不能包含DEFAULT_DELEGATE_TASK_TOOL_NAME、LEGACY_DELEGATE_TASK_TOOL_NAME、当前toolName或blockedToolNames。createChildRunId(input)与createChildSessionId(input)可选,用于自定义子运行和子会话 id。省略时会基于父 tool call id、父 run id 和 agent type 生成稳定 id。delegate_task工具输入使用DelegateTaskInput。goal必填且不能为空;context可提供额外背景;agentType默认来自defaultAgentType或"general";toolAllowlist限制子代理工具;maxTurns与timeoutMs必须是正整数,省略时使用选项默认值或包内默认值。childRunner(request)收到DelegationChildRunRequest,其中input是buildDelegationInput()生成的完整提示,另含goal、可选context、agentType、tools、maxTurns、timeoutMs、parentRunId、parentToolCallId、childRunId、childSessionId和可选signal。validateDelegationConfig(options)只验证静态配置,例如工具目录空名、重复名和递归默认 allowlist;运行时输入仍由工具执行路径单独验证。
注意事项
- 宿主必须提供子运行器;此包本身不会生成进程或代理。
- 该工具会阻止递归调用委派工具。
- 默认权限元数据将委派视为外部效果。无头/后台 profile 默认拒绝,而可信会话可以允许。
- 委派任务应保持自包含,并且只传递子任务所需的上下文。
相关包
@guga-agent/core提供工具和插件契约。@guga-agent/profile-code-agent可以在更高层的编码工作流中使用委派概念。
Plugin
@guga-agent/plugin-web-search
@guga-agent/plugin-web-search 贡献可选的 web_search 工具。它是一种搜索发现能力:返回 URL、标题、摘要、时间戳、排名和审计元数据。它不会抓取任意页面、渲染浏览器或截图。
用途
@guga-agent/plugin-web-search 贡献可选的 web_search 工具。它是一种搜索发现能力:返回 URL、标题、摘要、时间戳、排名和审计元数据。它不会抓取任意页面、渲染浏览器或截图。
导入
import {
createBraveSearchBackend,
createMockWebSearchBackend,
createWebSearchPlugin,
createWebSearchTool
} from "@guga-agent/plugin-web-search"; 主要 API
createWebSearchPlugin(options):将web_search工具注册为扩展能力。createWebSearchTool(options):直接创建工具定义。- 后端:
createMockWebSearchBackend()和createBraveSearchBackend()。 - 输入/schema 辅助项:
parseWebSearchInput()、webSearchInputSchema以及默认/最大值常量。 - 域名辅助函数:
applyDomainPolicy()、domainMatches()、hostForUrl()、normalizeDomainFilter()和normalizeDomainFilters()。 - 格式化:
formatWebSearchResult()。 - 常量:
WEB_SEARCH_PACKAGE_NAME、WEB_SEARCH_PLUGIN_ID和WEB_SEARCH_TOOL_NAME。 - 用于后端请求/响应、权限选项、输入、格式化输出、域名诊断和提供方 id 的类型。
常见用法
const runtime = createAgentRuntime({
plugins: [
createWebSearchPlugin({
backend: createBraveSearchBackend({
apiKeyEnv: "BRAVE_SEARCH_API_KEY"
})
})
]
});工具输入形态:
{
query: string;
maxResults?: number;
allowedDomains?: string[];
blockedDomains?: string[];
recencyDays?: number;
searchType?: "web" | "news";
contextMaxCharacters?: number;
} 参数说明
createWebSearchPlugin(options)与createWebSearchTool(options)使用WebSearchPluginOptions/CreateWebSearchToolOptions。backend是实际搜索后端;只传providerId时工具会暴露为缺少后端而不可用。availability可显式设置或按运行时上下文计算可用性;permission.defaultAction与permission.trustedSessionAction覆盖权限默认动作;timeoutMs默认15000;resultBudget默认以 reference 策略限制12000字符;now便于测试固定fetchedAt。WebSearchPluginOptions.pluginId可选,默认使用WEB_SEARCH_PLUGIN_ID。插件注册的是固定工具名WEB_SEARCH_TOOL_NAME,即"web_search"。WebSearchInput.query必填,不能为空且最多 400 字符。maxResults是1到MAX_WEB_SEARCH_RESULTS的整数,默认DEFAULT_WEB_SEARCH_MAX_RESULTS;contextMaxCharacters是1到MAX_WEB_SEARCH_CONTEXT_MAX_CHARACTERS的整数,默认DEFAULT_WEB_SEARCH_CONTEXT_MAX_CHARACTERS。allowedDomains和blockedDomains是域名字符串数组,会通过normalizeDomainFilters()标准化;允许传裸域名、URL 或*.example.com形式。域名策略会在后端查询前写入 Brave query,并在后端返回后再次过滤。recencyDays可选,必须是1到365的整数;Brave 后端会映射为 freshness 参数。searchType可选,只能是"web"或"news",默认"web"。createBraveSearchBackend(options)支持apiKey、apiKeyEnv、env、endpoint、fetch和providerId。省略apiKey时会从apiKeyEnv指定的环境变量读取,默认环境变量名为"BRAVE_SEARCH_API_KEY";fetch可注入测试实现。createMockWebSearchBackend(options)支持providerId、静态或函数式results以及metadata,用于 hermetic 测试或本地演示。
注意事项
GUGA_WEB_SEARCH等 CLI 环境开关属于宿主级配置。此包提供工具和后端;它本身不会读取所有宿主配置环境变量。- 域名过滤会在后端调用前后执行。
- Brave 后端使用可注入的 fetch 路径,因此测试不需要真实 API key。
web_fetch有意作为单独的未来能力,不属于此包。
相关包
@guga-agent/core通过常规 schema、hook、权限、超时、事件和结果预算路径执行该工具。@guga-agent/extension-sdk提供扩展元数据注册。
Profile
@guga-agent/profile-code-agent
@guga-agent/profile-code-agent 提供一方编码代理 profile 辅助函数、权限策略、运行时包组合、仓库上下文发现、测试命令发现和自主代码任务契约。
用途
@guga-agent/profile-code-agent 提供一方编码代理 profile 辅助函数、权限策略、运行时包组合、仓库上下文发现、测试命令发现和自主代码任务契约。
它组合现有运行时能力。它不拥有第二套代理循环,也不会绕过核心权限或工具执行路径。
导入
import {
CODE_AGENT_PROFILE_ID,
CodeTaskController,
createCodeAgentPlugins,
createCodeAgentProfile,
createCodeAgentRuntimeOptions
} from "@guga-agent/profile-code-agent"; 主要 API
- Profile:
createCodeAgentProfile()、createCodeAgentSystemPrompt()和CODE_AGENT_PROFILE_ID。 - 权限:
createCodeAgentPermissionPolicy()、createCodeAgentPermissionResolver()和isDestructiveShellCommand()。 - 包辅助函数:
createCodeAgentPlugins()和createCodeAgentRuntimeOptions()。 - 仓库/测试上下文:
buildRepoContext()、renderRepoContext()和discoverTestCommands()。 - 任务控制器和契约:
CodeTaskController、createCodeTask()、classifyCodeTask()、transitionCodeTask()、validateCodeTask()、buildCodeTaskStagePrompt()、runVerification()、selectVerificationCommands()、summarizeVerificationToolResult()、renderCodeTaskContext()、createCodeTaskHostRuntime()和createCodeTaskReinjectionSource()。 - 用于 profile、包、权限、仓库上下文、测试发现、代码任务、阶段运行、计划检查、验证尝试和任务生命周期的类型。
常见用法
const runtimeOptions = createCodeAgentRuntimeOptions({
workspaceRoot: process.cwd(),
skills: { roots: [{ path: ".guga/skills", namespace: "project" }] },
includeOperations: true
});
const runtime = createAgentRuntime(runtimeOptions);进行任务编排时,请使用 CodeTaskController,并由宿主运行时提供阶段运行器。
参数说明
createCodeAgentProfile(options)使用CodeAgentProfileOptions;workspaceRoot可选,传入后会写入返回的CodeAgentProfile,不传则只返回通用 profile 元数据和 system prompt。createCodeAgentPlugins(options)、createCodeAgentRuntimeOptions(options)和内部的createCodeAgentBuiltIns(options)使用CodeAgentBundleOptions。workspaceRoot必填,用于默认核心能力;skills.roots可选,传给createSkillsPlugin();mcp.servers可选,传给createMcpPlugin();includeOperations默认true,控制是否附带 ops health、audit export 和 eval runner 插件。createCodeAgentPermissionPolicy(options)使用CodeAgentPermissionOptions。delegate是宿主权限解析器,可接管非自动允许/拒绝的请求;timeoutMs默认30000。没有delegate时,写入或执行类请求会被拒绝并标记需要宿主 resolver。buildRepoContext(options)的workspaceRoot必填;gitStatus、activeFiles、packageScripts和notes可选。函数会去重/排序文件列表与脚本,并过滤空 notes。discoverTestCommands(options)可传packageManager、packageScripts和changedFiles,默认包管理器为"pnpm"。new CodeTaskController(options)需要invoker和runStage。invoker负责通过运行时工具路径执行验证命令;runStage负责运行 scout/planner/executor/repairer 阶段;now、maxRepairAttempts、onTaskCreated、onTransition和onVerificationStarted是可选控制点。CodeTaskController.start(options)使用StartCodeTaskOptions。taskId、sessionId、rootRunId、cwd、objective和prompt必填;changedFiles用于测试命令发现;plannedChecks可直接提供VerificationCommand[],覆盖自动发现。createCodeTask(input)使用CreateCodeTaskInput。taskId、sessionId、rootRunId、cwd、objective和now必填;maxRepairAttempts可选,默认2。runVerification(options)使用RunVerificationOptions。task、invoker和commands必填;now、runId和onAttemptStarted可选。selectVerificationCommands(options)需要cwd,并可接收plannedChecks或测试发现选项。createCodeTaskHostRuntime(options)使用CodeTaskHostRuntimeOptions。cwd必填;profileId、packageManager、packageScripts和maxRepairAttempts可选。返回对象的start(options)需要宿主提供emit()、runStage()和invokeTool()。
注意事项
- 包根目录从
src/index.ts导出公共 profile 和任务 API;子模块中的内部辅助函数并非全部公开。 - 验证通过运行时/工具路径执行,因此权限、hook、结果预算和持久事件仍然适用。
- 长时间运行任务的完成需要已验证或已完成的账本项,并且需要通过必需的验证证据。
相关包
@guga-agent/core提供运行时、内置能力、权限和工具执行。@guga-agent/plugin-skills、@guga-agent/plugin-mcp、@guga-agent/plugin-ops-health、@guga-agent/plugin-audit-export和@guga-agent/plugin-eval-runner可以组合进该 profile。
Profile
@guga-agent/profile-deep-research-agent
@guga-agent/profile-deep-research-agent 提供一方深度研究 profile 辅助函数。它聚焦于来源策略、证据账本和结构化报告生成。
用途
@guga-agent/profile-deep-research-agent 提供一方深度研究 profile 辅助函数。它聚焦于来源策略、证据账本和结构化报告生成。
在构建需要区分事实、推论和仍需验证声明的研究工作流时使用它。
导入
import {
DEEP_RESEARCH_PROFILE_ID,
createDeepResearchProfile,
createEvidenceLedger,
renderResearchReport,
sortSourcesByPolicy
} from "@guga-agent/profile-deep-research-agent"; 主要 API
- Profile:
createDeepResearchProfile()、createDeepResearchSystemPrompt()和DEEP_RESEARCH_PROFILE_ID。 - 来源策略:
classifyResearchSource()、defaultResearchSourcePolicy和sortSourcesByPolicy()。 - 证据账本:
createEvidenceLedger()、evidenceByStrength()和validateEvidenceLedger()。 - 报告写入器:
checkResearchReportInput()和renderResearchReport()。 - 类型:
DeepResearchProfile、ResearchSourceLayer、ResearchSourcePolicyItem、EvidenceItem、EvidenceLedger、EvidenceStrength、ResearchReportInput和ResearchReportQualityDiagnostic。
常见用法
const sources = sortSourcesByPolicy([
"docs/research/context-packs/agent-loop.md",
"/path/to/raw/source.ts"
]);
const evidence = createEvidenceLedger([
{
id: "evidence-1",
claim: "The design uses a curated research funnel.",
strength: "Fact",
source: sources[0],
summary: "Project instructions define a layered research process.",
capturedAt: new Date().toISOString(),
confidence: 1
}
]);
const report = renderResearchReport({
title: "Agent Loop Research",
conclusion: "Use curated evidence before opening raw source.",
projectComparison: ["Reference projects converge on explicit loop state."],
reusablePatterns: ["Keep evidence strength visible in reports."],
avoidPatterns: ["Do not start from raw source when curated context exists."],
gugaLanding: ["Document decisions with Fact/Inference/Pending Verification labels."],
ledger: evidence
}); 参数说明
createDeepResearchProfile()与createDeepResearchSystemPrompt()不接收参数,返回固定的一方深度研究 profile 元数据和系统提示。sortSourcesByPolicy(paths)接收路径字符串数组,按defaultResearchSourcePolicy的层级排序;classifyResearchSource(path)根据路径命中context-pack、graph、understand-anything、source-analysis、repomix-token-tree、repomix-packed-context或raw-source。createEvidenceLedger(items)接收EvidenceItem[]并按id排序。每个EvidenceItem需要id、claim、strength、source、summary、capturedAt和confidence;strength必须是"Fact"、"Inference"或"Pending Verification",confidence应在0到1之间。validateEvidenceLedger(ledger)检查证据 id 重复、confidence范围,以及Fact是否包含非空source。evidenceByStrength(ledger)按证据强度分组,不改变原账本。renderResearchReport(input)使用ResearchReportInput。title、conclusion、projectComparison、reusablePatterns、avoidPatterns、gugaLanding和ledger都是必填字段;数组字段可为空,但空数组会渲染为- (none)。checkResearchReportInput(input)使用同一个ResearchReportInput,返回ResearchReportQualityDiagnostic[]。空证据账本是 error;缺少projectComparison是 warning。
注意事项
- 此包不会修改代码,也不会自行执行 Web 或文件系统研究。
- 它提供 profile 文本和纯辅助函数,供宿主或代理应用。
- 来源策略旨在优先使用精选材料,然后再使用原始源码。
相关包
@guga-agent/profile-code-agent可以在规划期间消费研究输出。@guga-agent/profile-review-agent为另一类工作流提供发现项优先的评审 profile。
Profile
@guga-agent/profile-review-agent
@guga-agent/profile-review-agent 提供一方评审/eval profile 辅助函数。它创建评审 profile 元数据,管理发现项账本,并渲染发现项优先的 Markdown 报告。
用途
@guga-agent/profile-review-agent 提供一方评审/eval profile 辅助函数。它创建评审 profile 元数据,管理发现项账本,并渲染发现项优先的 Markdown 报告。
它不会编辑代码,也不会直接集成 PR 提供方。
导入
import {
REVIEW_AGENT_PROFILE_ID,
createReviewAgentProfile,
createReviewFindingLedger,
renderReviewReport
} from "@guga-agent/profile-review-agent"; 主要 API
- Profile:
createReviewAgentProfile()、createReviewAgentSystemPrompt()和REVIEW_AGENT_PROFILE_ID。 - 发现项账本:
createReviewFindingLedger()、findingsBySeverity()和validateReviewFindingLedger()。 - 报告写入器:
checkReviewReportInput()和renderReviewReport()。 - 类型:
ReviewAgentProfile、ReviewConfidence、ReviewFinding、ReviewFindingCategory、ReviewFindingLedger、ReviewSeverity、ReviewReportInput和ReviewReportQualityDiagnostic。
常见用法
const ledger = createReviewFindingLedger([
{
id: "finding-1",
severity: "P1",
category: "correctness",
confidence: "high",
title: "Missing failure path",
body: "The handler does not return an error on invalid input.",
evidence: ["Invalid input test returns success."],
recommendation: "Return a structured validation failure."
}
]);
const report = renderReviewReport({
title: "Code Review",
ledger
}); 参数说明
createReviewAgentProfile()与createReviewAgentSystemPrompt()不接收参数,返回固定的一方 review/eval profile 元数据和系统提示。createReviewFindingLedger(findings)接收ReviewFinding[]并按ReviewSeverity、位置和 id 排序。每个ReviewFinding需要id、title、severity、confidence、category、body和evidence;file、line和recommendation可选。ReviewSeverity只能是"P0"、"P1"、"P2"或"P3";ReviewConfidence只能是"high"、"medium"或"low";ReviewFindingCategory覆盖 correctness、security、performance、test-gap、maintainability、protocol、permission、context、session 和 profile。validateReviewFindingLedger(ledger)检查 finding id 重复、空标题、空正文、缺少证据,以及line是否为正整数。findingsBySeverity(ledger)按严重级别分组,不修改账本。renderReviewReport(input)使用ReviewReportInput。title和ledger必填;openQuestions与summary可选,省略时分别渲染为None.和No additional summary.。checkReviewReportInput(input)返回ReviewReportQualityDiagnostic[]。空 finding 列表是 warning;空标题和无效账本项是 error。
注意事项
- 报告先呈现可执行的发现项,然后再呈现支持性上下文。
- 发现项应基于文件、行号、命令、追踪或文档化证据。
- 该包是纯辅助/profile 包;宿主决定如何运行评审以及在哪里发布报告。
相关包
@guga-agent/profile-code-agent处理代码执行工作流。@guga-agent/plugin-eval-runner和@guga-agent/eval-fixtures支持 eval 风格的回归检查。