@dsh-prism/dsh-orchestrator 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -2
- package/README.zh_CN.md +43 -0
- package/dist/contracts.d.ts +87 -0
- package/dist/contracts.js +1 -0
- package/dist/core.d.ts +40 -0
- package/dist/core.js +359 -0
- package/dist/host-bindings.d.ts +16 -0
- package/dist/host-bindings.js +88 -0
- package/dist/host.d.ts +21 -0
- package/dist/host.js +274 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +38 -0
- package/dist/messages.d.ts +5 -0
- package/dist/messages.js +9 -0
- package/dist/policy.d.ts +6 -0
- package/dist/policy.js +72 -0
- package/dist/provider.d.ts +34 -0
- package/dist/provider.js +97 -0
- package/dist/store.d.ts +45 -0
- package/dist/store.js +85 -0
- package/icon.svg +11 -0
- package/locale/de.json +18 -0
- package/locale/en.json +19 -0
- package/locale/es.json +18 -0
- package/locale/fr.json +18 -0
- package/locale/ja.json +18 -0
- package/locale/pt.json +18 -0
- package/locale/ru.json +18 -0
- package/locale/zh.json +19 -0
- package/package.json +79 -4
package/README.md
CHANGED
|
@@ -1,3 +1,43 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<img src="icon.svg" width="256" height="256" alt="dsh-orchestrator icon">
|
|
4
|
+
|
|
5
|
+
# dsh-orchestrator
|
|
6
|
+
|
|
7
|
+
**Give Prism separate models for talking to users, planning their requests and executing each step.**
|
|
8
|
+
|
|
9
|
+
English | [简体中文](README.zh_CN.md)
|
|
10
|
+
|
|
11
|
+
</div>
|
|
12
|
+
|
|
13
|
+
## Set up Prism
|
|
14
|
+
|
|
15
|
+
Use Node.js 24.9 or later, npm, Git and credentials with read access to the five private plugin repositories. The checkout script places matching plugins and launcher files in a local `runtime/` directory. Run subsequent installation, configuration and launch commands there. The public guide is available without signing in. To use the example models, configure your DeepSeek credentials in DSH or set the `DEEPSEEK_API_KEY` environment variable. [Installation guide](https://prism.dsh-plug.in/)
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
git clone https://github.com/dsh-plugins/dsh-prism.git
|
|
19
|
+
cd dsh-prism
|
|
20
|
+
node scripts/checkout.mjs
|
|
21
|
+
cd runtime
|
|
22
|
+
npm ci
|
|
23
|
+
npm run build
|
|
24
|
+
npm start
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Set up the model roster
|
|
28
|
+
|
|
29
|
+
In `runtime/`, copy the Prism example to `prism.config.json`. Under `orchestrator.models`, list the models available to each layer. Give every model an `id` recognized by its DSH provider and a `description` that explains when to choose it. For example, a quick search model and a cross-file analysis model give the planner two distinct choices.
|
|
30
|
+
|
|
31
|
+
| Layer | Who chooses the model | What it can do |
|
|
32
|
+
| --- | --- | --- |
|
|
33
|
+
| L1 · conversation | The user, in Web or IM | Query project metadata, contact planners, check progress and send visible replies. |
|
|
34
|
+
| L2 · planning | L1, when assigning a project | Break a task into steps, choose execution models and report to L1. |
|
|
35
|
+
| L3 · execution | L2, for each step | Use the granted tools in the planner’s project and return results. |
|
|
36
|
+
|
|
37
|
+
Set `orchestrator.defaultProjectId` and optionally `defaultL1Model`. Use `prompt` on individual models to supply role guidance. The default `append` mode adds it to the system prompt. Set `promptMode` to `replace` to provide the full system prompt. After restarting, open the model selector and check that the description and L1 choices match your configuration.
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npm start -- prism.config.json --host 127.0.0.1 --port 3080 --no-open
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
[Prism documentation](https://prism.dsh-plug.in/) · [Technical reference](docs/TECH.md)
|
package/README.zh_CN.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
<img src="icon.svg" width="256" height="256" alt="dsh-orchestrator 图标">
|
|
4
|
+
|
|
5
|
+
# dsh-orchestrator
|
|
6
|
+
|
|
7
|
+
**为棱镜分别配置面向用户、规划任务和执行步骤的模型。**
|
|
8
|
+
|
|
9
|
+
[English](README.md) | 简体中文
|
|
10
|
+
|
|
11
|
+
</div>
|
|
12
|
+
|
|
13
|
+
## 接入棱镜
|
|
14
|
+
|
|
15
|
+
需要 Node.js 24.9 或更高版本、npm、Git,以及对五个私有插件仓库的 Git 读取权限。检出脚本把匹配的插件和启动文件放入本机的 `runtime/` 目录,后续安装、配置和运行命令均在该目录执行。公开使用指南可直接阅读。需要调用示例模型时,请先在 DSH 凭据存储中配置 DeepSeek 凭据,或设置环境变量 `DEEPSEEK_API_KEY`。[安装指南](https://prism.dsh-plug.in/zh/)
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
git clone https://github.com/dsh-plugins/dsh-prism.git
|
|
19
|
+
cd dsh-prism
|
|
20
|
+
node scripts/checkout.mjs
|
|
21
|
+
cd runtime
|
|
22
|
+
npm ci
|
|
23
|
+
npm run build
|
|
24
|
+
npm start
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## 配置可选模型
|
|
28
|
+
|
|
29
|
+
在 `runtime/` 中把示例配置复制为 `prism.config.json`,在 `orchestrator.models` 下分别列出各层可用模型。为每个模型填写 DSH 提供方可识别的 `id`,并用 `description` 说明适用场景。例如,为执行层提供一个适合快速检索的模型和一个擅长跨文件分析的模型,便于规划代理按步骤选择。
|
|
30
|
+
|
|
31
|
+
| 层级 | 谁选择模型 | 主要能力 |
|
|
32
|
+
| --- | --- | --- |
|
|
33
|
+
| L1 · 交互 | 用户在 Web 或 IM 中选择 | 查询项目元数据、联系规划代理、检查进度并主动向用户发信。 |
|
|
34
|
+
| L2 · 规划 | L1 派发项目任务时选择 | 拆分步骤、选择执行模型并向 L1 汇报。 |
|
|
35
|
+
| L3 · 执行 | L2 为每个步骤选择 | 在规划代理的项目中使用获准工具,返回执行结果。 |
|
|
36
|
+
|
|
37
|
+
设置 `orchestrator.defaultProjectId`,还可设置 `defaultL1Model`。每个模型可用 `prompt` 配置角色指令。默认的 `append` 模式将内容附加到系统提示词,将 `promptMode` 设为 `replace` 则提供完整系统提示词。重启后打开模型选择器,检查显示的 L1 模型与介绍是否与配置相符。
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
npm start -- prism.config.json --host 127.0.0.1 --port 3080 --no-open
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
[棱镜使用指南](https://prism.dsh-plug.in/zh/) · [技术参考](docs/TECH.md)
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
export type Layer = 'L1' | 'L2' | 'L3';
|
|
2
|
+
export interface ModelConfig {
|
|
3
|
+
id: string;
|
|
4
|
+
provider?: string;
|
|
5
|
+
description: string;
|
|
6
|
+
prompt?: string;
|
|
7
|
+
promptMode?: 'append' | 'replace';
|
|
8
|
+
}
|
|
9
|
+
export interface OrchestratorConfig {
|
|
10
|
+
defaultProjectId: string;
|
|
11
|
+
defaultL1Model?: string;
|
|
12
|
+
models: Record<Layer, ModelConfig[]>;
|
|
13
|
+
executionTools?: string[];
|
|
14
|
+
}
|
|
15
|
+
export interface ProjectMetadata {
|
|
16
|
+
id: string;
|
|
17
|
+
description: string;
|
|
18
|
+
stack: string[];
|
|
19
|
+
nodeId: string;
|
|
20
|
+
gitRemote?: string;
|
|
21
|
+
permissions: string[];
|
|
22
|
+
}
|
|
23
|
+
export interface RegistryPort {
|
|
24
|
+
query(owner: string, search?: string): ProjectMetadata[];
|
|
25
|
+
resolve(owner: string, projectId: string): ProjectMetadata & {
|
|
26
|
+
workspace: string;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export interface WorkspaceTarget {
|
|
30
|
+
projectId: string;
|
|
31
|
+
nodeId: string;
|
|
32
|
+
cwd: string;
|
|
33
|
+
}
|
|
34
|
+
export interface TurnSpec {
|
|
35
|
+
bindingId: string;
|
|
36
|
+
owner: string;
|
|
37
|
+
parentBindingId?: string;
|
|
38
|
+
layer: Layer;
|
|
39
|
+
model: ModelConfig;
|
|
40
|
+
workspace: WorkspaceTarget;
|
|
41
|
+
/** Native DSH tools only; orchestration capabilities are supplied separately. */
|
|
42
|
+
allowedTools: string[];
|
|
43
|
+
/** L2 may further delegate only these native capabilities to L3. */
|
|
44
|
+
delegationCeiling?: string[];
|
|
45
|
+
systemPrompt: string;
|
|
46
|
+
}
|
|
47
|
+
export interface ToolDefinition {
|
|
48
|
+
name: string;
|
|
49
|
+
description: string;
|
|
50
|
+
parameters: Record<string, unknown>;
|
|
51
|
+
}
|
|
52
|
+
export interface AgentTools {
|
|
53
|
+
definitions: ToolDefinition[];
|
|
54
|
+
invoke(name: string, args: unknown): Promise<unknown>;
|
|
55
|
+
}
|
|
56
|
+
export interface TraceEntry {
|
|
57
|
+
role: string;
|
|
58
|
+
text: string;
|
|
59
|
+
at?: string;
|
|
60
|
+
}
|
|
61
|
+
export interface SessionRunner {
|
|
62
|
+
run(spec: TurnSpec, text: string, tools: AgentTools, signal?: AbortSignal, onReady?: (sessionId: string) => void): Promise<void>;
|
|
63
|
+
transcript(spec: TurnSpec): Promise<TraceEntry[]>;
|
|
64
|
+
}
|
|
65
|
+
export interface PublicMessage {
|
|
66
|
+
id: string;
|
|
67
|
+
role: 'user' | 'assistant';
|
|
68
|
+
delivery?: 'pending' | 'processed' | 'failed';
|
|
69
|
+
text: string;
|
|
70
|
+
at: string;
|
|
71
|
+
}
|
|
72
|
+
export interface TaskCard {
|
|
73
|
+
id: string;
|
|
74
|
+
title: string;
|
|
75
|
+
status: 'queued' | 'running' | 'completed' | 'failed';
|
|
76
|
+
at: string;
|
|
77
|
+
parentId?: string;
|
|
78
|
+
}
|
|
79
|
+
export interface ConversationView {
|
|
80
|
+
modelId: string;
|
|
81
|
+
models: {
|
|
82
|
+
id: string;
|
|
83
|
+
description: string;
|
|
84
|
+
}[];
|
|
85
|
+
messages: PublicMessage[];
|
|
86
|
+
tasks: TaskCard[];
|
|
87
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ConversationView, OrchestratorConfig, RegistryPort, SessionRunner, TraceEntry, TurnSpec } from './contracts.js';
|
|
2
|
+
export type * from './contracts.js';
|
|
3
|
+
export declare class PrismError extends Error {
|
|
4
|
+
readonly code: 'INVALID_INPUT' | 'NOT_FOUND';
|
|
5
|
+
constructor(code: 'INVALID_INPUT' | 'NOT_FOUND', message: string);
|
|
6
|
+
}
|
|
7
|
+
export declare class Orchestrator {
|
|
8
|
+
private readonly registry;
|
|
9
|
+
private readonly runner;
|
|
10
|
+
private readonly store;
|
|
11
|
+
private readonly config;
|
|
12
|
+
private readonly active;
|
|
13
|
+
private readonly watchers;
|
|
14
|
+
private stopping;
|
|
15
|
+
constructor(config: OrchestratorConfig, registry: RegistryPort, runner: SessionRunner, stateDirectory: string);
|
|
16
|
+
start(): Promise<void>;
|
|
17
|
+
private defaultModel;
|
|
18
|
+
private newConversation;
|
|
19
|
+
private change;
|
|
20
|
+
private snapshot;
|
|
21
|
+
view(owner: string): Promise<ConversationView>;
|
|
22
|
+
message(owner: string, text: string, requestId?: string): Promise<ConversationView>;
|
|
23
|
+
selectModel(owner: string, modelId: string): Promise<ConversationView>;
|
|
24
|
+
trace(owner: string, taskId: string): Promise<TraceEntry[]>;
|
|
25
|
+
subscribe(owner: string, listener: (view: ConversationView) => void): () => void;
|
|
26
|
+
private publish;
|
|
27
|
+
private ceiling;
|
|
28
|
+
/** At the mesh boundary reconstruct all security-sensitive fields from worker-local configuration. */
|
|
29
|
+
authorizeRemote(spec: TurnSpec): TurnSpec;
|
|
30
|
+
private spec;
|
|
31
|
+
private wake;
|
|
32
|
+
private consume;
|
|
33
|
+
private settle;
|
|
34
|
+
private invoke;
|
|
35
|
+
private dispatch;
|
|
36
|
+
/** Wait for all in-process work, including events enqueued by completing agents. */
|
|
37
|
+
whenIdle(): Promise<void>;
|
|
38
|
+
/** Stop claiming new turns; committed outstanding messages remain available on restart. */
|
|
39
|
+
close(): Promise<void>;
|
|
40
|
+
}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
import { messages } from './messages.js';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { modelFor, nativeExecutionTools, systemPrompt, toolSets, validateConfig } from './policy.js';
|
|
4
|
+
import { ConversationStore, enqueue } from './store.js';
|
|
5
|
+
export class PrismError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
constructor(code, message) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.code = code;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function textField(value, max = 32_000) {
|
|
13
|
+
if (typeof value !== 'string' || !value.trim() || value.length > max)
|
|
14
|
+
throw new PrismError('INVALID_INPUT', '文本为空或过长');
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
function narrow(ceiling, requested) {
|
|
18
|
+
if (requested === undefined)
|
|
19
|
+
return [...ceiling];
|
|
20
|
+
if (!Array.isArray(requested) || requested.some(value => typeof value !== 'string' || !ceiling.includes(value))) {
|
|
21
|
+
throw new PrismError('INVALID_INPUT', messages.ceiling);
|
|
22
|
+
}
|
|
23
|
+
return [...new Set(requested)];
|
|
24
|
+
}
|
|
25
|
+
function binding(state, id) {
|
|
26
|
+
if (state.root.id === id)
|
|
27
|
+
return state.root;
|
|
28
|
+
const task = state.tasks.find(task => task.id === id);
|
|
29
|
+
if (!task)
|
|
30
|
+
throw new PrismError('NOT_FOUND', '找不到会话');
|
|
31
|
+
return task;
|
|
32
|
+
}
|
|
33
|
+
function publicCatalog(models) {
|
|
34
|
+
return models.map(({ id, description }) => ({ id, description }));
|
|
35
|
+
}
|
|
36
|
+
function now() { return new Date().toISOString(); }
|
|
37
|
+
function terminal(task) { return task.status === 'completed' || task.status === 'failed'; }
|
|
38
|
+
export class Orchestrator {
|
|
39
|
+
registry;
|
|
40
|
+
runner;
|
|
41
|
+
store;
|
|
42
|
+
config;
|
|
43
|
+
active = new Map();
|
|
44
|
+
watchers = new Map();
|
|
45
|
+
stopping = false;
|
|
46
|
+
constructor(config, registry, runner, stateDirectory) {
|
|
47
|
+
this.registry = registry;
|
|
48
|
+
this.runner = runner;
|
|
49
|
+
validateConfig(config);
|
|
50
|
+
this.config = structuredClone(config);
|
|
51
|
+
this.store = new ConversationStore(stateDirectory);
|
|
52
|
+
}
|
|
53
|
+
async start() {
|
|
54
|
+
for (const owner of this.store.owners()) {
|
|
55
|
+
this.change(owner, state => {
|
|
56
|
+
// Never repeat a turn that could have already written files or sent a message.
|
|
57
|
+
for (const job of [...state.queue]) {
|
|
58
|
+
if (job.worker && !this.store.workerAlive(job.worker))
|
|
59
|
+
this.settle(state, job, false);
|
|
60
|
+
}
|
|
61
|
+
if (!this.config.models.L1.some(model => model.id === state.root.modelId)) {
|
|
62
|
+
state.root.modelId = this.defaultModel();
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
this.wake(owner);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
defaultModel() { return this.config.defaultL1Model ?? this.config.models.L1[0].id; }
|
|
69
|
+
newConversation(owner) {
|
|
70
|
+
const project = this.registry.resolve(owner, this.config.defaultProjectId);
|
|
71
|
+
return {
|
|
72
|
+
root: { id: randomUUID(), layer: 'L1', modelId: this.defaultModel(), ceiling: [], target: { projectId: project.id, nodeId: project.nodeId, cwd: project.workspace } },
|
|
73
|
+
messages: [], tasks: [], requests: [], queue: [],
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
change(owner, fn) {
|
|
77
|
+
textField(owner, 2048);
|
|
78
|
+
return this.store.change(owner, () => this.newConversation(owner), fn);
|
|
79
|
+
}
|
|
80
|
+
snapshot(state) {
|
|
81
|
+
return {
|
|
82
|
+
modelId: state.root.modelId,
|
|
83
|
+
models: publicCatalog(this.config.models.L1),
|
|
84
|
+
messages: state.messages,
|
|
85
|
+
tasks: state.tasks.map(task => ({
|
|
86
|
+
id: task.id, title: task.layer === 'L3' ? '执行步骤' : task.title,
|
|
87
|
+
status: task.status, at: task.at, ...(task.layer === 'L3' ? { parentId: task.parent } : {}),
|
|
88
|
+
})),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
async view(owner) {
|
|
92
|
+
textField(owner, 2048);
|
|
93
|
+
const state = this.store.read(owner);
|
|
94
|
+
return state ? this.snapshot(state) : this.change(owner, state => this.snapshot(state));
|
|
95
|
+
}
|
|
96
|
+
async message(owner, text, requestId) {
|
|
97
|
+
if (this.stopping)
|
|
98
|
+
throw new Error('服务正在关闭');
|
|
99
|
+
textField(text);
|
|
100
|
+
if (requestId !== undefined)
|
|
101
|
+
textField(requestId, 1024);
|
|
102
|
+
const result = this.change(owner, state => {
|
|
103
|
+
if (requestId && state.requests.includes(requestId))
|
|
104
|
+
return this.snapshot(state);
|
|
105
|
+
if (requestId)
|
|
106
|
+
state.requests.push(requestId);
|
|
107
|
+
const messageId = randomUUID();
|
|
108
|
+
state.messages.push({ id: messageId, role: 'user', delivery: 'pending', text, at: now() });
|
|
109
|
+
enqueue(state, state.root, JSON.stringify({ kind: 'user', text }), messageId);
|
|
110
|
+
return this.snapshot(state);
|
|
111
|
+
});
|
|
112
|
+
this.publish(owner);
|
|
113
|
+
this.wake(owner);
|
|
114
|
+
return result;
|
|
115
|
+
}
|
|
116
|
+
async selectModel(owner, modelId) {
|
|
117
|
+
if (!this.config.models.L1.some(model => model.id === modelId))
|
|
118
|
+
throw new PrismError('INVALID_INPUT', '此交互模型不可用');
|
|
119
|
+
const view = this.change(owner, state => { state.root.modelId = modelId; return this.snapshot(state); });
|
|
120
|
+
this.publish(owner);
|
|
121
|
+
return view;
|
|
122
|
+
}
|
|
123
|
+
async trace(owner, taskId) {
|
|
124
|
+
const task = this.store.read(textField(owner, 2048))?.tasks.find(task => task.id === taskId);
|
|
125
|
+
if (!task)
|
|
126
|
+
throw new PrismError('NOT_FOUND', '找不到此任务');
|
|
127
|
+
return this.runner.transcript(this.spec(owner, task, task.modelId, task.parent));
|
|
128
|
+
}
|
|
129
|
+
subscribe(owner, listener) {
|
|
130
|
+
textField(owner, 2048);
|
|
131
|
+
const set = this.watchers.get(owner) ?? new Set();
|
|
132
|
+
this.watchers.set(owner, set);
|
|
133
|
+
set.add(listener);
|
|
134
|
+
return () => {
|
|
135
|
+
set.delete(listener);
|
|
136
|
+
if (!set.size)
|
|
137
|
+
this.watchers.delete(owner);
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
publish(owner) {
|
|
141
|
+
const watchers = this.watchers.get(owner);
|
|
142
|
+
if (!watchers?.size)
|
|
143
|
+
return;
|
|
144
|
+
const view = this.snapshot(this.store.read(owner));
|
|
145
|
+
for (const listener of watchers) {
|
|
146
|
+
try {
|
|
147
|
+
listener(structuredClone(view));
|
|
148
|
+
}
|
|
149
|
+
catch { /* A detached channel cannot roll back a committed event. */ }
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
ceiling(project) {
|
|
153
|
+
return (this.config.executionTools ?? nativeExecutionTools).filter(name => nativeExecutionTools.includes(name) && project.permissions.includes(name));
|
|
154
|
+
}
|
|
155
|
+
/** At the mesh boundary reconstruct all security-sensitive fields from worker-local configuration. */
|
|
156
|
+
authorizeRemote(spec) {
|
|
157
|
+
textField(spec.owner, 2048);
|
|
158
|
+
textField(spec.bindingId, 256);
|
|
159
|
+
if (!['L1', 'L2', 'L3'].includes(spec.layer))
|
|
160
|
+
throw new Error('未知代理层级');
|
|
161
|
+
if (spec.layer === 'L1') {
|
|
162
|
+
if (spec.parentBindingId !== undefined || spec.workspace.projectId !== this.config.defaultProjectId)
|
|
163
|
+
throw new Error('交互会话必须绑定默认项目');
|
|
164
|
+
}
|
|
165
|
+
else {
|
|
166
|
+
textField(spec.parentBindingId, 256);
|
|
167
|
+
}
|
|
168
|
+
const project = this.registry.resolve(spec.owner, spec.workspace.projectId);
|
|
169
|
+
if (project.nodeId !== spec.workspace.nodeId)
|
|
170
|
+
throw new Error('项目节点不匹配');
|
|
171
|
+
const model = modelFor(this.config, spec.layer, spec.model.id);
|
|
172
|
+
if (!Array.isArray(spec.allowedTools))
|
|
173
|
+
throw new Error('缺少权限声明');
|
|
174
|
+
const allowedTools = narrow(spec.layer === 'L3' ? this.ceiling(project) : [], spec.allowedTools);
|
|
175
|
+
return {
|
|
176
|
+
owner: spec.owner, bindingId: spec.bindingId, parentBindingId: spec.parentBindingId, layer: spec.layer,
|
|
177
|
+
model: { ...model }, systemPrompt: systemPrompt(spec.layer, model), allowedTools,
|
|
178
|
+
...(spec.layer === 'L2' && { delegationCeiling: narrow(this.ceiling(project), spec.delegationCeiling ?? []) }),
|
|
179
|
+
workspace: { projectId: project.id, nodeId: project.nodeId, cwd: project.workspace },
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
spec(owner, actor, modelId, parentBindingId) {
|
|
183
|
+
if (actor.layer === 'L1' && actor.target.projectId !== this.config.defaultProjectId)
|
|
184
|
+
throw new Error('默认项目绑定已变更');
|
|
185
|
+
const project = this.registry.resolve(owner, actor.target.projectId);
|
|
186
|
+
if (project.nodeId !== actor.target.nodeId || project.workspace !== actor.target.cwd)
|
|
187
|
+
throw new Error('会话绑定的工作区已变更');
|
|
188
|
+
const model = modelFor(this.config, actor.layer, modelId);
|
|
189
|
+
const currentCeiling = this.ceiling(project).filter(tool => actor.ceiling.includes(tool));
|
|
190
|
+
return {
|
|
191
|
+
owner, bindingId: actor.id, parentBindingId, layer: actor.layer, model: { ...model }, workspace: { ...actor.target },
|
|
192
|
+
allowedTools: actor.layer === 'L3' ? currentCeiling : [],
|
|
193
|
+
...(actor.layer === 'L2' && { delegationCeiling: currentCeiling }),
|
|
194
|
+
systemPrompt: systemPrompt(actor.layer, model),
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
wake(owner) {
|
|
198
|
+
if (this.stopping)
|
|
199
|
+
return;
|
|
200
|
+
const state = this.store.read(owner);
|
|
201
|
+
if (!state)
|
|
202
|
+
return;
|
|
203
|
+
for (const id of new Set(state.queue.map(job => job.bindingId))) {
|
|
204
|
+
if (this.active.has(id) || state.queue.find(job => job.bindingId === id)?.worker)
|
|
205
|
+
continue;
|
|
206
|
+
const promise = Promise.resolve().then(() => this.consume(owner, id))
|
|
207
|
+
.catch(error => console.error('[dsh-prism] 无法处理会话队列', error))
|
|
208
|
+
.finally(() => { this.active.delete(id); this.wake(owner); });
|
|
209
|
+
this.active.set(id, promise);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async consume(owner, id) {
|
|
213
|
+
const claimed = this.change(owner, state => {
|
|
214
|
+
const job = state.queue.find(item => item.bindingId === id);
|
|
215
|
+
if (!job || job.worker)
|
|
216
|
+
return;
|
|
217
|
+
job.worker = this.store.workerId;
|
|
218
|
+
const task = state.tasks.find(task => task.id === id);
|
|
219
|
+
if (task) {
|
|
220
|
+
task.status = 'running';
|
|
221
|
+
task.at = now();
|
|
222
|
+
}
|
|
223
|
+
return { job, actor: task ?? state.root, parent: task?.parent };
|
|
224
|
+
});
|
|
225
|
+
if (!claimed)
|
|
226
|
+
return;
|
|
227
|
+
this.publish(owner);
|
|
228
|
+
const { actor, job, parent } = claimed;
|
|
229
|
+
let succeeded = false;
|
|
230
|
+
try {
|
|
231
|
+
const spec = this.spec(owner, actor, job.modelId, parent);
|
|
232
|
+
const tools = {
|
|
233
|
+
definitions: structuredClone(toolSets[actor.layer]),
|
|
234
|
+
invoke: async (name, args) => {
|
|
235
|
+
const result = this.change(owner, state => {
|
|
236
|
+
if (!state.queue.some(item => item.id === job.id && item.worker === this.store.workerId))
|
|
237
|
+
throw new Error('本轮工具权限已失效');
|
|
238
|
+
return this.invoke(owner, state, actor.id, name, args);
|
|
239
|
+
});
|
|
240
|
+
this.publish(owner);
|
|
241
|
+
this.wake(owner);
|
|
242
|
+
return result;
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
await this.runner.run(spec, job.text, tools);
|
|
246
|
+
succeeded = true;
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
console.error('[dsh-prism] 会话运行失败', error instanceof Error ? error.message : error);
|
|
250
|
+
}
|
|
251
|
+
finally {
|
|
252
|
+
this.change(owner, state => this.settle(state, job, succeeded));
|
|
253
|
+
this.publish(owner);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
settle(state, job, ok) {
|
|
257
|
+
state.queue = state.queue.filter(item => item.id !== job.id);
|
|
258
|
+
const message = job.messageId && state.messages.find(item => item.id === job.messageId);
|
|
259
|
+
if (message)
|
|
260
|
+
message.delivery = ok ? 'processed' : 'failed';
|
|
261
|
+
const task = state.tasks.find(item => item.id === job.bindingId);
|
|
262
|
+
if (!task)
|
|
263
|
+
return;
|
|
264
|
+
const children = state.tasks.filter(child => child.parent === task.id);
|
|
265
|
+
if (!ok)
|
|
266
|
+
task.turnFailed = true;
|
|
267
|
+
if (state.queue.some(item => item.bindingId === task.id) || children.some(child => !terminal(child)))
|
|
268
|
+
return;
|
|
269
|
+
task.status = !task.turnFailed && children.every(child => child.status === 'completed') ? 'completed' : 'failed';
|
|
270
|
+
task.at = now();
|
|
271
|
+
const parent = binding(state, task.parent);
|
|
272
|
+
enqueue(state, parent, JSON.stringify({ kind: 'task_settled', taskId: task.id, status: task.status, progress: task.progress }));
|
|
273
|
+
}
|
|
274
|
+
invoke(owner, state, id, name, raw) {
|
|
275
|
+
const actor = binding(state, id);
|
|
276
|
+
const definition = toolSets[actor.layer].find(tool => tool.name === name);
|
|
277
|
+
if (!definition || !raw || typeof raw !== 'object' || Array.isArray(raw))
|
|
278
|
+
throw new Error('该层无权调用此工具,或参数格式无效');
|
|
279
|
+
const args = raw;
|
|
280
|
+
const schema = definition.parameters;
|
|
281
|
+
const properties = schema.properties;
|
|
282
|
+
if (Object.keys(args).some(key => !Object.hasOwn(properties, key)) || schema.required.some(key => !Object.hasOwn(args, key))) {
|
|
283
|
+
throw new Error('工具参数超出声明或缺少必填项');
|
|
284
|
+
}
|
|
285
|
+
switch (name) {
|
|
286
|
+
case 'send_user': {
|
|
287
|
+
state.messages.push({ id: randomUUID(), role: 'assistant', text: textField(args.text), at: now() });
|
|
288
|
+
return { sent: true };
|
|
289
|
+
}
|
|
290
|
+
case 'query_projects': {
|
|
291
|
+
const search = args.search === '' || args.search === undefined ? undefined : textField(args.search, 1024);
|
|
292
|
+
return this.registry.query(owner, search).map(({ id, description, stack, nodeId, gitRemote, permissions }) => ({
|
|
293
|
+
id, description, stack, nodeId, permissions, ...(gitRemote === undefined ? {} : { gitRemote }),
|
|
294
|
+
}));
|
|
295
|
+
}
|
|
296
|
+
case 'list_models': return publicCatalog(this.config.models[actor.layer === 'L1' ? 'L2' : 'L3']);
|
|
297
|
+
case 'dispatch_planner':
|
|
298
|
+
case 'dispatch_executor': return this.dispatch(owner, state, actor, args);
|
|
299
|
+
case 'report_progress': {
|
|
300
|
+
const task = state.tasks.find(task => task.id === id);
|
|
301
|
+
task.progress = textField(args.text);
|
|
302
|
+
task.at = now();
|
|
303
|
+
return { recorded: true };
|
|
304
|
+
}
|
|
305
|
+
case 'send_parent': {
|
|
306
|
+
const task = state.tasks.find(task => task.id === id);
|
|
307
|
+
enqueue(state, binding(state, task.parent), JSON.stringify({ kind: 'child_message', taskId: task.id, text: textField(args.text) }));
|
|
308
|
+
return { sent: true };
|
|
309
|
+
}
|
|
310
|
+
case 'get_progress':
|
|
311
|
+
case 'send_child': {
|
|
312
|
+
const child = state.tasks.find(task => task.id === args.taskId && task.parent === id);
|
|
313
|
+
if (!child)
|
|
314
|
+
throw new PrismError('NOT_FOUND', '找不到直接子任务');
|
|
315
|
+
if (name === 'get_progress') {
|
|
316
|
+
const children = state.tasks.filter(task => task.parent === child.id).map(({ id, title, status, progress }) => ({ id, title, status, progress }));
|
|
317
|
+
return { id: child.id, status: child.status, progress: child.progress, children };
|
|
318
|
+
}
|
|
319
|
+
if (terminal(child)) {
|
|
320
|
+
child.status = 'queued';
|
|
321
|
+
child.turnFailed = false;
|
|
322
|
+
child.at = now();
|
|
323
|
+
}
|
|
324
|
+
enqueue(state, child, JSON.stringify({ kind: 'parent_message', text: textField(args.text) }));
|
|
325
|
+
return { sent: true };
|
|
326
|
+
}
|
|
327
|
+
default: throw new Error('未知工具');
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
dispatch(owner, state, actor, args) {
|
|
331
|
+
const layer = actor.layer === 'L1' ? 'L2' : 'L3';
|
|
332
|
+
const model = modelFor(this.config, layer, textField(args.modelId, 256));
|
|
333
|
+
const projectId = layer === 'L2' ? textField(args.projectId, 1024) : actor.target.projectId;
|
|
334
|
+
const project = this.registry.resolve(owner, projectId);
|
|
335
|
+
const target = layer === 'L2' ? { projectId, nodeId: project.nodeId, cwd: project.workspace } : { ...actor.target };
|
|
336
|
+
if (target.nodeId !== project.nodeId || target.cwd !== project.workspace)
|
|
337
|
+
throw new Error('项目绑定已变更');
|
|
338
|
+
const ceiling = this.ceiling(project).filter(name => layer === 'L2' || actor.ceiling.includes(name));
|
|
339
|
+
const task = {
|
|
340
|
+
id: randomUUID(), layer, target, modelId: model.id, ceiling: narrow(ceiling, args.permissions),
|
|
341
|
+
parent: actor.id, title: textField(args.title, 240), progress: '', at: now(), status: 'queued',
|
|
342
|
+
};
|
|
343
|
+
state.tasks.push(task);
|
|
344
|
+
enqueue(state, task, JSON.stringify({ kind: 'assignment', text: textField(args.instruction), projectId, permissions: task.ceiling }));
|
|
345
|
+
return { taskId: task.id };
|
|
346
|
+
}
|
|
347
|
+
/** Wait for all in-process work, including events enqueued by completing agents. */
|
|
348
|
+
async whenIdle() {
|
|
349
|
+
while (this.active.size)
|
|
350
|
+
await Promise.all([...this.active.values()]);
|
|
351
|
+
}
|
|
352
|
+
/** Stop claiming new turns; committed outstanding messages remain available on restart. */
|
|
353
|
+
async close() {
|
|
354
|
+
this.stopping = true;
|
|
355
|
+
await this.whenIdle();
|
|
356
|
+
this.watchers.clear();
|
|
357
|
+
this.store.close();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { SessionId } from '@deepseek-ai/dsh-session';
|
|
2
|
+
import type { TurnSpec } from './contracts.js';
|
|
3
|
+
/** Updating the binding and recording the archive obligation is one durable commit.
|
|
4
|
+
* A failed archive can be retried even after the host restarts. */
|
|
5
|
+
export declare class SessionBindings {
|
|
6
|
+
private readonly db;
|
|
7
|
+
constructor(directory: string);
|
|
8
|
+
private scope;
|
|
9
|
+
current(spec: TurnSpec): SessionId | undefined;
|
|
10
|
+
parent(spec: TurnSpec): SessionId | undefined;
|
|
11
|
+
publish(spec: TurnSpec, expected: SessionId | undefined, next: SessionId): boolean;
|
|
12
|
+
queueArchive(binding: string, session: SessionId): void;
|
|
13
|
+
pending(binding: string): SessionId[];
|
|
14
|
+
archived(session: SessionId): void;
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|