Runtime 与 Sandbox 模块详细设计
本文档展开 kgent/runtime/ 和 kgent/sandbox/ 的代码设计。
这两个模块共同定义一次 kgent run 的生命周期、身份、状态和工作区边界,是未来调度、revision 和高并发的基础。
目标关联
Runtime 与 Sandbox 支撑:
- Sandbox-First Work Execution
- Tool-Mediated Action System
- Quality and Governance System
- Professional Workflow Orchestration
它们直接支撑可审计交付、上下文连续性、未来群组协作和专业可靠性。
模块范围
Runtime 包含:
- 创建 run IDs。
- 创建
RunContext。 - 协调一次 run。
- 更新 run state。
- 串联 config、sandbox、records、skills、tools、engine、governance。
Sandbox 包含:
- 创建 run directory。
- 写入基础 files。
- 解析和校验 sandbox paths。
- 生成
sandbox-manifest.json。 - 生成
artifact-manifest.json。
不包含:
- 领域逻辑。
- 直接调用模型细节。
- 直接执行 memory backend。
- 直接授予工具权限。
文件结构
src/kgent/runtime/
__init__.py
runner.py
context.py
ids.py
state.py
options.py
src/kgent/sandbox/
__init__.py
workspace.py
paths.py
manifest.py
数据模型
Run IDs
位置:runtime/ids.py
def new_session_id() -> str:
...
def new_task_id() -> str:
...
def new_run_id() -> str:
...
建议格式:
sess_<timestamp>_<short-random>
task_<timestamp>_<short-random>
run_<timestamp>_<short-random>
IDs 应适合文件名、安全、短且可读。
RunOptions / RunResult
位置:runtime/options.py
class RunOptions:
sandbox: Path | None
session_id: str | None
task_id: str | None
run_id: str | None
stream: bool | None
max_steps: int | None
timeout_seconds: int | None
class RunResult:
session_id: str
task_id: str
run_id: str
status: str
sandbox_root: Path
final_text: str | None
error: ErrorInfo | None
RunContext
位置:runtime/context.py
class RunContext:
session_id: str
task_id: str
run_id: str
profile_id: str
config_fingerprint: str
sandbox_root: Path
config: KgentConfig
records: RunRecords
RunContext 不包含模型内部状态。
Run State
位置:runtime/state.py
class RunStatus:
pending
running
completed
incomplete
failed
run.json 是 Phase 1 source of truth。
SandboxWorkspace
位置:sandbox/workspace.py
class SandboxWorkspace:
root: Path
workspace_dir: Path
deliverables_dir: Path
archive_dir: Path
logs_dir: Path
Manifests
位置:sandbox/manifest.py
class SandboxManifest:
root: Path
writable: list[str]
readonly: list[str]
forbidden: list[str]
created_at: str
class ArtifactRecord:
path: str
kind: str
created_by: str
required: bool
content_type: str | None
class ArtifactManifest:
artifacts: list[ArtifactRecord]
updated_at: str
目录创建规则
给定 run_id 和 sandbox root,必须创建:
runs/<run-id>/
workspace/
deliverables/
archive/
logs/
Phase 1 必须写入:
run.json
prompt.md
config.yaml
effective-system-prompt.md
sandbox-manifest.json
artifact-manifest.json
events.jsonl
transcript.md
Path Guard 规则
位置:sandbox/paths.py
def resolve_sandbox_path(root: Path, user_path: str, *, for_write: bool) -> Path:
...
必须拒绝:
- 绝对路径逃逸。
..traversal。- symlink 逃逸。
- 写入 sandbox root 外。
- 写入非允许目录。
允许写入:
workspace/deliverables/archive/logs/
其中工具默认只能写 workspace/ 和 deliverables/,内部 runtime 可以写 archive/ 和 logs/。
Runtime 主流程
位置:runtime/runner.py
def run(config_path: Path, prompt: str, options: RunOptions) -> RunResult:
...
流程:
load_config。apply_cli_overrides。fingerprint_config。- 创建或接收 IDs。
- 确定 sandbox root。
- 创建 workspace。
- 初始化
run.json,状态为pending。 - 初始化
RunRecords。 - 写入
prompt.md、config.yaml。 - discover skills。
- recall memory。
- render effective system prompt 并写入。
- 写入 manifests。
- 更新 run state 为
running。 - build toolsets。
- 调用 engine。
- validate deliverables。
- 更新 artifact manifest。
- 更新 run state 为
completed、incomplete或failed。 - finalize transcript。
run.json
Phase 1 字段:
{
"session_id": "...",
"task_id": "...",
"run_id": "...",
"profile_id": "...",
"config_fingerprint": "...",
"status": "running",
"created_at": "...",
"updated_at": "...",
"started_at": "...",
"completed_at": null,
"failure_reason": null
}
错误处理
- 创建 sandbox 失败:run 不启动,返回
RunResult(status="failed")。 - 写入基础 artifacts 失败:run 不启动或立即 failed。
- path guard 拒绝:返回
ErrorInfo(category="sandbox")。 - engine 失败:runtime 捕获并写入 errors log。
- deliverables 缺失:状态为
incomplete。
事件要求
Runtime/Sandbox 至少发出:
run.createdrun.startedrun.completedrun.failedfile.writtenfile.rejecteddeliverable.missing
测试设计
单元测试:
- IDs 格式合法且唯一。
RunOptions正确处理 CLI override。- 创建 sandbox 目录结构。
- 写入
run.json。 - 更新 run state。
- 生成
sandbox-manifest.json。 - 生成
artifact-manifest.json。 - path guard 拒绝
..。 - path guard 拒绝 sandbox 外绝对路径。
- path guard 拒绝 symlink escape。
- path guard 允许写入
workspace/和deliverables/。
集成测试:
- mock engine 完成最小 run。
- run 结束后所有基础 artifacts 存在。
- 缺失 deliverable 时状态为
incomplete。 - engine failure 时状态为
failed,并写入 errors log。
性能和调度考虑
- sandbox creation 应只是目录和小文件创建。
run.json更新要原子化,避免中断后损坏。- events append-only。
- manifests 可增量更新,但 Phase 1 可以简单重写小 JSON。
- 所有 paths 使用 sandbox-relative artifact paths。
RunContext和 manifests 足以让 future scheduler 重建环境。
验收标准
- Runtime 能创建完整 run sandbox。
run.json是状态 source of truth。- path guard 能阻止 sandbox escape。
- required base artifacts 被写入。
- manifests 被生成。
- mock engine run 可完成。
- 失败路径可写入 errors 和 run state。
- 缺失 deliverables 可标记为
incomplete。