dsh-cothread-mcp 0.1.8 → 0.1.10

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/src/device.js DELETED
@@ -1,86 +0,0 @@
1
- /**
2
- * 本机设备身份。
3
- *
4
- * 共序服务端按 device_id 认设备:同一个 device_id 再次授权会复用同一条连接器记录,
5
- * 换 device_id 则会被当成新设备——旧记录被撤销、新记录被创建,
6
- * 而服务端「一个成员只能有一条 active 绑定」的唯一索引会让这次授权撞上冲突。
7
- * 所以 deviceId 必须是这台机器稳定的身份,不能每次授权都重新生成。
8
- */
9
- import { randomUUID } from 'node:crypto'
10
- import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
11
- import { homedir } from 'node:os'
12
- import { resolve } from 'node:path'
13
-
14
- /** 合法 UUID。 */
15
- const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
16
-
17
- /**
18
- * 设备身份文件的位置。
19
- *
20
- * 放在 state/ 之外:state/ 是每个 profile 一个目录,而 deviceId 是机器级的设备身份,
21
- * 同一台机器上的多个 profile 应当共用同一个。
22
- */
23
- export function deviceFile() {
24
- return resolve(process.env.DSH_HOME || resolve(homedir(), '.dsh'), 'plugins', 'dsh-cothread-mcp', 'device.json')
25
- }
26
-
27
- /**
28
- * 读取本机 deviceId。
29
- *
30
- * 文件不存在、内容损坏、或者不是合法 UUID 时都自愈:重新生成一个并写回,
31
- * 不因为设备身份的问题中断授权。
32
- */
33
- export async function readDeviceId() {
34
- try {
35
- const raw = await readFile(deviceFile(), 'utf8')
36
- const parsed = JSON.parse(raw)
37
- const deviceId = typeof parsed?.deviceId === 'string' ? parsed.deviceId.trim() : ''
38
- if (UUID_PATTERN.test(deviceId)) return deviceId
39
- } catch {
40
- // 文件不存在或读不出来:下面重新生成。
41
- }
42
- const generated = randomUUID()
43
- await writeDeviceFile({ deviceId: generated })
44
- return generated
45
- }
46
-
47
- /**
48
- * 记录授权结果。
49
- *
50
- * deviceId 是我们发给服务端的设备身份(服务端按它认设备),必须落盘;
51
- * executorId 是服务端那条连接器记录的 id,只用于排查问题。
52
- */
53
- export async function saveDeviceIdentity({ deviceId, executorId }) {
54
- const current = await readDeviceRecord().catch(() => ({ deviceId: '', executorId: '' }))
55
- const next = {
56
- deviceId: typeof deviceId === 'string' && deviceId.trim() ? deviceId.trim() : current.deviceId,
57
- executorId: typeof executorId === 'string' && executorId.trim() ? executorId.trim() : current.executorId,
58
- }
59
- await writeDeviceFile(next)
60
- return next
61
- }
62
-
63
- /** 读取完整的设备身份记录。 */
64
- export async function readDeviceRecord() {
65
- try {
66
- const raw = await readFile(deviceFile(), 'utf8')
67
- const parsed = JSON.parse(raw)
68
- return {
69
- deviceId: typeof parsed?.deviceId === 'string' ? parsed.deviceId.trim() : '',
70
- executorId: typeof parsed?.executorId === 'string' ? parsed.executorId.trim() : '',
71
- }
72
- } catch {
73
- return { deviceId: '', executorId: '' }
74
- }
75
- }
76
-
77
- /** 原子写回设备身份文件。 */
78
- async function writeDeviceFile(record) {
79
- const file = deviceFile()
80
- await mkdir(resolve(file, '..'), { recursive: true, mode: 0o700 })
81
- const temp = `${file}.${randomUUID()}.tmp`
82
- try {
83
- await writeFile(temp, JSON.stringify(record), { mode: 0o600 })
84
- await rename(temp, file)
85
- } finally { await unlink(temp).catch(() => {}) }
86
- }
@@ -1,18 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
- export const ENVIRONMENTS = Object.freeze({
3
- production: Object.freeze({ label: '正式环境', origin: 'https://cothread.z2l.top', credential: 'COTHREAD_DEVICE_PRODUCTION' }),
4
- local: Object.freeze({ label: '本地环境', origin: 'http://127.0.0.1:3100', credential: 'COTHREAD_DEVICE_LOCAL' }),
5
- })
6
-
7
- /**
8
- * 取一个环境的地址与凭据名。
9
- *
10
- * 只认固定的两个环境:正式环境和本地环境。自定义环境已经下线,
11
- * 老配置里存着的 'custom' 一律按正式环境处理——凭据是按环境分开的,
12
- * 落到正式环境上,用户重新授权一次就能接着用,而不是插件直接加载失败。
13
- */
14
- export function environment(name = 'production') {
15
- const key = name === 'custom' ? 'production' : name
16
- if (!Object.hasOwn(ENVIRONMENTS, key)) throw new Error('未知的共序环境')
17
- return ENVIRONMENTS[key]
18
- }
package/src/events.js DELETED
@@ -1,7 +0,0 @@
1
- /** Map account inbox entries to the two user-configured trigger types. */
2
- export function classifyInboxEvent(item) {
3
- if (!item || !item.id || !item.project_id || !item.thread_id || !item.can_open) return null
4
- const trigger = item.kind === 'mention' ? 'mention' : ['task_assigned', 'task_decision'].includes(item.kind) ? 'task' : null
5
- if (!trigger) return null
6
- return { id: String(item.id), projectId: String(item.project_id), projectName: String(item.project_name || ''), threadId: String(item.thread_id), messageId: item.message_id ? String(item.message_id) : null, trigger, title: String(item.title || ''), body: String(item.body || ''), sender: String(item.sender_name || '') }
7
- }
package/src/index.js DELETED
@@ -1,131 +0,0 @@
1
- /**
2
- * @module dsh-cothread-mcp
3
- *
4
- * 把共序 CoThread 的远程 MCP(Streamable HTTP)挂到 DeepSeek Harness。
5
- *
6
- * 令牌只从插件配置读取,不写进源码,也不写进日志:连接失败时只报地址与状态,
7
- * 不打印 Authorization 头的值。
8
- */
9
- import { apply as connectMcp, Config as McpConfig } from "@deepseek-ai/dsh-mcp-client";
10
- import z from "@deepseek-ai/schemastery";
11
- import { CothreadService } from './service.js';
12
- import { environment } from './environments.js';
13
-
14
- export const name = "cothread-mcp";
15
- export const inject = ["tools", "credentials"];
16
-
17
- const DEFAULT_URL = "https://cothread.z2l.top/mcp";
18
- /**
19
- * 环境名:只认正式环境和本地环境。
20
- *
21
- * 自定义环境已经下线,但老配置里可能还存着 'custom'。这里用 transform 把它
22
- * 归一化成正式环境,而不是直接收紧 union——union 一收紧,插件读到旧值就会
23
- * 校验失败,整个插件加载不起来。归一化之后老用户重新授权一次就能接着用。
24
- */
25
- const legacyEnvironment = z.transform(
26
- z.union(['production', 'local', 'custom']),
27
- (value) => (value === 'custom' ? 'production' : value),
28
- true,
29
- );
30
- const SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
31
- const TOOL_CALL_TIMEOUT_MS = 180_000;
32
-
33
- export const Config = z.object({
34
- url: z.string().default(DEFAULT_URL),
35
- serverName: z.string().pattern(SERVER_NAME).default("cothread-mcp"),
36
- token: z.string().default(""),
37
- toolCallTimeoutMs: z.number().default(TOOL_CALL_TIMEOUT_MS),
38
- // 环境只剩正式环境和本地环境。老配置里的 'custom' 由 schema 归一化成正式环境,
39
- // 免得插件因为读不懂旧值而加载失败。
40
- environment: legacyEnvironment.default('production').volatile(),
41
- // 自定义环境已下线,这个字段留着只为兼容旧配置,不再使用。
42
- customUrl: z.string().default('').volatile(),
43
- projectId: z.string().default('').volatile(),
44
- workspace: z.string().default('').volatile(),
45
- receiveMessages: z.boolean().default(false).volatile(),
46
- workspaces: z.array(z.object({
47
- environment: legacyEnvironment.default('production'),
48
- // 自定义环境已下线,这个字段留着只为兼容旧配置,不再使用。
49
- customUrl: z.string().default(''),
50
- projectId: z.string().default(''),
51
- workspace: z.string().default(''),
52
- workspaceId: z.string().default(''),
53
- receiveMessages: z.boolean().default(false),
54
- action: z.union(['notify', 'summary', 'reuse', 'new']).default('notify'),
55
- // 动作:复述(只提醒用户)与思路(分析后回复或处理)。
56
- mentionAction: z.union(['', 'restate', 'analyze', 'notify', 'summary', 'reuse', 'new']).default(''),
57
- taskAction: z.union(['', 'restate', 'analyze', 'notify', 'summary', 'reuse', 'new']).default(''),
58
- // 旧配置字段,仅为兼容已保存的配置而保留,不再使用。
59
- action: z.union(['notify', 'summary', 'reuse', 'new']).default('notify'),
60
- mentionSession: z.union(['', 'reuse', 'new']).default(''),
61
- taskSession: z.union(['', 'reuse', 'new']).default(''),
62
- })).default([]).volatile(),
63
- // 自动化任务的巡检间隔(秒),宿主最短允许 60 秒。
64
- intervalSeconds: z.number().default(300),
65
- });
66
-
67
- const mcpPlugin = {
68
- name: "cothread-mcp-connection",
69
- inject: ["tools"],
70
- Config: McpConfig,
71
- apply: connectMcp,
72
- };
73
-
74
- export function cothreadHeaders(token) {
75
- const key = String(token || "").trim();
76
- if (key === "") return undefined;
77
- if (/[\r\n]/.test(key)) throw new Error("CoThread 令牌必须是单行文本");
78
- return { Authorization: `Bearer ${key}` };
79
- }
80
-
81
- export function cothreadEndpoint(raw) {
82
- const url = new URL(String(raw || DEFAULT_URL));
83
- if (url.protocol !== "https:" && url.protocol !== "http:")
84
- throw new Error("CoThread MCP 地址必须使用 http 或 https");
85
- if (url.username !== "" || url.password !== "")
86
- throw new Error("CoThread MCP 地址不能携带账号密码");
87
- return url.href;
88
- }
89
-
90
- export async function apply(ctx, config) {
91
- let fiber, generation = 0;
92
- const get = x => x && typeof x.get === 'function' ? x.get() : x;
93
- const reconnect = async () => {
94
- const current = ++generation;
95
- fiber?.dispose(); fiber = undefined;
96
- try {
97
- const name = get(config.environment) || 'production';
98
- const origin = environment(name).origin;
99
- const token = await service.mcpToken();
100
- if (current !== generation || !token || name !== (get(config.environment) || 'production') || origin !== environment(name).origin) return;
101
- fiber = ctx.plugin(mcpPlugin, {
102
- transport: 'streamable-http', serverName: get(config.serverName),
103
- url: new URL('/mcp', origin).href,
104
- headers: cothreadHeaders(token), toolCallTimeoutMs: Number(get(config.toolCallTimeoutMs)) || TOOL_CALL_TIMEOUT_MS,
105
- failOnStartupError: false,
106
- });
107
- void Promise.resolve(fiber).catch(() => ctx.logger.error('共序 MCP 连接失败,请检查网络和授权状态。'));
108
- } catch { ctx.logger.error('共序 MCP 凭据获取失败,请重新授权。'); }
109
- };
110
- const service = new CothreadService(ctx, config, reconnect);
111
- ctx.provide('cothread', service);
112
- service.start();
113
- // 记住切换前的环境:万一配置从别处被改了,要清理旧环境的凭据。
114
- let lastEnvironment = { name: get(config.environment) || 'production', origin: environment(get(config.environment) || 'production').origin }
115
- ctx.on('loader/volatile-update', (paths) => {
116
- const changed = Array.isArray(paths) && paths.some(path => path[0] === 'environment' || path[0] === 'customUrl')
117
- if (changed) {
118
- void (async () => {
119
- await service.handleEnvironmentChange(lastEnvironment)
120
- const name = get(config.environment) || 'production'
121
- lastEnvironment = { name, origin: environment(name).origin }
122
- await reconnect()
123
- await service.maintainAutomations()
124
- })()
125
- return
126
- }
127
- void reconnect(); void service.maintainAutomations();
128
- });
129
- ctx.effect(() => () => { generation++; service.dispose(); fiber?.dispose(); });
130
- await reconnect();
131
- }