@dsh-prism/dsh-mesh-node 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 CHANGED
@@ -1,3 +1,36 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="icon.svg" width="256" height="256" alt="dsh-mesh-node icon">
4
+
5
+ # dsh-mesh-node
6
+
7
+ **Let Prism run a task on the device that has the project, using the same delegation controls as a local task.**
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
+ ## Connect a second device
28
+
29
+ 1. Install Prism on both devices and give each its own `mesh.nodeId` and DSH data directory.
30
+ 2. On the coordinating device, add the worker to `mesh.peers` with its node ID, HTTPS URL and the name of the environment variable holding the link token.
31
+ 3. On the worker, add the coordinator to `mesh.incoming`. Set the same link token on both devices and list the project IDs the coordinator may request.
32
+ 4. In both project registries, identify the project by the same ID and assign it to the worker node. Register the real local directory on the worker. Configure that node’s models and project permissions, then start both hosts.
33
+
34
+ Open the coordinator’s usual chat and ask about the registered project. Its task card and read-only record are available in the same conversation. The technical reference includes matching configuration examples for both nodes.
35
+
36
+ [Prism documentation](https://prism.dsh-plug.in/) · [Technical reference](docs/TECH.md)
@@ -0,0 +1,36 @@
1
+ <div align="center">
2
+
3
+ <img src="icon.svg" width="256" height="256" alt="dsh-mesh-node 图标">
4
+
5
+ # dsh-mesh-node
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
+ 1. 在两台设备上安装棱镜,各自设置 `mesh.nodeId` 并使用独立的 DSH 数据目录。
30
+ 2. 在协调设备的 `mesh.peers` 中登记执行设备的节点 ID、HTTPS 地址和用于保存连接令牌的环境变量名。
31
+ 3. 在执行设备的 `mesh.incoming` 中登记协调设备,列出允许其派发的项目 ID。在两台设备上设置相同的连接令牌。
32
+ 4. 在两端注册表中使用相同的项目 ID,并将项目分配给执行设备。在执行设备上登记真实本地目录,配置该节点的模型和项目权限,然后启动两个宿主。
33
+
34
+ 打开协调设备的日常对话,提出与登记项目有关的请求。任务卡和只读记录会出现在同一对话中。技术参考中附有两端配套的配置示例。
35
+
36
+ [棱镜使用指南](https://prism.dsh-plug.in/zh/) · [技术参考](docs/TECH.md)
@@ -0,0 +1,14 @@
1
+ import type { AgentTools, SessionRunner, TraceEntry, TurnSpec } from '@dsh-prism/dsh-orchestrator/contracts';
2
+ import { type OutboundPeer } from './protocol.js';
3
+ /** Coordinator side. The same logical run and call IDs are reused on transport retries. */
4
+ export declare class MeshRunner implements SessionRunner {
5
+ private readonly from;
6
+ private readonly peer;
7
+ private readonly token;
8
+ private readonly endpoint;
9
+ constructor(from: string, peer: OutboundPeer, token: string);
10
+ private rpc;
11
+ private target;
12
+ run(spec: TurnSpec, text: string, tools: AgentTools, signal?: AbortSignal, onReady?: (sessionId: string) => void): Promise<void>;
13
+ transcript(spec: TurnSpec): Promise<TraceEntry[]>;
14
+ }
package/dist/client.js ADDED
@@ -0,0 +1,114 @@
1
+ import { messages } from './messages.js';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { maxBody, MeshError, peerUrl, record, string, wireTarget } from './protocol.js';
4
+ /** Coordinator side. The same logical run and call IDs are reused on transport retries. */
5
+ export class MeshRunner {
6
+ from;
7
+ peer;
8
+ token;
9
+ endpoint;
10
+ constructor(from, peer, token) {
11
+ this.from = from;
12
+ this.peer = peer;
13
+ this.token = token;
14
+ this.endpoint = peerUrl(peer.url);
15
+ }
16
+ async rpc(payload, signal) {
17
+ const body = JSON.stringify(payload);
18
+ if (Buffer.byteLength(body) > maxBody)
19
+ throw new Error(messages.tooLarge);
20
+ for (let attempt = 0;; attempt++) {
21
+ const deadline = AbortSignal.timeout(25_000);
22
+ try {
23
+ const response = await fetch(this.endpoint, {
24
+ method: 'POST', redirect: 'error', body, signal: signal ? AbortSignal.any([deadline, signal]) : deadline,
25
+ headers: { 'content-type': 'application/json', authorization: 'Bearer ' + this.token, 'x-prism-node': this.from },
26
+ });
27
+ if (!response.ok) {
28
+ await response.body?.cancel();
29
+ throw new MeshError(response.status, 'Mesh node rejected ' + payload.op + ' (' + response.status + ')');
30
+ }
31
+ const reader = response.body.getReader();
32
+ const chunks = [];
33
+ let length = 0;
34
+ while (true) {
35
+ const { value, done } = await reader.read();
36
+ if (done)
37
+ break;
38
+ length += value.byteLength;
39
+ if (length > maxBody) {
40
+ await reader.cancel();
41
+ throw new MeshError(413, 'Mesh response too large');
42
+ }
43
+ chunks.push(value);
44
+ }
45
+ return JSON.parse(Buffer.concat(chunks).toString());
46
+ }
47
+ catch (err) {
48
+ signal?.throwIfAborted();
49
+ if (attempt >= 1 || (err instanceof MeshError && err.status < 500))
50
+ throw err;
51
+ }
52
+ }
53
+ }
54
+ target(spec) {
55
+ if (spec.workspace.nodeId !== this.peer.id)
56
+ throw new Error(messages.destination);
57
+ return wireTarget(spec);
58
+ }
59
+ async run(spec, text, tools, signal, onReady) {
60
+ const target = this.target(spec);
61
+ const runId = randomUUID();
62
+ const allowed = tools.definitions.map(d => d.name);
63
+ let sessionId;
64
+ signal?.throwIfAborted();
65
+ try {
66
+ await this.rpc({ op: 'start', runId, target, text, tools: allowed }, signal);
67
+ while (true) {
68
+ const state = record(await this.rpc({ op: 'poll', runId, sessionId }, signal));
69
+ if (state.sessionId && !sessionId) {
70
+ sessionId = string(state.sessionId);
71
+ onReady?.(sessionId);
72
+ }
73
+ if (state.phase === 'done')
74
+ return;
75
+ if (state.phase !== 'running' || !Array.isArray(state.calls))
76
+ throw new Error(messages.remoteFailed);
77
+ await Promise.all(state.calls.map(async (raw) => {
78
+ const call = record(raw);
79
+ const name = string(call.name);
80
+ const callId = string(call.id);
81
+ let value;
82
+ let success = false;
83
+ try {
84
+ if (!allowed.includes(name))
85
+ throw new Error('Unregistered tool');
86
+ signal?.throwIfAborted();
87
+ value = await tools.invoke(name, call.args);
88
+ success = true;
89
+ }
90
+ catch {
91
+ // The remote model receives a generic error; keep local diagnostics on the coordinator.
92
+ }
93
+ await this.rpc({ op: 'reply', runId, callId, success, value }, signal);
94
+ }));
95
+ }
96
+ }
97
+ catch (err) {
98
+ // This also reaps an admitted turn when the start response was lost.
99
+ await this.rpc({ op: 'cancel', runId }).catch(() => { });
100
+ throw err;
101
+ }
102
+ }
103
+ async transcript(spec) {
104
+ const data = await this.rpc({ op: 'transcript', target: this.target(spec) });
105
+ if (!Array.isArray(data))
106
+ throw new Error('Invalid Mesh transcript');
107
+ return data.map(raw => {
108
+ const row = record(raw);
109
+ if (typeof row.role !== 'string' || typeof row.text !== 'string')
110
+ throw new Error('Invalid transcript entry');
111
+ return { role: row.role, text: row.text, ...(typeof row.at === 'string' ? { at: row.at } : {}) };
112
+ });
113
+ }
114
+ }
@@ -0,0 +1,29 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import { MeshRunner } from './client.js';
4
+ import { type WorkerServices } from './worker.js';
5
+ import { type MeshConfig } from './protocol.js';
6
+ export { MeshRunner } from './client.js';
7
+ export type { MeshConfig } from './protocol.js';
8
+ export type { WorkerServices } from './worker.js';
9
+ export declare const name = "dsh-mesh-node";
10
+ export declare const inject: string[];
11
+ declare module '@deepseek-ai/cordis' {
12
+ interface Context {
13
+ dshMesh: MeshNode;
14
+ }
15
+ }
16
+ /** Registered by the orchestrator as a standard SubagentProvider for each node ID. */
17
+ export declare class MeshNode {
18
+ readonly nodeId: string;
19
+ readonly nodeIds: string[];
20
+ private readonly worker;
21
+ private readonly peers;
22
+ private readonly incoming;
23
+ constructor(config: MeshConfig);
24
+ runnerFor(nodeId: string): MeshRunner;
25
+ attach(services: WorkerServices): () => void;
26
+ close(): Promise<void>;
27
+ handle(req: IncomingMessage, res: ServerResponse): Promise<void>;
28
+ }
29
+ export declare function apply(ctx: Context, config: MeshConfig): void;
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ import { messages } from './messages.js';
2
+ import { dshPath } from '@deepseek-ai/dsh-home-paths';
3
+ import { MeshRunner } from './client.js';
4
+ import { MeshWorker } from './worker.js';
5
+ import { authenticated, body, credentialHash, endpoint, maxBody, MeshError, names, string, token } from './protocol.js';
6
+ export { MeshRunner } from './client.js';
7
+ export const name = 'dsh-mesh-node';
8
+ export const inject = ['webServer'];
9
+ /** Registered by the orchestrator as a standard SubagentProvider for each node ID. */
10
+ export class MeshNode {
11
+ nodeId;
12
+ nodeIds;
13
+ worker;
14
+ peers = new Map();
15
+ incoming = new Map();
16
+ constructor(config) {
17
+ this.nodeId = string(config.nodeId, 128);
18
+ for (const peer of config.peers ?? []) {
19
+ string(peer.id, 128);
20
+ if (peer.id === this.nodeId || this.peers.has(peer.id))
21
+ throw new Error(messages.duplicate);
22
+ this.peers.set(peer.id, new MeshRunner(this.nodeId, peer, token(peer.tokenEnv)));
23
+ }
24
+ const hashes = new Set();
25
+ for (const peer of config.incoming ?? []) {
26
+ string(peer.id, 128);
27
+ names(peer.projects);
28
+ const hash = credentialHash(token(peer.tokenEnv));
29
+ if (peer.id === this.nodeId || this.incoming.has(peer.id) || hashes.has(hash.toString('hex'))) {
30
+ throw new Error(messages.credential);
31
+ }
32
+ hashes.add(hash.toString('hex'));
33
+ this.incoming.set(peer.id, { peer, hash });
34
+ }
35
+ this.nodeIds = Array.from(this.peers.keys());
36
+ this.worker = new MeshWorker(this.nodeId, config.stateDirectory ?? dshPath('data', 'prism', 'mesh'));
37
+ }
38
+ runnerFor(nodeId) {
39
+ const runner = this.peers.get(nodeId);
40
+ if (!runner)
41
+ throw new Error(messages.unknown);
42
+ return runner;
43
+ }
44
+ attach(services) { return this.worker.attach(services); }
45
+ close() { return this.worker.close(); }
46
+ async handle(req, res) {
47
+ res.setHeader('content-type', 'application/json; charset=utf-8');
48
+ res.setHeader('cache-control', 'no-store');
49
+ try {
50
+ if (req.method !== 'POST')
51
+ throw new MeshError(405, 'POST required');
52
+ const id = req.headers['x-prism-node'];
53
+ const entry = typeof id === 'string' ? this.incoming.get(id) : undefined;
54
+ if (!entry || !authenticated(entry.hash, req.headers.authorization))
55
+ throw new MeshError(401, 'Unauthorized');
56
+ if (req.headers['content-type']?.split(';')[0] !== 'application/json')
57
+ throw new MeshError(415, 'JSON required');
58
+ const result = await this.worker.handle(entry.peer, await body(req));
59
+ const serialized = JSON.stringify(result);
60
+ if (Buffer.byteLength(serialized) > maxBody)
61
+ throw new MeshError(413, 'Mesh response too large');
62
+ res.end(serialized);
63
+ }
64
+ catch (error) {
65
+ res.statusCode = error instanceof MeshError ? error.status : 500;
66
+ res.end(JSON.stringify({ error: error instanceof MeshError ? error.message : 'Mesh operation failed' }));
67
+ }
68
+ }
69
+ }
70
+ export function apply(ctx, config) {
71
+ const node = new MeshNode(config);
72
+ ctx.provide('dshMesh', node);
73
+ ctx.webServer.register({ kind: 'exact', path: endpoint, auth: 'anonymous', handler: (req, res) => node.handle(req, res) });
74
+ ctx.effect(() => () => node.close(), 'prism.mesh');
75
+ }
@@ -0,0 +1,5 @@
1
+ type Messages = Record<'duplicate' | 'credential' | 'unknown' | 'url' | 'https' | 'tooLarge' | 'destination' | 'remoteFailed', string>;
2
+ /** Operator diagnostics follow the host process language; wire codes stay stable. */
3
+ export declare function messagesFor(locale: string): Messages;
4
+ export declare const messages: Messages;
5
+ export {};
@@ -0,0 +1,9 @@
1
+ import { createRequire } from 'node:module';
2
+ const require = createRequire(import.meta.url);
3
+ /** Operator diagnostics follow the host process language; wire codes stay stable. */
4
+ export function messagesFor(locale) {
5
+ const base = locale.toLowerCase().split('-')[0];
6
+ const language = ['de', 'en', 'es', 'fr', 'ja', 'pt', 'ru', 'zh'].includes(base) ? base : 'en';
7
+ return require(`../locale/${language}.json`).messages;
8
+ }
9
+ export const messages = messagesFor(Intl.DateTimeFormat().resolvedOptions().locale);
@@ -0,0 +1,45 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import type { TurnSpec } from '@dsh-prism/dsh-orchestrator/contracts';
3
+ export declare const endpoint = "/prism/mesh/v1";
4
+ export declare const maxBody: number;
5
+ export declare class MeshError extends Error {
6
+ readonly status: number;
7
+ constructor(status: number, message: string);
8
+ }
9
+ export declare function record(value: unknown): Record<string, unknown>;
10
+ export declare function string(value: unknown, limit?: number): string;
11
+ export declare function names(value: unknown): string[];
12
+ /** Workspace paths, provider options and system prompts are resolved on the device. */
13
+ export declare function wireTarget(spec: TurnSpec): {
14
+ bindingId: string;
15
+ owner: string;
16
+ parentBindingId: string | undefined;
17
+ layer: import("@dsh-prism/dsh-orchestrator/contracts").Layer;
18
+ projectId: string;
19
+ nodeId: string;
20
+ modelId: string;
21
+ allowedTools: string[];
22
+ delegationCeiling: string[] | undefined;
23
+ };
24
+ export declare function parseTarget(raw: unknown, nodeId: string): TurnSpec;
25
+ export interface InboundPeer {
26
+ id: string;
27
+ tokenEnv: string;
28
+ projects: string[];
29
+ }
30
+ export interface OutboundPeer {
31
+ id: string;
32
+ tokenEnv: string;
33
+ url: string;
34
+ }
35
+ export interface MeshConfig {
36
+ nodeId: string;
37
+ peers?: OutboundPeer[];
38
+ incoming?: InboundPeer[];
39
+ stateDirectory?: string;
40
+ }
41
+ export declare function token(envName: string): string;
42
+ export declare function credentialHash(value: string): Buffer;
43
+ export declare function authenticated(expected: Buffer, authorization?: string): boolean;
44
+ export declare function peerUrl(url: string): URL;
45
+ export declare function body(request: IncomingMessage): Promise<unknown>;
@@ -0,0 +1,96 @@
1
+ import { messages } from './messages.js';
2
+ import { createHash, timingSafeEqual } from 'node:crypto';
3
+ export const endpoint = '/prism/mesh/v1';
4
+ export const maxBody = 4 * 1024 * 1024;
5
+ export class MeshError extends Error {
6
+ status;
7
+ constructor(status, message) {
8
+ super(message);
9
+ this.status = status;
10
+ }
11
+ }
12
+ export function record(value) {
13
+ if (!value || typeof value !== 'object' || Array.isArray(value))
14
+ throw new MeshError(400, 'Invalid mesh object');
15
+ return value;
16
+ }
17
+ export function string(value, limit = 512) {
18
+ if (typeof value !== 'string' || !value.trim() || value.length > limit)
19
+ throw new MeshError(400, 'Invalid mesh field');
20
+ return value;
21
+ }
22
+ export function names(value) {
23
+ if (!Array.isArray(value) || value.length > 128)
24
+ throw new MeshError(400, 'Invalid list');
25
+ const result = value.map(v => string(v, 128));
26
+ if (new Set(result).size !== result.length)
27
+ throw new MeshError(400, 'Duplicate name');
28
+ return result;
29
+ }
30
+ /** Workspace paths, provider options and system prompts are resolved on the device. */
31
+ export function wireTarget(spec) {
32
+ return {
33
+ bindingId: spec.bindingId, owner: spec.owner, parentBindingId: spec.parentBindingId,
34
+ layer: spec.layer, projectId: spec.workspace.projectId, nodeId: spec.workspace.nodeId,
35
+ modelId: spec.model.id, allowedTools: spec.allowedTools, delegationCeiling: spec.delegationCeiling,
36
+ };
37
+ }
38
+ export function parseTarget(raw, nodeId) {
39
+ const v = record(raw);
40
+ if (v.nodeId !== nodeId || (v.layer !== 'L1' && v.layer !== 'L2' && v.layer !== 'L3'))
41
+ throw new MeshError(403, 'Invalid delegation');
42
+ if (v.layer === 'L1' && v.parentBindingId !== undefined)
43
+ throw new MeshError(403, 'Invalid root delegation');
44
+ return {
45
+ layer: v.layer, workspace: { nodeId, projectId: string(v.projectId), cwd: '' },
46
+ model: { id: string(v.modelId), description: '' }, bindingId: string(v.bindingId),
47
+ owner: string(v.owner, 2048),
48
+ ...(v.layer !== 'L1' && { parentBindingId: string(v.parentBindingId) }),
49
+ allowedTools: names(v.allowedTools), systemPrompt: '',
50
+ ...(v.layer === 'L2' && { delegationCeiling: names(v.delegationCeiling ?? []) }),
51
+ };
52
+ }
53
+ export function token(envName) {
54
+ const value = process.env[envName];
55
+ if (!value || !/^[\x21-\x7E]+$/.test(value))
56
+ throw new Error('Invalid Mesh peer credential in ' + envName);
57
+ return value;
58
+ }
59
+ export function credentialHash(value) {
60
+ return createHash('sha256').update(value).digest();
61
+ }
62
+ export function authenticated(expected, authorization) {
63
+ return !!authorization?.startsWith('Bearer ') && timingSafeEqual(expected, credentialHash(authorization.slice(7)));
64
+ }
65
+ export function peerUrl(url) {
66
+ const parsed = new URL(url);
67
+ if (parsed.username || parsed.password || parsed.search || parsed.hash || parsed.pathname !== '/') {
68
+ throw new Error(messages.url);
69
+ }
70
+ const local = ['127.0.0.1', '[::1]', 'localhost'].includes(parsed.hostname);
71
+ if (parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && local)) {
72
+ throw new Error(messages.https);
73
+ }
74
+ return new URL(endpoint, parsed);
75
+ }
76
+ export async function body(request) {
77
+ if (Number(request.headers['content-length']) > maxBody)
78
+ throw new MeshError(413, 'Request too large');
79
+ const chunks = [];
80
+ let total = 0;
81
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
82
+ const buffer = Buffer.from(chunk);
83
+ total += buffer.length;
84
+ if (total > maxBody) {
85
+ request.resume();
86
+ throw new MeshError(413, 'Request too large');
87
+ }
88
+ chunks.push(buffer);
89
+ }
90
+ try {
91
+ return JSON.parse(Buffer.concat(chunks).toString());
92
+ }
93
+ catch {
94
+ throw new MeshError(400, 'Invalid JSON');
95
+ }
96
+ }
@@ -0,0 +1,23 @@
1
+ import type { Layer, SessionRunner, ToolDefinition, TurnSpec } from '@dsh-prism/dsh-orchestrator/contracts';
2
+ import { type InboundPeer } from './protocol.js';
3
+ export interface WorkerServices {
4
+ runner: SessionRunner;
5
+ authorize(spec: TurnSpec): TurnSpec;
6
+ definitionsFor(layer: Layer): ToolDefinition[];
7
+ }
8
+ /** A physical worker's durable, peer-scoped session lineage and live remote calls. */
9
+ export declare class MeshWorker {
10
+ readonly nodeId: string;
11
+ private readonly stateDirectory;
12
+ private readonly turns;
13
+ private readonly sweep;
14
+ private services?;
15
+ private database?;
16
+ private lastPrune;
17
+ constructor(nodeId: string, stateDirectory: string);
18
+ attach(services: WorkerServices): () => void;
19
+ close(): Promise<void>;
20
+ private db;
21
+ private bind;
22
+ handle(peer: InboundPeer, input: unknown): Promise<unknown>;
23
+ }
package/dist/worker.js ADDED
@@ -0,0 +1,238 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { chmodSync, mkdirSync } from 'node:fs';
3
+ import { DatabaseSync } from 'node:sqlite';
4
+ import { join } from 'node:path';
5
+ import { MeshError, names, parseTarget, record, string } from './protocol.js';
6
+ function digest(parts) {
7
+ return createHash('sha256').update(JSON.stringify(parts)).digest('hex');
8
+ }
9
+ /** One model turn. Tool calls stay on the coordinator, indexed until receipt. */
10
+ class WorkerTurn {
11
+ fingerprint;
12
+ calls = new Map();
13
+ changed = new Set();
14
+ controller = new AbortController();
15
+ done;
16
+ touched = Date.now();
17
+ phase = 'running';
18
+ sessionId;
19
+ constructor(fingerprint, runner, spec, text, definitions) {
20
+ this.fingerprint = fingerprint;
21
+ const invoke = async (name, args) => {
22
+ this.controller.signal.throwIfAborted();
23
+ if (!definitions.some(d => d.name === name))
24
+ throw new MeshError(403, 'Tool unavailable');
25
+ return new Promise((resolve, reject) => {
26
+ this.calls.set(randomUUID(), { name, args, resolve, reject });
27
+ this.notify();
28
+ });
29
+ };
30
+ this.done = Promise.resolve().then(() => runner.run(spec, text, { definitions, invoke }, this.controller.signal, id => {
31
+ this.sessionId = id;
32
+ this.notify();
33
+ })).then(() => { this.phase = 'done'; }, () => { this.phase = 'failed'; }).finally(() => this.notify());
34
+ }
35
+ notify() {
36
+ for (const wake of this.changed)
37
+ wake();
38
+ }
39
+ async poll(knownSession) {
40
+ if (this.phase === 'running' && !this.calls.size && this.sessionId === knownSession) {
41
+ await new Promise(resolve => {
42
+ const wake = () => { clearTimeout(timer); this.changed.delete(wake); resolve(); };
43
+ const timer = setTimeout(wake, 10_000);
44
+ this.changed.add(wake);
45
+ });
46
+ }
47
+ return {
48
+ phase: this.phase, sessionId: this.sessionId,
49
+ calls: Array.from(this.calls, ([id, call]) => ({ id, name: call.name, args: call.args })),
50
+ };
51
+ }
52
+ reply(id, success, value) {
53
+ const call = this.calls.get(id);
54
+ if (!call)
55
+ return; // Repeating an acknowledged reply has no side effects.
56
+ this.calls.delete(id);
57
+ if (success)
58
+ call.resolve(value);
59
+ else
60
+ call.reject(new Error('Coordinator tool failed'));
61
+ }
62
+ cancel() {
63
+ this.controller.abort();
64
+ for (const call of this.calls.values())
65
+ call.reject(new Error('Mesh turn cancelled'));
66
+ this.calls.clear();
67
+ this.notify();
68
+ }
69
+ }
70
+ /** A physical worker's durable, peer-scoped session lineage and live remote calls. */
71
+ export class MeshWorker {
72
+ nodeId;
73
+ stateDirectory;
74
+ turns = new Map();
75
+ sweep;
76
+ services;
77
+ database;
78
+ lastPrune = 0;
79
+ constructor(nodeId, stateDirectory) {
80
+ this.nodeId = nodeId;
81
+ this.stateDirectory = stateDirectory;
82
+ this.sweep = setInterval(() => {
83
+ for (const [id, turn] of this.turns) {
84
+ if (Date.now() - turn.touched < 120_000)
85
+ continue;
86
+ if (turn.phase === 'running')
87
+ turn.cancel();
88
+ else
89
+ this.turns.delete(id);
90
+ }
91
+ }, 30_000).unref();
92
+ }
93
+ attach(services) {
94
+ if (this.services)
95
+ throw new Error('Mesh worker already attached');
96
+ this.services = services;
97
+ return () => {
98
+ if (this.services === services) {
99
+ this.services = undefined;
100
+ for (const turn of this.turns.values())
101
+ turn.cancel();
102
+ }
103
+ };
104
+ }
105
+ async close() {
106
+ clearInterval(this.sweep);
107
+ for (const turn of this.turns.values())
108
+ turn.cancel();
109
+ await Promise.all(Array.from(this.turns.values(), turn => turn.done));
110
+ this.turns.clear();
111
+ this.database?.close();
112
+ this.database = undefined;
113
+ }
114
+ db() {
115
+ if (!this.database) {
116
+ mkdirSync(this.stateDirectory, { recursive: true, mode: 0o700 });
117
+ const path = join(this.stateDirectory, 'lineage.sqlite');
118
+ const db = new DatabaseSync(path);
119
+ chmodSync(path, 0o600);
120
+ db.exec(`PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL;
121
+ CREATE TABLE IF NOT EXISTS lineage (
122
+ id TEXT PRIMARY KEY, owner TEXT, layer TEXT, project TEXT, cwd TEXT, parent TEXT, ceiling TEXT NOT NULL
123
+ );
124
+ CREATE TABLE IF NOT EXISTS starts (run TEXT PRIMARY KEY, at INTEGER NOT NULL)`);
125
+ this.database = db;
126
+ }
127
+ return this.database;
128
+ }
129
+ bind(spec, runKey) {
130
+ const db = this.db();
131
+ const select = db.prepare('SELECT * FROM lineage WHERE id=?');
132
+ const parentId = spec.parentBindingId ?? null;
133
+ const { projectId, cwd } = spec.workspace;
134
+ const grant = spec.layer === 'L2' ? spec.delegationCeiling ?? [] : spec.allowedTools;
135
+ const permitted = (row) => {
136
+ const list = JSON.parse(String(row.ceiling));
137
+ return grant.every(name => list.includes(name));
138
+ };
139
+ db.exec('BEGIN IMMEDIATE');
140
+ try {
141
+ if (runKey) {
142
+ const now = Date.now();
143
+ if (now - this.lastPrune >= 3_600_000) {
144
+ db.prepare('DELETE FROM starts WHERE at < ?').run(now - 86_400_000);
145
+ this.lastPrune = now;
146
+ }
147
+ // A lost start reply followed by a worker restart must never repeat an accepted turn.
148
+ if (!db.prepare('INSERT OR IGNORE INTO starts VALUES(?,?)').run(runKey, now).changes) {
149
+ throw new MeshError(409, 'Turn already admitted on a prior worker');
150
+ }
151
+ }
152
+ if (spec.layer === 'L3') {
153
+ const parent = parentId ? select.get(parentId) : undefined;
154
+ if (!parent || parent.layer !== 'L2' || parent.owner !== spec.owner ||
155
+ parent.project !== projectId || parent.cwd !== cwd || !permitted(parent)) {
156
+ throw new MeshError(403, 'Invalid parent delegation');
157
+ }
158
+ }
159
+ const current = select.get(spec.bindingId);
160
+ if (!current && runKey) {
161
+ db.prepare('INSERT INTO lineage VALUES(?,?,?,?,?,?,?)')
162
+ .run(spec.bindingId, spec.owner, spec.layer, projectId, cwd, parentId, JSON.stringify(grant));
163
+ }
164
+ else {
165
+ if (!current || current.owner !== spec.owner || current.layer !== spec.layer ||
166
+ current.project !== projectId || current.cwd !== cwd || current.parent !== parentId || !permitted(current)) {
167
+ throw new MeshError(403, 'Session binding unavailable');
168
+ }
169
+ if (runKey)
170
+ db.prepare('UPDATE lineage SET ceiling=? WHERE id=?').run(JSON.stringify(grant), spec.bindingId);
171
+ }
172
+ db.exec('COMMIT');
173
+ }
174
+ catch (err) {
175
+ db.exec('ROLLBACK');
176
+ throw err;
177
+ }
178
+ }
179
+ async handle(peer, input) {
180
+ const data = record(input);
181
+ const op = string(data.op);
182
+ const services = this.services;
183
+ if (!services)
184
+ throw new MeshError(503, 'Mesh worker unavailable');
185
+ if (op === 'start' || op === 'transcript') {
186
+ const target = parseTarget(data.target, this.nodeId);
187
+ if (!peer.projects.includes(target.workspace.projectId))
188
+ throw new MeshError(403, 'Project unavailable');
189
+ let spec;
190
+ try {
191
+ spec = services.authorize(target);
192
+ }
193
+ catch {
194
+ throw new MeshError(403, 'Delegation denied');
195
+ }
196
+ const scopedId = (id) => 'mesh-' + digest([peer.id, id]);
197
+ spec = { ...spec, bindingId: scopedId(spec.bindingId), parentBindingId: spec.parentBindingId && scopedId(spec.parentBindingId) };
198
+ if (op === 'transcript') {
199
+ this.bind(spec);
200
+ return services.runner.transcript(spec);
201
+ }
202
+ const runKey = digest([peer.id, string(data.runId)]);
203
+ const text = string(data.text, 1_000_000);
204
+ const allowed = names(data.tools);
205
+ const definitions = services.definitionsFor(spec.layer).filter(d => allowed.includes(d.name));
206
+ if (allowed.length !== definitions.length)
207
+ throw new MeshError(403, 'Invalid tool delegation');
208
+ const fingerprint = digest([target, text, allowed]);
209
+ const current = this.turns.get(runKey);
210
+ if (current && current.fingerprint !== fingerprint)
211
+ throw new MeshError(409, 'Conflicting turn');
212
+ if (!current) {
213
+ this.bind(spec, runKey);
214
+ this.turns.set(runKey, new WorkerTurn(fingerprint, services.runner, spec, text, definitions));
215
+ }
216
+ return { accepted: true };
217
+ }
218
+ const turn = this.turns.get(digest([peer.id, string(data.runId)]));
219
+ if (!turn)
220
+ throw new MeshError(404, 'Turn unavailable');
221
+ turn.touched = Date.now();
222
+ if (op === 'poll')
223
+ return turn.poll(data.sessionId);
224
+ if (op === 'reply') {
225
+ if (typeof data.success !== 'boolean')
226
+ throw new MeshError(400, 'Invalid tool reply');
227
+ turn.reply(string(data.callId), data.success, data.value);
228
+ }
229
+ else if (op === 'cancel') {
230
+ turn.cancel();
231
+ await turn.done;
232
+ }
233
+ else {
234
+ throw new MeshError(400, 'Unknown operation');
235
+ }
236
+ return { accepted: true };
237
+ }
238
+ }
package/icon.svg ADDED
@@ -0,0 +1,11 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" role="img" aria-labelledby="title desc">
2
+ <title id="title">Mesh node</title>
3
+ <desc id="desc">Four device nodes connected across the faces of a tetrahedron.</desc>
4
+ <defs><linearGradient id="ground" x2="1" y2="1" gradientUnits="objectBoundingBox"><stop stop-color="#214F42"/><stop offset="1" stop-color="#102E2B"/></linearGradient></defs>
5
+ <rect x="3" y="3" width="122" height="122" rx="27" fill="url(#ground)"/>
6
+ <g stroke-linejoin="round" stroke-linecap="round">
7
+ <path fill="none" stroke="#A6D9C3" stroke-width="4" d="m61 25 42 53-44 23-34-28zM61 25l-2 76m-34-28 78 5"/>
8
+ <circle cx="61" cy="25" r="10" fill="#C7F4CC"/><circle cx="103" cy="78" r="9" fill="#B8A9F0"/>
9
+ <circle cx="59" cy="101" r="9" fill="#F6C581"/><circle cx="25" cy="73" r="10" fill="#78D3B1"/>
10
+ </g>
11
+ </svg>
package/locale/de.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "meta": {
3
+ "title": "Prism-Mesh-Knoten",
4
+ "description": "Authentifiziert Partnergeräte und führt entfernte DSH-Sitzungen als Unteragenten aus."
5
+ },
6
+ "messages": {
7
+ "duplicate": "Doppelte Mesh-Knoten-ID",
8
+ "credential": "Jeder eingehende Mesh-Knoten benötigt eine eindeutige ID und eigene Zugangsdaten",
9
+ "unknown": "Unbekannter Mesh-Knoten",
10
+ "url": "Die URL eines Mesh-Partners muss eine Origin sein",
11
+ "https": "Mesh verwendet HTTPS zwischen Geräten",
12
+ "tooLarge": "Mesh-Nutzlast zu groß",
13
+ "destination": "Ungültiges Mesh-Ziel",
14
+ "remoteFailed": "Entfernter Verarbeitungsschritt fehlgeschlagen"
15
+ }
16
+ }
package/locale/en.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "meta": {
3
+ "title": "Prism Mesh node",
4
+ "description": "Authenticate peer devices and run remote DSH sessions as subagents.",
5
+ "detail": "README.md"
6
+ },
7
+ "messages": {
8
+ "duplicate": "Duplicate Mesh node ID",
9
+ "credential": "Each incoming Mesh node requires a unique ID and credential",
10
+ "unknown": "Unknown Mesh node",
11
+ "url": "Mesh peer URL must be an origin",
12
+ "https": "Mesh uses HTTPS between devices",
13
+ "tooLarge": "Mesh payload too large",
14
+ "destination": "Invalid Mesh destination",
15
+ "remoteFailed": "Remote turn failed"
16
+ }
17
+ }
package/locale/es.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "meta": {
3
+ "title": "Nodo Mesh de Prism",
4
+ "description": "Autentica dispositivos pares y ejecuta sesiones DSH remotas como subagentes."
5
+ },
6
+ "messages": {
7
+ "duplicate": "ID de nodo Mesh duplicado",
8
+ "credential": "Cada nodo Mesh entrante requiere un ID y una credencial únicos",
9
+ "unknown": "Nodo Mesh desconocido",
10
+ "url": "La URL del par Mesh debe ser un origen",
11
+ "https": "Mesh utiliza HTTPS entre dispositivos",
12
+ "tooLarge": "Carga útil de Mesh demasiado grande",
13
+ "destination": "Destino Mesh no válido",
14
+ "remoteFailed": "Falló el turno remoto"
15
+ }
16
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "meta": {
3
+ "title": "Nœud Mesh Prism",
4
+ "description": "Authentifie les appareils pairs et exécute des sessions DSH distantes comme sous-agents."
5
+ },
6
+ "messages": {
7
+ "duplicate": "Identifiant de nœud Mesh en double",
8
+ "credential": "Chaque nœud Mesh entrant doit avoir un identifiant et des identifiants d’accès uniques",
9
+ "unknown": "Nœud Mesh inconnu",
10
+ "url": "L’URL du pair Mesh doit être une origine",
11
+ "https": "Mesh utilise HTTPS entre appareils",
12
+ "tooLarge": "Données Mesh trop volumineuses",
13
+ "destination": "Destination Mesh non valide",
14
+ "remoteFailed": "Échec du tour distant"
15
+ }
16
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "meta": {
3
+ "title": "プリズム Mesh ノード",
4
+ "description": "接続先端末を認証し、リモート DSH セッションをサブエージェントとして実行します。"
5
+ },
6
+ "messages": {
7
+ "duplicate": "Mesh ノード ID が重複しています",
8
+ "credential": "各受信 Mesh ノードには一意な ID と認証情報が必要です",
9
+ "unknown": "不明な Mesh ノードです",
10
+ "url": "Mesh ピアの URL にはオリジンを指定してください",
11
+ "https": "デバイス間の Mesh 接続には HTTPS を使用します",
12
+ "tooLarge": "Mesh のペイロードが大きすぎます",
13
+ "destination": "Mesh の宛先が無効です",
14
+ "remoteFailed": "リモートターンに失敗しました"
15
+ }
16
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "meta": {
3
+ "title": "Nó Mesh do Prism",
4
+ "description": "Autentica dispositivos pares e executa sessões DSH remotas como subagentes."
5
+ },
6
+ "messages": {
7
+ "duplicate": "ID de nó Mesh duplicado",
8
+ "credential": "Cada nó Mesh de entrada exige um ID e uma credencial únicos",
9
+ "unknown": "Nó Mesh desconhecido",
10
+ "url": "A URL do par Mesh deve ser uma origem",
11
+ "https": "O Mesh usa HTTPS entre dispositivos",
12
+ "tooLarge": "Dados do Mesh muito grandes",
13
+ "destination": "Destino Mesh inválido",
14
+ "remoteFailed": "Falha no turno remoto"
15
+ }
16
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "meta": {
3
+ "title": "Узел Mesh Призмы",
4
+ "description": "Аутентифицирует устройства и запускает удалённые сеансы DSH как субагенты."
5
+ },
6
+ "messages": {
7
+ "duplicate": "Повторяющийся идентификатор узла Mesh",
8
+ "credential": "Каждому входящему узлу Mesh нужны уникальные идентификатор и учётные данные",
9
+ "unknown": "Неизвестный узел Mesh",
10
+ "url": "URL узла Mesh должен содержать только адрес источника",
11
+ "https": "Для связи между устройствами Mesh использует HTTPS",
12
+ "tooLarge": "Слишком большой объём данных Mesh",
13
+ "destination": "Недопустимый узел назначения Mesh",
14
+ "remoteFailed": "Сбой удалённого шага"
15
+ }
16
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "meta": {
3
+ "title": "棱镜 Mesh 节点",
4
+ "description": "认证对端设备,将远程 DSH 会话作为子代理执行。",
5
+ "detail": "README.zh_CN.md"
6
+ },
7
+ "messages": {
8
+ "duplicate": "Mesh 节点 ID 重复",
9
+ "credential": "每个入站节点需要唯一的 ID 和凭据",
10
+ "unknown": "找不到 Mesh 节点",
11
+ "url": "Mesh 对端 URL 必须是源地址",
12
+ "https": "跨设备 Mesh 连接需要 HTTPS",
13
+ "tooLarge": "Mesh 数据超出大小限制",
14
+ "destination": "无效的 Mesh 目标节点",
15
+ "remoteFailed": "远程会话轮次失败"
16
+ }
17
+ }
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@dsh-prism/dsh-mesh-node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "types": "./dist/index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./dist/index.d.ts",
10
+ "import": "./dist/index.js"
11
+ },
12
+ "./locale/*.json": "./locale/*.json",
13
+ "./package.json": "./package.json"
14
+ },
15
+ "files": [
16
+ "dist/",
17
+ "!dist/*.test.*",
18
+ "!dist/*.tsbuildinfo",
19
+ "!dist/*probe.*",
20
+ "locale/*.json",
21
+ "icon.svg",
22
+ "README.zh_CN.md"
23
+ ],
24
+ "engines": {
25
+ "node": ">=24.0.0",
26
+ "dsh": "0.2.3-alpha.2"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "peerDependencies": {
32
+ "@deepseek-ai/cordis": "4.2.0-alpha.1",
33
+ "@deepseek-ai/dsh-host-webserver": "0.2.3-alpha.2",
34
+ "@dsh-prism/dsh-orchestrator": "0.1.0",
35
+ "@deepseek-ai/dsh-home-paths": "0.2.3-alpha.2"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc -b tsconfig.release.json",
39
+ "test": "node --test test/mesh.test.mjs"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/dsh-plugins/dsh-mesh-node.git"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "24.10.1",
47
+ "typescript": "6.0.3"
48
+ }
49
+ }