返回 AiToEarn
index.js
1 // AiToEarn 全域内容运营助手 · DeepSeek Harness 插件
2 //
3 // Two responsibilities:
4 // 1. Register the bundled skills/ directory as a skill provider.
5 // 2. Own an OAuth-authenticated MCP connection to AiToEarn and register its
6 // tools on ctx.tools. Tokens come from ~/.aitoearn/oauth.json and are
7 // refreshed automatically; a fresh CLI login is picked up without restart.
8 import { existsSync, readdirSync, readFileSync } from 'node:fs'
9 import { dirname, join } from 'node:path'
10 import { fileURLToPath } from 'node:url'
11 import { createTokenProvider, McpAuthError, McpHttpClient } from './mcp.js'
12 import { storeMtimeMs, SITES, DEFAULT_MCP_PATH } from './oauth.js'
13 import { syncTools } from './tool-bridge.js'
14
15 const PROVIDER_NAME = 'aitoearn-plugin'
16 const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..')
17 const SKILLS_ROOT = join(PACKAGE_ROOT, 'skills')
18 const LOGIN_COMMAND = `node ${join(PACKAGE_ROOT, 'scripts', 'aitoearn.mjs')} login`
19 const RESYNC_INTERVAL_MS = 15_000
20
21 // 解析 SKILL.md 的 YAML frontmatter(覆盖本包用到的形态:单行值、>- / > 折叠块)
22 function parseFrontmatter(raw) {
23 const m = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
24 if (!m) return {}
25 const out = {}
26 let cur = null
27 for (const line of m[1].split(/\r?\n/)) {
28 const kv = line.match(/^([A-Za-z0-9_-]+):[ \t]*(.*)$/)
29 if (kv) {
30 cur = kv[1]
31 // A value like ">-" or "|" is a YAML block-scalar header; the real
32 // content follows on the indented continuation lines, so start empty.
33 out[cur] = /^[>|][+-]?[0-9]?$/.test(kv[2].trim()) ? '' : kv[2]
34 } else if (cur && /^[ \t]+\S/.test(line)) {
35 out[cur] = (out[cur] ? out[cur] + ' ' : '') + line.trim()
36 }
37 }
38 return out
39 }
40
41 function loadCandidates() {
42 const list = []
43 let dirs = []
44 try { dirs = readdirSync(SKILLS_ROOT) } catch { return list }
45 for (const dir of dirs) {
46 const file = join(SKILLS_ROOT, dir, 'SKILL.md')
47 if (!existsSync(file)) continue
48 let raw = ''
49 try { raw = readFileSync(file, 'utf8') } catch { continue }
50 const fm = parseFrontmatter(raw)
51 list.push({
52 name: fm.name || dir,
53 description: fm.description || '',
54 invocation: { modelInvocable: true, userInvocable: true },
55 provider: PROVIDER_NAME,
56 source: 'bundled',
57 resourceBase: { kind: 'directory', path: join(SKILLS_ROOT, dir) },
58 rank: 600,
59 locator: file,
60 })
61 }
62 return list
63 }
64
65 const provider = {
66 name: PROVIDER_NAME,
67 list: () => Promise.resolve(loadCandidates()),
68 async get(candidate) {
69 const name = candidate && candidate.name
70 const file = join(SKILLS_ROOT, name, 'SKILL.md')
71 const raw = readFileSync(file, 'utf8')
72 const fm = parseFrontmatter(raw)
73 return {
74 name,
75 description: fm.description || (candidate && candidate.description) || '',
76 invocation: { modelInvocable: true, userInvocable: true },
77 provider: PROVIDER_NAME,
78 source: 'bundled',
79 resourceBase: { kind: 'directory', path: join(SKILLS_ROOT, name) },
80 content: raw,
81 }
82 },
83 }
84
85 function resolveConfig(config) {
86 const raw = config && typeof config === 'object' ? config : {}
87 const explicitUrl = String(raw.url || process.env.AITOEARN_MCP_URL || '').trim()
88 const configuredSite = String(raw.site || process.env.AITOEARN_SITE || 'cn').trim().toLowerCase()
89 const site = SITES[configuredSite] ? configuredSite : 'cn'
90 return {
91 url: explicitUrl || `${SITES[site]}${DEFAULT_MCP_PATH}`,
92 serverName: String(raw.serverName || 'aitoearn'),
93 site,
94 }
95 }
96
97 async function startMcp(ctx, { url, serverName, site }) {
98 const log = (level, message) => {
99 const fn = ctx.logger?.[level]
100 if (typeof fn === 'function') fn.call(ctx.logger, message)
101 }
102 const loginHint = `${LOGIN_COMMAND} --site ${site}`
103
104 const client = new McpHttpClient({
105 url,
106 serverName,
107 tokenProvider: createTokenProvider(url),
108 })
109 let disposers = new Map()
110 let closed = false
111 let lastStoreMtime = storeMtimeMs()
112 let warnedAboutLogin = false
113
114 const sync = async (reason) => {
115 if (closed) return
116 try {
117 if (!client.initialized) await client.initialize()
118 const next = await syncTools(client, ctx, serverName, disposers)
119 if (closed) {
120 for (const dispose of next.values()) dispose()
121 return
122 }
123 disposers = next
124 if (disposers.size === 0) {
125 log('warn', `aitoearn(${serverName}): 未发现可用工具,请完成 OAuth 授权后重试(${loginHint})`)
126 } else {
127 log('info', `aitoearn(${serverName}): ${disposers.size} 个工具已就绪(${reason})`)
128 }
129 warnedAboutLogin = false
130 } catch (error) {
131 if (error instanceof McpAuthError) {
132 if (!warnedAboutLogin) {
133 warnedAboutLogin = true
134 log('warn', `aitoearn(${serverName}): OAuth 尚未授权或已过期。运行 ${loginHint}`)
135 }
136 } else {
137 log('error', `aitoearn(${serverName}): 连接 MCP 失败:${String(error?.message || error)}`)
138 }
139 }
140 }
141
142 ctx.effect(() => {
143 sync('startup')
144
145 const timer = setInterval(() => {
146 if (closed) return
147 const mtime = storeMtimeMs()
148 if (mtime === lastStoreMtime) return
149 lastStoreMtime = mtime
150 // A new login (or a refresh) changed the credential file: handshake
151 // again so an auth-scoped tool list replaces the anonymous one.
152 client.close().then(() => sync('oauth credentials updated'))
153 }, RESYNC_INTERVAL_MS)
154
155 return async () => {
156 closed = true
157 clearInterval(timer)
158 for (const dispose of disposers.values()) dispose()
159 disposers = new Map()
160 await client.close()
161 }
162 }, 'dsh-plugin-aitoearn.mcp')
163 }
164
165 /** Cordis 插件名(与 cordis.patch.yml 条目一致)。 */
166 const name = 'dsh-plugin-aitoearn'
167 /** 技能注册表与工具注册表服务。 */
168 const inject = ['skills', 'tools']
169
170 /** 注册技能提供方,并建立 OAuth 鉴权的 MCP 连接。 */
171 async function apply(ctx, config) {
172 ctx.skills.registerProvider(() => provider)
173 const resolved = resolveConfig(config)
174 if (!resolved.url) {
175 const log = ctx.logger?.warn
176 if (typeof log === 'function') {
177 log.call(ctx.logger, `aitoearn: 尚未连接国内站。运行 ${LOGIN_COMMAND} ,在 https://aitoearn.cn 完成授权。`)
178 }
179 return
180 }
181 await startMcp(ctx, resolved)
182 }
183
184 export { apply, inject, name }
185
185 lines JAVASCRIPT