dsh-cothread-mcp 0.1.0 → 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.
- package/CHANGELOG.md +45 -0
- package/LICENSE +21 -0
- package/README.md +56 -16
- package/icon.svg +7 -4
- package/lib/client.js +732 -0
- package/package.json +28 -4
- package/scripts/build.mjs +61 -0
- package/src/authorization.js +144 -0
- package/src/automation.js +596 -0
- package/src/device.js +86 -0
- package/src/environments.js +18 -0
- package/src/events.js +7 -0
- package/src/index.js +81 -25
- package/src/service.js +640 -0
- package/src/state.js +78 -0
- package/src/version.js +17 -0
package/src/service.js
ADDED
|
@@ -0,0 +1,640 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { resolve } from 'node:path'
|
|
5
|
+
import { credentialRef } from '@deepseek-ai/dsh-credentials'
|
|
6
|
+
import { environment } from './environments.js'
|
|
7
|
+
import { startAuthorization, getMcpCredential } from './authorization.js'
|
|
8
|
+
import { readDeviceId, saveDeviceIdentity } from './device.js'
|
|
9
|
+
import { pluginVersion } from './version.js'
|
|
10
|
+
import { classifyInboxEvent } from './events.js'
|
|
11
|
+
import { DEFAULT_INTERVAL_SECONDS, automationKey, buildPrompt, resolveAction, syncAutomations, saveAutomation, planAutomationRemoval, removeAutomation } from './automation.js'
|
|
12
|
+
import { isPendingTask, readState, writeState } from './state.js'
|
|
13
|
+
|
|
14
|
+
const value = x => x && typeof x.get === 'function' ? x.get() : x
|
|
15
|
+
const serviceOf = (ctx, name) => (typeof ctx.get === 'function' ? ctx.get(name) : ctx[name]) || null
|
|
16
|
+
const keyFor = env => credentialRef(env.credential)
|
|
17
|
+
/** 把动作值折算成现在支持的动作,非法值退回「复述」。 */
|
|
18
|
+
const safeAction = raw => {
|
|
19
|
+
const action = String(raw || '').trim()
|
|
20
|
+
return action === 'analyze' || action === 'reuse' || action === 'new' ? 'analyze' : 'restate'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export class CothreadService {
|
|
24
|
+
constructor(ctx, config, reconnect) {
|
|
25
|
+
this.ctx = ctx; this.config = config; this.reconnect = reconnect
|
|
26
|
+
this.pending = null; this.starting = false; this.error = ''; this.authGeneration = 0; this.authWrite = Promise.resolve(); this.disconnecting = false; this.pollError = ''; this.cursors = new Map(); this.disposed = false
|
|
27
|
+
this.typertRemote = Object.freeze({ service: this, serviceKey: 'cothread', namespace: 'cothread' })
|
|
28
|
+
}
|
|
29
|
+
selected() { return value(this.config.environment) || 'production' }
|
|
30
|
+
selectedEnvironment(name = this.selected()) { return environment(name) }
|
|
31
|
+
async token(name = this.selected()) {
|
|
32
|
+
const found = await this.ctx.credentials.resolve(keyFor(this.selectedEnvironment(name)))
|
|
33
|
+
return found?.source === 'file' ? found.value : undefined
|
|
34
|
+
}
|
|
35
|
+
async status() {
|
|
36
|
+
try {
|
|
37
|
+
const name = this.selected()
|
|
38
|
+
return {
|
|
39
|
+
environment: name,
|
|
40
|
+
origin: this.selectedEnvironment(name).origin,
|
|
41
|
+
authenticated: Boolean(await this.token(name)),
|
|
42
|
+
pending: Boolean(this.pending || this.starting),
|
|
43
|
+
error: this.error,
|
|
44
|
+
pollError: this.pollError,
|
|
45
|
+
lastPollError: this.lastPollError || '',
|
|
46
|
+
automationError: this.automationError,
|
|
47
|
+
automations: this.automations || [],
|
|
48
|
+
projectRevision: this.projectRevision || 0,
|
|
49
|
+
}
|
|
50
|
+
} catch { return { authenticated: false, pending: false, error: '无法读取本机凭据' } }
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* 当前环境的共序账号信息:昵称与头像。
|
|
54
|
+
*
|
|
55
|
+
* 侧边栏底部的登录入口要用它来显示「是谁登录着」。
|
|
56
|
+
* 走 MCP 凭据换来的账号令牌读 /api/me,结果缓存一分钟——
|
|
57
|
+
* 这个界面会反复刷新,不该每次都去问服务端。
|
|
58
|
+
*/
|
|
59
|
+
async account() {
|
|
60
|
+
const name = this.selected(), origin = this.selectedEnvironment(name).origin
|
|
61
|
+
if (!await this.token(name)) return { ok: true, environment: name, origin, authenticated: false, account: null }
|
|
62
|
+
const key = `${name}|${origin}`
|
|
63
|
+
const cached = this.accountCache
|
|
64
|
+
if (cached && cached.key === key && Date.now() - cached.at < 60000) return { ok: true, ...cached.value }
|
|
65
|
+
try {
|
|
66
|
+
const token = await this.mcpToken()
|
|
67
|
+
if (!token) return { ok: true, environment: name, origin, authenticated: false, account: null }
|
|
68
|
+
const response = await fetch(new URL('/api/me', origin), {
|
|
69
|
+
headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(10000),
|
|
70
|
+
})
|
|
71
|
+
if (!response.ok) throw new Error(`读取账号信息失败(HTTP ${response.status})`)
|
|
72
|
+
const profile = await response.json()
|
|
73
|
+
const avatar = typeof profile?.avatar === 'string' ? profile.avatar : ''
|
|
74
|
+
const nickname = typeof profile?.name === 'string' && profile.name.trim() ? profile.name.trim() : (typeof profile?.username === 'string' ? profile.username : '')
|
|
75
|
+
const value = {
|
|
76
|
+
environment: name, origin, authenticated: true,
|
|
77
|
+
account: {
|
|
78
|
+
id: typeof profile?.id === 'string' ? profile.id : '',
|
|
79
|
+
name: nickname,
|
|
80
|
+
username: typeof profile?.username === 'string' ? profile.username : '',
|
|
81
|
+
motto: typeof profile?.motto === 'string' ? profile.motto : '',
|
|
82
|
+
avatar: avatar.startsWith('/') ? origin + avatar : avatar,
|
|
83
|
+
},
|
|
84
|
+
}
|
|
85
|
+
this.accountCache = { key, at: Date.now(), value }
|
|
86
|
+
return { ok: true, ...value }
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return { ok: false, message: error && error.message ? error.message : '读取共序账号信息失败' }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
async authorize() {
|
|
92
|
+
if (this.pending || this.starting || this.disconnecting) return { ok: false, message: '已有授权请求正在进行' }
|
|
93
|
+
const name = this.selected(), selectedEnv = this.selectedEnvironment(name)
|
|
94
|
+
const generation = ++this.authGeneration
|
|
95
|
+
this.starting = true
|
|
96
|
+
try {
|
|
97
|
+
// 设备身份要稳定,服务端按 device_id 认设备;版本号从 package.json 读,别写死。
|
|
98
|
+
const deviceId = await readDeviceId()
|
|
99
|
+
const version = await pluginVersion()
|
|
100
|
+
const flow = await startAuthorization(selectedEnv.origin, { deviceId, version })
|
|
101
|
+
if (this.disposed || generation !== this.authGeneration || (this.selected() !== name || this.selectedEnvironment().origin !== selectedEnv.origin)) { flow.cancel(); return { ok: false, message: '环境已变更,请重新授权' } }
|
|
102
|
+
this.pending = flow; this.error = ''
|
|
103
|
+
flow.result.then(({ token, deviceId: grantedDeviceId, executorId }) => {
|
|
104
|
+
this.authWrite = this.authWrite.then(async () => {
|
|
105
|
+
if (this.disposed || generation !== this.authGeneration) return
|
|
106
|
+
// 设备身份落盘:服务端按 device_id 认设备,下次授权要复用同一个。
|
|
107
|
+
await saveDeviceIdentity({ deviceId: grantedDeviceId, executorId }).catch(() => {})
|
|
108
|
+
await this.ctx.credentials.set(keyFor(selectedEnv), token)
|
|
109
|
+
if (!this.disposed && generation === this.authGeneration && this.selected() === name && this.selectedEnvironment().origin === selectedEnv.origin) {
|
|
110
|
+
const result = await this.refreshProjects()
|
|
111
|
+
if (!result.ok) this.error = result.message || '自动获取项目列表失败,请手动刷新'
|
|
112
|
+
await this.reconnect()
|
|
113
|
+
await this.maintainAutomations()
|
|
114
|
+
}
|
|
115
|
+
})
|
|
116
|
+
return this.authWrite
|
|
117
|
+
}).catch(error => { if (generation === this.authGeneration) this.error = error?.message || '授权未完成,请重新尝试' }).finally(() => { if (this.pending === flow) this.pending = null })
|
|
118
|
+
return { ok: true, url: flow.url }
|
|
119
|
+
} catch { this.error = '无法发起授权,请检查服务是否可访问'; return { ok: false, message: this.error } } finally { this.starting = false }
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* 取消进行中的授权。
|
|
123
|
+
*
|
|
124
|
+
* 浏览器授权页被关掉时,回环回调永远不会来,插件只能等到超时;
|
|
125
|
+
* 期间它一直占着「已有授权请求正在进行」,连换个环境重新授权都做不到。
|
|
126
|
+
* 所以给用户一个明确的取消出口。
|
|
127
|
+
*/
|
|
128
|
+
async cancelAuthorization() {
|
|
129
|
+
const flow = this.pending
|
|
130
|
+
if (!flow) return { ok: true, message: '当前没有进行中的授权' }
|
|
131
|
+
this.pending = null
|
|
132
|
+
try { flow.cancel() } catch { /* 已经结束了就算了 */ }
|
|
133
|
+
this.error = '已取消授权'
|
|
134
|
+
return { ok: true, message: '已取消授权' }
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* 环境被改掉时的善后。
|
|
138
|
+
*
|
|
139
|
+
* 正常路径是界面拦着不让切;万一配置从别处被改了(旧版本留下的、
|
|
140
|
+
* 或者别的插件改了同一个命名空间),旧环境的凭据就会留着,
|
|
141
|
+
* 自动化任务也会认错环境。这里把旧环境的凭据清掉。
|
|
142
|
+
*/
|
|
143
|
+
async handleEnvironmentChange(previous) {
|
|
144
|
+
try {
|
|
145
|
+
if (!previous || !previous.name) return { ok: true, cleared: false }
|
|
146
|
+
const now = this.selected()
|
|
147
|
+
const currentOrigin = this.selectedEnvironment(now).origin
|
|
148
|
+
// 传入的是切换前的环境;只有它跟现在确实不同,才需要清理。
|
|
149
|
+
if (previous.name === now && previous.origin === currentOrigin) return { ok: true, cleared: false }
|
|
150
|
+
// 环境要换了,旧环境的授权请求也就没意义了:把它取消掉。
|
|
151
|
+
// 不取消的话它会一直占着「已有授权请求正在进行」,新环境连授权都发不起。
|
|
152
|
+
const pendingFlow = this.pending
|
|
153
|
+
if (pendingFlow) { this.pending = null; try { pendingFlow.cancel() } catch { /* 已经结束了就算了 */ } }
|
|
154
|
+
// 环境变了:旧环境若还登录着,把它的凭据清掉。
|
|
155
|
+
const oldEnv = environment(previous.name)
|
|
156
|
+
await this.ctx.credentials.unset(keyFor(oldEnv)).catch(() => {})
|
|
157
|
+
this.accountCache = null
|
|
158
|
+
this.cursors = new Map()
|
|
159
|
+
this.pollScope = ''
|
|
160
|
+
this.automations = []
|
|
161
|
+
this.automationTasks = new Map()
|
|
162
|
+
this.error = '环境已切换,请重新授权登录'
|
|
163
|
+
return { ok: true, cleared: true, previous: previous.name, current: now }
|
|
164
|
+
} catch (error) {
|
|
165
|
+
return { ok: false, message: error && error.message ? error.message : '切换环境时清理旧凭据失败' }
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* 切换环境前先检查:当前环境还登录着的话,得先退出登录。
|
|
170
|
+
*
|
|
171
|
+
* 每个环境的凭据是分开的,没退出就换环境会让两个环境的凭据同时留着,
|
|
172
|
+
* 自动化任务也会认错环境,所以这里先拦一下。
|
|
173
|
+
*/
|
|
174
|
+
async planEnvironmentSwitch() {
|
|
175
|
+
try {
|
|
176
|
+
const name = this.selected()
|
|
177
|
+
const origin = this.selectedEnvironment(name).origin
|
|
178
|
+
const authenticated = Boolean(await this.token(name))
|
|
179
|
+
const rows = this.configuredRows()
|
|
180
|
+
const listed = await this.projects()
|
|
181
|
+
const projects = listed.ok ? listed.projects : []
|
|
182
|
+
return {
|
|
183
|
+
ok: true,
|
|
184
|
+
environment: name,
|
|
185
|
+
origin,
|
|
186
|
+
authenticated,
|
|
187
|
+
hasProjects: rows.length > 0,
|
|
188
|
+
projectCount: rows.length,
|
|
189
|
+
projects: rows.map(row => {
|
|
190
|
+
const match = projects.find(item => item.id === row.projectId)
|
|
191
|
+
return { projectId: row.projectId, name: match ? match.name : '', workspaceId: row.workspaceId || '' }
|
|
192
|
+
}),
|
|
193
|
+
}
|
|
194
|
+
} catch (error) {
|
|
195
|
+
return { ok: false, message: error && error.message ? error.message : '无法读取当前环境状态' }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* 退出登录前先看当前环境还留着哪些项目。
|
|
200
|
+
* 有项目就不能退出:这些项目还挂着自动化任务和会话,退出后它们会失去凭据继续跑。
|
|
201
|
+
*/
|
|
202
|
+
async planDisconnect() {
|
|
203
|
+
try {
|
|
204
|
+
const rows = this.configuredRows()
|
|
205
|
+
const listed = await this.projects()
|
|
206
|
+
const projects = listed.ok ? listed.projects : []
|
|
207
|
+
const names = rows.map(row => {
|
|
208
|
+
const match = projects.find(item => item.id === row.projectId)
|
|
209
|
+
return { projectId: row.projectId, name: match ? match.name : '', workspaceId: row.workspaceId || '' }
|
|
210
|
+
})
|
|
211
|
+
return { ok: true, hasProjects: rows.length > 0, count: rows.length, projects: names }
|
|
212
|
+
} catch (error) {
|
|
213
|
+
return { ok: false, message: error && error.message ? error.message : '无法读取项目配置' }
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
async disconnect() {
|
|
217
|
+
// 还有项目时先拦下来:请先删除项目,再退出登录。
|
|
218
|
+
const plan = await this.planDisconnect()
|
|
219
|
+
if (!plan.ok) return { ok: false, message: plan.message || '无法检查项目配置' }
|
|
220
|
+
if (plan.hasProjects) {
|
|
221
|
+
return { ok: false, message: '当前环境还有项目,请先删除全部项目再退出登录', projects: plan.projects }
|
|
222
|
+
}
|
|
223
|
+
this.disconnecting = true
|
|
224
|
+
++this.authGeneration
|
|
225
|
+
if (this.pending) { this.pending.cancel(); this.pending = null }
|
|
226
|
+
try {
|
|
227
|
+
await this.authWrite.catch(() => {})
|
|
228
|
+
await this.ctx.credentials.unset(keyFor(this.selectedEnvironment()))
|
|
229
|
+
this.accountCache = null
|
|
230
|
+
await this.reconnect()
|
|
231
|
+
return { ok: true }
|
|
232
|
+
} finally { this.disconnecting = false }
|
|
233
|
+
}
|
|
234
|
+
projectCacheFile(origin, token) {
|
|
235
|
+
const hash = createHash('sha256').update(origin).update('\0').update(token).digest('hex')
|
|
236
|
+
return resolve(process.env.DSH_HOME || resolve(homedir(), '.dsh'), 'plugins', 'dsh-cothread-mcp', 'projects', `${hash}.json`)
|
|
237
|
+
}
|
|
238
|
+
async projectContext() {
|
|
239
|
+
const name = this.selected(), selectedEnv = this.selectedEnvironment(name), token = await this.token(name)
|
|
240
|
+
if (this.selected() !== name || this.selectedEnvironment().origin !== selectedEnv.origin) throw new Error('环境已变更,请重试')
|
|
241
|
+
if (!token) throw new Error('请先授权登录')
|
|
242
|
+
return { name, origin: selectedEnv.origin, token, file: this.projectCacheFile(selectedEnv.origin, token) }
|
|
243
|
+
}
|
|
244
|
+
async projects() {
|
|
245
|
+
try {
|
|
246
|
+
const context = await this.projectContext()
|
|
247
|
+
let projects
|
|
248
|
+
try { projects = JSON.parse(await readFile(context.file, 'utf8')) } catch (error) {
|
|
249
|
+
if (error.code === 'ENOENT') return { ok: true, projects: [], cached: false }
|
|
250
|
+
throw error
|
|
251
|
+
}
|
|
252
|
+
if (!Array.isArray(projects)) throw new Error('本地项目列表格式无效,请重新获取')
|
|
253
|
+
if (this.selected() !== context.name || this.selectedEnvironment().origin !== context.origin) return { ok: false, message: '环境已变更,请重试' }
|
|
254
|
+
return { ok: true, projects, cached: true }
|
|
255
|
+
} catch (error) { return { ok: false, message: error.message || '无法读取本地项目列表' } }
|
|
256
|
+
}
|
|
257
|
+
async refreshProjects() {
|
|
258
|
+
let temp
|
|
259
|
+
try {
|
|
260
|
+
const context = await this.projectContext()
|
|
261
|
+
const res = await fetch(new URL('/api/local-executor/projects', context.origin), { headers: { authorization: `Bearer ${context.token}` }, signal: AbortSignal.timeout(10000) })
|
|
262
|
+
if (!res.ok) return { ok: false, message: `项目列表获取失败(HTTP ${res.status})` }
|
|
263
|
+
const data = await res.json()
|
|
264
|
+
if (!Array.isArray(data)) throw new Error('项目列表格式无效')
|
|
265
|
+
const projects = data.map(({ id, name, role }) => ({ id, name, role }))
|
|
266
|
+
if (this.selected() !== context.name || this.selectedEnvironment().origin !== context.origin || await this.token(context.name) !== context.token) return { ok: false, message: '环境或授权已变更,请重试' }
|
|
267
|
+
await mkdir(resolve(context.file, '..'), { recursive: true, mode: 0o700 })
|
|
268
|
+
temp = `${context.file}.${randomUUID()}.tmp`
|
|
269
|
+
await writeFile(temp, JSON.stringify(projects), { mode: 0o600 })
|
|
270
|
+
await rename(temp, context.file)
|
|
271
|
+
this.projectRevision++
|
|
272
|
+
return { ok: true, projects, cached: true }
|
|
273
|
+
} catch (error) { return { ok: false, message: error.message || '无法获取项目列表' } }
|
|
274
|
+
finally { if (temp) await unlink(temp).catch(() => {}) }
|
|
275
|
+
}
|
|
276
|
+
async localWorkspaces() {
|
|
277
|
+
try {
|
|
278
|
+
const registry = serviceOf(this.ctx, 'workspaceRegistry')
|
|
279
|
+
if (!registry || typeof registry.list !== 'function') return { ok: false, message: '当前 DSH 未提供工作区列表' }
|
|
280
|
+
const workspaces = registry.list().map(({ id, title, path }) => ({ id: String(id), title: String(title), path: String(path) }))
|
|
281
|
+
return { ok: true, workspaces }
|
|
282
|
+
} catch { return { ok: false, message: '无法读取 DSH 工作区' } }
|
|
283
|
+
}
|
|
284
|
+
async mcpToken() {
|
|
285
|
+
const name = this.selected(), selectedEnv = this.selectedEnvironment(name), token = await this.token(name)
|
|
286
|
+
if (this.selected() !== name || this.selectedEnvironment().origin !== selectedEnv.origin) return undefined
|
|
287
|
+
return token ? (await getMcpCredential(selectedEnv.origin, token)).token : undefined
|
|
288
|
+
}
|
|
289
|
+
async mcp(name, args, envName, token, origin = this.selectedEnvironment(envName).origin) {
|
|
290
|
+
const response = await fetch(new URL('/mcp', origin), {
|
|
291
|
+
method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-03-26' },
|
|
292
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), signal: AbortSignal.timeout(10000),
|
|
293
|
+
})
|
|
294
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
295
|
+
const result = await response.json()
|
|
296
|
+
if (result.error || result.result?.isError) throw new Error('MCP 请求失败')
|
|
297
|
+
const text = result.result?.content?.find(item => item.type === 'text')?.text
|
|
298
|
+
if (!text) throw new Error('MCP 响应为空')
|
|
299
|
+
return JSON.parse(text)
|
|
300
|
+
}
|
|
301
|
+
/** 已配置并启用的项目行,值统一取当前环境的实际内容。 */
|
|
302
|
+
configuredRows() {
|
|
303
|
+
const envName = this.selected(), origin = this.selectedEnvironment().origin
|
|
304
|
+
const configured = value(this.config.workspaces)
|
|
305
|
+
const rows = Array.isArray(configured) ? configured : []
|
|
306
|
+
return rows.map(row => Object.fromEntries(Object.entries(row || {}).map(([key, entry]) => [key, value(entry)])))
|
|
307
|
+
.filter(row => row.environment === envName && row.receiveMessages === true && row.projectId && row.workspaceId)
|
|
308
|
+
}
|
|
309
|
+
selectedProjects() {
|
|
310
|
+
const envName = this.selected(), configured = value(this.config.workspaces)
|
|
311
|
+
const entries = Array.isArray(configured) && configured.length ? configured : value(this.config.projectId) ? [{ environment: envName, projectId: value(this.config.projectId), receiveMessages: value(this.config.receiveMessages) }] : []
|
|
312
|
+
return [...new Set(entries.filter(row => row && value(row.environment) === envName && value(row.receiveMessages) === true).map(row => value(row.projectId)).filter(Boolean))]
|
|
313
|
+
}
|
|
314
|
+
/** 同步自动化任务:让每个已配置的项目都对应一个原生自动化任务。 */
|
|
315
|
+
async syncAutomations() {
|
|
316
|
+
try {
|
|
317
|
+
const context = await this.projectContext()
|
|
318
|
+
const rows = this.configuredRows()
|
|
319
|
+
const projectList = await this.projects()
|
|
320
|
+
const projectNames = new Map((projectList.ok ? projectList.projects : []).map(project => [project.id, project.name]))
|
|
321
|
+
const serverName = value(this.config.serverName) || 'cothread-mcp'
|
|
322
|
+
const result = await syncAutomations(this.ctx, {
|
|
323
|
+
rows,
|
|
324
|
+
projectNames,
|
|
325
|
+
origin: context.origin,
|
|
326
|
+
serverName,
|
|
327
|
+
intervalSeconds: value(this.config.intervalSeconds) || DEFAULT_INTERVAL_SECONDS,
|
|
328
|
+
promptFor: (row, meta) => this.promptFor(row, projectNames, serverName, meta),
|
|
329
|
+
})
|
|
330
|
+
this.automations = result.tasks
|
|
331
|
+
this.automationTasks = new Map(result.tasks.map(task => [task.key, task.id]))
|
|
332
|
+
this.automationError = result.ok ? '' : result.message || '自动化任务同步失败'
|
|
333
|
+
return result
|
|
334
|
+
} catch (error) {
|
|
335
|
+
const message = error.message || '自动化任务同步失败'
|
|
336
|
+
this.automationError = message === '请先授权登录' ? '' : message
|
|
337
|
+
return { ok: false, message, created: 0, updated: 0, deleted: 0, kept: 0, tasks: [] }
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
/** 把客户端传来的项目行整理成插件内部使用的形状。 */
|
|
341
|
+
normalizeRow(row) {
|
|
342
|
+
const source = row && typeof row === 'object' ? row : {}
|
|
343
|
+
return {
|
|
344
|
+
environment: String(source.environment || 'production'),
|
|
345
|
+
projectId: String(source.projectId || ''),
|
|
346
|
+
workspaceId: String(source.workspaceId || ''),
|
|
347
|
+
workspace: String(source.workspace || ''),
|
|
348
|
+
mentionAction: safeAction(source.mentionAction || source.action),
|
|
349
|
+
taskAction: safeAction(source.taskAction || source.action),
|
|
350
|
+
receiveMessages: true,
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** 这一行所属环境的服务地址。 */
|
|
355
|
+
rowOrigin(row) {
|
|
356
|
+
try {
|
|
357
|
+
return environment(row.environment || this.selected()).origin
|
|
358
|
+
} catch { return '' }
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** 记住刚保存的项目与它的自动化任务。 */
|
|
362
|
+
trackAutomation(result) {
|
|
363
|
+
const list = (this.automations || []).filter(item => item.key !== result.key)
|
|
364
|
+
list.push({
|
|
365
|
+
key: result.key,
|
|
366
|
+
id: result.taskId,
|
|
367
|
+
title: result.title,
|
|
368
|
+
projectId: result.row.projectId,
|
|
369
|
+
workspaceId: result.row.workspaceId,
|
|
370
|
+
sessionId: result.sessionId || '',
|
|
371
|
+
sessionName: result.sessionName || '',
|
|
372
|
+
})
|
|
373
|
+
this.automations = list
|
|
374
|
+
this.automationTasks = new Map(list.map(task => [task.key, task.id]))
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** 忘掉已经删掉的项目。 */
|
|
378
|
+
forgetAutomation(result) {
|
|
379
|
+
this.automations = (this.automations || []).filter(item => item.key !== result.key)
|
|
380
|
+
this.automationTasks = new Map(this.automations.map(task => [task.key, task.id]))
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** 保存一个项目行:没有自动化任务就新建,有就更新。 */
|
|
384
|
+
async saveRow(row) {
|
|
385
|
+
try {
|
|
386
|
+
const normalized = this.normalizeRow(row)
|
|
387
|
+
if (!normalized.projectId) return { ok: false, message: '请先选择项目' }
|
|
388
|
+
if (!normalized.workspaceId) return { ok: false, message: '请先选择关联工作区' }
|
|
389
|
+
const origin = this.rowOrigin(normalized)
|
|
390
|
+
if (!origin) return { ok: false, message: '当前环境地址无效,请先修正环境设置' }
|
|
391
|
+
const projectList = await this.projects()
|
|
392
|
+
const projectNames = new Map((projectList.ok ? projectList.projects : []).map(project => [project.id, project.name]))
|
|
393
|
+
const serverName = value(this.config.serverName) || 'cothread-mcp'
|
|
394
|
+
const prompt = await this.promptFor(normalized, projectNames, serverName)
|
|
395
|
+
const result = await saveAutomation(this.ctx, {
|
|
396
|
+
row: normalized,
|
|
397
|
+
origin,
|
|
398
|
+
projectName: projectNames.get(normalized.projectId) || '',
|
|
399
|
+
intervalSeconds: value(this.config.intervalSeconds) || DEFAULT_INTERVAL_SECONDS,
|
|
400
|
+
prompt,
|
|
401
|
+
})
|
|
402
|
+
if (!result.ok) return { ok: false, message: result.message || '保存失败' }
|
|
403
|
+
this.trackAutomation(result)
|
|
404
|
+
return {
|
|
405
|
+
ok: true,
|
|
406
|
+
created: result.created,
|
|
407
|
+
updated: result.updated,
|
|
408
|
+
deleted: result.deleted,
|
|
409
|
+
taskId: result.taskId,
|
|
410
|
+
sessionId: result.sessionId,
|
|
411
|
+
title: result.title,
|
|
412
|
+
message: result.created ? '已新建自动化任务' : '已更新自动化任务',
|
|
413
|
+
}
|
|
414
|
+
} catch (error) {
|
|
415
|
+
return { ok: false, message: error && error.message ? error.message : '保存失败' }
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** 看看删除一个项目行会牵动哪些自动化任务与会话,只读不改。 */
|
|
420
|
+
async planRemoval(row) {
|
|
421
|
+
try {
|
|
422
|
+
const normalized = this.normalizeRow(row)
|
|
423
|
+
const origin = this.rowOrigin(normalized)
|
|
424
|
+
const projectList = await this.projects()
|
|
425
|
+
const projectNames = new Map((projectList.ok ? projectList.projects : []).map(project => [project.id, project.name]))
|
|
426
|
+
const plan = await planAutomationRemoval(this.ctx, { row: normalized, origin, projectName: projectNames.get(normalized.projectId) || '' })
|
|
427
|
+
if (!plan.ok) return { ok: false, message: plan.message || '无法检查自动化任务' }
|
|
428
|
+
return plan
|
|
429
|
+
} catch (error) {
|
|
430
|
+
return { ok: false, message: error && error.message ? error.message : '无法检查自动化任务' }
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** 删除一个项目行:结束它的自动化任务,并归档它的自动化会话。 */
|
|
435
|
+
async removeRow(row, sessionId) {
|
|
436
|
+
try {
|
|
437
|
+
const normalized = this.normalizeRow(row)
|
|
438
|
+
const origin = this.rowOrigin(normalized)
|
|
439
|
+
const projectList = await this.projects()
|
|
440
|
+
const projectNames = new Map((projectList.ok ? projectList.projects : []).map(project => [project.id, project.name]))
|
|
441
|
+
const result = await removeAutomation(this.ctx, {
|
|
442
|
+
row: normalized,
|
|
443
|
+
origin,
|
|
444
|
+
projectName: projectNames.get(normalized.projectId) || '',
|
|
445
|
+
sessionId: String(sessionId || ''),
|
|
446
|
+
})
|
|
447
|
+
if (!result.ok) return { ok: false, message: result.message || '删除失败' }
|
|
448
|
+
this.forgetAutomation(result)
|
|
449
|
+
return {
|
|
450
|
+
ok: true,
|
|
451
|
+
deleted: result.deleted,
|
|
452
|
+
archived: result.archived,
|
|
453
|
+
archivedSessionId: result.archivedSessionId,
|
|
454
|
+
archiveError: result.archiveError,
|
|
455
|
+
archiveMissing: result.archiveMissing,
|
|
456
|
+
taskId: result.taskId,
|
|
457
|
+
sessionId: result.sessionId,
|
|
458
|
+
message: result.deleted ? '自动化任务已结束' : '没有找到自动化任务',
|
|
459
|
+
}
|
|
460
|
+
} catch (error) {
|
|
461
|
+
return { ok: false, message: error && error.message ? error.message : '删除失败' }
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** 立刻唤醒某个项目的自动化任务,让它马上检查共序消息。 */
|
|
466
|
+
async triggerAutomation(key) {
|
|
467
|
+
const id = this.automationTasks.get(key)
|
|
468
|
+
if (!id) return false
|
|
469
|
+
const schedule = serviceOf(this.ctx, 'schedule')
|
|
470
|
+
if (!schedule || typeof schedule.runNow !== 'function') return false
|
|
471
|
+
try {
|
|
472
|
+
const result = await schedule.runNow(id)
|
|
473
|
+
return Boolean(result && result.admitted)
|
|
474
|
+
} catch { return false }
|
|
475
|
+
}
|
|
476
|
+
/** 按项目算好本轮范围(会话、消息起点、待处理清单),拼成任务内容。 */
|
|
477
|
+
async promptFor(row, projectNames, serverName) {
|
|
478
|
+
const state = await readState(this.ctx, row.projectId).catch(() => null)
|
|
479
|
+
const pending = (state && state.pending) || null
|
|
480
|
+
return buildPrompt({
|
|
481
|
+
projectName: projectNames.get(row.projectId),
|
|
482
|
+
projectId: row.projectId,
|
|
483
|
+
serverName,
|
|
484
|
+
mentionAction: resolveAction(row, 'mention'),
|
|
485
|
+
taskAction: resolveAction(row, 'task'),
|
|
486
|
+
threadId: pending ? pending.threadId : '',
|
|
487
|
+
afterMessageId: pending ? pending.cursor : '',
|
|
488
|
+
messageIds: pending ? pending.messageIds : [],
|
|
489
|
+
taskIds: pending ? pending.taskIds : [],
|
|
490
|
+
})
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** 更新某个项目的自动化任务内容(不改标题和间隔)。 */
|
|
494
|
+
async applyPrompt(key, prompt) {
|
|
495
|
+
const id = this.automationTasks.get(key)
|
|
496
|
+
if (!id) return false
|
|
497
|
+
const schedule = serviceOf(this.ctx, 'schedule')
|
|
498
|
+
if (!schedule || typeof schedule.edit !== 'function') return false
|
|
499
|
+
try {
|
|
500
|
+
await schedule.edit({ id, action: 'update', patch: { prompt } })
|
|
501
|
+
return true
|
|
502
|
+
} catch { return false }
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** 任务最后一次投递的时间,用来判断上一轮是否已经送达。 */
|
|
506
|
+
async lastDeliveryAt(id) {
|
|
507
|
+
const schedule = serviceOf(this.ctx, 'schedule')
|
|
508
|
+
if (!schedule || typeof schedule.list !== 'function') return ''
|
|
509
|
+
try {
|
|
510
|
+
const page = await schedule.list({ limit: 500 })
|
|
511
|
+
const items = Array.isArray(page && page.items) ? page.items : []
|
|
512
|
+
const task = items.find(item => item.id === id)
|
|
513
|
+
return (task && task.lastDelivery && task.lastDelivery.deliveredAt) || ''
|
|
514
|
+
} catch { return '' }
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/** 巡检一个项目:算出新内容、写进任务内容、推进游标,并尝试立即触发。 */
|
|
518
|
+
async pollProject(row, envName, token, scope) {
|
|
519
|
+
const projectId = row.projectId
|
|
520
|
+
const key = automationKey(row, scope)
|
|
521
|
+
const taskId = this.automationTasks.get(key)
|
|
522
|
+
let context
|
|
523
|
+
try {
|
|
524
|
+
context = await this.mcp('get_project_context', { projectId }, envName, token, scope)
|
|
525
|
+
} catch (error) { this.lastPollError = 'ctx: ' + (error && error.message); return false }
|
|
526
|
+
const threads = Array.isArray(context.threads) ? context.threads : []
|
|
527
|
+
const thread = threads.find(item => item && item.status === 'active' && item.id)
|
|
528
|
+
if (!thread) return false
|
|
529
|
+
const state = await readState(this.ctx, projectId).catch(() => ({ initialized: false, cursor: '', pending: null, tasks: {} }))
|
|
530
|
+
const cursor = state.cursor || ''
|
|
531
|
+
let messages = []
|
|
532
|
+
let nextCursor = ''
|
|
533
|
+
try {
|
|
534
|
+
const data = await this.mcp('list_messages', { threadId: thread.id, limit: 100, ...(cursor ? { afterMessageId: cursor } : {}) }, envName, token, scope)
|
|
535
|
+
messages = Array.isArray(data.messages) ? data.messages : []
|
|
536
|
+
nextCursor = (data.page && data.page.afterMessageId) || (messages.at(-1) && messages.at(-1).id) || ''
|
|
537
|
+
} catch (error) { this.lastPollError = 'msg: ' + (error && error.message); return false }
|
|
538
|
+
// 第一次巡检只记住位置,不把历史消息当成新内容报一遍。
|
|
539
|
+
if (!state.initialized) {
|
|
540
|
+
const last = messages.at(-1)
|
|
541
|
+
await writeState(this.ctx, projectId, { ...state, initialized: true, cursor: nextCursor || (last && last.id) || '' }).catch(() => {})
|
|
542
|
+
return false
|
|
543
|
+
}
|
|
544
|
+
// 上一轮已经写进任务内容并且投递出去了,就清空它,避免重复复述。
|
|
545
|
+
if (state.pending && taskId) {
|
|
546
|
+
const deliveredAt = await this.lastDeliveryAt(taskId)
|
|
547
|
+
if (deliveredAt && state.pending.patchedAt && deliveredAt > state.pending.patchedAt) {
|
|
548
|
+
state.pending = null
|
|
549
|
+
await writeState(this.ctx, projectId, state).catch(() => {})
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (state.pending) {
|
|
553
|
+
// 上一轮还没送达:保持任务内容不变,再试一次触发。
|
|
554
|
+
await this.applyPrompt(key, await this.promptFor(row, new Map([[projectId, row.projectName || projectId]]), value(this.config.serverName) || 'cothread-mcp'))
|
|
555
|
+
await this.triggerAutomation(key)
|
|
556
|
+
return true
|
|
557
|
+
}
|
|
558
|
+
let tasks = []
|
|
559
|
+
try {
|
|
560
|
+
const listed = await this.mcp('list_tasks', { projectId }, envName, token, scope)
|
|
561
|
+
tasks = Array.isArray(listed) ? listed : []
|
|
562
|
+
} catch { tasks = [] }
|
|
563
|
+
const pendingTasks = tasks.filter(task => isPendingTask(task) && (!task.origin_thread_id || task.origin_thread_id === thread.id))
|
|
564
|
+
const fresh = pendingTasks.filter(task => {
|
|
565
|
+
const seen = state.tasks ? state.tasks[task.id] : undefined
|
|
566
|
+
return !seen || seen.revision !== task.revision || seen.updatedAt !== task.updated_at
|
|
567
|
+
})
|
|
568
|
+
const messageIds = messages.map(message => message && message.id).filter(id => id && id !== cursor)
|
|
569
|
+
if (!messageIds.length && !fresh.length) return false
|
|
570
|
+
const pending = { cursor, threadId: thread.id, messageIds, taskIds: fresh.map(task => task.id), patchedAt: new Date().toISOString() }
|
|
571
|
+
const prompt = buildPrompt({
|
|
572
|
+
projectName: row.projectName || projectId,
|
|
573
|
+
projectId,
|
|
574
|
+
serverName: value(this.config.serverName) || 'cothread-mcp',
|
|
575
|
+
mentionAction: resolveAction(row, 'mention'),
|
|
576
|
+
taskAction: resolveAction(row, 'task'),
|
|
577
|
+
threadId: thread.id,
|
|
578
|
+
afterMessageId: cursor,
|
|
579
|
+
messageIds,
|
|
580
|
+
taskIds: pending.taskIds,
|
|
581
|
+
})
|
|
582
|
+
await this.applyPrompt(key, prompt)
|
|
583
|
+
const next = { ...state, initialized: true, cursor: nextCursor || messageIds.at(-1) || cursor, pending }
|
|
584
|
+
for (const task of fresh) next.tasks[task.id] = { revision: task.revision, updatedAt: task.updated_at, reportedAt: new Date().toISOString() }
|
|
585
|
+
await writeState(this.ctx, projectId, next).catch(() => {})
|
|
586
|
+
await this.triggerAutomation(key)
|
|
587
|
+
return true
|
|
588
|
+
}
|
|
589
|
+
async poll() {
|
|
590
|
+
if (this.polling || this.disposed) return
|
|
591
|
+
const envName = this.selected(), projects = this.selectedProjects()
|
|
592
|
+
if (!projects.length) return
|
|
593
|
+
let scope
|
|
594
|
+
try { scope = this.selectedEnvironment(envName).origin } catch { this.pollError = '请填写有效的自定义环境地址'; return }
|
|
595
|
+
if (this.pollScope !== scope) { this.pollScope = scope }
|
|
596
|
+
this.polling = true
|
|
597
|
+
try {
|
|
598
|
+
const token = await this.mcpToken()
|
|
599
|
+
if (!token) { this.lastPollError = '没有 MCP 凭据'; return }
|
|
600
|
+
this.lastPollError = ''
|
|
601
|
+
const rows = this.configuredRows()
|
|
602
|
+
const projectList = await this.projects()
|
|
603
|
+
const names = new Map((projectList.ok ? projectList.projects : []).map(project => [project.id, project.name]))
|
|
604
|
+
let failures = 0
|
|
605
|
+
for (const row of rows) {
|
|
606
|
+
if (this.disposed || !this.selectedProjects().includes(row.projectId)) continue
|
|
607
|
+
try {
|
|
608
|
+
await this.pollProject({ ...row, projectName: names.get(row.projectId) || row.projectId }, envName, token, scope)
|
|
609
|
+
} catch { failures++ }
|
|
610
|
+
}
|
|
611
|
+
this.pollError = failures ? '部分项目消息检查失败,将在下次重试' : ''
|
|
612
|
+
if (failures) this.lastPollError = '部分项目巡检失败'
|
|
613
|
+
} catch (error) { this.pollError = '消息检查失败,将在下次重试'; this.lastPollError = 'poll: ' + (error && error.message) } finally { this.polling = false }
|
|
614
|
+
}
|
|
615
|
+
async maintainAutomations() {
|
|
616
|
+
if (this.disposed || this.syncing) return
|
|
617
|
+
this.syncing = true
|
|
618
|
+
try {
|
|
619
|
+
if (!this.configuredRows().length) { this.automationError = ''; this.automations = []; this.automationTasks = new Map(); return }
|
|
620
|
+
await this.syncAutomations()
|
|
621
|
+
} catch (error) { this.automationError = `自动化任务同步失败:${error.message || '请重试'}` }
|
|
622
|
+
finally { this.syncing = false }
|
|
623
|
+
}
|
|
624
|
+
start() {
|
|
625
|
+
// 维护任务与巡检串行执行:两者共用同一个轮询标志,并发调用会互相吞掉。
|
|
626
|
+
const run = () => {
|
|
627
|
+
if (this.running || this.disposed) return
|
|
628
|
+
this.running = true
|
|
629
|
+
void (async () => {
|
|
630
|
+
try { await this.maintainAutomations(); await this.poll() } finally { this.running = false }
|
|
631
|
+
})()
|
|
632
|
+
}
|
|
633
|
+
run(); this.timer = setInterval(run, 15000); this.timer.unref?.()
|
|
634
|
+
}
|
|
635
|
+
dispose() { this.disposed = true; ++this.authGeneration; clearInterval(this.timer); this.pending?.cancel(); this.pending = null }
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
Object.defineProperty(CothreadService.prototype, '@deepseek-ai/dsh-typert-protocol/remote-methods', {
|
|
639
|
+
value: Object.freeze({ version: 1, methods: Object.freeze(['status', 'account', 'authorize', 'cancelAuthorization', 'disconnect', 'planDisconnect', 'planEnvironmentSwitch', 'projects', 'refreshProjects', 'localWorkspaces', 'syncAutomations', 'saveRow', 'planRemoval', 'removeRow'].map(method => Object.freeze({ method, invocation: Object.freeze({ kind: 'direct' }) }))) }),
|
|
640
|
+
})
|