@lynn123411/dsh-kimi-cu 0.2.0 → 0.3.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.
package/lib/index.js CHANGED
@@ -39,74 +39,6 @@ function createStatusRoute(detect) {
39
39
  };
40
40
  }
41
41
 
42
- // src/server/status.ts
43
- import { existsSync, readFileSync } from "node:fs";
44
- import { dirname, join } from "node:path";
45
-
46
- // src/server/doctor.ts
47
- import { execFile } from "node:child_process";
48
- import { promisify } from "node:util";
49
- var execFileAsync = promisify(execFile);
50
- var MACOS_CHECK_IDS = {
51
- "accessibility (ax)": "accessibility",
52
- "screen recording": "screen-recording",
53
- "skylight post-to-pid": "skylight",
54
- "bg-input (window-location spi)": "bg-input",
55
- "signed keyboard": "signed-keyboard"
56
- };
57
- function parseDoctor(platform, raw) {
58
- const lines = raw.split("\n").map((line) => line.trim());
59
- if (platform === "darwin") {
60
- const checks = [];
61
- for (const line of lines) {
62
- const mark = line.slice(0, 1);
63
- if (mark !== "\u2705" && mark !== "\u274C") continue;
64
- const label = line.slice(1).trim();
65
- if (label === "") continue;
66
- const id = MACOS_CHECK_IDS[label.toLowerCase()] ?? "check-" + String(checks.length + 1);
67
- checks.push({ id, label, ok: mark === "\u2705" });
68
- }
69
- return { ok: checks.length > 0 && checks.every((check) => check.ok), checks, version: null };
70
- }
71
- if (platform === "win32") {
72
- let version = null;
73
- let mcp = null;
74
- for (const line of lines) {
75
- if (line.startsWith("version=")) version = line.slice("version=".length).trim() || null;
76
- else if (line.startsWith("mcp=")) mcp = line.slice("mcp=".length).trim();
77
- }
78
- return {
79
- ok: mcp === "true",
80
- checks: [{ id: "mcp", label: "MCP", ok: mcp === "true" }],
81
- version
82
- };
83
- }
84
- return { ok: false, checks: [], version: null };
85
- }
86
- async function runDoctor(platform, binaryPath) {
87
- if (platform === "other" || binaryPath === "") {
88
- return { ran: false, ok: false, checks: [], version: null, raw: "", error: "unsupported platform" };
89
- }
90
- try {
91
- const { stdout, stderr } = await execFileAsync(binaryPath, ["doctor"], {
92
- timeout: 15e3,
93
- windowsHide: true,
94
- encoding: "utf8"
95
- });
96
- const raw = String(stdout ?? "") + String(stderr ?? "");
97
- return { ran: true, ...parseDoctor(platform, raw), raw };
98
- } catch (error) {
99
- const record = error;
100
- const raw = String(record.stdout ?? "") + String(record.stderr ?? "");
101
- return {
102
- ran: true,
103
- ...parseDoctor(platform, raw),
104
- raw,
105
- error: error instanceof Error ? error.message : String(error)
106
- };
107
- }
108
- }
109
-
110
42
  // src/server/resolve.ts
111
43
  function toPlatform(platform) {
112
44
  if (platform === "darwin") return "darwin";
@@ -193,6 +125,74 @@ function resolveInstall(input) {
193
125
  };
194
126
  }
195
127
 
128
+ // src/server/status.ts
129
+ import { existsSync, readFileSync } from "node:fs";
130
+ import { dirname, join } from "node:path";
131
+
132
+ // src/server/doctor.ts
133
+ import { execFile } from "node:child_process";
134
+ import { promisify } from "node:util";
135
+ var execFileAsync = promisify(execFile);
136
+ var MACOS_CHECK_IDS = {
137
+ "accessibility (ax)": "accessibility",
138
+ "screen recording": "screen-recording",
139
+ "skylight post-to-pid": "skylight",
140
+ "bg-input (window-location spi)": "bg-input",
141
+ "signed keyboard": "signed-keyboard"
142
+ };
143
+ function parseDoctor(platform, raw) {
144
+ const lines = raw.split("\n").map((line) => line.trim());
145
+ if (platform === "darwin") {
146
+ const checks = [];
147
+ for (const line of lines) {
148
+ const mark = line.slice(0, 1);
149
+ if (mark !== "\u2705" && mark !== "\u274C") continue;
150
+ const label = line.slice(1).trim();
151
+ if (label === "") continue;
152
+ const id = MACOS_CHECK_IDS[label.toLowerCase()] ?? "check-" + String(checks.length + 1);
153
+ checks.push({ id, label, ok: mark === "\u2705" });
154
+ }
155
+ return { ok: checks.length > 0 && checks.every((check) => check.ok), checks, version: null };
156
+ }
157
+ if (platform === "win32") {
158
+ let version = null;
159
+ let mcp = null;
160
+ for (const line of lines) {
161
+ if (line.startsWith("version=")) version = line.slice("version=".length).trim() || null;
162
+ else if (line.startsWith("mcp=")) mcp = line.slice("mcp=".length).trim();
163
+ }
164
+ return {
165
+ ok: mcp === "true",
166
+ checks: [{ id: "mcp", label: "MCP", ok: mcp === "true" }],
167
+ version
168
+ };
169
+ }
170
+ return { ok: false, checks: [], version: null };
171
+ }
172
+ async function runDoctor(platform, binaryPath) {
173
+ if (platform === "other" || binaryPath === "") {
174
+ return { ran: false, ok: false, checks: [], version: null, raw: "", error: "unsupported platform" };
175
+ }
176
+ try {
177
+ const { stdout, stderr } = await execFileAsync(binaryPath, ["doctor"], {
178
+ timeout: 15e3,
179
+ windowsHide: true,
180
+ encoding: "utf8"
181
+ });
182
+ const raw = String(stdout ?? "") + String(stderr ?? "");
183
+ return { ran: true, ...parseDoctor(platform, raw), raw };
184
+ } catch (error) {
185
+ const record = error;
186
+ const raw = String(record.stdout ?? "") + String(record.stderr ?? "");
187
+ return {
188
+ ran: true,
189
+ ...parseDoctor(platform, raw),
190
+ raw,
191
+ error: error instanceof Error ? error.message : String(error)
192
+ };
193
+ }
194
+ }
195
+
196
196
  // src/server/status.ts
197
197
  function parseMacosVersion(plist) {
198
198
  const key = plist.indexOf("CFBundleShortVersionString");
@@ -309,12 +309,328 @@ function defaultStatusDetector() {
309
309
  });
310
310
  }
311
311
 
312
+ // src/shared/update.ts
313
+ var UPDATE_ROUTE_PATH = "/api/dsh-kimi-cu/update";
314
+ var MACOS_UPDATE_MANIFEST = "https://cdn.kimi.com/kimi-computer-use/latest/version.json";
315
+ var WINDOWS_UPDATE_MANIFEST = "https://cdn.kimi.com/kimi-computer-use-windows/latest/version.json";
316
+
317
+ // src/server/update.ts
318
+ function manifestUrl(platform) {
319
+ if (platform === "darwin") return MACOS_UPDATE_MANIFEST;
320
+ if (platform === "win32") return WINDOWS_UPDATE_MANIFEST;
321
+ return null;
322
+ }
323
+ function parseManifest(text) {
324
+ try {
325
+ const body = JSON.parse(text);
326
+ if (typeof body.version !== "string") return null;
327
+ const version = body.version.trim();
328
+ return version === "" ? null : version;
329
+ } catch {
330
+ return null;
331
+ }
332
+ }
333
+ function compareVersions(a, b) {
334
+ const parse = (value) => {
335
+ const parts = value.split(".");
336
+ const numbers = [];
337
+ for (const part of parts) {
338
+ if (!/^(0|[1-9]\d*)$/.test(part)) return null;
339
+ numbers.push(Number(part));
340
+ }
341
+ return numbers;
342
+ };
343
+ const left = parse(a);
344
+ const right = parse(b);
345
+ if (left === null || right === null) return null;
346
+ const length = Math.max(left.length, right.length);
347
+ for (let index = 0; index < length; index += 1) {
348
+ const one = left[index] ?? 0;
349
+ const other = right[index] ?? 0;
350
+ if (one > other) return 1;
351
+ if (one < other) return -1;
352
+ }
353
+ return 0;
354
+ }
355
+ var STAGE_RULES = [
356
+ [/下载|download/i, "downloading"],
357
+ [/校验|公证|签名|哈希|verif|signature|sha-?256/i, "verifying"],
358
+ [/替换|安装|install|replac/i, "installing"],
359
+ [/版本|version/i, "checking"]
360
+ ];
361
+ function parseStage(line) {
362
+ const text = line.trim();
363
+ if (text.startsWith("==>")) {
364
+ for (const [pattern, stage] of STAGE_RULES) {
365
+ if (pattern.test(text)) return stage;
366
+ }
367
+ return null;
368
+ }
369
+ if (text.startsWith("\u2713") && /签名|公证/.test(text)) return "installing";
370
+ return null;
371
+ }
372
+ var FAILURE_RULES = [
373
+ [/另一个升级|正在收尾|in progress|already running|another upgrade/i, "busy"],
374
+ [/sha-?256|签名|公证|gatekeeper|team id|bundle id|哈希|health check|not pass/i, "verify"],
375
+ [/权限|administrator|administ|permission|eacces|eperm|staging failed|not permitted/i, "permission"],
376
+ [/网络|下载失败|network|enotfound|econnrefused|etimedout|fetch failed|offline/i, "network"]
377
+ ];
378
+ function classifyFailure(raw, timedOut) {
379
+ if (timedOut) return "timeout";
380
+ const errors = raw.split("\n").map((line) => line.trim()).filter((line) => line !== "" && !line.startsWith("==>") && !line.startsWith("\u2713")).join("\n");
381
+ const text = errors === "" ? raw : errors;
382
+ for (const [pattern, kind] of FAILURE_RULES) {
383
+ if (pattern.test(text)) return kind;
384
+ }
385
+ return "unknown";
386
+ }
387
+ function createUpdater(deps) {
388
+ const now = deps.now ?? Date.now;
389
+ let running = false;
390
+ const readCurrent = async (refresh) => {
391
+ try {
392
+ return await deps.current(refresh);
393
+ } catch {
394
+ return { path: null, version: null };
395
+ }
396
+ };
397
+ const inspect = async (current) => {
398
+ const url = manifestUrl(deps.platform);
399
+ if (url === null) {
400
+ return { current: current.version, latest: null, hasUpdate: false, error: "unsupported platform", checkedAt: now() };
401
+ }
402
+ try {
403
+ const latest = parseManifest(await deps.fetchManifest(url));
404
+ if (latest === null) {
405
+ return { current: current.version, latest: null, hasUpdate: false, error: "manifest-invalid", checkedAt: now() };
406
+ }
407
+ const order = current.version === null ? null : compareVersions(latest, current.version);
408
+ return {
409
+ current: current.version,
410
+ latest,
411
+ hasUpdate: order === null ? true : order > 0,
412
+ error: null,
413
+ checkedAt: now()
414
+ };
415
+ } catch (error) {
416
+ return {
417
+ current: current.version,
418
+ latest: null,
419
+ hasUpdate: false,
420
+ error: error instanceof Error ? error.message : String(error),
421
+ checkedAt: now()
422
+ };
423
+ }
424
+ };
425
+ const check = async () => inspect(await readCurrent(false));
426
+ const run = async (emit) => {
427
+ if (running) {
428
+ emit({ type: "error", kind: "busy", raw: "" });
429
+ return;
430
+ }
431
+ running = true;
432
+ let release = true;
433
+ try {
434
+ emit({ type: "stage", stage: "checking" });
435
+ const current = await readCurrent(false);
436
+ if (current.path === null) {
437
+ emit({ type: "error", kind: "unknown", raw: "KimiCU is not installed" });
438
+ return;
439
+ }
440
+ const inspected = await inspect(current);
441
+ if (inspected.error !== null && deps.platform === "win32") {
442
+ emit({ type: "error", kind: "network", raw: inspected.error });
443
+ return;
444
+ }
445
+ if (inspected.error === null && !inspected.hasUpdate) {
446
+ emit({ type: "done", upToDate: true, version: current.version, reconnect: "skipped", raw: "" });
447
+ return;
448
+ }
449
+ emit({ type: "stage", stage: "downloading" });
450
+ let lastStage = "downloading";
451
+ const outcome = await deps.runUpgrade({
452
+ platform: deps.platform,
453
+ binaryPath: current.path,
454
+ version: deps.platform === "win32" ? inspected.latest : null,
455
+ onLine: (line) => {
456
+ const stage = parseStage(line);
457
+ if (stage === null || stage === lastStage) return;
458
+ lastStage = stage;
459
+ emit({ type: "stage", stage });
460
+ }
461
+ });
462
+ if (outcome.timedOut) {
463
+ release = false;
464
+ void outcome.whenExited.finally(() => {
465
+ running = false;
466
+ });
467
+ emit({ type: "error", kind: "timeout", raw: outcome.raw });
468
+ return;
469
+ }
470
+ if (outcome.code !== 0) {
471
+ emit({ type: "error", kind: classifyFailure(outcome.raw, false), raw: outcome.raw });
472
+ return;
473
+ }
474
+ const after = await readCurrent(true);
475
+ const changed = after.version !== null && after.version !== current.version;
476
+ let reconnect = "skipped";
477
+ if (changed && deps.reconnect !== null) {
478
+ emit({ type: "stage", stage: "restarting" });
479
+ try {
480
+ reconnect = await deps.reconnect() ? "done" : "failed";
481
+ } catch {
482
+ reconnect = "failed";
483
+ }
484
+ }
485
+ emit({ type: "done", upToDate: false, version: after.version, reconnect, raw: outcome.raw });
486
+ } finally {
487
+ if (release) running = false;
488
+ }
489
+ };
490
+ return { check, run };
491
+ }
492
+
493
+ // src/server/update-router.ts
494
+ function json(body, status = 200) {
495
+ return new Response(JSON.stringify(body), {
496
+ status,
497
+ headers: { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" }
498
+ });
499
+ }
500
+ function createUpdateRoute(updater) {
501
+ return {
502
+ path: UPDATE_ROUTE_PATH,
503
+ methods: ["GET", "POST"],
504
+ requestBody: "buffered",
505
+ fetch: async (request) => {
506
+ if (request.method === "GET") {
507
+ try {
508
+ return json(await updater.check());
509
+ } catch (error) {
510
+ return json({ error: error instanceof Error ? error.message : String(error) }, 500);
511
+ }
512
+ }
513
+ const encoder = new TextEncoder();
514
+ const stream = new ReadableStream({
515
+ start(controller) {
516
+ let closed = false;
517
+ const emit = (event) => {
518
+ if (closed) return;
519
+ try {
520
+ controller.enqueue(encoder.encode(JSON.stringify(event) + "\n"));
521
+ } catch {
522
+ closed = true;
523
+ }
524
+ };
525
+ void updater.run(emit).catch((error) => {
526
+ emit({ type: "error", kind: "unknown", raw: error instanceof Error ? error.message : String(error) });
527
+ }).finally(() => {
528
+ if (closed) return;
529
+ closed = true;
530
+ controller.close();
531
+ });
532
+ }
533
+ });
534
+ return new Response(stream, {
535
+ status: 200,
536
+ headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-store" }
537
+ });
538
+ }
539
+ };
540
+ }
541
+
542
+ // src/server/update-runtime.ts
543
+ import { spawn } from "node:child_process";
544
+ var UPDATE_TIMEOUT_MS = 3e5;
545
+ var MANIFEST_TIMEOUT_MS = 5e3;
546
+ async function fetchManifestText(url) {
547
+ const response = await fetch(url, { signal: AbortSignal.timeout(MANIFEST_TIMEOUT_MS) });
548
+ if (!response.ok) throw new Error("HTTP " + String(response.status));
549
+ return response.text();
550
+ }
551
+ function runUpgradeProcess(input) {
552
+ const timeoutMs = input.timeoutMs ?? UPDATE_TIMEOUT_MS;
553
+ return new Promise((resolve) => {
554
+ let raw = "";
555
+ let pending = "";
556
+ let settled = false;
557
+ let timer;
558
+ let markExited = () => {
559
+ };
560
+ const whenExited = new Promise((done) => {
561
+ markExited = done;
562
+ });
563
+ const finish = (run) => {
564
+ if (settled) return;
565
+ settled = true;
566
+ if (timer !== void 0) clearTimeout(timer);
567
+ resolve({ ...run, whenExited });
568
+ };
569
+ const push = (chunk) => {
570
+ raw += chunk;
571
+ pending += chunk;
572
+ const lines = pending.split("\n");
573
+ pending = lines.pop() ?? "";
574
+ for (const line of lines) input.onLine(line);
575
+ };
576
+ let child;
577
+ try {
578
+ child = spawn(input.binaryPath, input.args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
579
+ } catch (error) {
580
+ markExited();
581
+ finish({ code: null, raw: error instanceof Error ? error.message : String(error), timedOut: false });
582
+ return;
583
+ }
584
+ child.stdout?.setEncoding("utf8");
585
+ child.stderr?.setEncoding("utf8");
586
+ child.stdout?.on("data", (chunk) => push(chunk));
587
+ child.stderr?.on("data", (chunk) => push(chunk));
588
+ child.on("error", (error) => {
589
+ markExited();
590
+ finish({ code: null, raw: raw + (error instanceof Error ? error.message : String(error)), timedOut: false });
591
+ });
592
+ child.on("close", (code) => {
593
+ markExited();
594
+ if (pending !== "") input.onLine(pending);
595
+ finish({ code, raw, timedOut: false });
596
+ });
597
+ timer = setTimeout(() => finish({ code: null, raw, timedOut: true }), timeoutMs);
598
+ });
599
+ }
600
+
312
601
  // src/index.ts
313
602
  var name = "dsh-kimi-cu";
314
603
  var inject = ["tools"];
315
604
  var TOOL_NAME = "kimi_cu_status";
316
- function apply(ctx) {
317
- const detect = defaultStatusDetector();
605
+ var MCP_SERVER_NAME = "kimi-cu";
606
+ var COMPUTER_USE_PROVIDER = "kimi-cu";
607
+ var MCP_TOOL_TIMEOUT_MS = 3e5;
608
+ function apply(ctx, options) {
609
+ const detect = options?.detect ?? defaultStatusDetector();
610
+ let mcpCtx;
611
+ let disposeMcp;
612
+ let desktopDenied = false;
613
+ const reconnect = async () => {
614
+ const manager = mcpCtx?.mcpManager;
615
+ if (manager?.restart === void 0) return false;
616
+ await manager.restart(MCP_SERVER_NAME);
617
+ return true;
618
+ };
619
+ const updater = createUpdater({
620
+ platform: toPlatform(process.platform),
621
+ current: async (refresh) => {
622
+ const status = await detect(refresh);
623
+ return { path: status.path, version: status.version };
624
+ },
625
+ fetchManifest: fetchManifestText,
626
+ runUpgrade: (input) => runUpgradeProcess({
627
+ binaryPath: input.binaryPath,
628
+ // Windows 的 upgrade 必须带目标版本;macOS 交给 KimiCU 自己判断。
629
+ args: input.version === null ? ["upgrade"] : ["upgrade", input.version],
630
+ onLine: input.onLine
631
+ }),
632
+ reconnect
633
+ });
318
634
  ctx.tools.register(defineTool({
319
635
  name: TOOL_NAME,
320
636
  description: "Check whether KimiCU (Kimi Computer Use) is installed and ready on this machine, and get the platform-specific install or repair steps. Call this when the mcp__kimi-cu__* tools are missing or a KimiCU call fails with a connection error.",
@@ -344,13 +660,63 @@ function apply(ctx) {
344
660
  }
345
661
  }));
346
662
  ctx.inject(["connection"], (connectionCtx) => {
347
- const route = createStatusRoute(detect);
348
- const dispose = connectionCtx.connection.fetch.register(route);
663
+ const connection = connectionCtx.connection;
664
+ const disposers = [
665
+ connection.fetch.register(createStatusRoute(detect)),
666
+ connection.fetch.register(createUpdateRoute(updater))
667
+ ];
349
668
  return () => {
350
- void Promise.resolve(dispose()).catch(() => {
669
+ for (const dispose of disposers) void Promise.resolve(dispose()).catch(() => {
351
670
  });
352
671
  };
353
672
  });
673
+ const syncMcp = async () => {
674
+ if (desktopDenied || mcpCtx === void 0 || disposeMcp !== void 0) return;
675
+ const status = await detect();
676
+ if (desktopDenied || mcpCtx === void 0 || disposeMcp !== void 0) return;
677
+ if (status.mcp === null) return;
678
+ disposeMcp = mcpCtx.mcpManager.register(MCP_SERVER_NAME, {
679
+ transport: "stdio",
680
+ command: status.mcp.command,
681
+ args: status.mcp.args,
682
+ toolCallTimeoutMs: MCP_TOOL_TIMEOUT_MS
683
+ });
684
+ };
685
+ ctx.inject(["computerUse"], (cuCtx) => {
686
+ const registry = cuCtx.computerUse;
687
+ let release;
688
+ try {
689
+ release = registry.register(COMPUTER_USE_PROVIDER);
690
+ } catch (error) {
691
+ desktopDenied = true;
692
+ disposeMcp?.();
693
+ disposeMcp = void 0;
694
+ ctx.logger.warn(
695
+ "KimiCU \u6CA1\u6709\u5360\u7528\u684C\u9762\u64CD\u4F5C\u69FD\u4F4D\uFF08" + (error instanceof Error ? error.message : String(error)) + "\uFF09\uFF1B\u5DF2\u505C\u7528 mcp__kimi-cu__* \u5DE5\u5177\uFF0C\u907F\u514D\u4E24\u5957\u540E\u7AEF\u540C\u65F6\u63A7\u5236\u684C\u9762\u3002"
696
+ );
697
+ return () => {
698
+ desktopDenied = false;
699
+ void syncMcp().catch(() => {
700
+ });
701
+ };
702
+ }
703
+ void syncMcp().catch(() => {
704
+ });
705
+ return () => {
706
+ void Promise.resolve(release?.()).catch(() => {
707
+ });
708
+ };
709
+ });
710
+ ctx.inject(["mcpManager"], (injectedCtx) => {
711
+ mcpCtx = injectedCtx;
712
+ void syncMcp().catch(() => {
713
+ });
714
+ return () => {
715
+ mcpCtx = void 0;
716
+ disposeMcp?.();
717
+ disposeMcp = void 0;
718
+ };
719
+ });
354
720
  void detect().then((status) => {
355
721
  if (!status.supported || status.installed) return;
356
722
  ctx.logger.warn(