@hit-sudomaker/ccw 0.4.0 → 0.5.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.
@@ -1,60 +0,0 @@
1
- import { cancelled, json, object, removeFields, sequence, unchanged } from './model.js';
2
- const OWNED_RULES = ['mcp__amirc__organize_papers', 'mcp__amirc__search_papers', 'mcp__amirc__get_papers'];
3
- function allowedTools(settings) {
4
- const allow = object(settings.permissions).allow;
5
- if (allow === undefined)
6
- return [];
7
- if (!Array.isArray(allow) || !allow.every((rule) => typeof rule === 'string'))
8
- throw new Error('invalid-settings');
9
- return allow;
10
- }
11
- export async function hasLegacyAmircPermissions(ctx) {
12
- return allowedTools(await json(ctx.machine, ctx.settingsFile)).some(rule => OWNED_RULES.includes(rule));
13
- }
14
- /** 退役迁移只解除明确选择的旧注册与精确允许规则,保留技能与用户材料 */
15
- export async function prepareLegacyAmircDetach(ctx) {
16
- const before = object((await json(ctx.machine, ctx.stateFile)).mcpServers);
17
- const allowBefore = allowedTools(await json(ctx.machine, ctx.settingsFile));
18
- if (before.amirc === undefined && !allowBefore.some(rule => OWNED_RULES.includes(rule)))
19
- throw new Error('no-connection');
20
- let hasAttemptedWrite = false;
21
- let isWritten = false;
22
- let isComplete = false;
23
- const selected = OWNED_RULES.filter(rule => allowBefore.includes(rule));
24
- const verify = async () => {
25
- const current = allowedTools(await json(ctx.machine, ctx.settingsFile));
26
- if (current.some(rule => OWNED_RULES.includes(rule)))
27
- throw new Error('target-changed');
28
- };
29
- const permissions = {
30
- writes: [ctx.settingsFile],
31
- get changes() {
32
- return [{ code: isWritten ? 'removal-confirm' : 'amirc-permissions-remove' }];
33
- },
34
- async run(report, signal) {
35
- cancelled(signal);
36
- const current = allowedTools(await json(ctx.machine, ctx.settingsFile));
37
- if (selected.length && !isWritten && (!hasAttemptedWrite || current.some(rule => OWNED_RULES.includes(rule)))) {
38
- await ctx.machine.editJson(ctx.settingsFile, settings => {
39
- const allow = allowedTools(settings);
40
- unchanged(OWNED_RULES.filter(rule => allow.includes(rule)), selected);
41
- settings.permissions = {
42
- ...object(settings.permissions),
43
- allow: allow.filter(rule => !selected.includes(rule)),
44
- };
45
- hasAttemptedWrite = true;
46
- });
47
- isWritten = true;
48
- }
49
- await verify();
50
- isComplete = true;
51
- report({ state: 'done', code: 'amirc-permissions-removed' });
52
- },
53
- remaining: () => (isComplete ? undefined : permissions),
54
- verify,
55
- };
56
- return sequence([
57
- removeFields(ctx, ctx.stateFile, { amirc: before.amirc }, [{ code: 'mcp-remove-registration', detail: 'amirc' }, { code: 'mcp-keep-runtime' }], { state: 'done', code: 'registration-removed', detail: 'amirc' }, 'mcpServers'),
58
- permissions,
59
- ]);
60
- }
package/dist/mcp.js DELETED
@@ -1,299 +0,0 @@
1
- import path from 'node:path';
2
- import { randomUUID } from 'node:crypto';
3
- import { knownTitle } from './titles.js';
4
- import { mcpSpecs } from './management-catalog.js';
5
- import { errorCode, isObject } from './machine.js';
6
- import { cancelled, editFields, json, object, removeFields, restOf, success, unchanged } from './model.js';
7
- import { hasLegacyAmircPermissions, prepareLegacyAmircDetach } from './legacy-amirc.js';
8
- const MCP_PROTOCOLS = {
9
- http: ['http:', 'https:'],
10
- 'streamable-http': ['http:', 'https:'],
11
- sse: ['http:', 'https:'],
12
- ws: ['ws:', 'wss:'],
13
- };
14
- function validRegistration(value) {
15
- if (!isObject(value))
16
- return false;
17
- if (value.type === undefined || value.type === 'stdio')
18
- return (typeof value.command === 'string' &&
19
- Boolean(value.command.trim()) &&
20
- (value.args === undefined || (Array.isArray(value.args) && value.args.every(arg => typeof arg === 'string'))));
21
- const protocols = typeof value.type === 'string' ? MCP_PROTOCOLS[value.type] : undefined;
22
- if (protocols === undefined || typeof value.url !== 'string')
23
- return false;
24
- try {
25
- return protocols.includes(new URL(value.url).protocol);
26
- }
27
- catch {
28
- return false;
29
- }
30
- }
31
- /** 以本地形状证据判定注册身份:与 CCW 写入模板一致才算确认,证据不足保留原始键名;
32
- * 不联网、不启动程序 */
33
- function confirmedMcpTitle(name, registration) {
34
- if (registration === undefined)
35
- return knownTitle(`mcp:${name}`, name);
36
- if (!Object.hasOwn(mcpSpecs, name) || !isObject(registration) || !validRegistration(registration))
37
- return name;
38
- if (name === 'context7')
39
- return (registration.type === 'http' || registration.type === 'streamable-http') &&
40
- registration.url === mcpSpecs.context7.registration.url
41
- ? knownTitle('mcp:context7')
42
- : name;
43
- if (name === 'serena')
44
- return (registration.type === undefined || registration.type === 'stdio') &&
45
- typeof registration.command === 'string' &&
46
- /(?:^|[\\/])serena(?:\.exe)?$/.test(registration.command) &&
47
- Array.isArray(registration.args) &&
48
- registration.args[0] === mcpSpecs.serena.registration.args[0]
49
- ? knownTitle('mcp:serena')
50
- : name;
51
- return name;
52
- }
53
- /** 创建 MCP 域渠道:检查数组归一为聚合,余段即注册名;裸函数仍供跨域调用 */
54
- export function createMcpDomain(ctx) {
55
- return {
56
- async inspect() {
57
- return { items: await inspectMcp(ctx), problems: [] };
58
- },
59
- prepare(selection, describe) {
60
- const name = restOf(selection.id);
61
- if (name === undefined)
62
- throw new Error('unknown-selection');
63
- return prepareMcp(ctx, name, selection, describe ? { describe } : {});
64
- },
65
- };
66
- }
67
- /**
68
- * 判定退役 AMIRC 许可证据
69
- *
70
- * @returns 读取失败时返回 unknown,不以 absent 代替
71
- */
72
- async function readLegacyAmircPermissionEvidence(ctx) {
73
- try {
74
- return (await hasLegacyAmircPermissions(ctx)) ? { kind: 'present' } : { kind: 'absent' };
75
- }
76
- catch (error) {
77
- return { kind: 'unknown', problem: errorCode(error) };
78
- }
79
- }
80
- async function inspectMcp(ctx) {
81
- // 注册文件不可读时方案入口降级可见(带问题、无资格),与插件族同形,不整族消失
82
- let registrations = {};
83
- let readProblem;
84
- try {
85
- registrations = object((await json(ctx.machine, ctx.stateFile)).mcpServers);
86
- }
87
- catch (error) {
88
- readProblem = errorCode(error);
89
- }
90
- const result = [];
91
- const legacyAmircPermissionEvidence = await readLegacyAmircPermissionEvidence(ctx);
92
- for (const name of new Set([
93
- ...Object.keys(mcpSpecs),
94
- ...Object.keys(registrations),
95
- ...(legacyAmircPermissionEvidence.kind !== 'absent' ? ['amirc'] : []),
96
- ])) {
97
- const isRegistered = registrations[name] !== undefined;
98
- const isOffered = Object.hasOwn(mcpSpecs, name);
99
- const hasAmircPermissions = name === 'amirc' && legacyAmircPermissionEvidence.kind === 'present';
100
- let problem = name === 'amirc' && legacyAmircPermissionEvidence.kind === 'unknown'
101
- ? legacyAmircPermissionEvidence.problem
102
- : undefined;
103
- if (isRegistered && !validRegistration(registrations[name]))
104
- problem = 'invalid-mcp-registration';
105
- const itemProblem = problem ?? readProblem;
106
- // 许可证据未知时 AMIRC 不因注册在档获得解除资格,其余条目不受此证据影响
107
- const canDetach = readProblem === undefined &&
108
- (name !== 'amirc' || legacyAmircPermissionEvidence.kind !== 'unknown') &&
109
- (isRegistered || hasAmircPermissions);
110
- result.push({
111
- id: `mcp:${name}`,
112
- title: confirmedMcpTitle(name, registrations[name]),
113
- kind: 'mcp',
114
- canInstall: isOffered && readProblem === undefined,
115
- location: ctx.stateFile,
116
- facts: [
117
- ...(readProblem === undefined ? [{ code: isRegistered ? 'registration-exists' : 'not-registered' }] : []),
118
- ...(hasAmircPermissions ? [{ code: 'amirc-permissions-present' }] : []),
119
- ],
120
- ...(itemProblem !== undefined ? { problem: itemProblem } : {}),
121
- actions: [
122
- ...(isOffered && readProblem === undefined
123
- ? isRegistered
124
- ? ['connect', ...(name === 'serena' ? ['update'] : []), 'reinstall']
125
- : ['install']
126
- : []),
127
- ...(canDetach ? ['detach'] : []),
128
- ],
129
- });
130
- }
131
- return result;
132
- }
133
- export async function prepareMcp(ctx, name, selection, options = {}) {
134
- const { registration: customRegistration, hasDetached = false, describe } = options;
135
- if (name === 'amirc' && selection.action === 'detach')
136
- return prepareLegacyAmircDetach(ctx);
137
- if (name === 'amirc')
138
- throw new Error('action-unavailable');
139
- const before = object((await json(ctx.machine, ctx.stateFile)).mcpServers);
140
- describe?.(confirmedMcpTitle(name, before[name]));
141
- const action = selection.action;
142
- if (!['install', 'connect', 'update', 'reinstall', 'detach'].includes(action) ||
143
- (action === 'update' && name !== 'serena'))
144
- throw new Error('action-unavailable');
145
- if (action === 'detach' && before[name] === undefined)
146
- throw new Error('no-connection');
147
- if (action === 'detach')
148
- return removeFields(ctx, ctx.stateFile, { [name]: before[name] }, [{ code: 'mcp-remove-registration', detail: name }, { code: 'mcp-keep-runtime' }, { code: 'mcp-auth-unchanged' }], { state: 'done', code: 'registration-removed', detail: name }, 'mcpServers');
149
- if (!/^[\w.:-]+$/.test(name))
150
- throw new Error('invalid-mcp-name');
151
- if (!Object.hasOwn(mcpSpecs, name) && customRegistration === undefined)
152
- throw new Error('not-in-update-catalog');
153
- const value = isObject(before[name]) ? before[name] : {};
154
- if (action === 'install' && validRegistration(before[name]) && Object.keys(selection.fields ?? {}).length === 0) {
155
- return {
156
- changes: [{ code: 'registration-kept', detail: name }],
157
- async run(report) {
158
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], value);
159
- report({ state: 'kept', code: 'registration-kept', detail: name });
160
- },
161
- async verify() {
162
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], value);
163
- },
164
- };
165
- }
166
- if (hasDetached)
167
- before[name] = undefined;
168
- if (name === 'serena' &&
169
- action === 'update' &&
170
- (typeof value.command !== 'string' || !/(^|[\\/])serena(?:\.exe)?$/.test(value.command)))
171
- throw new Error('channel-change-required');
172
- let registration;
173
- let targetVersion;
174
- if (name === 'context7')
175
- registration = {
176
- ...mcpSpecs.context7.registration,
177
- ...(selection.fields?.secret
178
- ? { headers: { Authorization: `Bearer ${selection.fields.secret}` } }
179
- : value.headers !== undefined
180
- ? { headers: value.headers }
181
- : {}),
182
- };
183
- else if (customRegistration !== undefined)
184
- registration = customRegistration();
185
- else {
186
- const release = JSON.parse(await ctx.machine.fetchText(mcpSpecs.serena.release.metadataUrl));
187
- if (!isObject(release) ||
188
- !isObject(release.info) ||
189
- typeof release.info.version !== 'string' ||
190
- !/^\d+\.\d+\.\d+$/.test(release.info.version))
191
- throw new Error('invalid-release');
192
- targetVersion = release.info.version;
193
- registration = {
194
- command: 'serena',
195
- args: [...mcpSpecs.serena.registration.args],
196
- };
197
- }
198
- let isRemoved = false;
199
- let isToolReady = false;
200
- let isInitialized = false;
201
- let isRegistrationSaved = false;
202
- let toolStamp = null;
203
- return {
204
- get changes() {
205
- if (isRegistrationSaved)
206
- return [{ code: 'mcp-registration-confirm', detail: name }];
207
- return [
208
- {
209
- code: action === 'update' ? 'mcp-program-update' : 'mcp-register',
210
- detail: `${name}${targetVersion ? ` · ${targetVersion}` : ''}`,
211
- },
212
- ...(before[name] !== undefined && action !== 'update' ? [{ code: 'replace-existing-registration' }] : []),
213
- ...(name === 'serena' && !isToolReady ? [{ code: 'uv-python-dependency' }] : []),
214
- ...(name === 'serena' && !isInitialized && action !== 'update' ? [{ code: 'serena-initialize' }] : []),
215
- ...(action === 'reinstall' && !isRemoved ? [{ code: 'disconnect-before-reinstall' }] : []),
216
- ];
217
- },
218
- async run(report, signal) {
219
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], before[name]);
220
- cancelled(signal);
221
- if (action === 'reinstall' && !isRemoved)
222
- await editFields(ctx, ctx.stateFile, before, { [name]: undefined }, 'mcpServers', () => {
223
- before[name] = undefined;
224
- isRemoved = true;
225
- report({ state: 'done', code: 'registration-removed' });
226
- });
227
- if (name === 'serena') {
228
- if (isToolReady && (await ctx.machine.treeStamp(String(registration.command))) !== toolStamp)
229
- throw new Error('program-changed');
230
- if (!isToolReady) {
231
- let uv = (await ctx.machine.locate('uv'))[0];
232
- const localUv = path.join(ctx.home, '.local/bin', ctx.platform === 'win32' ? 'uv.exe' : 'uv');
233
- if (uv === undefined && (await ctx.machine.treeStamp(localUv)) !== null)
234
- uv = localUv;
235
- if (uv === undefined) {
236
- const file = path.join(ctx.storage, `install-uv-${randomUUID()}.${ctx.platform === 'win32' ? 'ps1' : 'sh'}`);
237
- await ctx.machine.initialize(file, await ctx.machine.fetchText(`https://astral.sh/uv/install.${ctx.platform === 'win32' ? 'ps1' : 'sh'}`));
238
- try {
239
- success(await ctx.machine.execute(ctx.platform === 'win32' ? 'powershell.exe' : 'sh', ctx.platform === 'win32' ? ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', file] : [file], { env: { UV_NO_MODIFY_PATH: '1', UV_INSTALL_DIR: path.join(ctx.home, '.local/bin') } }));
240
- }
241
- finally {
242
- const stamp = await ctx.machine.treeStamp(file);
243
- if (stamp !== null)
244
- await ctx.machine.removeTree(file, stamp);
245
- }
246
- uv = localUv;
247
- report({ state: 'done', code: 'uv-installed' });
248
- }
249
- cancelled(signal);
250
- const serenaIn = (text) => text
251
- .split('\n')
252
- .some(line => line.trim().split(/\s+/).slice(0, 2).join(' ') ===
253
- `${mcpSpecs.serena.release.package} v${targetVersion}`);
254
- const currentTools = await ctx.machine.execute(uv, ['tool', 'list']);
255
- const isAlreadyInstalled = !currentTools.failed && currentTools.code === 0 && serenaIn(currentTools.stdout);
256
- if (!isAlreadyInstalled || action === 'reinstall')
257
- success(await ctx.machine.execute(uv, [
258
- 'tool',
259
- 'install',
260
- '--python',
261
- mcpSpecs.serena.release.python,
262
- '--upgrade',
263
- ...(action === 'reinstall' ? ['--reinstall'] : []),
264
- `${mcpSpecs.serena.release.package}==${targetVersion}`,
265
- ]), 'serena-install-failed');
266
- const installed = success(await ctx.machine.execute(uv, ['tool', 'list']));
267
- if (!serenaIn(installed))
268
- throw new Error('binary-version-mismatch');
269
- const bin = success(await ctx.machine.execute(uv, ['tool', 'dir', '--bin'])).trim();
270
- if (!path.isAbsolute(bin) || /[\r\n]/.test(bin))
271
- throw new Error('invalid-tool-directory');
272
- registration.command = path.join(bin, ctx.platform === 'win32' ? 'serena.exe' : 'serena');
273
- if ((await ctx.machine.treeStamp(String(registration.command))) === null)
274
- throw new Error('program-not-ready');
275
- toolStamp = await ctx.machine.treeStamp(String(registration.command));
276
- isToolReady = true;
277
- report({ state: 'done', code: 'serena-installed' });
278
- }
279
- cancelled(signal);
280
- if (action !== 'update' && !isInitialized) {
281
- success(await ctx.machine.execute(String(registration.command), ['init']), 'serena-initialization-failed');
282
- isInitialized = true;
283
- report({ state: 'done', code: 'serena-initialized' });
284
- }
285
- }
286
- cancelled(signal);
287
- if (action !== 'update') {
288
- if (!isRegistrationSaved)
289
- await editFields(ctx, ctx.stateFile, before, { [name]: registration }, 'mcpServers', () => {
290
- isRegistrationSaved = true;
291
- before[name] = registration;
292
- report({ state: 'done', code: 'registration-saved', detail: name });
293
- });
294
- else
295
- unchanged(object((await json(ctx.machine, ctx.stateFile)).mcpServers)[name], registration);
296
- }
297
- },
298
- };
299
- }