dsh-cothread-mcp 0.1.1 → 0.1.3

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,18 @@
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 ADDED
@@ -0,0 +1,7 @@
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 CHANGED
@@ -8,11 +8,25 @@
8
8
  */
9
9
  import { apply as connectMcp, Config as McpConfig } from "@deepseek-ai/dsh-mcp-client";
10
10
  import z from "@deepseek-ai/schemastery";
11
+ import { CothreadService } from './service.js';
12
+ import { environment } from './environments.js';
11
13
 
12
14
  export const name = "cothread-mcp";
13
- export const inject = ["tools"];
15
+ export const inject = ["tools", "credentials"];
14
16
 
15
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
+ );
16
30
  const SERVER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
17
31
  const TOOL_CALL_TIMEOUT_MS = 180_000;
18
32
 
@@ -21,6 +35,33 @@ export const Config = z.object({
21
35
  serverName: z.string().pattern(SERVER_NAME).default("cothread-mcp"),
22
36
  token: z.string().default(""),
23
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),
24
65
  });
25
66
 
26
67
  const mcpPlugin = {
@@ -47,29 +88,44 @@ export function cothreadEndpoint(raw) {
47
88
  }
48
89
 
49
90
  export async function apply(ctx, config) {
50
- let endpoint;
51
- let headers;
52
- try {
53
- endpoint = cothreadEndpoint(config.url);
54
- headers = cothreadHeaders(config.token);
55
- } catch (error) {
56
- ctx.logger.error("CoThread MCP 配置无效。请检查 url 与令牌,不要把令牌写进地址。");
57
- ctx.logger.error(String(error?.message || error));
58
- return;
59
- }
60
- if (!headers)
61
- ctx.logger.warn("CoThread MCP 未填写令牌,将在未授权状态下连接(服务端会返回 401)。");
62
-
63
- const fiber = ctx.plugin(mcpPlugin, {
64
- transport: "streamable-http",
65
- serverName: config.serverName,
66
- url: endpoint,
67
- ...(headers ? { headers } : {}),
68
- toolCallTimeoutMs: Number(config.toolCallTimeoutMs) || TOOL_CALL_TIMEOUT_MS,
69
- failOnStartupError: false,
70
- });
71
- void Promise.resolve(fiber).catch((error) => {
72
- ctx.logger.error("CoThread MCP 连接失败。请检查地址与令牌是否有效(令牌不会写入日志)。");
73
- ctx.logger.error(String(error?.message || error));
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();
74
128
  });
129
+ ctx.effect(() => () => { generation++; service.dispose(); fiber?.dispose(); });
130
+ await reconnect();
75
131
  }