diff --git a/.github/workflows/pi-runtime.yml b/.github/workflows/pi-runtime.yml index fc62383d..e2b679b3 100644 --- a/.github/workflows/pi-runtime.yml +++ b/.github/workflows/pi-runtime.yml @@ -1,9 +1,9 @@ name: Pi runtime on: push: - paths: ['runtime/pi/**', 'internal/agentruntime/**', 'internal/multiagent/pi_*.go', '.github/workflows/pi-runtime.yml'] + paths: ['runtime/pi/**', 'internal/agentruntime/**', 'internal/multiagent/**', 'internal/assessment/**', 'internal/knowledge/**', 'internal/workflow/**', 'internal/config/**', 'cmd/build-runtime/**', 'scripts/build-pi-runtime.sh', '.github/workflows/pi-runtime.yml'] pull_request: - paths: ['runtime/pi/**', 'internal/agentruntime/**', 'internal/multiagent/pi_*.go', '.github/workflows/pi-runtime.yml'] + paths: ['runtime/pi/**', 'internal/agentruntime/**', 'internal/multiagent/**', 'internal/assessment/**', 'internal/knowledge/**', 'internal/workflow/**', 'internal/config/**', 'cmd/build-runtime/**', 'scripts/build-pi-runtime.sh', '.github/workflows/pi-runtime.yml'] permissions: contents: read jobs: @@ -23,4 +23,5 @@ jobs: working-directory: runtime/pi - run: npm run build && npm test working-directory: runtime/pi - - run: go test -race ./internal/agentruntime ./internal/multiagent + - run: go run ./cmd/build-runtime + - run: go test -race ./internal/agentruntime ./internal/multiagent ./internal/assessment ./internal/knowledge ./internal/workflow diff --git a/CHANGELOG.md b/CHANGELOG.md index f5f019f6..89ff279d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ ### Added +- 默认 Agent 运行时迁移为 Pi 1.5.2:Go 工具网关继续处理角色、审批、监控与证据;聊天、子代理及深度评估的模型提案接入 Pi。新增按源码指纹发布的 Node Worker、流式协议、会话恢复、原生工具检索和可配置的 DSH-Purge 能力增强。部署需 Node.js >=22.19;保留显式 Eino Agent 回退。 +- Workflow 改用原生 DAG 与版本化检查点,知识库改用自身文档、切分、Embedding 和检索组件。旧 Eino Workflow 检查点需由原版本恢复,详见 [Pi 迁移说明](docs/zh-CN/pi-runtime.md)。 +- 个人仓库正式命名为 `Sycun/CyberStrikeAI`,原上游贡献 fork 改为 `Sycun/CyberStrikeAI-upstream-fork`。新增任务接单、阶段汇报与主动请示的设计调研文档(尚未作为产品功能上线)。 + - AI 渠道支持自定义 HTTP 请求头、环境变量和会话 ID 占位符;保存后的鉴权头可安全用于连接测试,独立审计身份隔离主渠道请求头,自定义头不会跟随跨源重定向。 - 系统设置新增代理二级菜单,提供固定出口、代理池、最短切换间隔及凭证脱敏;配置仅注入后续 HTTP 工具进程,不影响 Kali 其他工具和模型 API。`http-framework-test` 新增可选代理池:支持静态/结构化代理列表与供应商接口、粘性/轮询策略、供应商故障静态回退、失败冷却及有界切换;仅自动重放 GET/HEAD/OPTIONS,遵守 429 Retry-After,切换失败时返回响应或错误且不回退直连。附中英文指南与本地 HTTP/HTTPS/SOCKS5 回归测试(#357)。 diff --git a/README.md b/README.md index a8c68e0b..c433a1f2 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,18 @@ CyberStrikeAI Logo -# CyberStrikeAI — Personal Maintenance +# CyberStrikeAI [中文](README_CN.md) | [English](README.md) -> **Repository role:** Sycun's personal maintenance line, based on [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI). Daily development is published here. The [architecture refactor](https://github.com/Sycun/csai-decouple-refactor) evolves separately; [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI) is the fork used for selected upstream contributions. +> **Repository role:** Sycun's personal maintenance line, based on [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI). Daily development is published here. The [architecture refactor](https://github.com/Sycun/csai-decouple-refactor) evolves separately; [Sycun/CyberStrikeAI-upstream-fork](https://github.com/Sycun/CyberStrikeAI-upstream-fork) is the fork used for selected upstream contributions. > > The current main line includes the [deep assessment workbench](docs/DEEP_ASSESSMENTS.md). Proxy-pool settings and local-model context profiles are integrated into this main line; see the [repository and branch guide](docs/REPOSITORY_GUIDE.md) for integration status. Code availability and automated checks do not establish acceptance with real models and real targets. **The system of action for AI-native cybersecurity—where intent becomes governed execution, evidence becomes operational memory, and every operation improves the next.** -CyberStrikeAI connects planning, execution, human oversight, evidence, and replay in one auditable workspace. Built in Go, it combines Eino-powered agents, MCP-native tools, RAG knowledge, visual workflows, and attack-chain modeling and analysis for authorized security operations. +CyberStrikeAI connects planning, execution, human oversight, evidence, and replay in one auditable workspace. Built in Go, it combines Pi-powered agents (with an explicit Eino migration fallback), MCP-native tools, RAG knowledge, visual workflows, and attack-chain modeling and analysis for authorized security operations. **Start here:** [Quick start](#quick-start-one-command-deployment) · [Documentation](docs/en-US/README.md) · [Security hardening](docs/en-US/security-hardening.md) @@ -198,11 +198,12 @@ See [tools/README_EN.md](tools/README_EN.md) for tool definitions, customization **Prerequisites:** - Go 1.25+ ([Install](https://go.dev/dl/); required by `go.mod`) - Python 3.10+ ([Install](https://www.python.org/downloads/)) +- Node.js 22.19+ (Pi runtime) **One-Command Deployment:** ```bash -git clone https://github.com/Sycun/CyberStrikeAI-personal.git -cd CyberStrikeAI-personal +git clone https://github.com/Sycun/CyberStrikeAI.git +cd CyberStrikeAI chmod +x run.sh && ./run.sh ``` diff --git a/README_CN.md b/README_CN.md index 2d6334fd..0fbbf8cf 100644 --- a/README_CN.md +++ b/README_CN.md @@ -2,17 +2,17 @@ CyberStrikeAI Logo -# CyberStrikeAI — 个人维护版 +# CyberStrikeAI [中文](README_CN.md) | [English](README.md) -> **仓库定位:** 本仓库是 Sycun 基于 [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) 的个人维护线,承接日常修复与优化。[架构重构线](https://github.com/Sycun/csai-decouple-refactor)独立演进;[Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI) 保留为向官方贡献选定改动的 fork。 +> **仓库定位:** 本仓库是 Sycun 基于 [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) 的个人维护线,承接日常修复与优化。[架构重构线](https://github.com/Sycun/csai-decouple-refactor)独立演进;[Sycun/CyberStrikeAI-upstream-fork](https://github.com/Sycun/CyberStrikeAI-upstream-fork) 保留为向官方贡献选定改动的 fork。 > > 当前主线包含[深度测评工作台](docs/DEEP_ASSESSMENTS.md)。代理池设置和本地模型上下文优化已整合进当前主线,使用与整合状态见[仓库与分支说明](docs/REPOSITORY_GUIDE.md)。代码已保存、自动化检查通过与真实模型、真实目标验收分别记录。 **CyberStrikeAI 是 AI 原生网络安全的智能执行中枢——让意图转化为受治理的行动,让证据沉淀为运营记忆,并让每次行动优化下一次行动。** -CyberStrikeAI 将规划、执行、人工监督、证据与复盘连接在同一个可审计工作空间中。项目基于 Go 构建,融合 Eino 智能体、MCP 原生工具、RAG 知识、可视化工作流以及攻击链建模与分析能力,面向已获得明确授权的安全任务。 +CyberStrikeAI 将规划、执行、人工监督、证据与复盘连接在同一个可审计工作空间中。项目基于 Go 构建,默认使用 Pi 智能体(保留显式 Eino 迁移回退)并融合、MCP 原生工具、RAG 知识、可视化工作流以及攻击链建模与分析能力,面向已获得明确授权的安全任务。 **从这里开始:** [快速上手](#快速上手一条命令部署) · [中文文档](docs/zh-CN/README.md) · [安全加固](docs/zh-CN/security-hardening.md) @@ -197,11 +197,12 @@ CyberStrikeAI 将规划、执行、人工监督、证据与复盘连接在同一 **环境要求:** - Go 1.25+([下载安装](https://go.dev/dl/),以 `go.mod` 为准) - Python 3.10+ ([下载安装](https://www.python.org/downloads/)) +- Node.js 22.19+ (Pi runtime) **一条命令部署:** ```bash -git clone https://github.com/Sycun/CyberStrikeAI-personal.git -cd CyberStrikeAI-personal +git clone https://github.com/Sycun/CyberStrikeAI.git +cd CyberStrikeAI chmod +x run.sh && ./run.sh ``` diff --git a/config.example.yaml b/config.example.yaml index d9830382..937fe77f 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -188,6 +188,17 @@ shodan: api_key: "" # Shodan API Key;也可通过 SHODAN_API_KEY 环境变量配置 # Agent 配置 # 达到最大迭代次数时,AI 会自动总结测试结果 +# Pi runtime (Node.js >=22.19). Build with: bash scripts/build-pi-runtime.sh +agent_runtime: + engine: pi # pi (default) | eino (legacy agent fallback) + node_path: node + worker_path: "" # empty: use the source-addressed runtime bundle + session_dir: data/pi-sessions + purge: + enabled: true + instruction: "" # additional model guidance; role and host tool policies still apply + model_instructions: {} # optional exact provider/model or model ID -> guidance + agent: # 修改后重启服务,对新任务生效;例如 1440 = 24 小时,单次工具超时独立生效。 task_timeout_minutes: 600 # 任务执行超时(分钟);未配置=600,0=不限时,负数无效;续跑重新计时 diff --git a/docs/REPOSITORY_GUIDE.md b/docs/REPOSITORY_GUIDE.md index 5cd8f4fd..f6e40414 100644 --- a/docs/REPOSITORY_GUIDE.md +++ b/docs/REPOSITORY_GUIDE.md @@ -1,12 +1,14 @@ # 仓库与分支说明 / Repository and branch guide +2026-11-11:个人仓库已由 `CyberStrikeAI-personal` 改名为 `CyberStrikeAI`;原同名上游 fork 已改名为 `CyberStrikeAI-upstream-fork`。日常发布继续进入个人独立仓库,官方贡献仍走 fork。 + ## 仓库职责 | 仓库 | 职责 | | --- | --- | -| [Sycun/CyberStrikeAI-personal](https://github.com/Sycun/CyberStrikeAI-personal) | 个人维护主线。日常修复、优化和文档先在这里保存、使用与验证。 | +| [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI) | 个人维护主线。日常修复、优化和文档先在这里保存、使用与验证。 | | [Sycun/csai-decouple-refactor](https://github.com/Sycun/csai-decouple-refactor) | 独立架构实验线,探索分层解耦与插件化;完成度以该仓库代码和验证记录为准。 | -| [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI) | 官方贡献 fork。仅将选定改动送往上游,保留已有 PR 的来源分支。 | +| [Sycun/CyberStrikeAI-upstream-fork](https://github.com/Sycun/CyberStrikeAI-upstream-fork) | 官方贡献 fork。仅将选定改动送往上游,保留已有 PR 的来源分支。 | | [AIPentest/CyberStrikeAI](https://github.com/AIPentest/CyberStrikeAI) | 官方上游。个人维护线与重构线均保留原始历史、许可证与版权说明。 | 个人主线与架构实验线分别演进,不把全部分支自动合入一个版本。向官方贡献时,应从官方基线组织可独立审查的改动。 @@ -37,6 +39,6 @@ ## Development workflow (English) -`CyberStrikeAI-personal/main` is the personal maintenance baseline. `csai-decouple-refactor` is a separate architecture experiment. `Sycun/CyberStrikeAI` remains the contribution fork for selected upstream PRs. +`CyberStrikeAI/main` is the personal maintenance baseline. `csai-decouple-refactor` is a separate architecture experiment. `Sycun/CyberStrikeAI-upstream-fork` remains the contribution fork for selected upstream PRs. The dated table above distinguishes integrated work, pending branches, and historical snapshots. Proxy-pool and local-model changes are integrated into the personal main line; upstream PR integration is tracked separately. Keep existing PR branches and archival refs. Automated checks and fixtures do not establish real-model or real-target acceptance; installation and deployment sources must be selected explicitly. diff --git a/docs/en-US/README.md b/docs/en-US/README.md index 79883569..0744580d 100644 --- a/docs/en-US/README.md +++ b/docs/en-US/README.md @@ -34,3 +34,5 @@ - [Developer Guide](developer-guide.md) · [Plugin Development](plugin-development.md) · [Frontend i18n](frontend-i18n.md) - [Testing](testing.md) · [Contributing](contributing-guide.md) · [Release Process](release-process.md) + +- [Pi runtime and migration](pi-runtime.md) diff --git a/docs/en-US/pi-runtime.md b/docs/en-US/pi-runtime.md new file mode 100644 index 00000000..d337656c --- /dev/null +++ b/docs/en-US/pi-runtime.md @@ -0,0 +1,26 @@ +# Pi runtime + +CyberStrikeAI uses Pi 1.5.2 by default. Go owns business state, permissions, MCP execution, evidence, and delivery checks; an isolated Node worker hosts the Pi SDK. The source repository is [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI). The upstream contribution fork is [CyberStrikeAI-upstream-fork](https://github.com/Sycun/CyberStrikeAI-upstream-fork). + +## Build + +Node.js >=22.19 and the Go version in go.mod are required: + +```sh +bash scripts/build-pi-runtime.sh +go build -o cyberstrike-ai ./cmd/server +``` + +The launcher and self-update build prepare the worker. Dependency installation uses the lockfile with lifecycle scripts disabled. Complete bundles are published under `runtime/pi/.builds/`; running workers keep their original dependencies, and source rollback selects the corresponding old bundle. Retain the runtime sources and matching bundle when deploying, or rebuild on the destination. A Go binary alone is insufficient for Pi. + +## Configuration + +`agent_runtime.engine` defaults to `pi`; `eino` explicitly selects the legacy Agent fallback. Optional `node_path`, `worker_path`, and `session_dir` control deployment. Settings exposes runtime selection and the DSH-Purge-derived capability guidance. `purge.model_instructions` provides additive guidance by exact `provider/model` or model ID. + +The guidance combines capability selection, main/child task anchors and evidence requirements. It does not ship DSH host patches or encrypted identity prompts. Attribution is in `runtime/pi/THIRD_PARTY_NOTICES.md`. + +Chat agents, specialists and workflow Agent nodes use Pi. Durable assessments use a single Pi model proposal per step; their existing engine retains tool execution, approvals and budgets. Large catalogs can use native tool search. Conversation task boards remain compatible with the existing UI. + +Workflow now uses a native DAG and versioned JSON checkpoints. Old Eino Workflow binary checkpoints require their original application version; `engine: eino` is an Agent fallback, not a converter for old Workflow checkpoints. Knowledge retrieval and indexing use native domain types and HTTP embeddings. Legacy Eino dependencies are still retained for the explicit Agent fallback. + +See the [Chinese implementation and validation guide](../zh-CN/pi-runtime.md) for protocol, recovery and test details. Local fixtures establish functional behavior, not live-provider reliability, refusal-rate improvements or production acceptance. diff --git a/docs/en-US/release-process.md b/docs/en-US/release-process.md index 883fa7cc..4709583b 100644 --- a/docs/en-US/release-process.md +++ b/docs/en-US/release-process.md @@ -53,6 +53,7 @@ SQLite migrations must be: ```bash go test ./internal/... go test ./cmd/... +bash scripts/build-pi-runtime.sh go build -o cyberstrike-ai ./cmd/server ``` diff --git a/docs/zh-CN/README.md b/docs/zh-CN/README.md index a15c1af6..33e82489 100644 --- a/docs/zh-CN/README.md +++ b/docs/zh-CN/README.md @@ -34,3 +34,6 @@ - [开发者指南](developer-guide.md) · [插件开发](plugin-development.md) · [前端国际化](frontend-i18n.md) - [测试指南](testing.md) · [贡献规范](contributing-guide.md) · [发布流程](release-process.md) + +- [Pi 原生运行时与迁移](pi-runtime.md) +- [任务委派、阶段汇报与主动请示(设计调研)](task-delegation-design.md) diff --git a/docs/zh-CN/architecture.md b/docs/zh-CN/architecture.md index 1520980a..74fb1a5e 100644 --- a/docs/zh-CN/architecture.md +++ b/docs/zh-CN/architecture.md @@ -58,14 +58,14 @@ Handler 负责参数解析、权限中间件后的业务协调和 HTTP 响应。 - `internal/agents/` - `agents/` -Eino ADK 提供单代理、Deep、Plan-Execute、Supervisor 等执行模式。多代理子 Agent 由 Markdown 文件定义。 +默认运行时是 Pi TypeScript SDK。`internal/agentruntime/` 管理子进程协议与构建,`internal/multiagent/pi_*.go` 负责角色、工具、审批和事件适配。单代理及 Deep、Plan-Execute、Supervisor 均使用 Pi 会话;角色仍由 Markdown 定义。旧 Eino 内核仅在 `agent_runtime.engine: eino` 时启用,供迁移回退。详见 [Pi 运行时](pi-runtime.md)。 ## MCP 与工具 MCP 相关: - `internal/mcp/`:Server、外部 MCP、连接恢复。 -- `internal/einomcp/`:Eino 与 MCP 工具适配。 +- `internal/agentruntime/` 与 `internal/multiagent/pi_runner.go`:Pi 与 Go MCP 执行链适配;`internal/einomcp/` 留作 Eino 兼容路径。 - `tools/`:YAML 命令工具。 - `internal/app/*_tools.go`:Go 内置工具注册。 @@ -73,7 +73,7 @@ MCP 相关: ## Workflow -工作流引擎在 `internal/workflow/`,HTTP 入口在 `internal/handler/workflow*.go`。它支持 start、agent、tool、condition、hitl、output、end 等节点。 +工作流引擎在 `internal/workflow/`,HTTP 入口在 `internal/handler/workflow*.go`。原生 DAG 执行器支持 start、agent、tool、condition、hitl、output、end 等节点,使用版本化 JSON 检查点保存恢复状态。 详细使用见 [工作流使用说明](workflow-graph.md)。 @@ -128,8 +128,8 @@ MCP 相关: 1. Gin 路由进入认证中间件。 2. Handler 解析请求体、会话 ID、角色、附件和 WebShell 上下文。 3. Agent 构建模型输入,包括历史消息、角色提示、项目事实、工具列表。 -4. Eino Runner 调用模型。 -5. 模型需要工具时走 MCP Tool。 +4. Pi Worker 调用模型,Go 接收生命周期事件。 +5. 模型需要工具时通过双向协议回到 Go 工具网关,再进入 MCP 或原生工具。 6. 工具调用前可能触发 HITL。 7. 工具执行结果写入过程详情和监控。 8. 模型继续推理并生成最终回答。 diff --git a/docs/zh-CN/pi-runtime.md b/docs/zh-CN/pi-runtime.md new file mode 100644 index 00000000..af671513 --- /dev/null +++ b/docs/zh-CN/pi-runtime.md @@ -0,0 +1,72 @@ +# Pi 原生运行时 + +CyberStrikeAI 默认使用 Pi 1.5.2(`@earendil-works/pi-coding-agent`、`pi-ai`),Go 保留业务、权限、工具执行和证据管理。个人主仓库为 [Sycun/CyberStrikeAI](https://github.com/Sycun/CyberStrikeAI),官方贡献 fork 为 [CyberStrikeAI-upstream-fork](https://github.com/Sycun/CyberStrikeAI-upstream-fork)。 + +## 构建与使用 + +需要 Go(版本见 go.mod)和 Node.js >=22.19。 + +```sh +bash scripts/build-pi-runtime.sh +go build -o cyberstrike-ai ./cmd/server +``` + +`run.sh` 和服务自更新的构建步骤都会准备 Pi。构建使用锁文件和 `npm ci --ignore-scripts`;发布到 `runtime/pi/.builds/<源码指纹>/` 后才会被选用。正在运行的 Worker 使用原来的依赖目录;源码回滚时选择对应旧指纹的包。缓存属于构建产物,不提交到 Git。部署时需保留运行时源码和已构建的匹配包,或在目标机器重新构建;只复制 Go 二进制不足以运行 Pi。 + +```yaml +agent_runtime: + engine: pi + node_path: node + worker_path: "" + session_dir: data/pi-sessions + purge: + enabled: true + instruction: "" + model_instructions: + "provider/model-id": "此模型的额外工作约定" +``` + +设置页可选择运行时、开关能力增强及编辑附加指令。`worker_path` 是管理员的显式覆盖,适合开发或独立打包;留空使用源码指纹校验后的构建包。未填写 engine 的新代码默认使用 Pi;现有部署的运行数据和模型配置不会因此自动迁移或部署。 + +## 执行边界 + +- 聊天、机器人、批量任务、工作流 Agent 节点通过统一调度入口进入 Pi。HTTP 路由与 `eino_single` 等历史模式值暂保留兼容,模式与运行时分别选择。 +- Go 管理每次调用的 Worker,支持流式事件、工具回调、补充指令与取消;同一进程中的相同会话存储串行访问,不同会话独立运行。 +- Worker 使用显式模型、内存凭据和资源加载器,不自动发现个人 Pi 配置、全局插件或默认文件/Shell 工具。 +- 工具较多时使用 Pi 原生 tool_search 按需加载,减少模型一次接收的工具定义。TaskCreate/Update/Get/List 和 write_todos 继续写入现有对话任务板。 +- MCP、文件和 Shell 工具回到 Go,经角色过滤、HITL 和现有执行监控处理。子代理工具集合受主代理集合约束。 +- Deep 使用任务委派;Supervisor 提供专家委派和 exit;Plan-Execute 使用计划记录与执行子代理。最终文本仍需通过既有证据验收。 +- 深度评估工作台调用 Pi 的单次模型生成,返回动作建议和用量,工具执行仍由持久任务引擎控制。不会开启第二个自动工具循环。 +- Pi 原生重试及虚拟模型路由承接聊天备用渠道。深度评估仍由自身的持久预算和重试策略控制。认证/配置错误不能用无界“继续”消除。 +- 上下文窗口和输出上限沿用渠道设置,包括 local profile;输入预算用于 Pi 压缩阈值。压缩后的模型上下文和完整会话记录分别保留。 + +## DSH-Purge 能力增强 + +融合的是能力目录选择、主/子代理任务锚点、模型定制指令、故障类型区分和证据约定。增强为可关闭的附加层,保留用户已有角色提示。模型专用指令按初始渠道的 `provider/model` 优先、模型 ID 次之选择。 + +没有复制 DSH 宿主二进制补丁、加密身份提示或宿主权限移除补丁;这些补丁针对另一种运行时。Go 端工具权限与人工决定继续独立生效。来源和许可证见 `runtime/pi/THIRD_PARTY_NOTICES.md`。 + +## 数据与兼容 + +- Pi Session 是模型会话及压缩记录的权威来源;SQLite 保存业务状态、工具记录和交付证据。两者通过会话和执行 ID 关联。 +- 同一个 Worker 收到重复工具调用 ID 时复用已完成结果;不同参数复用相同 ID 会被拒绝。 +- 进程中断后,未提交结果的调用标记为结果不确定。系统不把它自动当成成功,也不直接重放它;继续前须核对执行记录。这不是跨所有外部系统的“恰好一次”保证。 +- Eino **Agent** 回退仍可通过 `engine: eino` 显式选择,旧依赖尚未全量删除。 +- Workflow 已使用原生 DAG 和 JSON 检查点。旧 Eino Workflow 二进制检查点不能由新版直接恢复;应先完成旧工作流,或使用原版本完成恢复。新检查点记录图指纹和执行中的节点,拒绝用已修改的图或结果不确定的节点自动续跑。 +- 知识库使用自身 Document、切分、Embedding HTTP、向量检索、查询扩展和重排流程。向量与表结构保持兼容,新索引准备成功后在事务中替换旧行。 +- 本地测试和源码集成不等于真实模型、真实任务的长时验收。当前尚无拒答率、发现率或成本改进的实测结论。 + +## 回归 + +```sh +cd runtime/pi +npm ci --ignore-scripts +npm run build +npm test +cd ../.. +go test -race ./internal/agentruntime ./internal/multiagent ./internal/assessment ./internal/workflow ./internal/knowledge +go test ./... +node --test web/static/js/*.test.cjs +``` + +SDK 集成测试使用本地模拟模型和无副作用的工具夹具,覆盖 OpenAI/Claude 动作建议、审批编辑、子代理工具边界、流式输出、取消、进程中断及备用模型切换。 diff --git a/docs/zh-CN/release-process.md b/docs/zh-CN/release-process.md index 77d86d08..622beab5 100644 --- a/docs/zh-CN/release-process.md +++ b/docs/zh-CN/release-process.md @@ -8,7 +8,7 @@ - `README.md` 和 `README_CN.md` 的功能说明是否更新。 - `docs/` 是否补充新功能文档。 -- `config.yaml` 示例是否包含新增配置。 +- `config.example.yaml` 示例是否包含新增配置。 - OpenAPI 是否包含新增接口。 - 中英文 i18n 是否同步。 - 高风险功能是否有安全说明。 @@ -25,6 +25,7 @@ go test ./internal/... ```bash go test ./cmd/... +bash scripts/build-pi-runtime.sh go build -o cyberstrike-ai ./cmd/server ``` @@ -39,6 +40,7 @@ go build -o cyberstrike-ai ./cmd/server ## 构建 ```bash +bash scripts/build-pi-runtime.sh go build -o cyberstrike-ai ./cmd/server ``` @@ -47,7 +49,7 @@ go build -o cyberstrike-ai ./cmd/server - `cyberstrike-ai` - `web/templates/` - `web/static/` -- `config.yaml` 示例。 +- `config.example.yaml` 示例。 - `tools/` - `roles/` - `skills/` @@ -157,6 +159,7 @@ SQLite 迁移要考虑: ```bash go test ./internal/... go test ./cmd/... +bash scripts/build-pi-runtime.sh go build -o cyberstrike-ai ./cmd/server ``` diff --git a/docs/zh-CN/task-delegation-design.md b/docs/zh-CN/task-delegation-design.md new file mode 100644 index 00000000..46fd325c --- /dev/null +++ b/docs/zh-CN/task-delegation-design.md @@ -0,0 +1,136 @@ +# 任务委派、阶段汇报与主动请示 + +状态:2026-11-11 设计调研。本文定义 Pi 迁移后的下一阶段,不代表自然语言任务接单、主动提问或 ARTEX 适配已经上线。 + +## 结论 + +建议把现有深度评估工作台扩展为“交代工作 → 理解任务 → 自主执行 → 阶段汇报 → 必要时请示 → 验收”的任务系统。用户决定目标和关键取舍,LLM 负责理解、规划和选择行动,CSAI/ARTEX 等提供执行能力,后台持久化任务状态与证据。 + +不必再建立一套与 assessment 并行的长期任务引擎。新增重点是任务接单、问题与答复、阶段报告,以及统一执行适配器。这是结合当前源码作出的设计判断。 + +```mermaid +flowchart TB + U[用户:描述目标与关键决定] --> I[接单:识别意图、补齐任务信息] + I --> G[可执行任务约定:目标、范围、交付物、预算、验收] + G --> P[Pi / LLM:规划与调整] + P --> C[持久任务控制:依赖、状态、预算、审批] + C --> T[执行适配器:CSAI 工具 / ARTEX 任务 / 其他能力] + T --> E[真实结果与执行证据] + E --> P + E --> R[阶段报告:已完成、未完成、阻碍、下一步] + R --> U + P --> Q[提出需要用户判断的问题] + Q --> U + U --> A[有版本的答复或任务调整] + A --> G +``` + +模型推理、执行工具与可恢复会话分别管理,是当前实现能够延伸到此模式的基础。Anthropic 的架构文章也将模型执行循环、执行环境和持久会话分开,但本文的具体实现建议沿用本项目的 Pi 与 Go 服务。[架构参考](https://www.anthropic.com/research/managed-agents) + +## 已有能力与实际缺口 + +| 环节 | 当前源码中的能力 | 下一步要补充的行为 | +|---|---|---| +| 交代工作 | `assessment.Task` 有 Goal、Scope、Material、Criteria 与预算,创建时要求关键字段齐全 | 允许先提交模糊自然语言,形成未启动的任务草稿 | +| 规划执行 | Planner、Worker、依赖 DAG、专业角色、暂停/恢复、补充方向 | 将“信息不足,需要问用户”变成正常状态,而非普通失败 | +| 工作记忆 | 任务持久化、执行 ID、证据与有界记忆读取 | 保存当前任务约定的版本、尚未确认的假设与未回答的问题 | +| 阶段汇报 | 增量事件、步骤结果、Markdown 报告及验收复核 | 主动产生面向用户的阶段报告,并突出需要作出的决定 | +| 人工介入 | 工具审批、预算调整和 steer | 区分澄清问题、业务取舍与工具审批,支持有针对性的答复和续跑 | +| 工具使用 | Pi、Go 工具网关、MCP、角色和审批 | 给 ARTEX 等长任务提供一致的提交、状态、事件、取消和产物契约 | + +依据:`internal/assessment/types.go`、`engine.go`、`runtime.go`、`worker.go`、`memory.go`、`report.go`、`review.go`、`metrics.go`,以及 `internal/handler/assessment.go`。 + +## 分词器的位置 + +需要分开三个问题: + +1. **Token 计数与上下文预算**:控制一次模型请求装入多少内容。 +2. **文本分词与能力检索**:从工具、技能和项目名称中找候选项。Pi 1.5.2 的 `tool_search` 已使用 Unicode 分词(非 ASCII 使用 `Intl.Segmenter`)和 BM25;此次迁移已接入按需加载工具。 +3. **任务意图与缺失信息判断**:理解“帮我看看”“弄好一点”“做到能交付”究竟意味着什么,需要模型生成结构化解释,再由确定性规则核对目标、范围、预算和验收条件。 + +因此无需把另一个中文分词器作为任务理解的核心。先复用已有分词/检索,在接单层增加结构化意图提取;只有评测证明领域词匹配有明显缺口时,再补充术语词典或专门分词器。[Pi 工具检索源码](https://github.com/earendil-works/pi/blob/v1.5.2/packages/coding-agent/src/extensions/tool-search/tool.ts) + +## 任务约定与接单过程 + +建议增加一个允许字段不完整的 `IntakeDraft`。它完成澄清后才创建现有 `assessment.Task`,避免破坏目前 Task.Validate 对执行必需信息的要求。 + +```json +{ + "intent": "perform_work", + "goal": "用户希望达到的结果", + "deliverables": ["可交付成果"], + "project_id": "已解析的项目 ID,尚未确定时为空", + "scope": {"included": [], "excluded": []}, + "constraints": [], + "acceptance_criteria": [], + "budget": {"tokens": null, "deadline": null, "timezone": "Asia/Shanghai"}, + "assumptions": [], + "missing_fields": [], + "next_action": "ask_owner", + "revision": 1 +} +``` + +接单模型只做理解和提案,不绑定实际执行工具。系统根据现有项目、角色与已确认上下文填入可靠信息;模型推测进入 assumptions,不能伪装成用户要求。自然语言中的否定条件、排除项和用户更正要保留来源。 + +确定性规则负责验证必需字段、项目归属、工具可用性、范围和预算。模型输出一个“高置信度”数字,不足以替代这些检查。明确的信息沿用,缺失但不影响当前步骤的信息可以稍后问;阻碍正确执行或涉及关键取舍的信息必须先问。知识问答、解释和状态查询不应自动变成长期执行任务。 + +## 何时员工自己做,何时问老板 + +| 情况 | 建议行为 | +|---|---| +| 目标、范围与验收已明确,下一步是常规执行 | 自主执行并记录证据 | +| 缺少可从现有材料可靠读取的信息 | 先查材料,避免重复向用户索取 | +| 项目或目标存在多种合理解释 | 给出简短选项和影响,等待用户选择 | +| 成本、时限、质量或覆盖范围需要取舍 | 说明当前结果、选项和推荐,等待决定 | +| 工具需要人工批准 | 使用既有 HITL,批准只对应具体调用及参数 | +| 一条路径受阻,但存在已允许的替代方法 | 在预算内尝试并说明调整 | +| 继续需要扩大范围或改变已确认约束 | 提交任务约定的变更请求 | +| 只有某个子步骤依赖答复 | 暂停该依赖分支,其余独立工作可继续 | + +问题应具体。例如“目前已完成接口清单核对;A 系统缺少测试账号。可以先做公开接口检查,或者等待账号后再覆盖登录功能。我建议先做前者。”要比“是否继续?”更能支持决策。 + +## 主动请示的持久协议 + +建议新增原生元工具 `ask_owner`,返回和保存以下对象: + +- `question_id`、`task_id`、`step_id`、`task_revision`。 +- `kind`:`clarification`、`decision` 或 `approval`;approval 仍委托既有 HITL。 +- 问题、提出原因、有限的选项、推荐与各选项影响。 +- `blocked_step_ids`、是否存在可继续的独立工作。 +- `status`、答复者、答复内容与时间。 + +问答通过站内任务界面完成。提出问题后持久化状态并结束当前推理调用,不保持一个长时间空等的模型请求。用户回答时校验问题 ID、任务版本和访问权限,重复答复保持幂等;过期答复返回冲突并展示当前问题。答复只恢复对应的依赖分支。服务重启、模型切换和上下文压缩不能丢失未回答的问题。 + +建议状态:`understanding → awaiting_input → planned → running → awaiting_decision → running → reviewing → completed/partial`。这些状态由后台事件和校验规则推进,模型提出状态变更建议,不直接覆盖任务事实。 + +## 阶段回报 + +触发点优先采用完成一个里程碑、获得重要新证据、出现影响计划的阻碍、需要用户决定或预算接近耗尽。普通工具输出继续进入过程记录;用户没有要求周期通知时,不按每次调用反复打断。 + +每次阶段报告固定回答: + +- 已完成什么,以及对应步骤/证据。 +- 还有什么未完成,原因是什么。 +- 当前有什么阻碍或不确定性。 +- 下一步准备做什么。 +- 哪一项需要用户决定。 + +报告先从持久任务与证据记录生成结构化事实,再交给模型组织语言。宣称完成的步骤和执行 ID 必须真实存在;用户意图、模型假设、工具尝试与已验证结果分别标识。没有可计算的进度基准时展示完成项数和剩余项,不伪造百分比。最终交付继续经过现有 Review,而不是把某次阶段报告当作任务完成。 + +## CSAI 与 ARTEX 的位置 + +统一执行适配器建议提供:`describe_capabilities`、`submit`、`get_status`、`read_events`、`cancel`、`list_artifacts`。执行请求携带任务及步骤 ID、幂等键、范围、预算、允许能力和验收要求,长操作返回 job ID。主任务控制器负责等待和汇总,不让两个编排器同时主导同一任务。 + +CSAI 可以直接复用当前 Go/MCP 执行链。ARTEX 若本身已经自主编排,应作为有边界的委派任务接入,保留它的执行与取消语义。本文尚未核对当前 ARTEX 的 API、鉴权和取消契约,因此这些接口是适配器目标,不是对 ARTEX 现有端点的断言。 + +## 建议实施顺序与验收 + +1. **自然语言接单**:IntakeDraft、任务约定、缺失字段判断,复用项目选择和现有 Task.Validate。先验证模糊目标、同名项目、否定指令、用户改口和纯问答。 +2. **主动请示与阶段报告**:问题对象、答复 API、等待/恢复状态、里程碑报告。验证重启、重复答复、过期问题和多个子步骤同时等待。 +3. **统一执行适配器**:先封装 CSAI,再核对 ARTEX 后增加适配;验证取消传播、重复提交和部分完成。 +4. **固定评测集**:在现有 assessment 指标与 `scripts/assessment-evaluate.py` 上增加意图字段正确率、必要问题漏问率、不必要提问次数、报告事实一致性、答复后正确恢复率及成本/延迟。 + +首个可交付闭环应是:用户说一句模糊任务,系统提出必要的一两个问题,生成可执行约定;执行一个阶段后如实汇报,遇到需要用户判断的分支时提出具体问题,得到答复后从原进度继续。先把这一条链路验证稳定,再扩大到更多工具平台。 + +框架本身不替代业务判断。Pi 的会话、事件、steering 与扩展能力适合承载此流程;确定的状态转换、预算和执行证据仍由后台控制。[Pi SDK](https://github.com/earendil-works/pi/blob/v1.5.2/packages/coding-agent/docs/sdk.md);[工作流与 Agent 的组合原则](https://www.anthropic.com/research/building-effective-agents)。 diff --git a/go.mod b/go.mod index 7d319ebd..fde53f80 100644 --- a/go.mod +++ b/go.mod @@ -9,10 +9,6 @@ require ( github.com/bytedance/sonic v1.15.0 github.com/cloudwego/eino v0.9.21 github.com/cloudwego/eino-ext/adk/backend/local v0.2.6 - github.com/cloudwego/eino-ext/components/document/loader/file v0.0.0-20260427010451-749e3706378b - github.com/cloudwego/eino-ext/components/document/transformer/splitter/markdown v0.0.0-20260427010451-749e3706378b - github.com/cloudwego/eino-ext/components/document/transformer/splitter/recursive v0.0.0-20260427010451-749e3706378b - github.com/cloudwego/eino-ext/components/embedding/openai v0.0.0-20260427010451-749e3706378b github.com/cloudwego/eino-ext/components/model/agenticclaude v0.1.7 github.com/cloudwego/eino-ext/components/model/agenticopenai v0.2.4 github.com/cloudwego/eino-ext/components/model/openai v0.1.13 @@ -39,6 +35,7 @@ require ( go.uber.org/zap v1.26.0 golang.org/x/crypto v0.50.0 golang.org/x/net v0.53.0 + golang.org/x/sys v0.43.0 golang.org/x/term v0.42.0 golang.org/x/text v0.37.0 golang.org/x/time v0.14.0 @@ -117,6 +114,7 @@ require ( github.com/segmentio/encoding v0.5.4 // indirect github.com/sirupsen/logrus v1.9.3 // indirect github.com/slongfield/pyfmt v0.0.0-20220222012616-ea85ff4c361f // indirect + github.com/smarty/assertions v1.16.0 // indirect github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect github.com/tetratelabs/wazero v1.11.0 // indirect github.com/tidwall/gjson v1.18.0 // indirect @@ -142,7 +140,6 @@ require ( golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8 // indirect golang.org/x/oauth2 v0.34.0 // indirect golang.org/x/sync v0.20.0 // indirect - golang.org/x/sys v0.43.0 // indirect google.golang.org/api v0.189.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20251202230838-ff82c1b0f217 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 // indirect diff --git a/go.sum b/go.sum index cc4267ea..73ec3d96 100644 --- a/go.sum +++ b/go.sum @@ -79,32 +79,16 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= -github.com/cloudwego/eino v0.9.14 h1:suNVibjtkPMiW7csFBdBqN3FRG0nRlCqoGKE7t0UDwY= -github.com/cloudwego/eino v0.9.14/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ= github.com/cloudwego/eino v0.9.21 h1:kBAyAjsnPq5NDWjt0VdmP9HY/XVUHs05LoeqybudPRQ= github.com/cloudwego/eino v0.9.21/go.mod h1:OBD1mrkfkt/pJa4rkg1P0VnaMeOVl7l8IAdEqY//3IQ= github.com/cloudwego/eino-ext/adk/backend/local v0.2.6 h1:pxKAWcveIBWrbz28H2bDAMyJZnhysa9bh2Kh5s7iH7s= github.com/cloudwego/eino-ext/adk/backend/local v0.2.6/go.mod h1:uJlpYclMA2ScgUlHWHu2om+DDguV2Lzc+TNulWBXqfo= -github.com/cloudwego/eino-ext/components/document/loader/file v0.0.0-20260427010451-749e3706378b h1:GIOC/VnXuSQx79mnQ3HgMvECjtyqvpJipmSUTFFfVsc= -github.com/cloudwego/eino-ext/components/document/loader/file v0.0.0-20260427010451-749e3706378b/go.mod h1:HnxTQxmhuev6zaBl92EHUy/vEDWCuoE/OE4cTiF5JCg= -github.com/cloudwego/eino-ext/components/document/transformer/splitter/markdown v0.0.0-20260427010451-749e3706378b h1:3owjV4nv+XRplavTeqFlCeAV4v7EHR2tIXDqLEmPc38= -github.com/cloudwego/eino-ext/components/document/transformer/splitter/markdown v0.0.0-20260427010451-749e3706378b/go.mod h1:KVOVct4e2BQ7epDONW2QE1qU5+ccoh91FzJTs9vIJj0= -github.com/cloudwego/eino-ext/components/document/transformer/splitter/recursive v0.0.0-20260427010451-749e3706378b h1:j8sj/5QiooV3LWphFDsJvyD/csWwupz+UKXeG+nqiNg= -github.com/cloudwego/eino-ext/components/document/transformer/splitter/recursive v0.0.0-20260427010451-749e3706378b/go.mod h1:9R0RQrQSpg1JaNnRtw7+RfRAAv0HgdE348YnrlZ6coo= -github.com/cloudwego/eino-ext/components/embedding/openai v0.0.0-20260427010451-749e3706378b h1:pOqupZQyc46rw2Z0HeybtTmSMTwqfTrbRuGDuDsNf2A= -github.com/cloudwego/eino-ext/components/embedding/openai v0.0.0-20260427010451-749e3706378b/go.mod h1:zyPrZT2bO6LyRJgVksQowR18jVgyLSvqK93hnO53/Lc= -github.com/cloudwego/eino-ext/components/model/agenticclaude v0.1.3 h1:nfO9jUPhIKTHDPyL7rso6y7Mx8cAmrIgkeJC6KqTuXI= -github.com/cloudwego/eino-ext/components/model/agenticclaude v0.1.3/go.mod h1:/dX1P7HNC7D3/nYLDoXBvdKAFnGS4tBbtJ8NrkaXuUk= github.com/cloudwego/eino-ext/components/model/agenticclaude v0.1.7 h1:oxvyuAdZLlKSWYrzXwXS63AokgC3TqSljrzCGNRi4JA= github.com/cloudwego/eino-ext/components/model/agenticclaude v0.1.7/go.mod h1:LsIyLkRviQtfJsGYP6MX9PwqCX4jMtVxR4zR2A7ZB+g= -github.com/cloudwego/eino-ext/components/model/agenticopenai v0.2.1 h1:bIMyUxEZdBEofWbXQCozfGxXCsbyNjpZcRMfW+Kt5u0= -github.com/cloudwego/eino-ext/components/model/agenticopenai v0.2.1/go.mod h1:84jUcVAcmlGDRVX0ExABVJEfrIaplaAeRbjFYW9mzkI= github.com/cloudwego/eino-ext/components/model/agenticopenai v0.2.4 h1:M5ODiB1UaYV0I/dL2dmgc/HfZ2WUBV0saM9Tkhk2IDg= github.com/cloudwego/eino-ext/components/model/agenticopenai v0.2.4/go.mod h1:AfLNKxrTFFkJbCWSvOtqKK1ZXEp0hpe26CBQ8GSf5zo= github.com/cloudwego/eino-ext/components/model/openai v0.1.13 h1:5XHRTiTD5bt9KQrMHcfvuWNklEC3tpm3XHejdozt9vM= github.com/cloudwego/eino-ext/components/model/openai v0.1.13/go.mod h1:mgIoqYYOc0eECCqvLbEYpOJrQNTNxkwXzSJzFU+v5sQ= -github.com/cloudwego/eino-ext/libs/acl/openai v0.1.18-0.20260527084435-846f52bd97c6 h1:ES/xufN5eqJ3h+9tw/tq6F8kkgnAxBAHVUB6nqKsIDU= -github.com/cloudwego/eino-ext/libs/acl/openai v0.1.18-0.20260527084435-846f52bd97c6/go.mod h1:5Xj74dGrfHo1z7I07Fzp3SlTF7Bt4tss3A2FSt8SqQ4= github.com/cloudwego/eino-ext/libs/acl/openai v0.1.18-0.20260924031408-10df7cac3f6d h1:FaBHOMj/ZDBmtsI9UMoDMDu9CNZPbjJwK/O26JFuZ8k= github.com/cloudwego/eino-ext/libs/acl/openai v0.1.18-0.20260924031408-10df7cac3f6d/go.mod h1:6yg0Rv7B3jZCQPc/C5s13PNnVewQdaRxOp2OMru7Yw4= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= @@ -278,8 +262,6 @@ github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APP github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.18 h1:JL0eqdCOq6DJVNPSvArO/bIV9/P7fbGrV00LZHc+5aI= github.com/mattn/go-sqlite3 v1.14.18/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= -github.com/meguminnnnnnnnn/go-openai v0.1.2 h1:iXombGGjqjBrmE9WaSidUhhi3YQhf42QTHvHLMkgvCA= -github.com/meguminnnnnnnnn/go-openai v0.1.2/go.mod h1:qs96ysDmxhE4BZoU45I43zcyfnaYxU3X+aRzLko/htY= github.com/meguminnnnnnnnn/go-openai v0.1.6 h1:c74nk9F3+/agOd09eHeQt/Ayty4pw54X2Dj5JHdxcys= github.com/meguminnnnnnnnn/go-openai v0.1.6/go.mod h1:qs96ysDmxhE4BZoU45I43zcyfnaYxU3X+aRzLko/htY= github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4= @@ -308,8 +290,6 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY= github.com/onsi/gomega v1.40.0 h1:Vtol0e1MghCD2ZVIilPDIg44XSL9l2QAn8ZNaljWcJc= github.com/onsi/gomega v1.40.0/go.mod h1:M/Uqpu/8qTjtzCLUA2zJHX9Iilrau25x1PdoSRbWh5A= -github.com/openai/openai-go/v3 v3.35.0 h1:109x3epXMSE423KW2euR506GGFezcEt0s87MoWejpH0= -github.com/openai/openai-go/v3 v3.35.0/go.mod h1:cdufnVK14cWcT9qA1rRtrXx4FTRsgbDPW7Ia7SS5cZo= github.com/openai/openai-go/v3 v3.44.0 h1:kkGh+jb/sKfSh5P74Jk5mCRufaQ0q7oH+lq+pNlWjsk= github.com/openai/openai-go/v3 v3.44.0/go.mod h1:cdufnVK14cWcT9qA1rRtrXx4FTRsgbDPW7Ia7SS5cZo= github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= diff --git a/internal/agentruntime/build_test.go b/internal/agentruntime/build_test.go new file mode 100644 index 00000000..692a3aca --- /dev/null +++ b/internal/agentruntime/build_test.go @@ -0,0 +1,49 @@ +package agentruntime + +import ( + "os" + "path/filepath" + "testing" +) + +func TestSourceAddressedWorkerRejectsStaleBundleAndSupportsRollback(t *testing.T) { + root := t.TempDir() + t.Chdir(root) + runtimeRoot := filepath.Join(root, "runtime", "pi") + if err := os.MkdirAll(filepath.Join(runtimeRoot, "src"), 0o700); err != nil { + t.Fatal(err) + } + for _, name := range []string{"package.json", "package-lock.json", "tsconfig.json"} { + if err := os.WriteFile(filepath.Join(runtimeRoot, name), []byte("{}"), 0o600); err != nil { + t.Fatal(err) + } + } + source := filepath.Join(runtimeRoot, "src", "worker.ts") + os.WriteFile(source, []byte("version one"), 0o600) + hash, err := SourceFingerprint(runtimeRoot) + if err != nil { + t.Fatal(err) + } + bundle := filepath.Join(runtimeRoot, ".builds", hash) + os.MkdirAll(filepath.Join(bundle, "dist"), 0o700) + os.WriteFile(filepath.Join(bundle, "dist", "worker.js"), []byte("worker"), 0o600) + if _, err := ResolveWorker(""); err == nil { + t.Fatal("unpublished bundle was selected") + } + os.WriteFile(filepath.Join(bundle, ".ready"), []byte(hash), 0o600) + worker, err := ResolveWorker("") + if err != nil { + t.Fatal(err) + } + if worker != filepath.Join(bundle, "dist", "worker.js") { + t.Fatalf("wrong worker: %s", worker) + } + os.WriteFile(source, []byte("version two"), 0o600) + if _, err := ResolveWorker(""); err == nil { + t.Fatal("stale source bundle was selected") + } + os.WriteFile(source, []byte("version one"), 0o600) + if restored, err := ResolveWorker(""); err != nil || restored != worker { + t.Fatalf("rollback lost original bundle: %s %v", restored, err) + } +} diff --git a/internal/agentruntime/pi.go b/internal/agentruntime/pi.go index 5cd7d8c9..0bbf5f87 100644 --- a/internal/agentruntime/pi.go +++ b/internal/agentruntime/pi.go @@ -81,6 +81,13 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun if err := ctx.Err(); err != nil { return nil, err } + if req.WorkingDir == "" { + var err error + req.WorkingDir, err = os.Getwd() + if err != nil { + return nil, err + } + } release, err := acquireSession(ctx, req.SessionDir) if err != nil { return nil, err @@ -265,7 +272,7 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun return r.Result, ctx.Err() } if r.Result.Error != "" { - return r.Result, errors.New(r.Result.Error) + return r.Result, fmt.Errorf("Pi runtime error: %s", r.Result.Error) } if r.Result.Status == "canceled" { return r.Result, context.Canceled diff --git a/internal/agentruntime/types.go b/internal/agentruntime/types.go index 7f04171f..b650ce11 100644 --- a/internal/agentruntime/types.go +++ b/internal/agentruntime/types.go @@ -19,6 +19,8 @@ type Model struct { MaxTokens int `json:"maxTokens"` Thinking string `json:"thinking,omitempty"` ExtraFields map[string]any `json:"extraFields,omitempty"` + Compat map[string]any `json:"compat,omitempty"` + InputBudget int `json:"inputBudget,omitempty"` } type Tool struct { @@ -34,18 +36,23 @@ type PromptProfile struct { } type Request struct { - RunID string `json:"runId"` - ConversationID string `json:"conversationId"` - SystemPrompt string `json:"systemPrompt"` - Message string `json:"message"` - History json.RawMessage `json:"history,omitempty"` - Model Model `json:"model"` - FallbackModels []Model `json:"fallbackModels,omitempty"` - RetryMax int `json:"retryMax,omitempty"` - Tools []Tool `json:"tools"` - SessionDir string `json:"sessionDir,omitempty"` - MaxTurns int `json:"maxTurns"` - Profile PromptProfile `json:"profile"` + GenerateOnly bool `json:"generateOnly,omitempty"` + RunID string `json:"runId"` + ConversationID string `json:"conversationId"` + WorkingDir string `json:"workingDir,omitempty"` + SystemPrompt string `json:"systemPrompt"` + Message string `json:"message"` + History json.RawMessage `json:"history,omitempty"` + Model Model `json:"model"` + FallbackModels []Model `json:"fallbackModels,omitempty"` + RetryMax int `json:"retryMax,omitempty"` + Tools []Tool `json:"tools"` + ToolSearch bool `json:"toolSearch"` + ToolSearchMinTools int `json:"toolSearchMinTools,omitempty"` + AlwaysVisibleTools []string `json:"alwaysVisibleTools,omitempty"` + SessionDir string `json:"sessionDir,omitempty"` + MaxTurns int `json:"maxTurns"` + Profile PromptProfile `json:"profile"` } type Event struct { @@ -67,6 +74,7 @@ type ToolResult struct { } type Result struct { + TotalTokens int `json:"totalTokens,omitempty"` Response string `json:"response"` History json.RawMessage `json:"history"` Status string `json:"status"` diff --git a/internal/assessment/runtime.go b/internal/assessment/runtime.go index df90dcc6..c2690449 100644 --- a/internal/assessment/runtime.go +++ b/internal/assessment/runtime.go @@ -113,7 +113,7 @@ func (r *CSAIRuntime) Complete(ctx context.Context, t *Task, msgs []agent.ChatMe if !ok { return nil, fmt.Errorf("unknown model channel %q", t.Model) } - message, tokens, err := multiagent.CompleteBackgroundStep(ctx, cfg, msgs, tools, max, r.Logger) + message, tokens, err := multiagent.CompleteBackgroundStepWithRuntime(ctx, snapshot.AgentRuntime, cfg, msgs, tools, max, r.Logger) if err != nil { return nil, err } diff --git a/internal/handler/config.go b/internal/handler/config.go index f1dc5b7f..57764db9 100644 --- a/internal/handler/config.go +++ b/internal/handler/config.go @@ -18,6 +18,7 @@ import ( "cyberstrike-ai/internal/config" "cyberstrike-ai/internal/database" "cyberstrike-ai/internal/knowledge" + "cyberstrike-ai/internal/llm" "cyberstrike-ai/internal/mcp" "cyberstrike-ai/internal/mcp/builtin" "cyberstrike-ai/internal/modelmeta" @@ -827,10 +828,12 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) { } previousProxy := h.config.Proxy + previousRuntime := h.config.AgentRuntime proxySaved := false defer func() { if !proxySaved { h.config.Proxy = previousProxy + h.config.AgentRuntime = previousRuntime } }() if req.Proxy != nil { diff --git a/internal/knowledge/wire_retriever.go b/internal/knowledge/wire_retriever.go index 174b1917..6289c226 100644 --- a/internal/knowledge/wire_retriever.go +++ b/internal/knowledge/wire_retriever.go @@ -29,23 +29,28 @@ func WireRetrieverPipeline(ctx context.Context, r *Retriever, oa *config.OpenAIC if logger == nil { logger = zap.NewNop() } - mq := &nativeMultiQuery{inner: NewVectorRetriever(r), max: r.config.MultiQuery.MaxQueriesEffective(), client: openai.NewClient(oa, &http.Client{Timeout: 120 * time.Second}, logger), model: oa.Model, logger: logger} + mq := &nativeMultiQuery{inner: NewVectorRetriever(r), max: r.config.MultiQuery.MaxQueriesEffective(), client: openai.NewClient(oa, &http.Client{Timeout: 120 * time.Second}, logger), model: oa.Model, logger: logger, maxTokens: oa.MaxCompletionTokensEffective(), limitField: oa.OutputLimitField()} r.pipeline = newKnowledgePipelineRetriever(mq, r) return nil } type nativeMultiQuery struct { - inner DocumentRetriever - max int - client *openai.Client - model string - logger *zap.Logger + inner DocumentRetriever + max int + client *openai.Client + model string + logger *zap.Logger + maxTokens int + limitField string } func (q *nativeMultiQuery) Retrieve(ctx context.Context, query string, opts ...RetrievalOption) ([]*Document, error) { queries := []string{query} if q.max > 1 { payload := map[string]any{"model": q.model, "messages": []map[string]string{{"role": "system", "content": fmt.Sprintf("Return only a JSON array containing at most %d alternative search queries for the user's knowledge search. Preserve technical identifiers and the user's language.", q.max-1)}, {"role": "user", "content": query}}} + if q.maxTokens > 0 { + payload[q.limitField] = q.maxTokens + } var answer struct { Choices []struct { Message struct { diff --git a/internal/multiagent/background_completion.go b/internal/multiagent/background_completion.go index 3cd8395d..a5612310 100644 --- a/internal/multiagent/background_completion.go +++ b/internal/multiagent/background_completion.go @@ -16,7 +16,7 @@ import ( // CompleteBackgroundStep performs one model turn without entering chat/ADK run // persistence. Durable callers own their budget, transcript and task lifecycle. // Provider routing, headers and reasoning stay identical to the existing models. -func CompleteBackgroundStep(ctx context.Context, oa config.OpenAIConfig, msgs []agent.ChatMessage, tools []agent.Tool, maxTokens int, logger *zap.Logger) (*agent.ChatMessage, int, error) { +func completeBackgroundStepLegacy(ctx context.Context, oa config.OpenAIConfig, msgs []agent.ChatMessage, tools []agent.Tool, maxTokens int, logger *zap.Logger) (*agent.ChatMessage, int, error) { if logger == nil { logger = zap.NewNop() } diff --git a/internal/multiagent/background_completion_test.go b/internal/multiagent/background_completion_test.go index c145eee3..5e8eb2f2 100644 --- a/internal/multiagent/background_completion_test.go +++ b/internal/multiagent/background_completion_test.go @@ -42,7 +42,7 @@ func TestBackgroundCompletionPreservesToolsReasoningAndUsage(t *testing.T) { cfg.Model = "claude-test" } tools := []agent.Tool{{Type: "function", Function: agent.FunctionDefinition{Name: "inspect", Parameters: map[string]interface{}{"type": "object", "properties": map[string]interface{}{"target": map[string]interface{}{"type": "string"}}}}}} - message, tokens, err := CompleteBackgroundStep(context.Background(), cfg, []agent.ChatMessage{{Role: "user", Content: "inspect fixture"}}, tools, 512, nil) + message, tokens, err := completeBackgroundStepLegacy(context.Background(), cfg, []agent.ChatMessage{{Role: "user", Content: "inspect fixture"}}, tools, 512, nil) if err != nil { t.Fatal(err) } diff --git a/internal/multiagent/pi_background.go b/internal/multiagent/pi_background.go new file mode 100644 index 00000000..cec1c886 --- /dev/null +++ b/internal/multiagent/pi_background.go @@ -0,0 +1,66 @@ +package multiagent + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "cyberstrike-ai/internal/agent" + "cyberstrike-ai/internal/agentruntime" + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/openai" + "github.com/google/uuid" + "go.uber.org/zap" +) + +func CompleteBackgroundStep(ctx context.Context, oa config.OpenAIConfig, msgs []agent.ChatMessage, tools []agent.Tool, maxTokens int, logger *zap.Logger) (*agent.ChatMessage, int, error) { + return CompleteBackgroundStepWithRuntime(ctx, config.AgentRuntimeConfig{}, oa, msgs, tools, maxTokens, logger) +} + +// Generate one proposal only. The durable assessment engine owns tool execution, +// approvals, retries, budgets and transcript persistence; the SDK cannot execute here. +func CompleteBackgroundStepWithRuntime(ctx context.Context, runtime config.AgentRuntimeConfig, oa config.OpenAIConfig, msgs []agent.ChatMessage, tools []agent.Tool, maxTokens int, logger *zap.Logger) (*agent.ChatMessage, int, error) { + if err := runtime.Validate(); err != nil { + return nil, 0, err + } + if !runtime.UsesPi() { + return completeBackgroundStepLegacy(ctx, oa, msgs, tools, maxTokens, logger) + } + if maxTokens <= 0 { + return nil, 0, fmt.Errorf("background generation budget is exhausted") + } + if oa.MaxCompletionTokensEffective() > maxTokens { + oa.MaxCompletionTokens = maxTokens + } + var system []string + var history []agent.ChatMessage + for _, m := range msgs { + if m.Role == "system" { + system = append(system, m.Content) + } else { + history = append(history, m) + } + } + raw, err := json.Marshal(history) + if err != nil { + return nil, 0, err + } + defs := make([]agentruntime.Tool, 0, len(tools)) + for _, t := range tools { + defs = append(defs, agentruntime.Tool{Name: t.Function.Name, Description: t.Function.Description, Parameters: t.Function.Parameters}) + } + req := agentruntime.Request{RunID: uuid.NewString(), GenerateOnly: true, SystemPrompt: strings.Join(system, "\n\n"), History: raw, Model: piModelConfig(oa, nil, openai.SessionIDFromContext(ctx)), Tools: defs, MaxTurns: 1, Profile: agentruntime.PromptProfile{Enabled: runtime.Purge.EnabledEffective(), Instruction: runtime.Purge.InstructionFor(oa.Provider, oa.Model), Child: true}} + result, err := (agentruntime.Pi{NodePath: runtime.NodePath, WorkerPath: runtime.WorkerPath}).Run(ctx, req, nil, nil, nil) + if err != nil { + return nil, 0, err + } + var messages []agent.ChatMessage + if err = json.Unmarshal(result.History, &messages); err != nil { + return nil, 0, err + } + if len(messages) != 1 { + return nil, 0, fmt.Errorf("Pi returned no background proposal") + } + return &messages[0], result.TotalTokens, nil +} diff --git a/internal/multiagent/pi_integration_test.go b/internal/multiagent/pi_integration_test.go index af1394d9..017026b2 100644 --- a/internal/multiagent/pi_integration_test.go +++ b/internal/multiagent/pi_integration_test.go @@ -50,12 +50,60 @@ func piReply(w http.ResponseWriter, tool, id string, args map[string]any, text s delta["content"] = text } for _, choice := range []map[string]any{{"index": 0, "delta": delta, "finish_reason": nil}, {"index": 0, "delta": map[string]any{}, "finish_reason": reason}} { - b, _ := json.Marshal(map[string]any{"id": "fixture", "object": "chat.completion.chunk", "model": "fixture", "choices": []any{choice}}) + b, _ := json.Marshal(map[string]any{"id": "fixture", "object": "chat.completion.chunk", "model": "fixture", "choices": []any{choice}, "usage": map[string]any{"prompt_tokens": 20, "completion_tokens": 10, "total_tokens": 30}}) fmt.Fprintf(w, "data: %s\n\n", b) } fmt.Fprint(w, "data: [DONE]\n\n") } +func TestPiBackgroundGenerationReturnsProposalWithoutExecutingTools(t *testing.T) { + for _, provider := range []string{"openai", "claude"} { + t.Run(provider, func(t *testing.T) { + cfg := piTestConfig(t) + cfg.OpenAI.Provider = provider + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body map[string]any + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + t.Error(err) + } + if body["stream"] != true { + t.Error("Pi transport must request streaming") + } + if provider == "openai" { + piReply(w, "inspect", "call-1", map[string]any{"target": "fixture"}, "") + return + } + w.Header().Set("Content-Type", "text/event-stream") + events := []string{ + `{"type":"message_start","message":{"id":"msg-1","type":"message","role":"assistant","model":"fixture","content":[],"stop_reason":null,"usage":{"input_tokens":20,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call-1","name":"inspect","input":{}}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"target\":\"fixture\"}"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":10}}`, + `{"type":"message_stop"}`, + } + for _, data := range events { + var event map[string]any + json.Unmarshal([]byte(data), &event) + fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event["type"], data) + } + })) + defer server.Close() + cfg.OpenAI.BaseURL = server.URL + tools := []agent.Tool{{Type: "function", Function: agent.FunctionDefinition{Name: "inspect", Description: "Inspect fixture", Parameters: map[string]any{"type": "object", "properties": map[string]any{"target": map[string]any{"type": "string"}}}}}} + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + message, tokens, err := CompleteBackgroundStepWithRuntime(ctx, cfg.AgentRuntime, cfg.OpenAI, []agent.ChatMessage{{Role: "system", Content: "Propose one action"}, {Role: "user", Content: "inspect"}}, tools, 512, nil) + if err != nil { + t.Fatal(err) + } + if tokens != 30 || len(message.ToolCalls) != 1 || message.ToolCalls[0].Function.Arguments["target"] != "fixture" { + t.Fatalf("message=%+v tokens=%d", message, tokens) + } + }) + } +} + func piTestAgent(cfg *config.Config, handler mcp.ToolHandler) *agent.Agent { srv := mcp.NewServer(zap.NewNop()) schema := map[string]any{"type": "object", "properties": map[string]any{"text": map[string]any{"type": "string"}}, "required": []string{"text"}} diff --git a/internal/multiagent/pi_local_tools.go b/internal/multiagent/pi_local_tools.go index ea8abc18..620cfe65 100644 --- a/internal/multiagent/pi_local_tools.go +++ b/internal/multiagent/pi_local_tools.go @@ -29,6 +29,12 @@ func (r *piRun) piLocalCatalog(ctx context.Context) ([]agentruntime.Tool, map[st return tools, names, "", nil } str := map[string]any{"type": "string"} + if r.cfg.MultiAgent.EinoMiddleware.PlantaskEnable && r.cfg.SkillsDir != "" { + for _, t := range piPlanTools() { + tools = append(tools, t) + names[t.Name] = true + } + } if root := strings.TrimSpace(r.cfg.SkillsDir); root != "" { skills, err := skillpackage.ListSkillSummaries(root) if err != nil && !os.IsNotExist(err) { @@ -109,6 +115,9 @@ func (b *piBoundedOutput) String() string { } func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall) (agentruntime.ToolResult, error) { + if call.Name == "TaskCreate" || call.Name == "TaskUpdate" || call.Name == "TaskGet" || call.Name == "TaskList" { + return r.executePiPlan(ctx, call) + } arg := func(key string) string { v, _ := call.Arguments[key].(string); return v } skillName := r.cfg.MultiAgent.EinoSkills.SkillToolName if skillName == "" { diff --git a/internal/multiagent/pi_model.go b/internal/multiagent/pi_model.go new file mode 100644 index 00000000..a16d243b --- /dev/null +++ b/internal/multiagent/pi_model.go @@ -0,0 +1,67 @@ +package multiagent + +import ( + "cyberstrike-ai/internal/agentruntime" + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/reasoning" + "strings" +) + +func piModelConfig(oa config.OpenAIConfig, intent *reasoning.ClientIntent, conversationID string) agentruntime.Model { + mode, effort := oa.Reasoning.ModeEffective(), oa.Reasoning.Effort + if intent != nil && oa.Reasoning.AllowClientReasoningEffective() { + if intent.Mode != "" { + mode = intent.Mode + } + if intent.Effort != "" { + effort = intent.Effort + } + } + thinking := "off" + if mode == "on" || (mode == "auto" && effort != "") { + thinking = effort + if thinking == "" { + thinking = "medium" + } + } + api := "openai-completions" + provider := strings.ToLower(strings.TrimSpace(oa.Provider)) + if provider == "claude" || provider == "anthropic" { + api = "anthropic-messages" + } else if oa.OpenAIToolsRequireResponses() { + api = "openai-responses" + } + base := strings.TrimRight(strings.TrimSpace(oa.BaseURL), "/") + if base == "" { + base = "https://api.openai.com/v1" + if api == "anthropic-messages" { + base = "https://api.anthropic.com" + } + } + headers := map[string]string{} + for key, value := range oa.Headers { + if strings.Contains(value, "%session_id%") && conversationID == "" { + continue + } + headers[key] = strings.ReplaceAll(value, "%session_id%", conversationID) + } + budget := oa.EffectiveMaxTotalTokens() + window := oa.EffectiveContextWindow() + if window <= 0 { + window = budget + oa.MaxCompletionTokensEffective() + } + extra := reasoning.AgenticOpenAIExtraFields(&oa, intent) + if api == "openai-responses" { + extra = oa.Reasoning.ExtraRequestFields + } + compat := map[string]any{} + if oa.IsLocalContextProfile() { + compat["maxTokensField"] = "max_tokens" + compat["supportsStore"] = false + } + if oa.Reasoning.ProfileEffective() == "deepseek_compat" || (oa.Reasoning.ProfileEffective() == "auto" && oa.IsDeepSeekEndpointOrModel()) { + compat["thinkingFormat"] = "deepseek" + compat["requiresReasoningContentOnAssistantMessages"] = true + } + return agentruntime.Model{Provider: provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: window, InputBudget: budget, MaxTokens: oa.MaxCompletionTokensEffective(), Thinking: thinking, ExtraFields: extra, Compat: compat} +} diff --git a/internal/multiagent/pi_plan_tools.go b/internal/multiagent/pi_plan_tools.go new file mode 100644 index 00000000..cef18f95 --- /dev/null +++ b/internal/multiagent/pi_plan_tools.go @@ -0,0 +1,211 @@ +package multiagent + +import ( + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "sync" + + "cyberstrike-ai/internal/agentruntime" +) + +var piPlanMu sync.Mutex + +func piPlanTools() []agentruntime.Tool { + str := map[string]any{"type": "string"} + return []agentruntime.Tool{ + {Name: "TaskCreate", Description: "Create a persisted task on this conversation's progress board", Parameters: piToolSchema(map[string]any{"subject": str, "description": str, "activeForm": str}, "subject")}, + {Name: "TaskUpdate", Description: "Update an existing task's status or description", Parameters: piToolSchema(map[string]any{"taskId": str, "subject": str, "description": str, "activeForm": str, "status": map[string]any{"type": "string", "enum": []string{"pending", "in_progress", "completed", "deleted"}}}, "taskId")}, + {Name: "TaskGet", Description: "Read a task by its conversation-local ID", Parameters: piToolSchema(map[string]any{"taskId": str}, "taskId")}, + {Name: "TaskList", Description: "Read the current conversation progress board", Parameters: piToolSchema(map[string]any{})}, + } +} + +func (r *piRun) planDir() (string, error) { + if r.conversationID == "" || strings.ContainsAny(r.conversationID, "/\\") || r.conversationID == ".." { + return "", fmt.Errorf("valid conversation ID required for a task board") + } + root := r.cfg.SkillsDir + if root == "" { + return "", fmt.Errorf("skills directory required for task board") + } + rel := r.cfg.MultiAgent.EinoMiddleware.PlantaskRelDir + if rel == "" { + rel = ".eino/plantask" + } + return filepath.Join(root, rel, r.conversationID), nil +} + +func readPiPlan(dir string) ([]map[string]any, error) { + entries, err := os.ReadDir(dir) + if os.IsNotExist(err) { + return []map[string]any{}, nil + } + if err != nil { + return nil, err + } + var tasks []map[string]any + for _, e := range entries { + if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") { + continue + } + if _, err := strconv.Atoi(strings.TrimSuffix(e.Name(), ".json")); err != nil { + continue + } + b, err := os.ReadFile(filepath.Join(dir, e.Name())) + if err != nil { + return nil, err + } + var task map[string]any + if err = json.Unmarshal(b, &task); err != nil { + return nil, err + } + tasks = append(tasks, task) + } + sort.Slice(tasks, func(i, j int) bool { + a, _ := strconv.Atoi(fmt.Sprint(tasks[i]["id"])) + b, _ := strconv.Atoi(fmt.Sprint(tasks[j]["id"])) + return a < b + }) + return tasks, nil +} + +func writePiPlanTask(dir string, task map[string]any) error { + id := fmt.Sprint(task["id"]) + if n, err := strconv.Atoi(id); err != nil || n <= 0 { + return fmt.Errorf("invalid task ID") + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return err + } + b, err := json.Marshal(task) + if err != nil { + return err + } + f, err := os.CreateTemp(dir, ".task-") + if err != nil { + return err + } + defer os.Remove(f.Name()) + if _, err = f.Write(b); err != nil { + f.Close() + return err + } + if err = f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), filepath.Join(dir, id+".json")) +} + +func (r *piRun) executePiPlan(ctx context.Context, call agentruntime.ToolCall) (agentruntime.ToolResult, error) { + if err := ctx.Err(); err != nil { + return agentruntime.ToolResult{}, err + } + dir, err := r.planDir() + if err != nil { + return agentruntime.ToolResult{}, err + } + piPlanMu.Lock() + defer piPlanMu.Unlock() + tasks, err := readPiPlan(dir) + if err != nil { + return agentruntime.ToolResult{}, err + } + var output any + if call.Name == "write_todos" { + todos, ok := call.Arguments["todos"].([]any) + if !ok { + return agentruntime.ToolResult{}, fmt.Errorf("todos must be an array") + } + var replacement []map[string]any + for i, entry := range todos { + todo, ok := entry.(map[string]any) + if !ok { + return agentruntime.ToolResult{}, fmt.Errorf("invalid todo") + } + subject, _ := todo["content"].(string) + status, _ := todo["status"].(string) + if subject == "" || (status != "pending" && status != "in_progress" && status != "completed") { + return agentruntime.ToolResult{}, fmt.Errorf("invalid todo subject/status") + } + replacement = append(replacement, map[string]any{"id": strconv.Itoa(i + 1), "subject": subject, "status": status}) + } + for _, task := range replacement { + if err = writePiPlanTask(dir, task); err != nil { + return agentruntime.ToolResult{}, err + } + } + for _, task := range tasks { + id, _ := strconv.Atoi(fmt.Sprint(task["id"])) + if id > len(replacement) { + task["status"] = "deleted" + if err = writePiPlanTask(dir, task); err != nil { + return agentruntime.ToolResult{}, err + } + } + } + output = map[string]any{"tasks": replacement} + } else if call.Name == "TaskList" { + visible := []map[string]any{} + for _, task := range tasks { + if task["status"] != "deleted" { + visible = append(visible, task) + } + } + output = map[string]any{"tasks": visible} + } else if call.Name == "TaskCreate" { + subject, _ := call.Arguments["subject"].(string) + if strings.TrimSpace(subject) == "" { + return agentruntime.ToolResult{}, fmt.Errorf("subject is required") + } + id := 1 + for _, task := range tasks { + n, _ := strconv.Atoi(fmt.Sprint(task["id"])) + if n >= id { + id = n + 1 + } + } + task := map[string]any{"id": strconv.Itoa(id), "subject": subject, "status": "pending", "description": call.Arguments["description"], "activeForm": call.Arguments["activeForm"]} + if err = writePiPlanTask(dir, task); err != nil { + return agentruntime.ToolResult{}, err + } + output = task + } else { + id, _ := call.Arguments["taskId"].(string) + var selected map[string]any + for _, task := range tasks { + if fmt.Sprint(task["id"]) == id { + selected = task + break + } + } + if selected == nil { + return agentruntime.ToolResult{}, fmt.Errorf("task does not exist") + } + if call.Name == "TaskUpdate" { + for _, key := range []string{"subject", "description", "activeForm", "status"} { + if v, ok := call.Arguments[key]; ok { + value, ok := v.(string) + if !ok { + return agentruntime.ToolResult{}, fmt.Errorf("%s must be a string", key) + } + if key == "status" && value != "pending" && value != "in_progress" && value != "completed" && value != "deleted" { + return agentruntime.ToolResult{}, fmt.Errorf("invalid task status") + } + selected[key] = v + } + } + if err = writePiPlanTask(dir, selected); err != nil { + return agentruntime.ToolResult{}, err + } + } + output = selected + } + body, err := json.Marshal(output) + return agentruntime.ToolResult{Content: string(body)}, err +} diff --git a/internal/multiagent/pi_plan_tools_test.go b/internal/multiagent/pi_plan_tools_test.go new file mode 100644 index 00000000..4ea3c698 --- /dev/null +++ b/internal/multiagent/pi_plan_tools_test.go @@ -0,0 +1,55 @@ +package multiagent + +import ( + "context" + "encoding/json" + "path/filepath" + "testing" + + "cyberstrike-ai/internal/agentruntime" + "cyberstrike-ai/internal/config" + "cyberstrike-ai/internal/database" + "go.uber.org/zap" +) + +func TestPiPlanBoardRemainsReadableByConversationAPI(t *testing.T) { + dir := t.TempDir() + cfg := &config.Config{SkillsDir: dir} + r := &piRun{cfg: cfg, conversationID: "fixture"} + db, err := database.NewDB(filepath.Join(dir, "fixture.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + db.SetEinoConversationDirs(filepath.Join(dir, ".eino", "plantask"), "", "", "") + created, err := r.executePiPlan(context.Background(), agentruntime.ToolCall{Name: "TaskCreate", Arguments: map[string]any{"subject": "Collect evidence"}}) + if err != nil { + t.Fatal(err) + } + var task map[string]any + if err = json.Unmarshal([]byte(created.Content), &task); err != nil { + t.Fatal(err) + } + _, err = r.executePiPlan(context.Background(), agentruntime.ToolCall{Name: "TaskUpdate", Arguments: map[string]any{"taskId": task["id"], "status": "completed"}}) + if err != nil { + t.Fatal(err) + } + tasks, err := db.ListConversationPlanTasks("fixture") + if err != nil { + t.Fatal(err) + } + if len(tasks) != 1 || tasks[0].Status != "completed" || tasks[0].Subject != "Collect evidence" { + t.Fatalf("API lost plan state: %+v", tasks) + } + _, err = r.executePiPlan(context.Background(), agentruntime.ToolCall{Name: "write_todos", Arguments: map[string]any{"todos": []any{map[string]any{"content": "Verify result", "status": "in_progress"}}}}) + if err != nil { + t.Fatal(err) + } + tasks, err = db.ListConversationPlanTasks("fixture") + if err != nil { + t.Fatal(err) + } + if len(tasks) != 1 || tasks[0].Subject != "Verify result" || tasks[0].Status != "in_progress" { + t.Fatalf("replacement board incorrect: %+v", tasks) + } +} diff --git a/internal/multiagent/pi_runner.go b/internal/multiagent/pi_runner.go index 2a761b01..8dc7abca 100644 --- a/internal/multiagent/pi_runner.go +++ b/internal/multiagent/pi_runner.go @@ -17,6 +17,7 @@ import ( "cyberstrike-ai/internal/database" "cyberstrike-ai/internal/project" "cyberstrike-ai/internal/reasoning" + "cyberstrike-ai/internal/tooloutput" "github.com/google/uuid" "go.uber.org/zap" @@ -29,6 +30,7 @@ type piRun struct { history []agent.ChatMessage roleTools []string catalogAllow map[string]bool + availableCatalog map[string]bool progress func(string, string, interface{}) reasoning *reasoning.ClientIntent child bool @@ -129,6 +131,9 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo return agentruntime.ToolResult{Content: text, Terminate: true}, nil } if call.Name == "write_todos" { + if cfg.MultiAgent.EinoMiddleware.PlantaskEnable && cfg.SkillsDir != "" { + return main.executePiPlan(callCtx, call) + } b, _ := json.Marshal(call.Arguments) if progress != nil { progress("plan_update", string(b), call.Arguments) @@ -155,10 +160,7 @@ func runPiMulti(ctx context.Context, cfg *config.Config, ma *config.MultiAgentCo } } // A child may narrow its parent's catalog, never expand it. - parentNames := map[string]bool{} - for _, t := range ag.ToolsForRole(roleTools) { - parentNames[t.Function.Name] = true - } + parentNames := main.availableCatalog childPrompt := project.AppendSystemPromptBlock(sub.Instruction, extra) + "\n\nOriginal user task:\n" + message child := &piRun{cfg: cfg, ag: ag, conversationID: conversationID, agentID: id, systemPrompt: childPrompt, roleTools: tools, catalogAllow: parentNames, progress: progress, reasoning: intent, child: true, sessionKey: call.ID, maxTurns: sub.MaxIterations} res, err := child.run(callCtx, task) @@ -200,6 +202,10 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { tools = append(tools, agentruntime.Tool{Name: d.Function.Name, Description: d.Function.Description, Parameters: d.Function.Parameters}) } for _, t := range localDefs { + if r.catalogAllow != nil && !r.catalogAllow[t.Name] { + delete(localNames, t.Name) + continue + } if !allowed[t.Name] { tools = append(tools, t) allowed[t.Name] = true @@ -208,6 +214,7 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { } } extraNames := map[string]bool{} + r.availableCatalog = allowed for _, t := range r.extraTools { if allowed[t.Name] { return nil, fmt.Errorf("Pi tool name collision: %s", t.Name) @@ -216,40 +223,6 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { tools = append(tools, t) } oa := r.cfg.OpenAI - headers := make(map[string]string, len(oa.Headers)) - for name, value := range oa.Headers { - if strings.Contains(value, "%session_id%") && r.conversationID == "" { - continue - } - headers[name] = strings.ReplaceAll(value, "%session_id%", r.conversationID) - } - mode, effort := oa.Reasoning.ModeEffective(), oa.Reasoning.Effort - if r.reasoning != nil && oa.Reasoning.AllowClientReasoningEffective() { - if r.reasoning.Mode != "" { - mode = r.reasoning.Mode - } - if r.reasoning.Effort != "" { - effort = r.reasoning.Effort - } - } - thinking := "off" - if mode == "on" { - thinking = effort - if thinking == "" { - thinking = "medium" - } - } - api := "openai-completions" - if oa.Provider == "claude" || oa.Provider == "anthropic" { - api = "anthropic-messages" - } - base := oa.BaseURL - if base == "" { - base = "https://api.openai.com/v1" - if api == "anthropic-messages" { - base = "https://api.anthropic.com" - } - } root := r.cfg.AgentRuntime.SessionDir if root == "" { root = filepath.Join(filepath.Dir(r.cfg.Database.Path), "pi-sessions") @@ -268,11 +241,27 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { } runID := uuid.NewString() req := agentruntime.Request{RunID: runID, ConversationID: r.conversationID, SystemPrompt: r.systemPrompt, Message: message, History: history, - Model: agentruntime.Model{Provider: oa.Provider, API: api, ID: oa.Model, BaseURL: base, APIKey: oa.APIKey, Headers: headers, ContextWindow: oa.MaxTotalTokens, MaxTokens: oa.MaxCompletionTokensEffective(), Thinking: thinking, ExtraFields: reasoning.AgenticOpenAIExtraFields(&oa, r.reasoning)}, + Model: piModelConfig(oa, r.reasoning, r.conversationID), Tools: tools, SessionDir: filepath.Join(root, key), MaxTurns: max, Profile: agentruntime.PromptProfile{Enabled: r.cfg.AgentRuntime.Purge.EnabledEffective(), Instruction: r.cfg.AgentRuntime.Purge.InstructionFor(oa.Provider, oa.Model), Child: r.child}} if strings.TrimSpace(r.conversationID) == "" { req.SessionDir = "" } + req.ToolSearch = r.cfg.MultiAgent.EinoMiddleware.ToolSearchEnable + req.ToolSearchMinTools = r.cfg.MultiAgent.EinoMiddleware.ToolSearchMinTools + req.AlwaysVisibleTools = append([]string(nil), r.cfg.MultiAgent.EinoMiddleware.ToolSearchAlwaysVisibleTools...) + visibleCount := r.cfg.MultiAgent.EinoMiddleware.ToolSearchAlwaysVisible + if visibleCount <= 0 { + visibleCount = 12 + } + if oa.IsLocalContextProfile() && visibleCount > 6 { + visibleCount = 6 + } + for i, t := range tools { + if i >= visibleCount { + break + } + req.AlwaysVisibleTools = append(req.AlwaysVisibleTools, t.Name) + } req.RetryMax = r.cfg.MultiAgent.EinoMiddleware.ModelRetryMaxRetries for _, id := range r.cfg.MultiAgent.EinoMiddleware.ModelFailoverChannels { ch, _, ok := r.cfg.ResolveAIChannel(id) @@ -282,28 +271,7 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { if ch.Model == oa.Model && ch.BaseURL == oa.BaseURL && ch.Provider == oa.Provider { continue } - fallback := req.Model - fallback.Provider = ch.Provider - fallback.ID = ch.Model - fallback.APIKey = ch.APIKey - fallback.BaseURL = ch.BaseURL - fallback.Headers = map[string]string{} - for key, value := range ch.Headers { - fallback.Headers[key] = strings.ReplaceAll(value, "%session_id%", r.conversationID) - } - fallback.API = "openai-completions" - if ch.Provider == "claude" || ch.Provider == "anthropic" { - fallback.API = "anthropic-messages" - } - if fallback.BaseURL == "" { - fallback.BaseURL = "https://api.openai.com/v1" - if fallback.API == "anthropic-messages" { - fallback.BaseURL = "https://api.anthropic.com" - } - } - fallback.MaxTokens = ch.MaxCompletionTokensEffective() - fallback.ContextWindow = ch.MaxTotalTokens - fallback.ExtraFields = reasoning.AgenticOpenAIExtraFields(&ch, r.reasoning) + fallback := piModelConfig(ch, r.reasoning, r.conversationID) req.FallbackModels = append(req.FallbackModels, fallback) if cap := r.cfg.MultiAgent.EinoMiddleware.ModelFailoverMaxRetries; cap > 0 && len(req.FallbackModels) >= cap { break @@ -382,6 +350,9 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { result.Content = err.Error() result.IsError = true } + if r.cfg.MultiAgent.EinoMiddleware.ReductionEnable { + result.Content = tooloutput.BoundWithSpill(result.Content, r.cfg.MultiAgent.EinoMiddleware.ReductionMaxLengthForTruncEffective(), tooloutput.SpillOpts{RootDir: r.cfg.MultiAgent.EinoMiddleware.ReductionRootDir, ConversationID: r.conversationID, ExecutionID: result.ExecutionID}) + } progress("tool_result", result.Content, map[string]any{"toolName": call.Name, "toolCallId": call.ID, "executionId": result.ExecutionID, "result": result.Content, "success": !result.IsError, "isError": result.IsError, "agentFacing": true}) return result, err } diff --git a/runtime/pi/src/worker.ts b/runtime/pi/src/worker.ts index 0515831c..a497abde 100644 --- a/runtime/pi/src/worker.ts +++ b/runtime/pi/src/worker.ts @@ -1,10 +1,11 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { InMemoryCredentialStore, type Model, type Api } from "@earendil-works/pi-ai"; +import { InMemoryCredentialStore, type Model, type Api, type Message } from "@earendil-works/pi-ai"; import { createAgentSession, createExtensionRuntime, ModelRuntime, SessionManager, SettingsManager, type AgentSession, type ResourceLoader, type ToolDefinition, + DefaultResourceLoader, createToolSearchExtension, } from "@earendil-works/pi-coding-agent"; import { composePrompt, type PromptProfile } from "./profile.js"; import { PROTOCOL_VERSION, RecordReader, send } from "./protocol.js"; @@ -14,18 +15,24 @@ interface ModelConfig { id: string; baseUrl: string; apiKey: string; headers?: Record; contextWindow: number; maxTokens: number; thinking?: string; extraFields?: Record; + compat?: Record; inputBudget?: number; } interface RunRequest { + generateOnly?: boolean; runId: string; conversationId: string; systemPrompt: string; message: string; + workingDir?: string; model: ModelConfig; tools: { name: string; description: string; parameters: Record }[]; sessionDir?: string; history?: Record[]; maxTurns: number; profile: PromptProfile; fallbackModels?: ModelConfig[]; retryMax?: number; + toolSearch?: boolean; alwaysVisibleTools?: string[]; + toolSearchMinTools?: number; } interface ToolReply { content: string; isError?: boolean; executionId?: string; terminate?: boolean } let session: AgentSession | undefined; let started = false; let canceled = false; +const generationAbort = new AbortController(); const queuedSteering: string[] = []; const pending = new Map void; reject: (e: Error) => void }>(); const scratch = mkdtempSync(join(process.env.CYBERSTRIKE_PI_TMP_PARENT || tmpdir(), "cyberstrike-pi-")); @@ -73,6 +80,7 @@ function importHistory(manager: SessionManager, history: Record[], if (message.role === "user") manager.appendMessage({ role: "user", content: message.content ?? "", timestamp }); else if (message.role === "assistant") { const content: any[] = []; + if (message.reasoning_content && model.api !== "anthropic-messages") content.push({ type: "thinking", thinking: message.reasoning_content }); if (typeof message.content === "string" && message.content) content.push({ type: "text", text: message.content }); for (const call of message.tool_calls ?? []) { if (!replies.has(call.id)) continue; // An incomplete legacy call is never replayed. @@ -130,8 +138,10 @@ async function run(req: RunRequest): Promise { let status = "completed"; let failure = ""; let manager: SessionManager | undefined; + let directResult: Record | undefined; try { if (!req.runId || !req.model?.id || !Array.isArray(req.tools)) throw new Error("Invalid run request"); + const workingDir = req.workingDir ? resolve(req.workingDir) : scratch; const names = req.tools.map(t => t.name); if (new Set(names).size !== names.length || names.some(n => !/^[a-zA-Z0-9_.-]+$/.test(n))) throw new Error("Invalid tool catalog"); const runtime = await ModelRuntime.create({ credentials: new InMemoryCredentialStore(), modelsPath: null, @@ -145,7 +155,7 @@ async function run(req: RunRequest): Promise { runtime.registerProvider(provider, { api, baseUrl: config.baseUrl, headers: config.headers, models: [{ id: config.id, name: config.id, api, reasoning: config.thinking !== "off" && !!config.thinking, - input: ["text", "image"], contextWindow: config.contextWindow || 128000, maxTokens: config.maxTokens || 16384, + input: ["text", "image"], contextWindow: config.contextWindow || 128000, maxTokens: config.maxTokens || 16384, compat: config.compat, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }], }); await runtime.setRuntimeApiKey(provider, config.apiKey || "local-no-key"); @@ -184,6 +194,18 @@ async function run(req: RunRequest): Promise { model = runtime.getModel("cyberstrike-router", "auto")!; } if (!model) throw new Error("Model registration failed"); + if (req.generateOnly) { + const input = SessionManager.inMemory(scratch); + importHistory(input, req.history ?? [], req.model); + const answer = await runtime.completeSimple(physical[0], { + systemPrompt: composePrompt(req.systemPrompt, req.profile, names), + messages: input.buildSessionContext().messages as Message[], + tools: req.tools, + }, { maxTokens: req.model.maxTokens, reasoning: (req.model.thinking && req.model.thinking !== "off" ? req.model.thinking : undefined) as any, signal: generationAbort.signal }); + if (answer.stopReason === "error" || answer.stopReason === "aborted") throw new Error(answer.errorMessage || answer.stopReason); + directResult = { response: answer.content.filter(b => b.type === "text").map(b => b.text).join(""), history: exportHistory([answer]), totalTokens: answer.usage.totalTokens }; + return; + } if (req.sessionDir) { const dir = resolve(req.sessionDir); mkdirSync(dir, { recursive: true, mode: 0o700 }); @@ -191,23 +213,38 @@ async function run(req: RunRequest): Promise { if (existsSync(pointer)) { const file = readFileSync(pointer, "utf8").trim(); if (!/^\d{4}.*\.jsonl$/.test(file) || file.includes("/") || file.includes("\\")) throw new Error("Invalid session pointer"); - manager = SessionManager.open(join(dir, file), dir, scratch); + manager = SessionManager.open(join(dir, file), dir, workingDir); } else { - manager = SessionManager.create(scratch, dir); + manager = SessionManager.create(workingDir, dir); importHistory(manager, req.history ?? [], req.model); } // Session files materialize when Pi appends its first entry; the pointer is published after prompting. } else { - manager = SessionManager.inMemory(scratch); + manager = SessionManager.inMemory(workingDir); importHistory(manager, req.history ?? [], req.model); } repairInterruptedCalls(manager); - ({ session } = await createAgentSession({ cwd: scratch, agentDir: scratch, modelRuntime: runtime, model, + const searchEnabled = req.toolSearch === true && names.length >= (req.toolSearchMinTools || 20) && !names.includes("tool_search"); + const always = new Set(["task", "exit", "transfer_to_agent", "write_todos", "TaskCreate", "TaskUpdate", "TaskGet", "TaskList", "skill", "read_file", "execute", "wait_tool_execution", "get_tool_execution", ...(req.alwaysVisibleTools ?? [])]); + const visibleNames = searchEnabled ? ["tool_search", ...names.filter(n => always.has(n))] : names; + const loader = resources(composePrompt(req.systemPrompt, req.profile, visibleNames) + (searchEnabled ? "\nDiscover additional task tools with tool_search. Search results enable matching tools for subsequent calls." : "")); + if (searchEnabled) { + const extensions = new DefaultResourceLoader({ cwd: scratch, agentDir: scratch, settingsManager: SettingsManager.inMemory(), + noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, + extensionFactories: [createToolSearchExtension()], disabledBuiltinExtensions: ["mcp", "codemode"], + }); + await extensions.reload(); + loader.getExtensions = () => extensions.getExtensions(); + if (loader.getExtensions().errors.length) throw new Error("Pi tool search extension failed to initialize"); + } + const inputBudget = Math.max(1024, Math.min(req.model.inputBudget || model.contextWindow - model.maxTokens, model.contextWindow - model.maxTokens)); + ({ session } = await createAgentSession({ cwd: workingDir, agentDir: scratch, modelRuntime: runtime, model, thinkingLevel: (req.model.thinking || "off") as any, sessionManager: manager, - settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1) }, compaction: { enabled: true } }), - noTools: "builtin", tools: names, customTools: req.tools.map(hostTool), - resourceLoader: resources(composePrompt(req.systemPrompt, req.profile, names)), + settingsManager: SettingsManager.inMemory({ retry: { enabled: true, maxRetries: req.retryMax ?? Math.max(2, configs.length - 1) }, compaction: { enabled: true, reserveTokens: model.contextWindow - inputBudget, keepRecentTokens: Math.min(20000, Math.floor(inputBudget / 2)) } }), + noTools: "builtin", tools: searchEnabled ? ["+tool_search"] : names, customTools: req.tools.map(def => ({ ...hostTool(def), exposure: searchEnabled && !always.has(def.name) ? "deferred" : "direct" })), + resourceLoader: loader, })); + if (searchEnabled) await session.bindExtensions({}); session.agent.toolExecution = "sequential"; publishSession(manager, req.sessionDir); let turns = 0; @@ -222,7 +259,10 @@ async function run(req: RunRequest): Promise { if (e.type === "agent_start") for (const note of queuedSteering.splice(0)) void session?.steer(note).catch(fatal); if (e.type === "message_end") publishSession(manager!, req.sessionDir); let data: unknown = e; - if (e.type === "message_update") data = { assistantMessageEvent: e.assistantMessageEvent }; + if (e.type === "message_update") { + const { partial: _partial, ...delta } = e.assistantMessageEvent; + data = { assistantMessageEvent: delta }; + } if (e.type === "agent_end") data = {}; void send({ type: "event", event: { type: e.type, data } }).catch(() => session?.abort()); }); @@ -237,7 +277,7 @@ async function run(req: RunRequest): Promise { failure = error instanceof Error ? error.message : String(error); } finally { const result = { response: session?.getLastAssistantText() ?? "", - history: exportHistory(session?.messages ?? []), status, error: failure, sessionFile: manager?.getSessionFile() }; + history: exportHistory(session?.messages ?? []), ...directResult, status, error: failure, sessionFile: manager?.getSessionFile() }; session?.dispose(); rmSync(scratch, { recursive: true, force: true }); await send({ type: "result", result }); @@ -255,6 +295,7 @@ async function command(record: any): Promise { if (call) { pending.delete(record.id); call.resolve(record.result); } } else if (record.type === "cancel") { canceled = true; + generationAbort.abort(); for (const p of pending.values()) p.reject(new Error("Run canceled")); pending.clear(); await session?.abort(); diff --git a/runtime/pi/test/worker.test.mjs b/runtime/pi/test/worker.test.mjs index f998287f..36bdc28e 100644 --- a/runtime/pi/test/worker.test.mjs +++ b/runtime/pi/test/worker.test.mjs @@ -98,6 +98,7 @@ test("real Pi SDK streams, invokes only host tools and restores persisted sessio assert.deepEqual(fixture.requests[0].tools.map(t => t.function.name), ["echo"]); assert.ok(fixture.requests[1].messages.some(m => m.role === "tool" && m.content === "hello")); assert.ok(first.records.some(r => r.event?.type === "message_update")); + assert.ok(first.records.filter(r => r.event?.type === "message_update").every(r => !Object.hasOwn(r.event.data.assistantMessageEvent, "partial"))); const second = await invoke(t, { ...request(fixture.url, dir), runId: "run-2", message: "summarize prior result" }); assert.equal(second.result.status, "completed", second.result.error); assert.ok(fixture.requests[2].messages.some(m => m.role === "tool" && m.content === "hello")); @@ -149,3 +150,25 @@ test("process loss preserves the session and marks uncertain tools without repla assert.equal(fixture.requests.length, 2); assert.ok(fixture.requests[1].messages.some(m => m.role === "tool" && /effects are unknown/.test(m.content))); }); + +test("native tool search loads a deferred host tool without exposing the full catalog", { timeout: 30000 }, async t => { + const fixture = await startFixture(t, (body, res, count) => { + const names = body.tools.map(t => t.function.name); + if (count === 1) { + assert.deepEqual(names, ["tool_search"]); + sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "search-1", type: "function", function: { name: "tool_search", arguments: '{"query":"echo","limit":1}' } }] }, "tool_calls"); + } else if (count === 2) { + assert.ok(names.includes("echo"), JSON.stringify(body.messages)); + sse(res, { role: "assistant", tool_calls: [{ index: 0, id: "echo-1", type: "function", function: { name: "echo", arguments: '{"text":"found"}' } }] }, "tool_calls"); + } else sse(res, { role: "assistant", content: "discovery verified" }, "stop"); + }); + const req = request(fixture.url); + req.tools.push(...Array.from({ length: 45 }, (_, i) => ({ name: "unrelated_" + i, description: "Unrelated operation", parameters: { type: "object", properties: {} } }))); + let hostCalls = 0; + const { result } = await invoke(t, { ...req, toolSearch: true }, (r, send) => { + if (r.type === "tool_call") { hostCalls++; assert.equal(r.call.name, "echo"); send({ type: "tool_result", id: r.call.id, result: { content: "found" } }); } + }); + assert.equal(result.status, "completed", result.error); + assert.equal(result.response, "discovery verified"); + assert.equal(hostCalls, 1); +}); diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index c1de32a2..36d06b52 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -944,8 +944,8 @@ "historyGroupEarlier": "Older", "agentModeSelectAria": "Choose conversation execution mode", "agentModePanelTitle": "Conversation mode", - "agentModeEinoSingle": "Eino single (ADK)", - "agentModeEinoSingleHint": "Eino ChatModelAgent + Runner with MCP tools (/api/eino-agent)", + "agentModeEinoSingle": "Single agent", + "agentModeEinoSingleHint": "Run a single agent using the runtime selected in Settings", "agentModeDeep": "Deep (DeepAgent)", "agentModeDeepHint": "Eino DeepAgent for complex security testing, multi-stage task delegation, and synthesis", "agentModePlanExecuteLabel": "Plan-Execute", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 1331a7b1..c4a390cc 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -932,8 +932,8 @@ "historyGroupEarlier": "更早", "agentModeSelectAria": "选择对话执行模式", "agentModePanelTitle": "对话模式", - "agentModeEinoSingle": "Eino 单代理(ADK)", - "agentModeEinoSingleHint": "Eino ChatModelAgent + Runner,MCP 工具(/api/eino-agent)", + "agentModeEinoSingle": "单代理", + "agentModeEinoSingleHint": "使用设置中选择的 Pi 或兼容运行时执行单代理任务", "agentModeDeep": "Deep(DeepAgent)", "agentModeDeepHint": "Eino DeepAgent,适合复杂安全测试、多阶段 task 子代理委派与汇总", "agentModePlanExecuteLabel": "Plan-Execute", diff --git a/web/static/js/chat-plan-progress.js b/web/static/js/chat-plan-progress.js index 2c2ec887..87c39acc 100644 --- a/web/static/js/chat-plan-progress.js +++ b/web/static/js/chat-plan-progress.js @@ -1,7 +1,7 @@ (function (root) { 'use strict'; - const PLAN_TOOL_NAMES = new Set(['taskcreate', 'taskupdate', 'tasklist', 'taskget']); + const PLAN_TOOL_NAMES = new Set(['taskcreate', 'taskupdate', 'tasklist', 'taskget', 'write_todos']); const ACTIVE_POLL_INTERVAL_MS = 1500; const ERROR_RETRY_INTERVAL_MS = 4000; const FINAL_STATE_HOLD_MS = 2400;