Skip to content
dsh.fish
Bundle

dsh-csp-runtime

Cognitive State Protocol (CSP) v0.1 — the cross-framework interop layer that makes AI thinking state serializable, persistable, and transferable. Host-side Cordis plugin for the DSH ecosystem.

Source
helibeiqi
stars
1 stars
License
MIT
Updated
Updated 13 days ago

Readme

# dsh-csp-runtime

> 让 AI 的**思考过程**(目标 / 信念 / 计划 / 决策 / 不确定性 / 交接令牌)成为可序列化、可迁移的一等公民。

![CI](https://img.shields.io/badge/CI-pass-brightgreen)
![npm](https://img.shields.io/badge/npm-dsh--csp--runtime-blue)
![License](https://img.shields.io/badge/license-MIT-green)

---

## 它是什么

**CSP(Cognitive State Protocol)v0.1** 是一套跨框架认知状态交换格式。它把 agent 的"思考状态"——
当前在做什么(goal)、基于什么相信(belief)、下一步怎么走(plan)、为何这样选(decision)、
不知道什么(uncertainty)、以及如何交接(handoff)——打包成一个纯 JSON 快照,
可序列化、可持久化、可跨 agent 迁移。

### ⚠️ 定位:它是互操作层,不是事件溯源的替代品

CSP **不是** 重新发明 DSH 事件溯源日志。它是 DSH event stream 的**导出/导入互操作层**:

- DSH 内部仍以事件溯源(event-sourced)方式记录会话;
- 非 DSH agent(crewai / langgraph / 通用 JSON 消费方)可**导入** CSP,无需理解 DSH 内核;
- CSP 只描述"思考状态",不定义工具、不做编排执行。

### 与 CDP / 意图网络正交(三者可同时安装)

| 层 | 角色 | CSP 边界 |
|----|------|---------|
| **CDP**(语义层) | 工具能力元数据、`capability_id` | CSP **不写** CDP;仅 `agent.capability_id` 引用 |
| **意图网络**(编排层) | 工具编排、`trace_id` | CSP **不写** 执行器;可间接引用 `trace_id` |
| **CSP(本插件)** | 认知状态快照、跨 agent 迁移 | 6 类状态模型的唯一权威定义方 |

> 引用而非重复定义:CSP 允许出现 `capability_id` / `trace_id`,但**绝不**在 schema 内重新声明这些实体。

### DSH 版本区间

- 要求 DSH 宿主 runtime:`@deepseek-ai/cordis >= 0.1.0`、`@deepseek-ai/dsh-tools >= 0.1.0`
- Node.js `>= 22.19`

> 🧪 **Developer Preview**:M1 为协议设计层交付物。API 与 schema 在 0.x 阶段可能变动,生产使用前请锁定版本。

---

## 安装

```bash
dsh plugin --profile web add github:helibeiqi/dsh-csp-runtime
dsh plugin --profile web add dsh-csp-runtime
dsh plugin --profile web add "file:./dsh-csp-runtime"
```

依赖纯净:必选 `@deepseek-ai/cordis` + `@deepseek-ai/dsh-tools`;
可选 `@deepseek-ai/cdp-metadata` / `@deepseek-ai/intent-network`;**严禁** `@modelcontextprotocol/*`。

---

## 配置字段

插件 config 仅允许以下 5 个顶层字段(多出的字段会被 `console.warn` 并忽略):

| 字段 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| `sources` | `{ statesDir?: string }` | `./csp-states` | CSP 状态来源目录 |
| `capture` | `{ enabled: boolean; autoInstrumentTools: boolean }` | `{ enabled: false, autoInstrumentTools: false }` | 捕获策略(**默认关闭,零开销**) |
| `persistence` | `{ enabled: boolean; path: string; format: 'json' }` | `{ enabled: true, path: './csp-states', format: 'json' }` | 文件持久化后端 |
| `handoff` | `{ enabled: boolean; tokenTtlSeconds: number }` | `{ enabled: true, tokenTtlSeconds: 3600 }` | 交接令牌配置 |
| `interop` | `{ dshExport: boolean; genericImport: boolean }` | `{ dshExport: true, genericImport: true }` | 跨框架导入/导出 |

服务注册:本插件**仅**注册 `ctx.provide('cspStore', store)`,禁用 `cdpRegistry` / `universalAdapter` / `intentNetwork`。

---

## 端到端示例:AAPL 分析场景

`csp-states/aapl-analysis.csp.json`(同 `docs/examples/aapl-analysis.csp.json`)展示了一次完整的股票分析认知状态:

```jsonc
{
  "id": "aapl-analysis-2026-08-23",
  "schema_version": "0.1",
  "agent": { "id": "dsh-analyst-07", "framework": "dsh", "capability_id": "cdp:equity-research" },
  "goal_stack": [
    { "id": "goal-1", "intent": "评估 AAPL 当前估值是否合理", "status": "active" },
    { "id": "goal-2", "intent": "校验最近一季度营收增速", "status": "done", "parent": "goal-1" },
    { "id": "goal-3", "intent": "判断美联储利率路径影响", "status": "abandoned", "parent": "goal-1" }
  ],
  "belief_set": [
    { "id": "belief-1", "proposition": "AAPL 动态市盈率约 30x,高于 5 年均值 25x", "confidence": 0.85, "evidence": ["market-data-feed"], "contradicted_by": [] },
    { "id": "belief-3", "proposition": "服务业务毛利率扩张支撑利润率", "confidence": 0.6, "evidence": ["segment-report"], "contradicted_by": ["belief-4"] },
    { "id": "belief-4", "proposition": "监管可能压缩服务业务定价", "confidence": 0.55, "evidence": ["regulatory-news"], "contradicted_by": ["belief-3"] }
  ],
  "plan_tree": {
    "root_goal": "评估 AAPL 当前估值是否合理",
    "steps": [
      { "id": "step-1", "kind": "observe", "action": "fetch_price_metrics", "status": "done", "result_ref": "r-price", "depends_on": [] },
      { "id": "step-3", "kind": "hypothesize", "action": "model_margin_path", "status": "in_progress", "depends_on": ["step-2"] },
      { "id": "step-4", "kind": "decide", "action": "issue_rating", "status": "pending", "depends_on": ["step-1", "step-3"] }
    ]
  },
  "decision_trace": [
    { "at": "2026-08-23T10:22:00Z", "step": "step-4", "chosen": "暂给'持有'而非'买入'", "alternatives_considered": ["买入", "卖出"], "rationale": "估值偏高但基本面稳健" }
  ],
  "uncertainty": { "overall": 0.45, "bottlenecks": ["监管裁决未公布", "下季指引模糊"] },
  "handoff": {
    "mode": "transferable",
    "continuation_prompt": "已从 step-3 续做:请基于 r-price/r-earnings 完成利润率假设并触发 step-4。注意 belief-3 与 belief-4 互斥。",
    "required_capabilities": ["cdp:equity-research", "cdp:financial-modeling"]
  }
}
```

### DSH event stream → CSP 导出 → 非 DSH agent 接续

```ts
import { CSPStore } from 'dsh-csp-runtime';
import { dshToCsp, cspToGeneric } from 'dsh-csp-runtime';

// 1) DSH event stream 降采样为 CSP
const csp = dshToCsp(dshEventStream, store);

// 2) 导出为框架无关对象,交给 crewai / langgraph / 通用消费方
const generic = cspToGeneric(csp); // 去掉 DSH 特定标记,保留 6 类语义
```

接手方用 `cspFromGeneric(generic)` 重建 CSP 状态继续工作。

---

## 交接令牌(核心原创特性)

handoff token 是 CSP 区别于"会话日志"的杀手特性:它定义了该状态**能否 / 如何被接手**。

```ts
import { createHandoff, verifyHandoff } from 'dsh-csp-runtime';

// A 方:生成令牌
const token = createHandoff(store, stateId, {
  mode: 'transferable',
  continuation_prompt: '从 step-3 续做利润率假设',
  required_capabilities: ['cdp:equity-research'],
  ttl_seconds: 3600,
});
const tokenJson = JSON.stringify(token); // 可经任意通道传递

// B 方:校验并重建可接续骨架(belief 每条标 transferred:true)
const result = verifyHandoff(tokenJson);
if (result.ok) {
  // result.skeleton.goal_stack / plan_tree 完整保留
  // result.skeleton.belief_set[].transferred === true
  // → B 带着敬畏心续做,不重复已否决路径
}
```

`mode` 三态语义:
- `transferable`:A 把进行中的任务交给 B,B 应**继续**做;
- `final`:A 已完成,B 仅需**消费结果**;
- `blocked`:A 卡住(缺权限/缺数据),B 接手前需**先解除阻塞**。

---

## CLI

交互式编辑 `.csp.json`:

```bash
node scripts/csp-edit.ts create ./my-state.csp.json
node scripts/csp-edit.ts view   ./my-state.csp.json
node scripts/csp-edit.ts edit   ./my-state.csp.json
```

---

## 已知限制(M1)

- **不实现 crewai / langgraph 具体适配**:仅提供 `dshToCsp` / `cspToGeneric` / `cspFromGeneric` 通用映射,框架专属字段映射留 TODO。
- **capture 默认关闭**:需显式配置 `capture.enabled=true` 才捕获,避免无意识采集。
- **belief 自动提取为 best-effort**:`fromDshEventStream` 可能引入错误信念,迁移前应由接手 agent 复核 `evidence`。
- **handoff token 仅做哈希完整性校验**,M1 不做加密签名;生产环境应在 Host 层叠加传输加密与能力匹配鉴权。

---

## 开发

```bash
npm install
npm run typecheck   # tsc 零错误
npm run lint        # eslint 零警告(禁止 any)
npm run test        # vitest 全绿,核心模块覆盖率 >= 80%
npm run build       # 编译到 lib/
```

详见 [CONTRIBUTING.md](./CONTRIBUTING.md) 与 [SECURITY.md](./SECURITY.md)。

## License

[MIT](./LICENSE) © helibeiqi

Install

dsh plugin --profile web add github:helibeiqi/dsh-csp-runtime

Profile: web

  • This package builds from source on install. pnpm will ask you to allow its build script — that is permission to run the package’s code on your machine, outside the agent sandbox. Only allow sources you trust.
  • This source has no pinned commit, so a later push upstream changes what installs. Prefer pinning a commit.
Source