@yusho/server 0.0.0-stage → 0.1.17
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/README.md +135 -2
- package/app/appguide.mjs +33 -0
- package/app/asr.mjs +82 -0
- package/app/assets/agents/claude-192.webp +0 -0
- package/app/assets/agents/claude-96.webp +0 -0
- package/app/assets/agents/codex-192.webp +0 -0
- package/app/assets/agents/codex-96.webp +0 -0
- package/app/assets/agents/default-192.webp +0 -0
- package/app/assets/agents/default-96.webp +0 -0
- package/app/assets/agents/dsh-192.webp +0 -0
- package/app/assets/agents/dsh-96.webp +0 -0
- package/app/assets/brand/logo.webp +0 -0
- package/app/assets/lib/THIRD-PARTY.txt +1 -0
- package/app/assets/lib/jsqr.js +10102 -0
- package/app/assets/linux/alpine-arm64.tar.gz +0 -0
- package/app/assets/linux/alpine-x64.tar.gz +0 -0
- package/app/assets/live/claude.livliv +0 -0
- package/app/assets/live/dafeiyu.livliv +0 -0
- package/app/assets/live/gpt.livliv +0 -0
- package/app/assets/live/sho.livliv +0 -0
- package/app/assets/live//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
- package/app/assets/livliv/LICENSE +202 -0
- package/app/assets/livliv/NOTICE +7 -0
- package/app/assets/livliv/player.mjs +15 -0
- package/app/assets/looks/claude.webp +0 -0
- package/app/assets/looks/dafeiyu.webp +0 -0
- package/app/assets/looks/gpt.webp +0 -0
- package/app/assets/looks//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
- package/app/assets/sho/avatar.webp +0 -0
- package/app/assets/sho/done.webp +0 -0
- package/app/assets/sho/eat.webp +0 -0
- package/app/assets/sho/idle-blink.webp +0 -0
- package/app/assets/sho/idle.webp +0 -0
- package/app/assets/sho/listen.webp +0 -0
- package/app/assets/sho/need.webp +0 -0
- package/app/assets/sho/work.webp +0 -0
- package/app/companion.mjs +519 -0
- package/app/diag.mjs +51 -0
- package/app/index.html +497 -0
- package/app/judge.mjs +103 -0
- package/app/lanxfer.mjs +157 -0
- package/app/launcher.mjs +2715 -0
- package/app/linux.mjs +97 -0
- package/app/livliv-pack.mjs +12 -0
- package/app/memory.mjs +53 -0
- package/app/net.mjs +717 -0
- package/app/office.mjs +172 -0
- package/app/p2plink.mjs +134 -0
- package/app/pcupdate.mjs +55 -0
- package/app/plans.mjs +126 -0
- package/app/plugins.mjs +79 -0
- package/app/realtime.mjs +67 -0
- package/app/skills/app-icon/SKILL.md +31 -0
- package/app/skills/daily-brief/SKILL.md +29 -0
- package/app/skills/expense-review/SKILL.md +28 -0
- package/app/skills/make-app/SKILL.md +92 -0
- package/app/skills/make-skin/SKILL.md +51 -0
- package/app/skills/meeting-notes/SKILL.md +23 -0
- package/app/skills/reading-notes/SKILL.md +25 -0
- package/app/skills/sho-stickers/SKILL.md +34 -0
- package/app/skills/sho-stickers/stickers/eat.webp +0 -0
- package/app/skills/sho-stickers/stickers/got-it.webp +0 -0
- package/app/skills/sho-stickers/stickers/hi.webp +0 -0
- package/app/skills/sho-stickers/stickers/huh.webp +0 -0
- package/app/skills/sho-stickers/stickers/on-it.webp +0 -0
- package/app/skills/sho-stickers/stickers/yay.webp +0 -0
- package/app/skills/sho-stickers/stickers.json +12 -0
- package/app/skills/study-plan/SKILL.md +30 -0
- package/app/skills/trip-planner/SKILL.md +29 -0
- package/app/skills/weekly-report/SKILL.md +30 -0
- package/app/skills/workout-plan/SKILL.md +30 -0
- package/app/skills/writing-polish/SKILL.md +33 -0
- package/app/skills.mjs +173 -0
- package/app/skins.mjs +40 -0
- package/app/social.mjs +1067 -0
- package/app/storage.mjs +143 -0
- package/app/tts.mjs +68 -0
- package/app/ttslocal.mjs +77 -0
- package/app/voices.mjs +102 -0
- package/backup.mjs +109 -0
- package/bin/yusho.mjs +141 -0
- package/connector/lib/api.mjs +14 -0
- package/connector/lib/autostart.mjs +40 -0
- package/connector/lib/client.js +165 -0
- package/connector/lib/connector.mjs +468 -0
- package/connector/lib/dsh-acp.mjs +129 -0
- package/connector/lib/dsh-headless.patch.yml +4 -0
- package/connector/lib/dsh-plugin.mjs +80 -0
- package/connector/lib/lanfile.mjs +151 -0
- package/connector/lib/nostr.mjs +53 -0
- package/connector/lib/page.html +121 -0
- package/connector/lib/qr.mjs +4 -0
- package/connector/lib/service.mjs +54 -0
- package/node_modules/@local/shoal-mobile/lib/index.js +485 -0
- package/node_modules/@local/shoal-mobile/lib/polyfill.js +82 -0
- package/node_modules/@local/shoal-mobile/lib/session-context.js +34 -0
- package/node_modules/@local/shoal-mobile/lib/shell.js +60 -0
- package/node_modules/@local/shoal-mobile/lib/web-startup.js +33 -0
- package/node_modules/@local/shoal-mobile/package.json +24 -0
- package/node_modules/@local/yusho-pc/lib/client.js +9100 -0
- package/node_modules/@local/yusho-pc/lib/index.js +3 -0
- package/node_modules/@local/yusho-pc/package.json +28 -0
- package/node_modules/@local/yusho-web-login/brand/icon-192.webp +0 -0
- package/node_modules/@local/yusho-web-login/brand/logo-dark.svg +25 -0
- package/node_modules/@local/yusho-web-login/brand.mjs +8 -0
- package/node_modules/@local/yusho-web-login/dsh-web-login.mjs +974 -0
- package/node_modules/@local/yusho-web-login/lib/client.js +607 -0
- package/node_modules/@local/yusho-web-login/login-page.mjs +609 -0
- package/node_modules/@local/yusho-web-login/login-store.mjs +708 -0
- package/node_modules/@local/yusho-web-login/package.json +25 -0
- package/node_modules/@local/yusho-web-login/whale-scene.mjs +509 -0
- package/node_modules/@local/yusho-web-login/yusho-scene.mjs +227 -0
- package/package.json +38 -4
- package/pc.patch.yml +83 -0
- package/run.mjs +138 -0
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
// 鱼Sho 连接器:让这台电脑上的 Agent(Codex、Claude Code、DSH)出现在你手机的鱼Sho 里,可以直接和它们说话、派活。
|
|
2
|
+
// · 身份:第一次运行自动生成,存在 ~/.yusho-connect(或 YUSHO_HOME);自动领一个鱼Sho号,中继和文件服务器就放行它的消息
|
|
3
|
+
// · 配对:显示二维码和 6 位码,手机扫码(或输入码)后,在电脑上核对指纹、点确认,这部手机就是主人
|
|
4
|
+
// · 干活:主人派来的活,经 ACP 驱动本机已经登录的 Agent;进度、要批的操作、结果、改动的文件(加密上传)都回给手机
|
|
5
|
+
// 原则:只驱动本机已经登录的 CLI,绝不代管任何账号或密钥;只听配对过的主人;只在工作目录里干活。
|
|
6
|
+
import { spawn, spawnSync, execFile } from 'node:child_process'
|
|
7
|
+
import { Readable, Writable } from 'node:stream'
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
import crypto from 'node:crypto'
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { fileURLToPath } from 'node:url'
|
|
14
|
+
import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure'
|
|
15
|
+
import { bytesToHex, hexToBytes } from 'nostr-tools/utils'
|
|
16
|
+
import * as acp from '@agentclientprotocol/sdk'
|
|
17
|
+
import { openInbox, parseContent } from './nostr.mjs'
|
|
18
|
+
import { createLanFiles } from './lanfile.mjs'
|
|
19
|
+
|
|
20
|
+
const here = path.dirname(fileURLToPath(import.meta.url))
|
|
21
|
+
const require = createRequire(import.meta.url)
|
|
22
|
+
/** 把 Agent 那边的错误说清楚:ACP 把真正的原因放在 data.details 里,只看 message 就只剩“Internal error” */
|
|
23
|
+
const errText = (e) => {
|
|
24
|
+
const d = e?.data?.details ?? e?.data?.message ?? (typeof e?.data === 'string' ? e.data : null), m = String(e?.message ?? e)
|
|
25
|
+
const raw = (d && !m.includes(d) ? m.replace(/^Internal error:?\s*/i, '') + (/^Internal error:?\s*$/i.test(m) ? '' : ':') + d : m.replace(/^Internal error:?\s*/i, '')).slice(0, 700)
|
|
26
|
+
// 常见的几种说成人话,原话留在后面方便查
|
|
27
|
+
const why = /\b429\b|quota|rate.?limit|exhausted|insufficient.?(balance|quota)|余额不足|额度/i.test(raw) ? '这个 Agent 用的模型额度用完了或被限流。到它自己的设置里换个密钥或模型再试(不是鱼Sho 的问题)'
|
|
28
|
+
: /\b401\b|unauthori[sz]ed|invalid.{0,12}(api.?key|token)|not.?logged.?in|login required|authentication.?required|please.{0,10}log.?in|需要登录/i.test(raw) ? '这个 Agent 没登录或密钥失效了,到电脑上重新登录它再试'
|
|
29
|
+
: /ECONNREFUSED|ENOTFOUND|ETIMEDOUT|Connection refused|network|fetch failed|socket hang up/i.test(raw) ? '这个 Agent 连不上它的服务器(网络、代理或防火墙),电脑联网正常后再试'
|
|
30
|
+
: null
|
|
31
|
+
return why ? why + '。原话:' + raw.slice(0, 300) : raw
|
|
32
|
+
}
|
|
33
|
+
export const DEFAULTS = { relay: 'wss://relay.yusho.chat', idService: 'https://yusho.chat', blossom: 'https://files.yusho.chat' }
|
|
34
|
+
export const pairTag = (code) => 'shoal-pair:' + crypto.createHash('sha256').update('shoal-pair-v0:' + code).digest('hex') // 和手机 App 一致
|
|
35
|
+
export const fingerprint = (pk) => pk.slice(0, 8).toUpperCase().replace(/(....)(....)/, '$1 $2')
|
|
36
|
+
const sha256 = (b) => crypto.createHash('sha256').update(b).digest('hex')
|
|
37
|
+
|
|
38
|
+
// ── 这台电脑上有哪些 Agent:登录过(有登录文件)或者装了命令就算有。只用你本机已经登录的,连接器不碰账号
|
|
39
|
+
// Codex 的 ACP 适配器随连接器带(它自带 Codex);Claude Code 的适配器用 npx 现取;DSH 用随带的适配器
|
|
40
|
+
function has(cmd) { const r = spawnSync(process.platform === 'win32' ? 'where' : 'which', [cmd], { stdio: 'ignore' }); return r.status === 0 }
|
|
41
|
+
const homeHas = (...p) => fs.existsSync(path.join(os.homedir(), ...p))
|
|
42
|
+
/** 没检测到、但看得出装过的 Agent:告诉用户差什么 */
|
|
43
|
+
export function agentHints(found) {
|
|
44
|
+
const h = []
|
|
45
|
+
if (!found.claude && homeHas('.claude.json') && !desktopClaude()) h.push('Claude Code:看起来只在 Claude 桌面 App 里登录过,那个登录连接器用不了。装命令行版(npm i -g @anthropic-ai/claude-code)后在终端运行一次 claude 登录,再重启连接器。')
|
|
46
|
+
if (!found.codex && has('npx') && homeHas('.codex')) h.push('Codex:没找到登录信息。在终端运行一次 codex 登录,再重启连接器。')
|
|
47
|
+
return h
|
|
48
|
+
}
|
|
49
|
+
/** Claude 桌面 App 自带的 Claude Code:取版本号最新的那份(App 升级后路径会变,每次启动都重新找) */
|
|
50
|
+
function desktopClaude() {
|
|
51
|
+
const roots = process.platform === 'win32' ? ['Claude-3p', 'AnthropicClaude', 'Claude'].map((d) => path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), d, 'claude-code'))
|
|
52
|
+
: [path.join(os.homedir(), 'Library', 'Application Support', 'Claude', 'claude-code'), path.join(os.homedir(), 'Library', 'Application Support', 'Claude-3p', 'claude-code')]
|
|
53
|
+
const exe = process.platform === 'win32' ? 'claude.exe' : 'claude', found = []
|
|
54
|
+
const ver = (v) => v.split('.').map((n) => parseInt(n, 10) || 0)
|
|
55
|
+
for (const r of roots) { let vs = []; try { vs = fs.readdirSync(r) } catch { continue }
|
|
56
|
+
for (const v of vs) { if (!/^\d+\.\d+\.\d+$/.test(v)) continue; const dir = path.join(r, v); const cands = [path.join(dir, exe)]; try { for (const sub of fs.readdirSync(dir)) cands.push(path.join(dir, sub, exe)) } catch {}
|
|
57
|
+
for (const c of cands) { try { if (fs.statSync(c).isFile()) found.push({ c, v: ver(v) }) } catch {} } } }
|
|
58
|
+
found.sort((a, b) => { for (let i = 0; i < 3; i++) if (a.v[i] !== b.v[i]) return b.v[i] - a.v[i]; return 0 })
|
|
59
|
+
return found[0]?.c ?? null
|
|
60
|
+
}
|
|
61
|
+
export function detectAgents() {
|
|
62
|
+
const out = {}
|
|
63
|
+
if (has('codex') || homeHas('.codex', 'auth.json')) { let entry = null; try { entry = require.resolve('@agentclientprotocol/codex-acp/package.json') } catch {} ; const env = { INITIAL_AGENT_MODE: 'workspace-write', NO_BROWSER: '1' }; if (!entry) out.codex = { command: 'npx', args: ['-y', '@agentclientprotocol/codex-acp@2.9.0'], env } /* 适配器带着一整份 Codex(几百 MB),不放进安装包,第一次派活时再下载 */; else { const pkg = JSON.parse(fs.readFileSync(entry, 'utf8')); const bin = typeof pkg.bin === 'string' ? pkg.bin : Object.values(pkg.bin ?? {})[0]; out.codex = { command: process.execPath, args: [path.join(path.dirname(entry), bin)], env } } }
|
|
64
|
+
// Claude Code:要有命令行版的登录(claude 命令,或 ~/.claude/.credentials.json),或者设了 ANTHROPIC_API_KEY。
|
|
65
|
+
// 只在 Claude 桌面 App 里登录过的不算:桌面 App 的登录只给它自己用,连接器借不到(会报“需要登录”)
|
|
66
|
+
if (has('claude') || homeHas('.claude', '.credentials.json') || process.env.ANTHROPIC_API_KEY) out.claude = { command: 'npx', args: ['-y', '@agentclientprotocol/claude-agent-acp@0.107.0'], env: {} }
|
|
67
|
+
// 没有命令行版:Claude 桌面 App 自带一份 Claude Code(claude.exe),它在桌面 App 外面也能单独用(登录是这台电脑上的),就让适配器用它
|
|
68
|
+
else { const exe = desktopClaude(); if (exe) out.claude = { command: 'npx', args: ['-y', '@agentclientprotocol/claude-agent-acp@0.107.0'], env: { CLAUDE_CODE_EXECUTABLE: exe }, via: 'desktop' } }
|
|
69
|
+
if (has('dsh')) out.dsh = { command: process.execPath, args: [path.join(here, 'dsh-acp.mjs')], env: {} }
|
|
70
|
+
return out
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 怎么启动一个 Agent:command 是 npx 时,换成“Node + npm 的 npx-cli.js”(找不到才退回系统的 npx) */
|
|
74
|
+
function launcher(ag) {
|
|
75
|
+
if (ag.command !== 'npx') return [ag.command, ag.args]
|
|
76
|
+
const cli = path.join(path.dirname(process.execPath), process.platform === 'win32' ? '' : '..', process.platform === 'win32' ? 'node_modules' : 'lib/node_modules', 'npm', 'bin', 'npx-cli.js')
|
|
77
|
+
return fs.existsSync(cli) ? [process.execPath, [cli, ...ag.args]] : [ag.command, ag.args]
|
|
78
|
+
}
|
|
79
|
+
/** 结束一个 Agent 和它开的所有子进程(npx → node → 真正的 Agent) */
|
|
80
|
+
function killTree(child) {
|
|
81
|
+
if (child.exitCode !== null || !child.pid) return
|
|
82
|
+
if (process.platform === 'win32') execFile('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true }, () => {})
|
|
83
|
+
else try { process.kill(-child.pid, 'SIGTERM') } catch { child.kill() }
|
|
84
|
+
}
|
|
85
|
+
const alive = (pid) => { try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' } }
|
|
86
|
+
|
|
87
|
+
export async function createConnector({ home = process.env.YUSHO_HOME || path.join(os.homedir(), '.yusho-connect'), name = os.hostname(), log = (...a) => console.log(new Date().toTimeString().slice(0, 8), ...a), onChange = () => {}, owner = '后台服务', sink = null /* 测试用:不经中继,消息直接交给它 */, custom = null /* 自己跑的 Agent:{ dsh: { run } },见 runCustom */, p2p = null /* 打洞直连:{ create, iceServers }(鱼Sho 内核给,见 p2plink.mjs);没有就只走局域网 */ } = {}) {
|
|
88
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
89
|
+
const F = (n) => path.join(home, n)
|
|
90
|
+
const readJ = (n, d) => { try { return JSON.parse(fs.readFileSync(F(n), 'utf8')) } catch { return d } }
|
|
91
|
+
const writeJ = (n, v, mode) => fs.writeFileSync(F(n), JSON.stringify(v, null, 1), mode ? { mode } : undefined)
|
|
92
|
+
|
|
93
|
+
// 配置:中继、号码服务、文件服务、工作目录、Agent(没写就自动检测)。用户可以改 config.json
|
|
94
|
+
const cfg = { ...DEFAULTS, workDir: path.join(os.homedir(), 'YushoWork'), name, ...readJ('config.json', {}) }
|
|
95
|
+
if (!fs.existsSync(F('config.json'))) writeJ('config.json', { name: cfg.name, workDir: cfg.workDir })
|
|
96
|
+
fs.mkdirSync(cfg.workDir, { recursive: true })
|
|
97
|
+
// custom:宿主自己跑的 Agent(鱼Sho 电脑版把 DSH 的活开成网页版里看得到的任务),盖过自动检测到的同名 Agent
|
|
98
|
+
const agents = { ...(cfg.agents ?? detectAgents()), ...(custom ?? {}) }
|
|
99
|
+
|
|
100
|
+
// 身份
|
|
101
|
+
let id = readJ('identity.json', null)
|
|
102
|
+
if (!id) { const sk = generateSecretKey(); id = { sk: bytesToHex(sk), pk: getPublicKey(sk), created: Date.now() }; writeJ('identity.json', id, 0o600); log('生成了这台电脑的身份') }
|
|
103
|
+
const key = { pk: id.pk, skBytes: hexToBytes(id.sk) }
|
|
104
|
+
|
|
105
|
+
// 领鱼Sho号(NIP-98 签名):领了号,中继就放行发给这台电脑的加密消息,文件服务器也收它上传的文件
|
|
106
|
+
async function claimNumber() {
|
|
107
|
+
if (id.number) return id.number
|
|
108
|
+
const url = cfg.idService + '/api/id/claim'
|
|
109
|
+
const ev = finalizeEvent({ kind: 27235, created_at: Math.floor(Date.now() / 1000), tags: [['u', url], ['method', 'POST']], content: '' }, key.skBytes)
|
|
110
|
+
const r = await fetch(url, { method: 'POST', headers: { 'x-yusho-kind': 'computer', authorization: 'Nostr ' + Buffer.from(JSON.stringify(ev)).toString('base64') }, signal: AbortSignal.timeout(15000) })
|
|
111
|
+
const j = await r.json().catch(() => ({}))
|
|
112
|
+
if (!r.ok || j.pk !== id.pk || !/^\d{6,15}$/.test(String(j.number))) throw new Error('领号失败:' + (j.error || 'HTTP ' + r.status))
|
|
113
|
+
id.number = String(j.number); writeJ('identity.json', id, 0o600); log('领到了鱼Sho号', id.number); return id.number
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 主人的设备(配对过的手机)
|
|
117
|
+
const devices = () => readJ('devices.json', [])
|
|
118
|
+
const owners = () => new Map(devices().filter((d) => !d.revoked).map((d) => [d.pk, d.label]))
|
|
119
|
+
const revoked = () => new Set(devices().filter((d) => d.revoked).map((d) => d.pk))
|
|
120
|
+
|
|
121
|
+
// ── 连中继
|
|
122
|
+
let inbox = null
|
|
123
|
+
const send = (to, payload) => (sink ? Promise.resolve(sink(to, { shoal: 1, from: 'runner', ...payload })) : inbox.send(to, { shoal: 1, from: 'runner', ...payload }))
|
|
124
|
+
const tasks = new Map() // task_id -> { pendingApprovals, cancel, agent, title, started }
|
|
125
|
+
// 手机 ↔ 电脑直连传文件(同一个 Wi-Fi 时):见 lanfile.mjs
|
|
126
|
+
const lan = createLanFiles({ workDir: cfg.workDir, log })
|
|
127
|
+
// 不在同一个网络时:手机发来打洞信令(file.rtc),这边接听,通道打开后照局域网那套处理分块请求
|
|
128
|
+
let rtc = null
|
|
129
|
+
const results = new Map(readJ('results.json', []))
|
|
130
|
+
const saveResult = (id2, p) => { results.set(id2, p); writeJ('results.json', [...results].slice(-200)) }
|
|
131
|
+
|
|
132
|
+
// ── 配对(同时只开一个):发一条“配对邀请”(kind 30078,按连接码的哈希找,5 分钟过期,只含名字和公钥),等手机来
|
|
133
|
+
let pairing = null
|
|
134
|
+
async function startPairing({ restore = null } = {}) {
|
|
135
|
+
if (!id.number) await claimNumber()
|
|
136
|
+
const code = String(crypto.randomInt(0, 1_000_000)).padStart(6, '0'), ttl = 300, expires = Math.floor(Date.now() / 1000) + ttl
|
|
137
|
+
const offer = finalizeEvent({ kind: 30078, created_at: Math.floor(Date.now() / 1000), tags: [['d', pairTag(code)], ['expiration', String(expires)]], content: JSON.stringify({ v: 0, name: cfg.name, agents: Object.keys(agents), ...(restore ? { restore: true } : {}) }) }, key.skBytes)
|
|
138
|
+
await inbox.publish(offer)
|
|
139
|
+
pairing = { code, expires: expires * 1000, restore, request: null }
|
|
140
|
+
onChange()
|
|
141
|
+
log('配对码 ' + code + '(5 分钟内有效)')
|
|
142
|
+
return { code, expires: pairing.expires, qr: 'yusho:pair?c=' + code + '&k=' + id.pk, fingerprint: fingerprint(id.pk) }
|
|
143
|
+
}
|
|
144
|
+
function cancelPairing() { pairing = null; onChange() }
|
|
145
|
+
/** 电脑上的人核对完指纹:确认或拒绝 */
|
|
146
|
+
async function answerPairing(ok) {
|
|
147
|
+
const p = pairing; if (!p?.request) throw new Error('没有等确认的手机')
|
|
148
|
+
const { pk, label } = p.request; pairing = null; onChange()
|
|
149
|
+
if (!ok) { await send(pk, { type: p.restore ? 'restore.failed' : 'pair.failed', reason: '电脑上取消了' }); return { ok: false } }
|
|
150
|
+
if (p.restore) {
|
|
151
|
+
const b = p.restore, d = devices().filter((x) => x.pk !== b.pk); d.push({ pk: b.pk, label: b.label, added: Date.now(), restoredTo: label }); writeJ('devices.json', d)
|
|
152
|
+
await send(pk, { type: 'restore.ok', sk: b.sk, pk: b.pk, label: b.label, members: b.members ?? [], name: cfg.name, agents: Object.keys(agents) })
|
|
153
|
+
log('把身份交给了新手机:' + b.label); return { ok: true }
|
|
154
|
+
}
|
|
155
|
+
const d = devices().filter((x) => x.pk !== pk); d.push({ pk, label, number: p.request.number ?? null, added: Date.now() }); writeJ('devices.json', d)
|
|
156
|
+
await send(pk, { type: 'pair.ok', name: cfg.name, agents: Object.keys(agents) })
|
|
157
|
+
log('连上了:' + label); onChange(); return { ok: true }
|
|
158
|
+
}
|
|
159
|
+
async function onPairRequest(rumor, m) {
|
|
160
|
+
const p = pairing, restoreMode = !!p?.restore
|
|
161
|
+
if (!p || p.request || Date.now() > p.expires || m.type !== (restoreMode ? 'restore.request' : 'pair.request')) return
|
|
162
|
+
if (m.code !== p.code) return send(rumor.pubkey, { type: restoreMode ? 'restore.failed' : 'pair.failed', reason: '连接码不对或已经过期,看一眼电脑上的新码' })
|
|
163
|
+
// 手机要领过鱼Sho号(中继才会放行发给它的消息),并且号码真是这部手机的
|
|
164
|
+
let number = /^\d{6,15}$/.test(String(m.number ?? '')) ? String(m.number) : null
|
|
165
|
+
if (number) { try { const j = await (await fetch(`${cfg.idService}/.well-known/nostr.json?name=${number}`, { signal: AbortSignal.timeout(10000) })).json(); if (j?.names?.[number] !== rumor.pubkey) number = null } catch { number = null } }
|
|
166
|
+
if (!number && !restoreMode) return send(rumor.pubkey, { type: 'pair.failed', reason: '这部手机还没领到鱼Sho号(联网后会自动领),稍等一下再试' })
|
|
167
|
+
p.request = { pk: rumor.pubkey, label: String(m.label || '手机').slice(0, 40), number, fingerprint: fingerprint(rumor.pubkey), at: Date.now() }
|
|
168
|
+
log(`「${p.request.label}」想连上这台电脑,指纹 ${p.request.fingerprint},等你确认`)
|
|
169
|
+
onChange()
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// ── 收消息
|
|
173
|
+
async function onRumor(rumor) {
|
|
174
|
+
const from = rumor.pubkey, m = parseContent(rumor.content)
|
|
175
|
+
if (m.type === 'pair.request' || m.type === 'restore.request') return onPairRequest(rumor, m)
|
|
176
|
+
const own = owners()
|
|
177
|
+
if (!own.has(from)) { if (revoked().has(from)) return send(from, { type: 'pair.revoked', task_id: m.task_id }); return } // 只听主人的;断开过的告诉它一声
|
|
178
|
+
try { await route(m, from) } catch (e) { log('处理出错', e?.message ?? e); await send(from, { type: 'error', message: String(e?.message ?? e) }) }
|
|
179
|
+
}
|
|
180
|
+
async function route(m, from) {
|
|
181
|
+
if (m.type === 'backup.store') { // 手机的身份备份:换手机时用“从电脑恢复”(只收它自己的钥匙)
|
|
182
|
+
let ok = false; try { ok = getPublicKey(hexToBytes(String(m.sk))) === from } catch {}
|
|
183
|
+
if (!ok) return send(from, { type: 'error', message: '备份里的钥匙和发件人对不上,没存' })
|
|
184
|
+
fs.mkdirSync(F('device-backups'), { recursive: true, mode: 0o700 })
|
|
185
|
+
fs.writeFileSync(F('device-backups/' + from + '.json'), JSON.stringify({ pk: from, label: owners().get(from), sk: m.sk, members: m.members ?? [], at: Date.now() }), { mode: 0o600 })
|
|
186
|
+
return send(from, { type: 'backup.ok', at: Date.now() })
|
|
187
|
+
}
|
|
188
|
+
if (m.type === 'file.rtc') { if (p2p?.create) { rtc ??= p2p.create({ send: (pk, o) => send(pk, o), iceServers: p2p.iceServers, log: (...a) => log(...a) }); rtc.onSignal(from, m, (link) => lan.serveLink(link)) } else send(from, { type: 'file.rtc', sid: m.sid, k: 'nope', reason: '这台电脑的连接器不能打洞直连' }); return }
|
|
189
|
+
if (m.type === 'file.offer') { try { return send(from, await lan.offer(m, (ev) => send(from, ev))) } catch (e) { return send(from, { type: 'file.failed', id: m.id, reason: e.message }) } }
|
|
190
|
+
if (m.type === 'file.request') { try { return send(from, await lan.request(m)) } catch (e) { return send(from, { type: 'file.failed', id: m.id ?? null, req: m.req ?? null, reason: e.message }) } }
|
|
191
|
+
if (m.type === 'task.create') return runTask(m, from)
|
|
192
|
+
if (m.type === 'task.approve') return resolveApproval(m.task_id, m.request_id, m.option_id)
|
|
193
|
+
if (m.type === 'task.cancel') return tasks.get(m.task_id)?.cancel()
|
|
194
|
+
if (m.type === 'task.query') return send(from, results.has(m.task_id) ? { ...results.get(m.task_id), resent: true } : { type: 'task.status', task_id: m.task_id, state: tasks.has(m.task_id) ? 'running' : 'unknown' })
|
|
195
|
+
if (m.type === 'ping') return send(from, { type: 'pong', nonce: m.nonce, agents: Object.keys(agents), busy: [...tasks.keys()], opts: agentOpts })
|
|
196
|
+
if (m.type === 'agents.query') return send(from, { type: 'agents.opts', name: cfg.name, opts: agentOpts })
|
|
197
|
+
if (m.type === 'presence.query') return send(from, { type: 'presence.state', who: 'runner', nonce: m.nonce, state: tasks.size ? '工作中' : '空闲', agents: Object.keys(agents) })
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ── 干活:改动的文件加密上传(文件服务器只存密文,钥匙只在给手机的加密消息里)
|
|
201
|
+
const ART = { maxFiles: 10, maxBytes: 50 * 1024 * 1024, maxDepth: 4, maxScan: 2000, skip: new Set(['node_modules', '.git', '.venv', '__pycache__', 'dist', 'build']) }
|
|
202
|
+
function snapshot(dir) {
|
|
203
|
+
const files = new Map()
|
|
204
|
+
const walk = (d, depth) => { if (depth > ART.maxDepth || files.size >= ART.maxScan) return; let es = []; try { es = fs.readdirSync(d, { withFileTypes: true }) } catch { return } for (const e of es) { if (e.name.startsWith('.') || ART.skip.has(e.name)) continue; const p = path.join(d, e.name); if (e.isDirectory()) walk(p, depth + 1); else if (e.isFile()) { try { const st = fs.statSync(p); files.set(p, st.size + ':' + st.mtimeMs) } catch {} } } }
|
|
205
|
+
walk(dir, 0); return files
|
|
206
|
+
}
|
|
207
|
+
async function upload(plain, name) {
|
|
208
|
+
const k = crypto.randomBytes(32), nonce = crypto.randomBytes(12), c = crypto.createCipheriv('aes-256-gcm', k, nonce)
|
|
209
|
+
const cipher = Buffer.concat([c.update(plain), c.final(), c.getAuthTag()]), ch = sha256(cipher), now = Math.floor(Date.now() / 1000)
|
|
210
|
+
const auth = finalizeEvent({ kind: 24242, created_at: now, content: 'upload ' + ch, tags: [['t', 'upload'], ['expiration', String(now + 300)], ['x', ch]] }, key.skBytes)
|
|
211
|
+
const r = await fetch(cfg.blossom + '/upload', { method: 'PUT', headers: { authorization: 'Nostr ' + Buffer.from(JSON.stringify(auth)).toString('base64'), 'content-type': 'application/octet-stream', 'x-sha-256': ch }, body: cipher })
|
|
212
|
+
if (!r.ok) throw new Error('上传失败 HTTP ' + r.status)
|
|
213
|
+
const d = await r.json(); if (d.sha256 !== ch) throw new Error('服务器返回的哈希对不上')
|
|
214
|
+
const ext = path.extname(name).toLowerCase(), MIME = { '.md': 'text/markdown', '.txt': 'text/plain', '.json': 'application/json', '.html': 'text/html', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.svg': 'image/svg+xml', '.pdf': 'application/pdf', '.mp4': 'video/mp4' }
|
|
215
|
+
return { name, size: plain.length, type: MIME[ext] ?? 'application/octet-stream', sha256: sha256(plain), url: d.url, cipher_sha256: ch, key: k.toString('hex'), nonce: nonce.toString('hex'), alg: 'aes-256-gcm' }
|
|
216
|
+
}
|
|
217
|
+
async function collectArtifacts(cwd, before) {
|
|
218
|
+
const after = snapshot(cwd), changed = [...after.entries()].filter(([p, s]) => before.get(p) !== s).map(([p]) => p), out = []
|
|
219
|
+
for (const p of changed.slice(0, ART.maxFiles)) { try { if (fs.statSync(p).size > ART.maxBytes) continue; out.push(await upload(fs.readFileSync(p), path.relative(cwd, p).split(path.sep).join('/'))) } catch (e) { log('文件上传失败', p, e?.message ?? e) } }
|
|
220
|
+
return out
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ── 连续的活接着同一个会话:手机派活时带 thread(同一串活的编号)。同一个 thread、同一个 Agent 的下一件活,
|
|
224
|
+
// 直接在上一件活留下的 Agent 进程和会话里接着说,Agent 记得前面做过什么;新的活(没带 thread)照旧新开会话。
|
|
225
|
+
// 空闲 30 分钟的会话自动关掉;最多同时留 3 个,多了先关最久没用的
|
|
226
|
+
const lives = new Map() // thread → { agent, child, ctx, sessionId, cur, idle, dead, ready, exited, lastUsed }
|
|
227
|
+
const LIVE_IDLE = 30 * 60_000, LIVE_MAX = 3
|
|
228
|
+
// ── 模型、思考等级、快速模式:Agent 在建会话时经 ACP 的 configOptions 报上来(Codex 有;Claude Code 的适配器有就用)。
|
|
229
|
+
// 记在 agent-opts.json 里,跟着 hello / pong 告诉手机;派活时手机带上选择,发任务前用 session/set_config_option 设好
|
|
230
|
+
const OPT_CATS = ['model', 'thought_level', 'speed']
|
|
231
|
+
let agentOpts = (() => { try { return JSON.parse(fs.readFileSync(F('agent-opts.json'), 'utf8')) } catch { return {} } })()
|
|
232
|
+
function noteOpts(agentKey, config) {
|
|
233
|
+
const xs = (config ?? []).filter((c) => OPT_CATS.includes(c.category) && c.type === 'select' && Array.isArray(c.options)).map((c) => ({ id: c.id, category: c.category, name: c.name, current: c.currentValue, options: c.options.slice(0, 40).map((o) => ({ value: o.value, name: o.name, description: String(o.description ?? '').slice(0, 120) })) }))
|
|
234
|
+
if (!xs.length) return
|
|
235
|
+
const sig = JSON.stringify(xs.map((x) => [x.category, x.options.map((o) => o.value)]))
|
|
236
|
+
if (JSON.stringify((agentOpts[agentKey] ?? []).map((x) => [x.category, x.options.map((o) => o.value)])) === sig) return
|
|
237
|
+
agentOpts = { ...agentOpts, [agentKey]: xs }; try { fs.writeFileSync(F('agent-opts.json'), JSON.stringify(agentOpts)) } catch {}
|
|
238
|
+
for (const pk of owners().keys()) send(pk, { type: 'agents.opts', name: cfg.name, opts: agentOpts }).catch(() => {})
|
|
239
|
+
}
|
|
240
|
+
/** 按手机的选择设好这一轮的模型、思考等级、快速模式(先设模型,因为换模型后思考等级的可选项可能变) */
|
|
241
|
+
async function applyOpts(live, want) {
|
|
242
|
+
if (!want || !live.config?.length) return []
|
|
243
|
+
const done = []
|
|
244
|
+
for (const [cat, val] of [['model', want.model], ['thought_level', want.thought], ['speed', want.speed]]) {
|
|
245
|
+
if (val == null || val === '') continue
|
|
246
|
+
const o = live.config.find((c) => c.category === cat); if (!o || o.currentValue === val || !o.options?.some((x) => x.value === val)) continue
|
|
247
|
+
try {
|
|
248
|
+
const r = await live.ctx.request(acp.methods.agent.session.setConfigOption, { sessionId: live.sessionId, configId: o.id, value: val })
|
|
249
|
+
if (Array.isArray(r?.configOptions)) live.config = r.configOptions; else o.currentValue = val
|
|
250
|
+
done.push((o.name || cat) + ':' + (o.options.find((x) => x.value === val)?.name ?? val))
|
|
251
|
+
} catch (e) { log('设置' + (o.name || cat) + '没成:', e?.message ?? e) }
|
|
252
|
+
}
|
|
253
|
+
return done
|
|
254
|
+
}
|
|
255
|
+
function closeLive(thread) { const l = lives.get(thread); if (!l) return; lives.delete(thread); clearTimeout(l.idle); l.dead = true; try { l.close?.() } catch {} killTree(l.child); onChange() }
|
|
256
|
+
function openLive(agentKey, ag, cwd, logName) {
|
|
257
|
+
fs.mkdirSync(F('logs'), { recursive: true })
|
|
258
|
+
const logFile = fs.createWriteStream(F('logs/' + logName + '.' + agentKey + '.log'))
|
|
259
|
+
// 不经过 cmd:npx 直接用 Node 跑 npm 自带的 npx-cli.js(cmd 包一层时,结束一个会把 Ctrl-C 波及同一控制台里的别的 Agent)。
|
|
260
|
+
// 结束时连它开的子进程一起结束(killTree)。非 Windows 单独一个进程组,好整组结束
|
|
261
|
+
const [cmd, args] = launcher(ag)
|
|
262
|
+
const win = process.platform === 'win32'
|
|
263
|
+
const child = spawn(cmd, args, { cwd, env: { ...process.env, ...ag.env }, stdio: ['pipe', 'pipe', 'pipe'], shell: win && cmd !== process.execPath, detached: !win, windowsHide: true })
|
|
264
|
+
child.stderr.pipe(logFile)
|
|
265
|
+
const live = { agent: agentKey, child, ctx: null, sessionId: null, cur: null, idle: null, dead: false, lastUsed: Date.now() }
|
|
266
|
+
live.exited = new Promise((_, rej) => child.on('exit', (code, sig) => { live.dead = true; rej(new Error(`Agent 进程退出(code=${code}${sig ? ', ' + sig : ''})`)) }))
|
|
267
|
+
live.exited.catch(() => {})
|
|
268
|
+
const stream = acp.ndJsonStream(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout))
|
|
269
|
+
const app = acp.client({ name: 'yusho-connect' })
|
|
270
|
+
.onNotification(acp.methods.client.session.update, ({ params }) => live.cur?.onUpdate(params.update))
|
|
271
|
+
.onRequest(acp.methods.client.session.requestPermission, async ({ params }) => (live.cur ? live.cur.onPermission(params) : { outcome: { outcome: 'cancelled' } }))
|
|
272
|
+
live.ready = new Promise((ok, no) => {
|
|
273
|
+
app.connectWith(stream, async (ctx) => {
|
|
274
|
+
await ctx.request(acp.methods.agent.initialize, { protocolVersion: acp.PROTOCOL_VERSION, clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false } })
|
|
275
|
+
const sNew = await ctx.request(acp.methods.agent.session.new, { cwd, mcpServers: [] }), { sessionId } = sNew
|
|
276
|
+
live.config = Array.isArray(sNew.configOptions) ? sNew.configOptions : []; noteOpts(agentKey, live.config)
|
|
277
|
+
live.modes = sNew.modes ?? null // 权限模式(Claude Code:default 每次问 / acceptEdits / auto …)
|
|
278
|
+
live.ctx = ctx; live.sessionId = sessionId; ok()
|
|
279
|
+
await new Promise((r) => { live.close = r }) // 会话一直开着,直到关掉
|
|
280
|
+
}).catch(no)
|
|
281
|
+
live.exited.catch(no)
|
|
282
|
+
})
|
|
283
|
+
live.ready.catch(() => {})
|
|
284
|
+
return live
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
let seq = 0
|
|
288
|
+
const STALL_MS = Math.max(60_000, Number(process.env.YUSHO_STALL_MS) || 10 * 60_000)
|
|
289
|
+
async function runTask(t, from) {
|
|
290
|
+
const task_id = t.task_id ?? 't_' + Date.now().toString(36) + (seq++).toString(36)
|
|
291
|
+
// 手机重发同一件活(之前没收到接单):在做就再回一次接单,做完了就把结果再发一遍,不重复做
|
|
292
|
+
if (tasks.has(task_id)) return send(from, { type: 'task.ack', task_id, agent: t.agent, note: '已经在做了', resent: true })
|
|
293
|
+
if (results.has(task_id)) return send(from, { ...results.get(task_id), resent: true })
|
|
294
|
+
const reply = (p) => { if (p.type === 'task.result' || p.type === 'task.failed') saveResult(task_id, p); return send(from, p) }
|
|
295
|
+
const ag = agents[t.agent]
|
|
296
|
+
if (!ag) return reply({ type: 'task.failed', task_id, reason: `这台电脑上没有 ${t.agent}(有:${Object.keys(agents).join('、') || '无'})` })
|
|
297
|
+
if (typeof ag.run === 'function') return runCustom(t, from, task_id, ag, reply)
|
|
298
|
+
const thread = /^[\w:.-]{4,80}$/.test(String(t.thread ?? '')) ? from.slice(0, 8) + ':' + t.thread : null
|
|
299
|
+
if (!thread) return runTaskIn(t, from, task_id, ag, reply, null, false)
|
|
300
|
+
// 同一串对话(同一个 thread)一件一件来:上一件还在做,这件先接单、排在它后面,等它做完接着同一个会话做(不打断它、不串话)。
|
|
301
|
+
// 不同的对话照样同时做
|
|
302
|
+
const prev = threadQ.get(thread)
|
|
303
|
+
let release; const gate = new Promise((r) => { release = r })
|
|
304
|
+
const chain = (prev ?? Promise.resolve()).then(() => gate)
|
|
305
|
+
threadQ.set(thread, chain)
|
|
306
|
+
let queued = false
|
|
307
|
+
if (prev) {
|
|
308
|
+
queued = true
|
|
309
|
+
let stop = false
|
|
310
|
+
tasks.set(task_id, { pendingApprovals: new Map(), cancel: () => { stop = true }, agent: t.agent, title: t.title ?? String(t.instruction).slice(0, 20), started: Date.now(), thread, queued: true }); onChange()
|
|
311
|
+
await reply({ type: 'task.ack', task_id, agent: t.agent, cwd: cfg.workDir, instruction: t.instruction, note: '排在上一件后面:它做完就接着同一个会话做', session: 'continued', queued: true })
|
|
312
|
+
await prev
|
|
313
|
+
tasks.delete(task_id)
|
|
314
|
+
if (stop) { release(); if (threadQ.get(thread) === chain) threadQ.delete(thread); onChange(); return reply({ type: 'task.failed', task_id, reason: '手机上叫停了(还没开始做)' }) }
|
|
315
|
+
await reply({ type: 'task.progress', task_id, lines: ['上一件做完了,开始做这件'] })
|
|
316
|
+
}
|
|
317
|
+
try { return await runTaskIn(t, from, task_id, ag, reply, thread, queued) }
|
|
318
|
+
finally { release(); if (threadQ.get(thread) === chain) threadQ.delete(thread) }
|
|
319
|
+
}
|
|
320
|
+
const threadQ = new Map() // thread → 这串对话里最后一件活做完的时候
|
|
321
|
+
async function runTaskIn(t, from, task_id, ag, reply, thread, acked) {
|
|
322
|
+
const cwd = cfg.workDir // 只在工作目录里干活
|
|
323
|
+
let live = thread ? lives.get(thread) : null
|
|
324
|
+
if (live && (live.dead || live.agent !== t.agent || live.cur)) live = null // 进程没了、换了 Agent、或者上一件还在做:新开
|
|
325
|
+
const continued = !!live
|
|
326
|
+
if (!live) {
|
|
327
|
+
if (thread) { closeLive(thread); const idle = [...lives.entries()].filter(([, l]) => !l.cur).sort((a, b) => a[1].lastUsed - b[1].lastUsed); while (lives.size >= LIVE_MAX && idle.length) closeLive(idle.shift()[0]) }
|
|
328
|
+
live = openLive(t.agent, ag, cwd, task_id)
|
|
329
|
+
if (thread) lives.set(thread, live)
|
|
330
|
+
}
|
|
331
|
+
clearTimeout(live.idle); live.lastUsed = Date.now()
|
|
332
|
+
const state = { pendingApprovals: new Map(), cancel: () => {}, agent: t.agent, title: t.title ?? String(t.instruction).slice(0, 20), started: Date.now(), thread }
|
|
333
|
+
tasks.set(task_id, state); onChange()
|
|
334
|
+
const before = snapshot(cwd), started = Date.now()
|
|
335
|
+
if (!acked) await reply({ type: 'task.ack', task_id, agent: t.agent, cwd, instruction: t.instruction, note: continued ? '已接单,接着上次的会话做' : '已接单,开始执行', session: continued ? 'continued' : 'new' })
|
|
336
|
+
let progress = [], finalText = '', preamble = ''
|
|
337
|
+
const titles = new Map(), short = (s) => (s.length > 80 ? s.slice(0, 77) + '…' : s)
|
|
338
|
+
const flush = async () => { if (progress.length) { const lines = progress; progress = []; await reply({ type: 'task.progress', task_id, lines }) } }
|
|
339
|
+
const timer = setInterval(flush, 4000)
|
|
340
|
+
let limitTimer, stallTimer, lastAct = Date.now()
|
|
341
|
+
const overtime = new Promise((_, rej) => {
|
|
342
|
+
limitTimer = setTimeout(() => { state.cancel(); rej(new Error('超过 30 分钟,已取消')) }, 30 * 60_000)
|
|
343
|
+
// 卡住了:Agent 一直没有任何输出、也不在等你批,10 分钟就停掉,免得白白耗额度
|
|
344
|
+
stallTimer = setInterval(() => { if (!state.pendingApprovals.size && Date.now() - lastAct > STALL_MS) { state.cancel(); rej(new Error(Math.round(STALL_MS / 60000) + ' 分钟没有任何动静,自动停了(防止卡住白耗额度)')) } }, 30_000)
|
|
345
|
+
})
|
|
346
|
+
// 叫停:先请它停(ACP 的 session/cancel),6 秒还没停就直接结束进程——有的 Agent 不理取消,会把活做完
|
|
347
|
+
let stopNow, killed = false
|
|
348
|
+
const stopped = new Promise((_, rej) => { stopNow = () => rej(new Error('手机上叫停了')) })
|
|
349
|
+
state.cancel = () => { if (live.ctx) live.ctx.notify(acp.methods.agent.session.cancel, { sessionId: live.sessionId }).catch(() => {}); setTimeout(() => { if (!tasks.has(task_id)) return; killed = true; stopNow(); if (thread) closeLive(thread); else killTree(live.child) }, 6000).unref?.() }
|
|
350
|
+
overtime.catch(() => {}); stopped.catch(() => {})
|
|
351
|
+
live.cur = {
|
|
352
|
+
onUpdate(u) {
|
|
353
|
+
lastAct = Date.now()
|
|
354
|
+
if (u.sessionUpdate === 'agent_message_chunk' && u.content?.type === 'text') finalText += u.content.text
|
|
355
|
+
else if (u.sessionUpdate === 'tool_call') { if (finalText.trim()) { preamble = finalText; finalText = '' } titles.set(u.toolCallId, short(u.title ?? u.kind ?? '工具调用')); progress.push('▶ ' + titles.get(u.toolCallId)) }
|
|
356
|
+
else if (u.sessionUpdate === 'tool_call_update') { if (u.title) titles.set(u.toolCallId, short(u.title)); if (u.status === 'completed' || u.status === 'failed') progress.push((u.status === 'completed' ? '✓ ' : '✗ ') + (titles.get(u.toolCallId) ?? u.toolCallId)) }
|
|
357
|
+
else if (u.sessionUpdate === 'plan') progress.push('计划:' + (u.entries ?? []).map((e) => `[${e.status === 'completed' ? 'x' : ' '}] ${e.content}`).join(';'))
|
|
358
|
+
},
|
|
359
|
+
async onPermission(params) {
|
|
360
|
+
// Agent 要权限:一律转给主人(派活的那部手机)批,10 分钟没人批就算拒绝
|
|
361
|
+
const request_id = 'r' + (state.pendingApprovals.size + 1)
|
|
362
|
+
const options = params.options.map((o, i) => ({ n: i + 1, id: o.optionId, name: o.name, kind: o.kind }))
|
|
363
|
+
await flush()
|
|
364
|
+
await reply({ type: 'task.need_approval', task_id, request_id, action: params.toolCall?.title ?? '未知操作', options })
|
|
365
|
+
onChange()
|
|
366
|
+
const optionId = await new Promise((res) => { state.pendingApprovals.set(request_id, { res, options }); setTimeout(() => res(null), 600_000) })
|
|
367
|
+
state.pendingApprovals.delete(request_id); lastAct = Date.now(); onChange()
|
|
368
|
+
return optionId ? { outcome: { outcome: 'selected', optionId } } : { outcome: { outcome: 'cancelled' } }
|
|
369
|
+
},
|
|
370
|
+
}
|
|
371
|
+
// 新开的会话:手机附带的“之前说过的”放在前面让它接得上;接着原来的会话就不用了(它自己记得)
|
|
372
|
+
const text = (!continued && t.context ? '[我们之前说过的(只作参考,不用再做)]\n' + String(t.context) + '\n\n[现在]\n' : '') + String(t.instruction)
|
|
373
|
+
try {
|
|
374
|
+
await Promise.race([live.exited, overtime, stopped, live.ready])
|
|
375
|
+
const set = await applyOpts(live, t.opts); if (set.length) { progress.push('用 ' + set.join(',')); await flush() }
|
|
376
|
+
// 手机上选了“每次问我”:Agent 自己默认是自动模式的(Claude Code 默认 auto,改文件不问),这件活切到“每次都问”
|
|
377
|
+
// 各家“每次问”的模式名不一样:Claude Code 叫 default,Codex 叫 read-only(改文件、跑命令、联网都先问)
|
|
378
|
+
const askMode = t.perm === 'ask' ? ['default', 'read-only'].find((id) => live.modes?.availableModes?.some((x) => x.id === id)) : null
|
|
379
|
+
if (askMode && live.modes.currentModeId !== askMode) {
|
|
380
|
+
try { await live.ctx.request(acp.methods.agent.session.setMode, { sessionId: live.sessionId, modeId: askMode }); live.modes.currentModeId = askMode; progress.push('按你的设置:要权限的操作每次先问你') } catch (e) { log('切换权限模式没成', e?.message) }
|
|
381
|
+
}
|
|
382
|
+
const stopReason = await Promise.race([live.exited, overtime, stopped, live.ctx.request(acp.methods.agent.session.prompt, { sessionId: live.sessionId, prompt: [{ type: 'text', text }] }).then((r) => r.stopReason)])
|
|
383
|
+
await flush()
|
|
384
|
+
const seconds = Math.round((Date.now() - started) / 1000), artifacts = await collectArtifacts(cwd, before)
|
|
385
|
+
if (stopReason === 'end_turn') await reply({ type: 'task.result', task_id, agent: t.agent, seconds, text: finalText.trim() || preamble.trim() || '(Agent 没有输出文字)', ...(artifacts.length ? { artifacts } : {}) })
|
|
386
|
+
else await reply({ type: 'task.failed', task_id, reason: stopReason === 'cancelled' ? '手机上叫停了' : '停止原因:' + stopReason, seconds, text: (finalText.trim() || preamble.trim()) })
|
|
387
|
+
} catch (e) {
|
|
388
|
+
await flush(); await reply({ type: 'task.failed', task_id, reason: errText(e) })
|
|
389
|
+
} finally {
|
|
390
|
+
clearInterval(timer); clearTimeout(limitTimer); clearInterval(stallTimer); tasks.delete(task_id); live.cur = null; live.lastUsed = Date.now()
|
|
391
|
+
// 连续的活:会话留着等下一件(30 分钟没动静就关);单件的活:做完就关
|
|
392
|
+
if (thread && !live.dead && !killed) live.idle = setTimeout(() => closeLive(thread), LIVE_IDLE)
|
|
393
|
+
else if (thread) closeLive(thread)
|
|
394
|
+
else { try { live.close?.() } catch {} killTree(live.child) }
|
|
395
|
+
onChange()
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
// 宿主自己跑的 Agent:接单、进度、要你批(手机和电脑两边,哪边先批算哪边)、叫停、结果和交回的文件都和别的 Agent 一样
|
|
399
|
+
async function runCustom(t, from, task_id, ag, reply) {
|
|
400
|
+
const cwd = cfg.workDir, ac = new AbortController(), started = Date.now(), before = snapshot(cwd)
|
|
401
|
+
const state = { pendingApprovals: new Map(), cancel: () => ac.abort(), agent: t.agent, title: t.title ?? String(t.instruction).slice(0, 20), started, thread: null }
|
|
402
|
+
tasks.set(task_id, state); onChange()
|
|
403
|
+
await reply({ type: 'task.ack', task_id, agent: t.agent, cwd, instruction: t.instruction, note: '已接单,开始执行', session: 'new' })
|
|
404
|
+
let n = 0
|
|
405
|
+
const approval = async (action) => {
|
|
406
|
+
const request_id = 'r' + ++n, options = [{ n: 1, id: 'allow_once', name: '允许这一次', kind: 'allow_once' }, { n: 2, id: 'reject_once', name: '拒绝', kind: 'reject_once' }]
|
|
407
|
+
let res; const answer = new Promise((ok) => { res = ok })
|
|
408
|
+
state.pendingApprovals.set(request_id, { res, options }); onChange()
|
|
409
|
+
await reply({ type: 'task.need_approval', task_id, request_id, action, options })
|
|
410
|
+
return {
|
|
411
|
+
answer: answer.then((id) => (id === 'allow_once' ? 'allow' : id ? 'reject' : null)),
|
|
412
|
+
// 电脑上先批了:手机那边的“要你批”收起来
|
|
413
|
+
done: (outcome) => { if (!state.pendingApprovals.delete(request_id)) return; res(null); onChange(); send(from, { type: 'task.approved', task_id, request_id, outcome }).catch(() => {}) },
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const progress = (lines) => reply({ type: 'task.progress', task_id, lines: [].concat(lines).map(String) }).catch(() => {})
|
|
417
|
+
try {
|
|
418
|
+
// thread:手机上同一段对话(接着说的活)——宿主可以接着用同一个会话,不用再带“之前说过的”
|
|
419
|
+
const thread = /^[\w:.-]{4,80}$/.test(String(t.thread ?? '')) ? from.slice(0, 8) + ':' + t.thread : null
|
|
420
|
+
const r = await ag.run({ task_id, instruction: String(t.instruction), title: state.title, context: t.context ?? null, thread, cwd, signal: ac.signal, progress, approval })
|
|
421
|
+
const seconds = Math.round((Date.now() - started) / 1000), artifacts = await collectArtifacts(cwd, before)
|
|
422
|
+
await reply({ type: 'task.result', task_id, agent: t.agent, seconds, text: String(r?.text ?? '').trim() || '(没有输出文字)', ...(artifacts.length ? { artifacts } : {}) })
|
|
423
|
+
} catch (e) {
|
|
424
|
+
await reply({ type: 'task.failed', task_id, reason: ac.signal.aborted ? '手机上叫停了' : errText(e) })
|
|
425
|
+
} finally { tasks.delete(task_id); onChange() }
|
|
426
|
+
}
|
|
427
|
+
function resolveApproval(task_id, request_id, option_id) {
|
|
428
|
+
const st = tasks.get(task_id); if (!st) return
|
|
429
|
+
const [, p] = request_id ? [request_id, st.pendingApprovals.get(request_id)] : [...st.pendingApprovals.entries()].at(-1) ?? []
|
|
430
|
+
if (!p) return
|
|
431
|
+
const chosen = option_id === 'reject' ? p.options.find((o) => o.kind?.startsWith('reject')) : p.options.find((o) => o.id === option_id)
|
|
432
|
+
p.res(chosen?.id ?? null)
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
return {
|
|
436
|
+
async start() {
|
|
437
|
+
// 同一台电脑同一个身份只能有一个连接器在线(DSH 插件和后台服务二选一),不然手机发一次活会做两遍
|
|
438
|
+
const lk = readJ('running.json', null)
|
|
439
|
+
if (lk && lk.pid !== process.pid && alive(lk.pid)) throw new Error('连接器已经在' + lk.owner + '里运行(进程 ' + lk.pid + '),到那边管理')
|
|
440
|
+
writeJ('running.json', { pid: process.pid, owner, at: Date.now() })
|
|
441
|
+
try { await claimNumber() } catch (e) { log(e.message + '。没有号,手机连不上;每分钟再试一次'); const t = setInterval(() => claimNumber().then(() => { clearInterval(t); onChange() }).catch(() => {}), 60000); t.unref?.() }
|
|
442
|
+
inbox = await openInbox(cfg.relay, key, (r) => onRumor(r).catch((e) => log('出错', e?.message ?? e)), { log })
|
|
443
|
+
// 告诉连着的手机:现在这台电脑能用哪些 Agent(装了 / 卸了 / 登录了,手机上的列表跟着变)
|
|
444
|
+
for (const pk of owners().keys()) send(pk, { type: 'hello', name: cfg.name, agents: Object.keys(agents), opts: agentOpts }).catch(() => {})
|
|
445
|
+
// 还不知道某个 Agent 有哪些模型、思考等级:开一次会话读一下就关(不发任务,不花额度),读到了会告诉手机
|
|
446
|
+
setTimeout(async () => {
|
|
447
|
+
for (const k of Object.keys(agents)) {
|
|
448
|
+
if (k === 'dsh' || agentOpts[k]) continue
|
|
449
|
+
try { const l = openLive(k, agents[k], cfg.workDir, 'probe'); await Promise.race([l.ready, l.exited, new Promise((_, no) => setTimeout(() => no(new Error('3 分钟没连上')), 180_000))]); try { l.close?.() } catch {} ; killTree(l.child) } catch (e) { log('读 ' + k + ' 的模型列表没成:', e?.message ?? e) }
|
|
450
|
+
}
|
|
451
|
+
}, 15_000)
|
|
452
|
+
log(`连接器在线:${cfg.name}(鱼Sho号 ${id.number ?? '没领到'}),Agent:${Object.keys(agents).join('、') || '没找到'},工作目录 ${cfg.workDir}`)
|
|
453
|
+
onChange()
|
|
454
|
+
},
|
|
455
|
+
...(sink ? { _rumor: (pubkey, m) => onRumor({ pubkey, content: JSON.stringify({ shoal: 1, ...m }) }) } : {}), // 测试用:不经中继直接收一条
|
|
456
|
+
/** 电脑主动把文件发给手机(主人的设备都发;手机收到后自己来拿) */
|
|
457
|
+
async pushFiles(paths) { const out = []; for (const p of (Array.isArray(paths) ? paths : []).slice(0, 20)) { const m = await lan.push(p); for (const pk of owners().keys()) await send(pk, m).catch(() => {}); out.push({ id: m.id, name: m.name, size: m.size }) } return out },
|
|
458
|
+
files: () => lan.list(), saveDir: () => lan.saveDir,
|
|
459
|
+
info: () => ({ agentOpts, hints: cfg.agents ? [] : agentHints(agents), name: cfg.name, pk: id.pk, fingerprint: fingerprint(id.pk), number: id.number ?? null, agents: Object.keys(agents), workDir: cfg.workDir, home, online: !!inbox?.relay, devices: devices().map(({ pk, label, number, added, revoked: rv }) => ({ pk, label, number, added, revoked: rv ?? null, fingerprint: fingerprint(pk) })), tasks: [...tasks].map(([tid, s]) => ({ id: tid, agent: s.agent, title: s.title, started: s.started, waiting: s.pendingApprovals.size > 0 })), pairing: pairing ? { code: pairing.code, expires: pairing.expires, qr: 'yusho:pair?c=' + pairing.code + '&k=' + id.pk, request: pairing.request, restore: !!pairing.restore } : null }),
|
|
460
|
+
startPairing, cancelPairing, answerPairing,
|
|
461
|
+
/** 换手机:把这台电脑上存的某部手机的身份备份交给新手机 */
|
|
462
|
+
backups: () => { const d = F('device-backups'); return fs.existsSync(d) ? fs.readdirSync(d).filter((f) => f.endsWith('.json')).map((f) => JSON.parse(fs.readFileSync(path.join(d, f), 'utf8'))).map(({ pk, label, at }) => ({ pk, label, at, fingerprint: fingerprint(pk) })) : [] },
|
|
463
|
+
startRestore(pk) { const p = F('device-backups/' + pk + '.json'); if (!fs.existsSync(p)) throw new Error('没有这部手机的备份'); return startPairing({ restore: JSON.parse(fs.readFileSync(p, 'utf8')) }) },
|
|
464
|
+
removeDevice(pk) { const d = devices(), x = d.find((y) => y.pk === pk || y.pk.startsWith(String(pk).toLowerCase())); if (!x) throw new Error('没有这台设备'); x.revoked = Date.now(); writeJ('devices.json', d); onChange(); return x },
|
|
465
|
+
_runTaskForTest: (t, from) => runTask(t, from),
|
|
466
|
+
stop() { for (const k of [...lives.keys()]) closeLive(k); inbox?.close(); if (readJ('running.json', null)?.pid === process.pid) fs.rmSync(F('running.json'), { force: true }) },
|
|
467
|
+
}
|
|
468
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// DSH(DeepSeek Harness)的 ACP 适配器:把 `dsh --profile headless --json` 包装成标准 ACP Agent(stdio)。
|
|
2
|
+
// 执行端用同一套 ACP 客户端代码即可驱动 DSH,和 Codex / Claude Code 一样。
|
|
3
|
+
//
|
|
4
|
+
// 映射:
|
|
5
|
+
// session/new → 记下工作目录,返回本地会话号(首次 prompt 后绑定 DSH 的 sessionId,后续轮次续用)
|
|
6
|
+
// session/prompt → 启动一次 dsh headless,任务从 stdin 传入;NDJSON 事件转成 session/update
|
|
7
|
+
// session/cancel → 结束 dsh 进程
|
|
8
|
+
// 限制:DSH headless 不能交互式审批,这里固定 --approval-policy never(超出权限预设的操作直接被拒),
|
|
9
|
+
// 所以 DSH 的审批暂时无法转给主人。
|
|
10
|
+
import { spawn } from 'node:child_process'
|
|
11
|
+
import { Readable, Writable } from 'node:stream'
|
|
12
|
+
import { createInterface } from 'node:readline'
|
|
13
|
+
import { resolve, join } from 'node:path'
|
|
14
|
+
import { existsSync, readFileSync, writeFileSync, rmSync } from 'node:fs'
|
|
15
|
+
import { tmpdir } from 'node:os'
|
|
16
|
+
import { fileURLToPath } from 'node:url'
|
|
17
|
+
import * as acp from '@agentclientprotocol/sdk'
|
|
18
|
+
|
|
19
|
+
const DSH = process.env.DSH_BIN || 'dsh'
|
|
20
|
+
const PATCH0 = process.env.DSH_PATCH || fileURLToPath(new URL('./dsh-headless.patch.yml', import.meta.url)) // 随连接器带的补丁
|
|
21
|
+
// 装在某个 DSH 配置(profile)里当插件时:把那个配置里选好的模型(llm-* 的服务商设置、agent-default-model)
|
|
22
|
+
// 一起带给 headless,不然 headless 用默认的 DeepSeek 官方线路,没有密钥就报 MISSING_CREDENTIAL
|
|
23
|
+
function buildPatch() {
|
|
24
|
+
try {
|
|
25
|
+
const here = fileURLToPath(import.meta.url), m = /^(.*[\\/]profiles[\\/][^\\/]+)[\\/]node_modules[\\/]/.exec(here)
|
|
26
|
+
const host = process.env.DSH_HOST_PROFILE_DIR || (m && m[1]); if (!host || !existsSync(join(host, 'cordis.patch.yml'))) return PATCH0
|
|
27
|
+
const keep = []; let on = false
|
|
28
|
+
for (const line of readFileSync(join(host, 'cordis.patch.yml'), 'utf8').split(/\r?\n/)) {
|
|
29
|
+
if (/^- /.test(line)) on = /^- id:\s*["']?(llm-[\w-]+|agent-default-model)["']?\s*$/.test(line)
|
|
30
|
+
if (on) keep.push(line)
|
|
31
|
+
}
|
|
32
|
+
if (!keep.length) return PATCH0
|
|
33
|
+
const out = join(tmpdir(), 'yusho-dsh-headless-' + process.pid + '.patch.yml')
|
|
34
|
+
writeFileSync(out, readFileSync(PATCH0, 'utf8').replace(/\s*$/, '\n') + '# 下面是从 ' + host + ' 复制来的模型设置\n' + keep.join('\n') + '\n')
|
|
35
|
+
process.on('exit', () => { try { rmSync(out) } catch {} })
|
|
36
|
+
return out
|
|
37
|
+
} catch (e) { process.stderr.write('[dsh-acp] 没能带上宿主配置的模型设置:' + e.message + '\n'); return PATCH0 }
|
|
38
|
+
}
|
|
39
|
+
const PATCH = buildPatch()
|
|
40
|
+
const PERMISSION = process.env.DSH_PERMISSION_MODE // 可选:DSH 的权限预设名
|
|
41
|
+
const sessions = new Map() // 本地会话号 -> { cwd, dshSessionId, child }
|
|
42
|
+
let seq = 0
|
|
43
|
+
|
|
44
|
+
const kindOf = (tool) =>
|
|
45
|
+
/read|glob|grep|list|ls|search|find/i.test(tool) ? 'read' : /write|edit|patch/i.test(tool) ? 'edit' : /web|fetch/i.test(tool) ? 'fetch' : /shell|pwsh|bash|exec|run/i.test(tool) ? 'execute' : 'other'
|
|
46
|
+
|
|
47
|
+
const app = acp
|
|
48
|
+
.agent({ name: 'dsh-acp' })
|
|
49
|
+
.onRequest(acp.methods.agent.initialize, () => ({
|
|
50
|
+
protocolVersion: acp.PROTOCOL_VERSION,
|
|
51
|
+
agentCapabilities: { loadSession: false, promptCapabilities: { image: false, audio: false, embeddedContext: false } },
|
|
52
|
+
agentInfo: { name: 'dsh-acp', version: '0.0.1' },
|
|
53
|
+
authMethods: [],
|
|
54
|
+
}))
|
|
55
|
+
.onRequest(acp.methods.agent.session.new, ({ params }) => {
|
|
56
|
+
const sessionId = `dsh-acp-${Date.now().toString(36)}-${seq++}`
|
|
57
|
+
sessions.set(sessionId, { cwd: params.cwd, dshSessionId: null, child: null })
|
|
58
|
+
return { sessionId }
|
|
59
|
+
})
|
|
60
|
+
.onNotification(acp.methods.agent.session.cancel, ({ params }) => {
|
|
61
|
+
sessions.get(params.sessionId)?.child?.kill()
|
|
62
|
+
})
|
|
63
|
+
.onRequest(acp.methods.agent.session.prompt, async ({ params, client }) => {
|
|
64
|
+
const s = sessions.get(params.sessionId)
|
|
65
|
+
if (!s) throw acp.RequestError.invalidParams?.('unknown session') ?? new Error('unknown session')
|
|
66
|
+
const text = params.prompt.filter((b) => b.type === 'text').map((b) => b.text).join('\n')
|
|
67
|
+
const update = (u) => client.notify(acp.methods.client.session.update, { sessionId: params.sessionId, update: u })
|
|
68
|
+
|
|
69
|
+
const win = process.platform === 'win32'
|
|
70
|
+
const args = ['--profile', 'headless', '--patch', win ? `"${PATCH}"` : PATCH, '--json', '--approval-policy', 'never'] // Windows 要走 shell 才找得到 dsh.cmd,路径得加引号;Linux / macOS 不走 shell,加了引号反而找不到文件
|
|
71
|
+
if (s.dshSessionId) args.push('--session-id', s.dshSessionId)
|
|
72
|
+
if (PERMISSION) args.push('--permission-mode', PERMISSION)
|
|
73
|
+
args.push('-') // 任务从 stdin 读取,避免命令行转义问题
|
|
74
|
+
|
|
75
|
+
const child = spawn(DSH, args, { cwd: s.cwd, shell: win, stdio: ['pipe', 'pipe', 'pipe'] })
|
|
76
|
+
s.child = child
|
|
77
|
+
const spawnErr = new Promise((r) => child.on('error', r)) // 找不到 dsh 命令(比如服务器上 PATH 里没有)
|
|
78
|
+
child.stdin.end(text)
|
|
79
|
+
let stderr = ''
|
|
80
|
+
child.stderr.on('data', (d) => { stderr += d; process.stderr.write(d) })
|
|
81
|
+
|
|
82
|
+
let stopReason = 'end_turn'
|
|
83
|
+
let finalError = null
|
|
84
|
+
const titles = new Map()
|
|
85
|
+
for await (const line of createInterface({ input: child.stdout })) {
|
|
86
|
+
let ev
|
|
87
|
+
try { ev = JSON.parse(line) } catch { continue }
|
|
88
|
+
switch (ev.type) {
|
|
89
|
+
case 'session':
|
|
90
|
+
s.dshSessionId = ev.sessionId
|
|
91
|
+
break
|
|
92
|
+
case 'thinking':
|
|
93
|
+
await update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: ev.text } })
|
|
94
|
+
break
|
|
95
|
+
case 'text':
|
|
96
|
+
await update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: ev.text } })
|
|
97
|
+
break
|
|
98
|
+
case 'tool_call': {
|
|
99
|
+
const title = `${ev.tool} ${JSON.stringify(ev.input ?? {})}`.slice(0, 200)
|
|
100
|
+
titles.set(ev.callId, title)
|
|
101
|
+
await update({ sessionUpdate: 'tool_call', toolCallId: ev.callId, title, kind: kindOf(ev.tool), status: 'in_progress', rawInput: ev.input })
|
|
102
|
+
break
|
|
103
|
+
}
|
|
104
|
+
case 'tool_result':
|
|
105
|
+
await update({
|
|
106
|
+
sessionUpdate: 'tool_call_update',
|
|
107
|
+
toolCallId: ev.callId,
|
|
108
|
+
title: titles.get(ev.callId),
|
|
109
|
+
status: ev.status === 'completed' ? 'completed' : 'failed',
|
|
110
|
+
content: typeof ev.result === 'string' ? [{ type: 'content', content: { type: 'text', text: ev.result.slice(0, 4000) } }] : undefined,
|
|
111
|
+
})
|
|
112
|
+
break
|
|
113
|
+
case 'final':
|
|
114
|
+
if (ev.reason?.kind === 'cancelled') stopReason = 'cancelled'
|
|
115
|
+
else if (ev.reason?.kind === 'error') finalError = ev.reason.error?.message ?? 'DSH 运行出错'
|
|
116
|
+
break
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const code = await Promise.race([new Promise((r) => (child.exitCode !== null ? r(child.exitCode) : child.on('close', r))), spawnErr.then((e) => { finalError = e?.code === 'ENOENT' ? '这台电脑上找不到 dsh 命令(' + DSH + ')。装好 DSH,或者用环境变量 DSH_BIN 指定它的完整路径' : '启动 dsh 失败:' + (e?.message ?? e); return -1 })])
|
|
120
|
+
s.child = null
|
|
121
|
+
if (finalError || (code !== 0 && stopReason !== 'cancelled')) {
|
|
122
|
+
const why = finalError ?? `dsh 退出码 ${code}:${stderr.trim().split('\n').slice(-3).join(' ').slice(0, 500) || '没有输出'}`
|
|
123
|
+
process.stderr.write('[dsh-acp] 没做成:' + why + '\n')
|
|
124
|
+
throw acp.RequestError.internalError({ details: why }, why) // 原因放进错误信息里,手机上能看到
|
|
125
|
+
}
|
|
126
|
+
return { stopReason }
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
app.connect(acp.ndJsonStream(Writable.toWeb(process.stdout), Readable.toWeb(process.stdin)))
|