@dsh-prism/dsh-orchestrator 0.1.0 → 0.1.1

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.
@@ -0,0 +1,33 @@
1
+ - insert:
2
+ - id: prism-preset-l1
3
+ name: '@deepseek-ai/dsh-agent-preset'
4
+ config:
5
+ id: prism-l1
6
+ name: Prism L1
7
+ plugins: []
8
+ - id: prism-preset-l2
9
+ name: '@deepseek-ai/dsh-agent-preset'
10
+ config:
11
+ id: prism-l2
12
+ name: Prism L2
13
+ plugins: []
14
+ - id: prism-preset-l3
15
+ name: '@deepseek-ai/dsh-agent-preset'
16
+ config:
17
+ id: prism-l3
18
+ name: Prism L3
19
+ plugins:
20
+ - id: prism-fs
21
+ name: '@deepseek-ai/dsh-tool-fs'
22
+ config:
23
+ applyPatch: true
24
+ - id: prism-search
25
+ name: '@deepseek-ai/dsh-tool-fs-search'
26
+ config:
27
+ sampleOverCapGlobResults: false
28
+ - id: prism-bash
29
+ name: '@deepseek-ai/dsh-tool-bash'
30
+ - id: dsh-orchestrator
31
+ name: '@dsh-prism/dsh-orchestrator'
32
+ config:
33
+ useHostModel: true
@@ -6,11 +6,17 @@ export interface ModelConfig {
6
6
  prompt?: string;
7
7
  promptMode?: 'append' | 'replace';
8
8
  }
9
- export interface OrchestratorConfig {
10
- defaultProjectId: string;
9
+ interface ProjectPolicy {
10
+ defaultProjectId?: string;
11
+ executionTools?: string[];
12
+ }
13
+ export interface HostModelConfig extends ProjectPolicy {
14
+ useHostModel: true;
15
+ }
16
+ export interface OrchestratorConfig extends ProjectPolicy {
17
+ useHostModel?: false;
11
18
  defaultL1Model?: string;
12
19
  models: Record<Layer, ModelConfig[]>;
13
- executionTools?: string[];
14
20
  }
15
21
  export interface ProjectMetadata {
16
22
  id: string;
@@ -66,6 +72,7 @@ export interface PublicMessage {
66
72
  id: string;
67
73
  role: 'user' | 'assistant';
68
74
  delivery?: 'pending' | 'processed' | 'failed';
75
+ deliveryError?: 'no_response';
69
76
  text: string;
70
77
  at: string;
71
78
  }
@@ -85,3 +92,4 @@ export interface ConversationView {
85
92
  messages: PublicMessage[];
86
93
  tasks: TaskCard[];
87
94
  }
95
+ export {};
package/dist/core.d.ts CHANGED
@@ -1,21 +1,25 @@
1
- import type { ConversationView, OrchestratorConfig, RegistryPort, SessionRunner, TraceEntry, TurnSpec } from './contracts.js';
1
+ import type { ConversationView, HostModelConfig, ModelConfig, OrchestratorConfig, RegistryPort, SessionRunner, TraceEntry, TurnSpec } from './contracts.js';
2
2
  export type * from './contracts.js';
3
3
  export declare class PrismError extends Error {
4
- readonly code: 'INVALID_INPUT' | 'NOT_FOUND';
5
- constructor(code: 'INVALID_INPUT' | 'NOT_FOUND', message: string);
4
+ readonly code: 'INVALID_INPUT' | 'NOT_FOUND' | 'NO_PROJECT';
5
+ constructor(code: 'INVALID_INPUT' | 'NOT_FOUND' | 'NO_PROJECT', message: string);
6
6
  }
7
7
  export declare class Orchestrator {
8
8
  private readonly registry;
9
9
  private readonly runner;
10
10
  private readonly store;
11
11
  private readonly config;
12
+ private readonly readHostModel?;
12
13
  private readonly active;
13
14
  private readonly watchers;
14
15
  private stopping;
15
- constructor(config: OrchestratorConfig, registry: RegistryPort, runner: SessionRunner, stateDirectory: string);
16
+ constructor(config: OrchestratorConfig | HostModelConfig, registry: RegistryPort, runner: SessionRunner, stateDirectory: string, hostModel?: () => ModelConfig);
17
+ private currentConfig;
16
18
  start(): Promise<void>;
17
19
  private defaultModel;
20
+ private newRoot;
18
21
  private newConversation;
22
+ private refreshRoot;
19
23
  private change;
20
24
  private snapshot;
21
25
  view(owner: string): Promise<ConversationView>;
@@ -31,6 +35,9 @@ export declare class Orchestrator {
31
35
  private wake;
32
36
  private consume;
33
37
  private settle;
38
+ private finishReplies;
39
+ private finalizationText;
40
+ private settleTask;
34
41
  private invoke;
35
42
  private dispatch;
36
43
  /** Wait for all in-process work, including events enqueued by completing agents. */
package/dist/core.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { messages } from './messages.js';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { modelFor, nativeExecutionTools, systemPrompt, toolSets, validateConfig } from './policy.js';
3
+ import { modelFor, nativeExecutionTools, resolveBinding, systemPrompt, toolSets, validateConfig } from './policy.js';
4
4
  import { ConversationStore, enqueue } from './store.js';
5
5
  export class PrismError extends Error {
6
6
  code;
@@ -25,10 +25,10 @@ function narrow(ceiling, requested) {
25
25
  function binding(state, id) {
26
26
  if (state.root.id === id)
27
27
  return state.root;
28
- const task = state.tasks.find(task => task.id === id);
29
- if (!task)
28
+ const actor = state.tasks.find(task => task.id === id) ?? state.previousRoots?.find(root => root.id === id);
29
+ if (!actor)
30
30
  throw new PrismError('NOT_FOUND', '找不到会话');
31
- return task;
31
+ return actor;
32
32
  }
33
33
  function publicCatalog(models) {
34
34
  return models.map(({ id, description }) => ({ id, description }));
@@ -40,16 +40,31 @@ export class Orchestrator {
40
40
  runner;
41
41
  store;
42
42
  config;
43
+ readHostModel;
43
44
  active = new Map();
44
45
  watchers = new Map();
45
46
  stopping = false;
46
- constructor(config, registry, runner, stateDirectory) {
47
+ constructor(config, registry, runner, stateDirectory, hostModel) {
47
48
  this.registry = registry;
48
49
  this.runner = runner;
49
- validateConfig(config);
50
50
  this.config = structuredClone(config);
51
+ if (config.useHostModel) {
52
+ if (!hostModel)
53
+ throw new Error('DSH default model selection is unavailable');
54
+ this.readHostModel = hostModel;
55
+ }
56
+ validateConfig(this.currentConfig());
51
57
  this.store = new ConversationStore(stateDirectory);
52
58
  }
59
+ currentConfig() {
60
+ if (!this.config.useHostModel)
61
+ return this.config;
62
+ const model = this.readHostModel();
63
+ return {
64
+ defaultProjectId: this.config.defaultProjectId, executionTools: this.config.executionTools,
65
+ models: { L1: [model], L2: [model], L3: [model] },
66
+ };
67
+ }
53
68
  async start() {
54
69
  for (const owner of this.store.owners()) {
55
70
  this.change(owner, state => {
@@ -58,29 +73,56 @@ export class Orchestrator {
58
73
  if (job.worker && !this.store.workerAlive(job.worker))
59
74
  this.settle(state, job, false);
60
75
  }
61
- if (!this.config.models.L1.some(model => model.id === state.root.modelId)) {
76
+ if (!this.currentConfig().models.L1.some(model => model.id === state.root.modelId)) {
62
77
  state.root.modelId = this.defaultModel();
63
78
  }
64
79
  });
65
80
  this.wake(owner);
66
81
  }
67
82
  }
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);
83
+ defaultModel() {
84
+ const config = this.currentConfig();
85
+ return config.defaultL1Model ?? config.models.L1[0].id;
86
+ }
87
+ newRoot(owner, projectId) {
88
+ if (projectId === undefined)
89
+ throw new PrismError('NO_PROJECT', 'No authorized Prism project is available');
90
+ const project = this.registry.resolve(owner, projectId);
71
91
  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: [],
92
+ id: randomUUID(), layer: 'L1', modelId: this.defaultModel(), ceiling: [],
93
+ target: { projectId: project.id, nodeId: project.nodeId, cwd: project.workspace },
74
94
  };
75
95
  }
96
+ newConversation(owner) {
97
+ const projectId = this.config.defaultProjectId ?? this.registry.query(owner)[0]?.id;
98
+ return { root: this.newRoot(owner, projectId), messages: [], tasks: [], requests: [], queue: [] };
99
+ }
100
+ refreshRoot(owner, state) {
101
+ if (this.config.defaultProjectId !== undefined)
102
+ return;
103
+ const available = this.registry.query(owner);
104
+ const target = state.root.target;
105
+ if (available.some(project => project.id === target.projectId)) {
106
+ const project = this.registry.resolve(owner, target.projectId);
107
+ if (project.nodeId === target.nodeId && project.workspace === target.cwd)
108
+ return;
109
+ }
110
+ const next = this.newRoot(owner, available[0]?.id);
111
+ // Existing jobs, agent sessions and child notifications retain the original
112
+ // binding ID and its authorization checks, even across a host restart.
113
+ const previous = state.previousRoots ??= [];
114
+ previous.push(state.root);
115
+ state.root = next;
116
+ }
76
117
  change(owner, fn) {
77
118
  textField(owner, 2048);
78
119
  return this.store.change(owner, () => this.newConversation(owner), fn);
79
120
  }
80
121
  snapshot(state) {
122
+ const models = this.currentConfig().models.L1;
81
123
  return {
82
- modelId: state.root.modelId,
83
- models: publicCatalog(this.config.models.L1),
124
+ modelId: this.config.useHostModel ? models[0].id : state.root.modelId,
125
+ models: publicCatalog(models),
84
126
  messages: state.messages,
85
127
  tasks: state.tasks.map(task => ({
86
128
  id: task.id, title: task.layer === 'L3' ? '执行步骤' : task.title,
@@ -102,11 +144,21 @@ export class Orchestrator {
102
144
  const result = this.change(owner, state => {
103
145
  if (requestId && state.requests.includes(requestId))
104
146
  return this.snapshot(state);
147
+ this.refreshRoot(owner, state);
105
148
  if (requestId)
106
149
  state.requests.push(requestId);
107
150
  const messageId = randomUUID();
108
151
  state.messages.push({ id: messageId, role: 'user', delivery: 'pending', text, at: now() });
109
- enqueue(state, state.root, JSON.stringify({ kind: 'user', text }), messageId);
152
+ if (this.readHostModel) {
153
+ state.root.hostModel = this.readHostModel();
154
+ state.root.modelId = state.root.hostModel.id;
155
+ }
156
+ const originId = this.config.useHostModel ? messageId : undefined;
157
+ if (originId) {
158
+ const awaiting = state.awaitingReplies ??= {};
159
+ awaiting[originId] = { rootId: state.root.id, plannerIds: [] };
160
+ }
161
+ enqueue(state, state.root, JSON.stringify({ kind: 'user', text }), messageId, originId);
110
162
  return this.snapshot(state);
111
163
  });
112
164
  this.publish(owner);
@@ -114,7 +166,7 @@ export class Orchestrator {
114
166
  return result;
115
167
  }
116
168
  async selectModel(owner, modelId) {
117
- if (!this.config.models.L1.some(model => model.id === modelId))
169
+ if (!this.currentConfig().models.L1.some(model => model.id === modelId))
118
170
  throw new PrismError('INVALID_INPUT', '此交互模型不可用');
119
171
  const view = this.change(owner, state => { state.root.modelId = modelId; return this.snapshot(state); });
120
172
  this.publish(owner);
@@ -159,7 +211,7 @@ export class Orchestrator {
159
211
  if (!['L1', 'L2', 'L3'].includes(spec.layer))
160
212
  throw new Error('未知代理层级');
161
213
  if (spec.layer === 'L1') {
162
- if (spec.parentBindingId !== undefined || spec.workspace.projectId !== this.config.defaultProjectId)
214
+ if (spec.parentBindingId !== undefined || (this.config.defaultProjectId !== undefined && spec.workspace.projectId !== this.config.defaultProjectId))
163
215
  throw new Error('交互会话必须绑定默认项目');
164
216
  }
165
217
  else {
@@ -168,7 +220,7 @@ export class Orchestrator {
168
220
  const project = this.registry.resolve(spec.owner, spec.workspace.projectId);
169
221
  if (project.nodeId !== spec.workspace.nodeId)
170
222
  throw new Error('项目节点不匹配');
171
- const model = modelFor(this.config, spec.layer, spec.model.id);
223
+ const model = modelFor(this.currentConfig(), spec.layer, spec.model.id);
172
224
  if (!Array.isArray(spec.allowedTools))
173
225
  throw new Error('缺少权限声明');
174
226
  const allowedTools = narrow(spec.layer === 'L3' ? this.ceiling(project) : [], spec.allowedTools);
@@ -179,13 +231,11 @@ export class Orchestrator {
179
231
  workspace: { projectId: project.id, nodeId: project.nodeId, cwd: project.workspace },
180
232
  };
181
233
  }
182
- spec(owner, actor, modelId, parentBindingId) {
183
- if (actor.layer === 'L1' && actor.target.projectId !== this.config.defaultProjectId)
234
+ spec(owner, actor, modelId, parentBindingId, hostModel = actor.hostModel) {
235
+ if (actor.layer === 'L1' && this.config.defaultProjectId !== undefined && actor.target.projectId !== this.config.defaultProjectId)
184
236
  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);
237
+ const project = resolveBinding(this.registry, owner, actor.target);
238
+ const model = this.readHostModel ? hostModel ?? this.readHostModel() : modelFor(this.currentConfig(), actor.layer, modelId);
189
239
  const currentCeiling = this.ceiling(project).filter(tool => actor.ceiling.includes(tool));
190
240
  return {
191
241
  owner, bindingId: actor.id, parentBindingId, layer: actor.layer, model: { ...model }, workspace: { ...actor.target },
@@ -220,7 +270,7 @@ export class Orchestrator {
220
270
  task.status = 'running';
221
271
  task.at = now();
222
272
  }
223
- return { job, actor: task ?? state.root, parent: task?.parent };
273
+ return { job, actor: binding(state, id), parent: task?.parent };
224
274
  });
225
275
  if (!claimed)
226
276
  return;
@@ -228,21 +278,29 @@ export class Orchestrator {
228
278
  const { actor, job, parent } = claimed;
229
279
  let succeeded = false;
230
280
  try {
231
- const spec = this.spec(owner, actor, job.modelId, parent);
281
+ const spec = this.spec(owner, actor, job.modelId, parent, job.hostModel);
232
282
  const tools = {
233
- definitions: structuredClone(toolSets[actor.layer]),
283
+ definitions: structuredClone(job.deliveryOnly ? toolSets.L1.filter(tool => tool.name === 'send_user') : toolSets[actor.layer]),
234
284
  invoke: async (name, args) => {
235
285
  const result = this.change(owner, state => {
236
286
  if (!state.queue.some(item => item.id === job.id && item.worker === this.store.workerId))
237
287
  throw new Error('本轮工具权限已失效');
238
- return this.invoke(owner, state, actor.id, name, args);
288
+ if (job.deliveryOnly) {
289
+ if (name !== 'send_user')
290
+ throw new Error('This delivery turn can only call send_user');
291
+ const reply = job.originId && state.awaitingReplies?.[job.originId];
292
+ if (!reply || reply.delivered)
293
+ return { sent: true };
294
+ }
295
+ return this.invoke(owner, state, actor.id, name, args, job.originId);
239
296
  });
240
297
  this.publish(owner);
241
298
  this.wake(owner);
242
299
  return result;
243
300
  },
244
301
  };
245
- await this.runner.run(spec, job.text, tools);
302
+ const input = job.deliveryOnly ? this.finalizationText(owner, job) : job.text;
303
+ await this.runner.run(spec, input, tools);
246
304
  succeeded = true;
247
305
  }
248
306
  catch (error) {
@@ -259,8 +317,60 @@ export class Orchestrator {
259
317
  if (message)
260
318
  message.delivery = ok ? 'processed' : 'failed';
261
319
  const task = state.tasks.find(item => item.id === job.bindingId);
262
- if (!task)
263
- return;
320
+ if (task)
321
+ this.settleTask(state, task, ok, job.originId);
322
+ if (job.deliveryOnly && job.originId && state.awaitingReplies?.[job.originId]) {
323
+ const original = state.messages.find(item => item.id === job.originId);
324
+ if (original && !state.awaitingReplies[job.originId].delivered) {
325
+ original.delivery = 'failed';
326
+ original.deliveryError = 'no_response';
327
+ }
328
+ delete state.awaitingReplies[job.originId];
329
+ }
330
+ if (state.awaitingReplies)
331
+ this.finishReplies(state);
332
+ }
333
+ finishReplies(state) {
334
+ for (const [originId, reply] of Object.entries(state.awaitingReplies ?? {})) {
335
+ if (state.queue.some(job => job.originId === originId))
336
+ continue;
337
+ const planners = state.tasks.filter(task => reply.plannerIds.includes(task.id));
338
+ if (planners.some(task => !terminal(task)))
339
+ continue;
340
+ if (reply.delivered || !planners.length) {
341
+ delete state.awaitingReplies[originId];
342
+ continue;
343
+ }
344
+ // This single delivery job and the receipt are committed together. A silent
345
+ // final turn fails the original message and consumes the receipt in settle.
346
+ enqueue(state, binding(state, reply.rootId), '{"kind":"finalize_response"}', undefined, originId).deliveryOnly = true;
347
+ }
348
+ }
349
+ finalizationText(owner, job) {
350
+ const state = this.store.read(owner);
351
+ const reply = job.originId && state?.awaitingReplies?.[job.originId];
352
+ const original = state?.messages.find(message => message.id === job.originId);
353
+ if (!state || !reply || !original)
354
+ throw new Error('Missing pending delivery request');
355
+ const tasks = state.tasks.filter(task => reply.plannerIds.includes(task.id)).flatMap(task => {
356
+ // A grant may have changed between task completion and this last turn.
357
+ // Reintroduce evidence only for a workspace that is still authorized.
358
+ try {
359
+ resolveBinding(this.registry, owner, task.target);
360
+ }
361
+ catch {
362
+ return [];
363
+ }
364
+ return [{ id: task.id, projectId: task.target.projectId, title: task.title, status: task.status,
365
+ result: task.finalReport ?? task.progress }];
366
+ });
367
+ return JSON.stringify({
368
+ kind: 'finalize_response',
369
+ instruction: 'The delegated work has finished. Its final answer has not been delivered to the user. Call the send_user tool now, using the language and format of the specific user request below. Ordinary text is private and never delivered. Use these task results as evidence, sharing only the requested facts. If evidence is missing, explicitly send that limitation.',
370
+ userRequest: original.text, tasks,
371
+ });
372
+ }
373
+ settleTask(state, task, ok, originId) {
264
374
  const children = state.tasks.filter(child => child.parent === task.id);
265
375
  if (!ok)
266
376
  task.turnFailed = true;
@@ -269,10 +379,14 @@ export class Orchestrator {
269
379
  task.status = !task.turnFailed && children.every(child => child.status === 'completed') ? 'completed' : 'failed';
270
380
  task.at = now();
271
381
  const parent = binding(state, task.parent);
272
- enqueue(state, parent, JSON.stringify({ kind: 'task_settled', taskId: task.id, status: task.status, progress: task.progress }));
382
+ enqueue(state, parent, JSON.stringify({
383
+ kind: 'task_settled', taskId: task.id, title: task.title, projectId: task.target.projectId,
384
+ status: task.status, progress: task.progress, result: task.finalReport,
385
+ }), undefined, originId);
273
386
  }
274
- invoke(owner, state, id, name, raw) {
387
+ invoke(owner, state, id, name, raw, originId) {
275
388
  const actor = binding(state, id);
389
+ resolveBinding(this.registry, owner, actor.target);
276
390
  const definition = toolSets[actor.layer].find(tool => tool.name === name);
277
391
  if (!definition || !raw || typeof raw !== 'object' || Array.isArray(raw))
278
392
  throw new Error('该层无权调用此工具,或参数格式无效');
@@ -285,6 +399,9 @@ export class Orchestrator {
285
399
  switch (name) {
286
400
  case 'send_user': {
287
401
  state.messages.push({ id: randomUUID(), role: 'assistant', text: textField(args.text), at: now() });
402
+ const reply = originId && state.awaitingReplies?.[originId];
403
+ if (reply)
404
+ reply.delivered = !state.tasks.some(task => reply.plannerIds.includes(task.id) && !terminal(task));
288
405
  return { sent: true };
289
406
  }
290
407
  case 'query_projects': {
@@ -293,9 +410,9 @@ export class Orchestrator {
293
410
  id, description, stack, nodeId, permissions, ...(gitRemote === undefined ? {} : { gitRemote }),
294
411
  }));
295
412
  }
296
- case 'list_models': return publicCatalog(this.config.models[actor.layer === 'L1' ? 'L2' : 'L3']);
413
+ case 'list_models': return publicCatalog(this.currentConfig().models[actor.layer === 'L1' ? 'L2' : 'L3']);
297
414
  case 'dispatch_planner':
298
- case 'dispatch_executor': return this.dispatch(owner, state, actor, args);
415
+ case 'dispatch_executor': return this.dispatch(owner, state, actor, args, originId);
299
416
  case 'report_progress': {
300
417
  const task = state.tasks.find(task => task.id === id);
301
418
  task.progress = textField(args.text);
@@ -304,7 +421,17 @@ export class Orchestrator {
304
421
  }
305
422
  case 'send_parent': {
306
423
  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) }));
424
+ const text = textField(args.text);
425
+ if (args.final !== undefined && typeof args.final !== 'boolean')
426
+ throw new PrismError('INVALID_INPUT', 'final 必须为布尔值');
427
+ if (args.final) {
428
+ if (state.tasks.some(child => child.parent === id && !terminal(child))) {
429
+ throw new PrismError('INVALID_INPUT', '等待仍在运行的子任务完成后提交最终结果');
430
+ }
431
+ task.finalReport = text;
432
+ return { recorded: true, delivery: 'task_settled' };
433
+ }
434
+ enqueue(state, binding(state, task.parent), JSON.stringify({ kind: 'child_message', taskId: task.id, text }), undefined, originId);
308
435
  return { sent: true };
309
436
  }
310
437
  case 'get_progress':
@@ -314,22 +441,32 @@ export class Orchestrator {
314
441
  throw new PrismError('NOT_FOUND', '找不到直接子任务');
315
442
  if (name === 'get_progress') {
316
443
  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 };
444
+ return {
445
+ id: child.id, status: child.status, progress: child.progress, children,
446
+ ...(child.finalReport === undefined ? {} : { result: child.finalReport }),
447
+ };
318
448
  }
319
449
  if (terminal(child)) {
320
450
  child.status = 'queued';
321
451
  child.turnFailed = false;
322
452
  child.at = now();
323
453
  }
324
- enqueue(state, child, JSON.stringify({ kind: 'parent_message', text: textField(args.text) }));
454
+ delete child.finalReport;
455
+ const reply = originId && state.awaitingReplies?.[originId];
456
+ if (reply && actor.layer === 'L1') {
457
+ reply.delivered = false;
458
+ if (!reply.plannerIds.includes(child.id))
459
+ reply.plannerIds.push(child.id);
460
+ }
461
+ enqueue(state, child, JSON.stringify({ kind: 'parent_message', text: textField(args.text) }), undefined, originId);
325
462
  return { sent: true };
326
463
  }
327
464
  default: throw new Error('未知工具');
328
465
  }
329
466
  }
330
- dispatch(owner, state, actor, args) {
467
+ dispatch(owner, state, actor, args, originId) {
331
468
  const layer = actor.layer === 'L1' ? 'L2' : 'L3';
332
- const model = modelFor(this.config, layer, textField(args.modelId, 256));
469
+ const model = modelFor(this.currentConfig(), layer, textField(args.modelId, 256));
333
470
  const projectId = layer === 'L2' ? textField(args.projectId, 1024) : actor.target.projectId;
334
471
  const project = this.registry.resolve(owner, projectId);
335
472
  const target = layer === 'L2' ? { projectId, nodeId: project.nodeId, cwd: project.workspace } : { ...actor.target };
@@ -338,10 +475,16 @@ export class Orchestrator {
338
475
  const ceiling = this.ceiling(project).filter(name => layer === 'L2' || actor.ceiling.includes(name));
339
476
  const task = {
340
477
  id: randomUUID(), layer, target, modelId: model.id, ceiling: narrow(ceiling, args.permissions),
478
+ ...(this.config.useHostModel && { hostModel: model }),
341
479
  parent: actor.id, title: textField(args.title, 240), progress: '', at: now(), status: 'queued',
342
480
  };
343
481
  state.tasks.push(task);
344
- enqueue(state, task, JSON.stringify({ kind: 'assignment', text: textField(args.instruction), projectId, permissions: task.ceiling }));
482
+ const reply = originId && state.awaitingReplies?.[originId];
483
+ if (reply && layer === 'L2') {
484
+ reply.delivered = false;
485
+ reply.plannerIds.push(task.id);
486
+ }
487
+ enqueue(state, task, JSON.stringify({ kind: 'assignment', text: textField(args.instruction), projectId, permissions: task.ceiling }), undefined, originId);
345
488
  return { taskId: task.id };
346
489
  }
347
490
  /** Wait for all in-process work, including events enqueued by completing agents. */
package/dist/host.d.ts CHANGED
@@ -1,14 +1,15 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import type { Agent } from '@deepseek-ai/dsh-agent';
3
- import type { AgentTools, SessionRunner, TraceEntry, TurnSpec } from './contracts.js';
3
+ import type { AgentTools, RegistryPort, SessionRunner, TraceEntry, TurnSpec } from './contracts.js';
4
4
  export declare class DshSessionRunner implements SessionRunner {
5
5
  private readonly ctx;
6
+ private readonly registry?;
6
7
  private readonly bindings;
7
8
  private readonly turns;
8
9
  private readonly live;
9
10
  private readonly shutdown;
10
11
  private closing?;
11
- constructor(ctx: Context, stateDirectory: string);
12
+ constructor(ctx: Context, stateDirectory: string, registry?: RegistryPort | undefined);
12
13
  activeAgent(bindingId: string): Agent | undefined;
13
14
  run(spec: TurnSpec, text: string, tools: AgentTools, signal?: AbortSignal, onReady?: (id: string) => void): Promise<void>;
14
15
  transcript(spec: TurnSpec): Promise<TraceEntry[]>;
package/dist/host.js CHANGED
@@ -56,6 +56,7 @@ import { buildForkSeed, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-ses
56
56
  import { SessionAlreadyOwnedError } from '@deepseek-ai/dsh-session-persistence';
57
57
  import { NativeToolExecutor } from '@deepseek-ai/dsh-tool-executor-native';
58
58
  import { SessionBindings } from './host-bindings.js';
59
+ import { resolveBinding } from './policy.js';
59
60
  function trace(events) {
60
61
  const entries = [];
61
62
  for (const event of events) {
@@ -73,13 +74,15 @@ function trace(events) {
73
74
  }
74
75
  export class DshSessionRunner {
75
76
  ctx;
77
+ registry;
76
78
  bindings;
77
79
  turns = new Map();
78
80
  live = new Map();
79
81
  shutdown = new AbortController();
80
82
  closing;
81
- constructor(ctx, stateDirectory) {
83
+ constructor(ctx, stateDirectory, registry) {
82
84
  this.ctx = ctx;
85
+ this.registry = registry;
83
86
  this.bindings = new SessionBindings(stateDirectory);
84
87
  }
85
88
  activeAgent(bindingId) { return this.live.get(bindingId); }
@@ -133,6 +136,16 @@ export class DshSessionRunner {
133
136
  return 'Tool exceeds this session’s permission ceiling';
134
137
  if (this.bindings.current(spec) !== agent.session.id)
135
138
  return 'Session binding has moved';
139
+ if (this.registry) {
140
+ try {
141
+ const project = resolveBinding(this.registry, spec.owner, spec.workspace);
142
+ if (native.includes(exec.name) && !project.permissions.includes(exec.name))
143
+ return 'Project tool permission was revoked';
144
+ }
145
+ catch {
146
+ return 'Project access was revoked or the workspace moved';
147
+ }
148
+ }
136
149
  });
137
150
  if (spec.layer !== 'L3') {
138
151
  // DSH marks its global cwd reminder required. Shadow that specific registration
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
- import type { OrchestratorConfig } from './contracts.js';
2
+ import type { HostModelConfig, OrchestratorConfig } from './contracts.js';
3
3
  import { Orchestrator } from './core.js';
4
4
  export * from './core.js';
5
5
  export * from './contracts.js';
@@ -7,9 +7,9 @@ export * from './provider.js';
7
7
  export { DshSessionRunner } from './host.js';
8
8
  export declare const name = "dsh-orchestrator";
9
9
  export declare const inject: string[];
10
- export interface Config extends OrchestratorConfig {
10
+ export type Config = (OrchestratorConfig | HostModelConfig) & {
11
11
  stateDirectory?: string;
12
- }
12
+ };
13
13
  declare module '@deepseek-ai/cordis' {
14
14
  interface Context {
15
15
  prism: Orchestrator;
package/dist/index.js CHANGED
@@ -13,13 +13,16 @@ export const inject = ['prismRegistry', 'dshMesh', 'subagents', 'agents', 'agent
13
13
  export async function apply(ctx, config) {
14
14
  const mesh = ctx.get('dshMesh', true);
15
15
  const directory = config.stateDirectory ?? dshPath('data', 'prism');
16
- const local = new DshSessionRunner(ctx, directory);
16
+ const local = new DshSessionRunner(ctx, directory, ctx.prismRegistry);
17
17
  for (const id of [mesh.nodeId, ...mesh.nodeIds]) {
18
18
  const provider = new PrismProvider(id, id === mesh.nodeId ? local : mesh.runnerFor(id));
19
19
  ctx.subagents.registerProvider(provider);
20
20
  }
21
21
  const router = new ProviderRouter(ctx.subagents);
22
- const core = new Orchestrator(config, ctx.prismRegistry, router, directory);
22
+ const core = new Orchestrator(config, ctx.prismRegistry, router, directory, () => {
23
+ const { provider, model } = ctx.agentDefaultModel.currentSelection();
24
+ return { id: model, provider, description: provider };
25
+ });
23
26
  const detach = mesh.attach({ runner: local, authorize: spec => core.authorizeRemote(spec), definitionsFor: layer => toolSets[layer] });
24
27
  const close = async () => {
25
28
  router.close();
package/dist/policy.d.ts CHANGED
@@ -1,5 +1,9 @@
1
- import type { Layer, ModelConfig, OrchestratorConfig, ToolDefinition } from './contracts.js';
1
+ import type { Layer, ModelConfig, OrchestratorConfig, RegistryPort, ToolDefinition, WorkspaceTarget } from './contracts.js';
2
2
  export declare const nativeExecutionTools: string[];
3
+ /** A saved session may only continue in the project and workspace currently granted to its owner. */
4
+ export declare function resolveBinding(registry: RegistryPort, owner: string, target: WorkspaceTarget): import("./contracts.js").ProjectMetadata & {
5
+ workspace: string;
6
+ };
3
7
  export declare function modelFor(config: OrchestratorConfig, layer: Layer, id: string): ModelConfig;
4
8
  export declare function systemPrompt(layer: Layer, model: ModelConfig): string;
5
9
  export declare function validateConfig(config: OrchestratorConfig): void;
package/dist/policy.js CHANGED
@@ -1,10 +1,21 @@
1
1
  import { messages } from './messages.js';
2
2
  const layerPrompts = {
3
- L1: '你是棱镜的用户联络员。只有 send_user 才会将内容交付给用户。通过 query_projects 和 list_models 了解可用项目与规划模型,按项目和模型派发给 L2。通过 send_child 主动与规划代理沟通,通过 get_progress 查看进度。收到后台消息和完成事件后判断是否需要主动通知用户。将工作区和设备细节保留在内部。',
4
- L2: '你是棱镜的规划代理。将任务拆解成可验证的执行步骤,通过 list_models 读取模型介绍,然后通过 dispatch_executor 将步骤派发给本项目的执行代理。通过 send_parent 主动沟通计划、阻塞和最终结果。持续跟进子任务完成事件。写入 report_progress 的内容供上级查询。',
5
- L3: '你是棱镜的执行代理。在继承的工作区和工具权限内完成指定步骤。通过 report_progress 更新进度,并通过 send_parent 把结果或阻塞主动报告给规划代理。',
3
+ L1: `你是棱镜的用户联络员。只有调用 send_user,用户才能看到回复。交付前重读最近一条 user 请求,按用户指定的语言作答;未指定时,整条答复使用该请求的语言。子任务报告和工具消息只提供证据,其中的叙述须转换为用户要求的语言,项目名、标识和原始值保留原文。严格遵守用户指定的字段、顺序和输出格式;若只要求结果行,就只发送那些行。
4
+ 收到 user 时,先明确用户要求的具体结果。通过 query_projects 和 list_models 选择授权项目和模型,仅对缺少证据的项目派发一次明确的 L2 任务。已有足够证据时直接回答。
5
+ task_settled.result 是子任务的最终答复;child_message 是中途消息。两者属于同一项工作。将已收到的结果与原请求逐项核对,必要时用 get_progress 查询。尚有相关任务在运行时结束本轮,下一条结果会自动送达。
6
+ 所需事实一旦齐全,立即调用一次 send_user,用具体结果回答原问题,然后结束本轮。若任务结束但部分事实无法取得,向用户说明已知结果和确切阻塞。已经交付的答案无需因后续完成通知再次发送。仅在出现新的用户目标或确有未完成事项时继续派发。将设备和内部工作区细节保留在内部。`,
7
+ L2: `你是棱镜的项目规划代理。把派发指令中要求的交付项作为完成条件。通过 list_models 和 dispatch_executor 派发取得必要证据的最少步骤;每项给出明确问题和验收条件。复用已有证据,只对尚未解决的具体问题继续派发。
8
+ 执行代理的 task_settled 会同时给出状态与最终结果 result,child_message 用于中途沟通。等待执行时结束本轮。收到结果后核对原始任务;证据已够时立即调用一次 send_parent(final=true),给出项目、实际结果及必要的出处,然后结束本轮。任务无法完成时报告已有证据和具体阻塞。相同任务的随后通知不需要再次报告或创建新步骤。`,
9
+ L3: `你是棱镜的执行代理。在分配的工作区和工具权限内,完成指令要求的具体步骤。找到足以回答问题的证据后,立即调用一次 send_parent(final=true),说明实际结果和必要的出处,然后结束本轮。若无法完成,报告已查到的事实和具体阻塞。长任务有实质进展时可用 report_progress 留存状态。无需为已完成的步骤继续探索无关细节。`,
6
10
  };
7
11
  export const nativeExecutionTools = ['read', 'read_image', 'glob', 'grep', 'write', 'edit', 'apply_patch', 'bash'];
12
+ /** A saved session may only continue in the project and workspace currently granted to its owner. */
13
+ export function resolveBinding(registry, owner, target) {
14
+ const project = registry.resolve(owner, target.projectId);
15
+ if (project.nodeId !== target.nodeId || project.workspace !== target.cwd)
16
+ throw new Error('会话绑定的工作区已变更');
17
+ return project;
18
+ }
8
19
  export function modelFor(config, layer, id) {
9
20
  const entry = config.models[layer]?.find(model => model.id === id);
10
21
  if (!entry)
@@ -17,7 +28,7 @@ export function systemPrompt(layer, model) {
17
28
  return [layerPrompts[layer], model.prompt].filter(Boolean).join('\n\n');
18
29
  }
19
30
  export function validateConfig(config) {
20
- if (!config.defaultProjectId?.trim())
31
+ if (config.defaultProjectId !== undefined && !config.defaultProjectId?.trim())
21
32
  throw new Error(messages.defaultProject);
22
33
  for (const layer of ['L1', 'L2', 'L3']) {
23
34
  const models = config.models?.[layer];
@@ -51,21 +62,21 @@ function tool(name, description, properties, required = Object.keys(properties))
51
62
  return { name, description, parameters: { type: 'object', properties, required, additionalProperties: false } };
52
63
  }
53
64
  const models = tool('list_models', '查看下一级可选模型的 ID 和能力介绍。', {});
54
- const progress = tool('get_progress', '查看本次派发的直接子任务的状态、进展和执行步骤。', { taskId: string });
55
- const childMessage = tool('send_child', '主动向自己的一个直接子任务发信。', { taskId: string, text: string });
56
- const parentMessage = tool('send_parent', '主动发信给派发此任务的上级。', { text: string });
57
- const report = tool('report_progress', '记录供上级查询的任务进度。', { text: string });
65
+ const progress = tool('get_progress', '查看指定子任务已记录的状态、进展和执行步骤;子任务的新消息会自动送达。', { taskId: string });
66
+ const childMessage = tool('send_child', '向已有的直接子任务补充具体指令。这会再次唤醒该任务,只在确有待处理问题时调用。', { taskId: string, text: string });
67
+ const parentMessage = tool('send_parent', '交付最终结果和证据时传 final=true,结果会与完成状态一起送达上级,然后结束本轮。只在工作尚未完成、确需上级立即参与时发送中途消息。', { text: string, final: { type: 'boolean' } }, ['text']);
68
+ const report = tool('report_progress', '保存进度供上级查询。最终结果通过 send_parent 交付。', { text: string });
58
69
  export const toolSets = {
59
70
  L1: [
60
- tool('send_user', '向当前会话用户发送一条可见消息。', { text: string }),
71
+ tool('send_user', '按最近 user 请求的语言和格式发送完整答复。结果齐备时调用一次,然后结束本轮。', { text: string }),
61
72
  tool('query_projects', '查询授权项目的元数据。', { search: { type: 'string' } }, []),
62
73
  models,
63
- tool('dispatch_planner', '选择项目、规划模型和可选的后代工具权限,创建 L2 任务。', { projectId: string, modelId: string, title: string, instruction: string, permissions: toolNames }, ['projectId', 'modelId', 'title', 'instruction']),
74
+ tool('dispatch_planner', '在授权项目中创建 L2 任务。指令应写明原请求尚缺的交付项;同一目标已有任务时复用其结果。', { projectId: string, modelId: string, title: string, instruction: string, permissions: toolNames }, ['projectId', 'modelId', 'title', 'instruction']),
64
75
  progress, childMessage,
65
76
  ],
66
77
  L2: [
67
78
  models,
68
- tool('dispatch_executor', '在当前项目中选择执行模型和可选的工具权限,创建 L3 步骤。', { modelId: string, title: string, instruction: string, permissions: toolNames }, ['modelId', 'title', 'instruction']),
79
+ tool('dispatch_executor', '为当前项目尚未解决的具体交付项创建 L3 步骤。说明要返回的结果,已有证据能回答时直接向上级交付。', { modelId: string, title: string, instruction: string, permissions: toolNames }, ['modelId', 'title', 'instruction']),
69
80
  progress, childMessage, parentMessage, report,
70
81
  ],
71
82
  L3: [parentMessage, report],
package/dist/store.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import type { Layer, PublicMessage, TaskCard, WorkspaceTarget } from './contracts.js';
1
+ import type { Layer, ModelConfig, PublicMessage, TaskCard, WorkspaceTarget } from './contracts.js';
2
2
  export interface Binding {
3
3
  id: string;
4
4
  layer: Layer;
5
5
  modelId: string;
6
+ hostModel?: ModelConfig;
6
7
  target: WorkspaceTarget;
7
8
  ceiling: string[];
8
9
  }
@@ -12,24 +13,34 @@ export interface Task extends Binding {
12
13
  status: TaskCard['status'];
13
14
  at: string;
14
15
  progress: string;
16
+ finalReport?: string;
15
17
  turnFailed?: boolean;
16
18
  }
17
19
  export interface Job {
18
20
  id: string;
19
21
  bindingId: string;
20
22
  modelId: string;
23
+ hostModel?: ModelConfig;
21
24
  text: string;
22
25
  worker?: string | number;
23
26
  messageId?: string;
27
+ originId?: string;
28
+ deliveryOnly?: boolean;
24
29
  }
25
30
  export interface Conversation {
26
31
  root: Binding;
32
+ previousRoots?: Binding[];
33
+ awaitingReplies?: Record<string, {
34
+ rootId: string;
35
+ plannerIds: string[];
36
+ delivered?: boolean;
37
+ }>;
27
38
  tasks: Task[];
28
39
  messages: PublicMessage[];
29
40
  requests: string[];
30
41
  queue: Job[];
31
42
  }
32
- export declare function enqueue(state: Conversation, target: Binding, text: string, messageId?: string): void;
43
+ export declare function enqueue(state: Conversation, target: Binding, text: string, messageId?: string, originId?: string): Job;
33
44
  export declare class ConversationStore {
34
45
  private db;
35
46
  readonly workerId: `${string}-${string}-${string}-${string}-${string}`;
package/dist/store.js CHANGED
@@ -2,8 +2,10 @@ import { randomUUID } from 'node:crypto';
2
2
  import { chmodSync, existsSync, mkdirSync, rmSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { DatabaseSync } from 'node:sqlite';
5
- export function enqueue(state, target, text, messageId) {
6
- state.queue.push({ id: randomUUID(), bindingId: target.id, modelId: target.modelId, text, messageId });
5
+ export function enqueue(state, target, text, messageId, originId) {
6
+ const job = { id: randomUUID(), bindingId: target.id, modelId: target.modelId, hostModel: target.hostModel, text, messageId, originId };
7
+ state.queue.push(job);
8
+ return job;
7
9
  }
8
10
  export class ConversationStore {
9
11
  db;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-prism/dsh-orchestrator",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -30,7 +30,8 @@
30
30
  "import": "./dist/host.js"
31
31
  },
32
32
  "./locale/*.json": "./locale/*.json",
33
- "./package.json": "./package.json"
33
+ "./package.json": "./package.json",
34
+ "./cordis.patch.yml": "./cordis.patch.yml"
34
35
  },
35
36
  "files": [
36
37
  "dist/",
@@ -39,7 +40,8 @@
39
40
  "!dist/*probe.*",
40
41
  "locale/*.json",
41
42
  "icon.svg",
42
- "README.zh_CN.md"
43
+ "README.zh_CN.md",
44
+ "cordis.patch.yml"
43
45
  ],
44
46
  "engines": {
45
47
  "node": ">=24.0.0",
@@ -63,7 +65,11 @@
63
65
  "@deepseek-ai/dsh-workspace": "0.2.3-alpha.2",
64
66
  "@deepseek-ai/dsh-tools": "0.2.3-alpha.2",
65
67
  "@deepseek-ai/dsh-system-prompt": "0.2.3-alpha.2",
66
- "@dsh-prism/dsh-workspace-registry": "0.1.0"
68
+ "@dsh-prism/dsh-workspace-registry": "^0.1.1",
69
+ "@deepseek-ai/dsh-agent-preset": "0.2.3-alpha.2",
70
+ "@deepseek-ai/dsh-tool-fs": "0.2.3-alpha.2",
71
+ "@deepseek-ai/dsh-tool-fs-search": "0.2.3-alpha.2",
72
+ "@deepseek-ai/dsh-tool-bash": "0.2.3-alpha.2"
67
73
  },
68
74
  "scripts": {
69
75
  "build": "tsc -b tsconfig.release.json",
@@ -77,5 +83,10 @@
77
83
  "@deepseek-ai/dsh": "0.2.3-alpha.2",
78
84
  "@types/node": "24.10.1",
79
85
  "typescript": "6.0.3"
86
+ },
87
+ "dsh": {
88
+ "bundle": {
89
+ "patch": "./cordis.patch.yml"
90
+ }
80
91
  }
81
92
  }