@yusho/server 0.0.0-stage → 0.1.16

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.
Files changed (115) hide show
  1. package/README.md +135 -2
  2. package/app/appguide.mjs +33 -0
  3. package/app/asr.mjs +82 -0
  4. package/app/assets/agents/claude-192.webp +0 -0
  5. package/app/assets/agents/claude-96.webp +0 -0
  6. package/app/assets/agents/codex-192.webp +0 -0
  7. package/app/assets/agents/codex-96.webp +0 -0
  8. package/app/assets/agents/default-192.webp +0 -0
  9. package/app/assets/agents/default-96.webp +0 -0
  10. package/app/assets/agents/dsh-192.webp +0 -0
  11. package/app/assets/agents/dsh-96.webp +0 -0
  12. package/app/assets/brand/logo.webp +0 -0
  13. package/app/assets/lib/THIRD-PARTY.txt +1 -0
  14. package/app/assets/lib/jsqr.js +10102 -0
  15. package/app/assets/linux/alpine-arm64.tar.gz +0 -0
  16. package/app/assets/linux/alpine-x64.tar.gz +0 -0
  17. package/app/assets/live/claude.livliv +0 -0
  18. package/app/assets/live/dafeiyu.livliv +0 -0
  19. package/app/assets/live/gpt.livliv +0 -0
  20. package/app/assets/live/sho.livliv +0 -0
  21. package/app/assets/live//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
  22. package/app/assets/livliv/LICENSE +202 -0
  23. package/app/assets/livliv/NOTICE +7 -0
  24. package/app/assets/livliv/player.mjs +15 -0
  25. package/app/assets/looks/claude.webp +0 -0
  26. package/app/assets/looks/dafeiyu.webp +0 -0
  27. package/app/assets/looks/gpt.webp +0 -0
  28. package/app/assets/looks//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
  29. package/app/assets/sho/avatar.webp +0 -0
  30. package/app/assets/sho/done.webp +0 -0
  31. package/app/assets/sho/eat.webp +0 -0
  32. package/app/assets/sho/idle-blink.webp +0 -0
  33. package/app/assets/sho/idle.webp +0 -0
  34. package/app/assets/sho/listen.webp +0 -0
  35. package/app/assets/sho/need.webp +0 -0
  36. package/app/assets/sho/work.webp +0 -0
  37. package/app/companion.mjs +519 -0
  38. package/app/diag.mjs +51 -0
  39. package/app/index.html +497 -0
  40. package/app/judge.mjs +103 -0
  41. package/app/lanxfer.mjs +157 -0
  42. package/app/launcher.mjs +2711 -0
  43. package/app/linux.mjs +97 -0
  44. package/app/livliv-pack.mjs +12 -0
  45. package/app/memory.mjs +53 -0
  46. package/app/net.mjs +717 -0
  47. package/app/office.mjs +172 -0
  48. package/app/p2plink.mjs +134 -0
  49. package/app/pcupdate.mjs +55 -0
  50. package/app/plans.mjs +126 -0
  51. package/app/plugins.mjs +79 -0
  52. package/app/realtime.mjs +67 -0
  53. package/app/skills/app-icon/SKILL.md +31 -0
  54. package/app/skills/daily-brief/SKILL.md +29 -0
  55. package/app/skills/expense-review/SKILL.md +28 -0
  56. package/app/skills/make-app/SKILL.md +92 -0
  57. package/app/skills/make-skin/SKILL.md +51 -0
  58. package/app/skills/meeting-notes/SKILL.md +23 -0
  59. package/app/skills/reading-notes/SKILL.md +25 -0
  60. package/app/skills/sho-stickers/SKILL.md +34 -0
  61. package/app/skills/sho-stickers/stickers/eat.webp +0 -0
  62. package/app/skills/sho-stickers/stickers/got-it.webp +0 -0
  63. package/app/skills/sho-stickers/stickers/hi.webp +0 -0
  64. package/app/skills/sho-stickers/stickers/huh.webp +0 -0
  65. package/app/skills/sho-stickers/stickers/on-it.webp +0 -0
  66. package/app/skills/sho-stickers/stickers/yay.webp +0 -0
  67. package/app/skills/sho-stickers/stickers.json +12 -0
  68. package/app/skills/study-plan/SKILL.md +30 -0
  69. package/app/skills/trip-planner/SKILL.md +29 -0
  70. package/app/skills/weekly-report/SKILL.md +30 -0
  71. package/app/skills/workout-plan/SKILL.md +30 -0
  72. package/app/skills/writing-polish/SKILL.md +33 -0
  73. package/app/skills.mjs +173 -0
  74. package/app/skins.mjs +40 -0
  75. package/app/social.mjs +1067 -0
  76. package/app/storage.mjs +143 -0
  77. package/app/tts.mjs +68 -0
  78. package/app/ttslocal.mjs +77 -0
  79. package/app/voices.mjs +102 -0
  80. package/backup.mjs +109 -0
  81. package/bin/yusho.mjs +141 -0
  82. package/connector/lib/api.mjs +14 -0
  83. package/connector/lib/autostart.mjs +40 -0
  84. package/connector/lib/client.js +165 -0
  85. package/connector/lib/connector.mjs +468 -0
  86. package/connector/lib/dsh-acp.mjs +129 -0
  87. package/connector/lib/dsh-headless.patch.yml +4 -0
  88. package/connector/lib/dsh-plugin.mjs +80 -0
  89. package/connector/lib/lanfile.mjs +151 -0
  90. package/connector/lib/nostr.mjs +53 -0
  91. package/connector/lib/page.html +121 -0
  92. package/connector/lib/qr.mjs +4 -0
  93. package/connector/lib/service.mjs +54 -0
  94. package/node_modules/@local/shoal-mobile/lib/index.js +485 -0
  95. package/node_modules/@local/shoal-mobile/lib/polyfill.js +82 -0
  96. package/node_modules/@local/shoal-mobile/lib/session-context.js +34 -0
  97. package/node_modules/@local/shoal-mobile/lib/shell.js +60 -0
  98. package/node_modules/@local/shoal-mobile/lib/web-startup.js +33 -0
  99. package/node_modules/@local/shoal-mobile/package.json +24 -0
  100. package/node_modules/@local/yusho-pc/lib/client.js +9100 -0
  101. package/node_modules/@local/yusho-pc/lib/index.js +3 -0
  102. package/node_modules/@local/yusho-pc/package.json +28 -0
  103. package/node_modules/@local/yusho-web-login/brand/icon-192.webp +0 -0
  104. package/node_modules/@local/yusho-web-login/brand/logo-dark.svg +25 -0
  105. package/node_modules/@local/yusho-web-login/brand.mjs +8 -0
  106. package/node_modules/@local/yusho-web-login/dsh-web-login.mjs +974 -0
  107. package/node_modules/@local/yusho-web-login/lib/client.js +607 -0
  108. package/node_modules/@local/yusho-web-login/login-page.mjs +609 -0
  109. package/node_modules/@local/yusho-web-login/login-store.mjs +708 -0
  110. package/node_modules/@local/yusho-web-login/package.json +25 -0
  111. package/node_modules/@local/yusho-web-login/whale-scene.mjs +509 -0
  112. package/node_modules/@local/yusho-web-login/yusho-scene.mjs +227 -0
  113. package/package.json +38 -4
  114. package/pc.patch.yml +83 -0
  115. package/run.mjs +136 -0
package/app/office.mjs ADDED
@@ -0,0 +1,172 @@
1
+ // 读 zip(PPT、Word、Excel 都是 zip 包):只读中央目录 + 解压单个条目,不用第三方库
2
+ import fs from 'node:fs'
3
+ import zlib from 'node:zlib'
4
+
5
+ /** 打开一个 zip:返回 { names, read(name) → Buffer|null }。条目超过 20 MB 不解(防炸弹) */
6
+ export function openZip(file) {
7
+ const buf = fs.readFileSync(file)
8
+ let e = -1
9
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65557); i--) if (buf.readUInt32LE(i) === 0x06054b50) { e = i; break }
10
+ if (e < 0) throw new Error('不是 zip 文件')
11
+ const count = buf.readUInt16LE(e + 10), cdOff = buf.readUInt32LE(e + 16), ents = new Map()
12
+ for (let p = cdOff, k = 0; k < count && p + 46 <= buf.length; k++) {
13
+ if (buf.readUInt32LE(p) !== 0x02014b50) break
14
+ const method = buf.readUInt16LE(p + 10), csize = buf.readUInt32LE(p + 20), usize = buf.readUInt32LE(p + 24), nl = buf.readUInt16LE(p + 28), xl = buf.readUInt16LE(p + 30), cl = buf.readUInt16LE(p + 32), lho = buf.readUInt32LE(p + 42)
15
+ ents.set(buf.subarray(p + 46, p + 46 + nl).toString('utf8'), { method, csize, usize, lho })
16
+ p += 46 + nl + xl + cl
17
+ }
18
+ return {
19
+ names: [...ents.keys()],
20
+ read(name) {
21
+ const x = ents.get(name); if (!x || x.usize > 20_000_000) return null
22
+ const nl = buf.readUInt16LE(x.lho + 26), xl = buf.readUInt16LE(x.lho + 28), start = x.lho + 30 + nl + xl, data = buf.subarray(start, start + x.csize)
23
+ return x.method === 0 ? Buffer.from(data) : x.method === 8 ? zlib.inflateRawSync(data, { maxOutputLength: 20_000_000 }) : null
24
+ },
25
+ }
26
+ }
27
+
28
+ const unxml = (s) => String(s).replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(+n)).replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16))).replace(/&amp;/g, '&')
29
+ const rels = (z, file) => { const m = new Map(), dir = file.replace(/[^/]+$/, ''), x = z.read(dir + '_rels/' + file.slice(dir.length) + '.rels'); if (!x) return m; for (const r of x.toString('utf8').matchAll(/<Relationship\b[^>]*>/g)) { const id = /Id="([^"]+)"/.exec(r[0])?.[1], t = /Target="([^"]+)"/.exec(r[0])?.[1]; if (id && t) m.set(id, t.startsWith('/') ? t.slice(1) : normalize(dir + t)) } return m }
30
+ const normalize = (p) => { const out = []; for (const s of p.split('/')) { if (s === '..') out.pop(); else if (s && s !== '.') out.push(s) } return out.join('/') }
31
+ const nat = (a, b) => (parseInt(/(\d+)\.xml$/.exec(a)?.[1]) || 0) - (parseInt(/(\d+)\.xml$/.exec(b)?.[1]) || 0)
32
+
33
+ /** PPT:每页的标题、文字(按段落)、图片(zip 里的路径) */
34
+ function pptx(z) {
35
+ const slides = z.names.filter((n) => /^ppt\/slides\/slide\d+\.xml$/.test(n)).sort(nat), ctx = pptCtx(z)
36
+ return { kind: 'pptx', slides: slides.slice(0, 200).map((n) => {
37
+ const x = z.read(n).toString('utf8'), r = rels(z, n), paras = []
38
+ let title = ''
39
+ for (const sp of x.matchAll(/<p:sp\b[\s\S]*?<\/p:sp>/g)) {
40
+ const isTitle = /<p:ph[^>]*type="(title|ctrTitle)"/.test(sp[0])
41
+ const ps = [...sp[0].matchAll(/<a:p\b[\s\S]*?<\/a:p>/g)].map((p) => ({ t: [...p[0].matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((t) => unxml(t[1])).join(''), lvl: +(/<a:pPr[^>]*lvl="(\d)"/.exec(p[0])?.[1] ?? 0) })).filter((p) => p.t.trim())
42
+ if (isTitle && !title) title = ps.map((p) => p.t).join(' ')
43
+ else paras.push(...ps)
44
+ }
45
+ for (const t of x.matchAll(/<a:tbl>[\s\S]*?<\/a:tbl>/g)) for (const row of t[0].matchAll(/<a:tr\b[\s\S]*?<\/a:tr>/g)) paras.push({ t: [...row[0].matchAll(/<a:tc\b[\s\S]*?<\/a:tc>/g)].map((c) => [...c[0].matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((q) => unxml(q[1])).join('')).join(' | '), lvl: 0 })
46
+ const images = [...x.matchAll(/r:embed="([^"]+)"/g)].map((m) => r.get(m[1])).filter((p) => p && /\.(png|jpe?g|gif|webp|bmp)$/i.test(p))
47
+ const notesN = [...r.values()].find((p) => /notesSlide/.test(p)), notes = notesN && z.read(notesN) ? [...z.read(notesN).toString('utf8').matchAll(/<p:sp\b[\s\S]*?<\/p:sp>/g)].filter((sp) => !/type="(sldNum|sldImg|hdr|ftr|dt)"/.test(sp[0])).map((sp) => [...sp[0].matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((t) => unxml(t[1])).join('')).join('\n').trim() : ''
48
+ if (!title && paras.length > 1 && paras[0].t.length <= 40) title = paras.shift().t // 没有标题占位的:第一行当标题
49
+ return { title, paras: paras.slice(0, 60), images: [...new Set(images)].slice(0, 6), notes: notes.slice(0, 1000), ...slideLayout(z, n, x, r, ctx) }
50
+ }) }
51
+ }
52
+
53
+ // ── PPT 按原版式:每个文本框、图片、表格的位置大小(EMU)、文字的字号颜色粗细对齐、填充色、背景。
54
+ // 占位符没写位置的,到版式(layout)、母版(master)里找同类型的占位符。主题色(accent1、tx1…)从主题里取
55
+ const attr = (s, k) => new RegExp('\\b' + k + '="([^"]*)"').exec(s)?.[1]
56
+ function pptCtx(z) {
57
+ const pres = z.read('ppt/presentation.xml')?.toString('utf8') ?? '', sz = /<p:sldSz\b[^>]*>/.exec(pres)?.[0] ?? ''
58
+ const theme = z.names.find((n) => /^ppt\/theme\/theme\d+\.xml$/.test(n)), th = theme ? z.read(theme).toString('utf8') : '', clr = {}
59
+ for (const m of (/<a:clrScheme\b[\s\S]*?<\/a:clrScheme>/.exec(th)?.[0] ?? '').matchAll(/<a:(dk1|lt1|dk2|lt2|accent\d|hlink|folHlink)>([\s\S]*?)<\/a:\1>/g)) clr[m[1]] = /srgbClr val="([0-9A-Fa-f]{6})"/.exec(m[2])?.[1] ?? attr(m[2], 'lastClr') ?? (/val="window"/.test(m[2]) ? 'FFFFFF' : '000000')
60
+ Object.assign(clr, { tx1: clr.dk1, bg1: clr.lt1, tx2: clr.dk2, bg2: clr.lt2 })
61
+ return { w: +(attr(sz, 'cx') ?? 12192000), h: +(attr(sz, 'cy') ?? 6858000), clr, cache: new Map() }
62
+ }
63
+ const colorOf = (s, ctx) => { if (!s) return null; const rgb = /<a:srgbClr val="([0-9A-Fa-f]{6})"/.exec(s)?.[1]; if (rgb) return '#' + rgb; const sc = /<a:schemeClr val="(\w+)"/.exec(s)?.[1]; return sc && ctx.clr[sc] ? '#' + ctx.clr[sc] : null }
64
+ const xfrmOf = (s) => { const off = /<a:off x="(-?\d+)" y="(-?\d+)"/.exec(s), ext = /<a:ext cx="(\d+)" cy="(\d+)"/.exec(s); return off && ext ? { x: +off[1], y: +off[2], w: +ext[1], h: +ext[2] } : null }
65
+ const phOf = (s) => { const p = /<p:ph\b[^>]*>/.exec(s)?.[0]; return p ? { type: attr(p, 'type') ?? 'body', idx: attr(p, 'idx') } : null }
66
+ /** 版式、母版里的占位符:位置、默认字号 */
67
+ function phMap(z, file, ctx) {
68
+ if (ctx.cache.has(file)) return ctx.cache.get(file)
69
+ const x = z.read(file)?.toString('utf8') ?? '', out = []
70
+ for (const sp of x.matchAll(/<p:sp\b[\s\S]*?<\/p:sp>/g)) { const ph = phOf(sp[0]); if (ph) out.push({ ...ph, xf: xfrmOf(/<p:spPr\b[\s\S]*?<\/p:spPr>/.exec(sp[0])?.[0] ?? ''), sz: +(/<a:lvl1pPr\b[\s\S]*?<a:defRPr\b[^>]*\bsz="(\d+)"/.exec(sp[0])?.[1] ?? 0) || null, algn: /<a:lvl1pPr\b[^>]*algn="(\w+)"/.exec(sp[0])?.[1], color: colorOf(/<a:lvl1pPr\b[\s\S]*?<\/a:lvl1pPr>/.exec(sp[0])?.[0], ctx) }) }
71
+ const bg = /<p:bg>[\s\S]*?<\/p:bg>/.exec(x)?.[0]
72
+ const r = { phs: out, bg, rels: rels(z, file), x }
73
+ ctx.cache.set(file, r); return r
74
+ }
75
+ function slideLayout(z, n, x, r, ctx) {
76
+ const layoutF = [...r.values()].find((p) => /slideLayouts\//.test(p)), lay = layoutF ? phMap(z, layoutF, ctx) : null
77
+ const masterF = layoutF ? [...lay.rels.values()].find((p) => /slideMasters\//.test(p)) : null, mas = masterF ? phMap(z, masterF, ctx) : null
78
+ const findPh = (ph) => { for (const L of [lay, mas]) { if (!L) continue; const hit = L.phs.find((q) => ph.idx != null && q.idx === ph.idx && q.type === ph.type) ?? L.phs.find((q) => q.type === ph.type) ?? (ph.type === 'body' || ph.type === 'obj' ? L.phs.find((q) => q.idx === ph.idx) : null); if (hit?.xf) return hit } return null }
79
+ const titleSz = mas ? +(/<p:titleStyle>[\s\S]*?<a:defRPr\b[^>]*\bsz="(\d+)"/.exec(mas.x)?.[1] ?? 0) || 4400 : 4400, bodySz = mas ? +(/<p:bodyStyle>[\s\S]*?<a:defRPr\b[^>]*\bsz="(\d+)"/.exec(mas.x)?.[1] ?? 0) || 2800 : 2800
80
+ // 背景:这一页 > 版式 > 母版
81
+ const bgX = /<p:bg>[\s\S]*?<\/p:bg>/.exec(x)?.[0] ?? lay?.bg ?? mas?.bg, bgRels = /<p:bg>/.test(x) ? r : lay?.bg ? lay.rels : mas?.rels
82
+ const bgImg = bgX && /r:embed="([^"]+)"/.exec(bgX)?.[1], bg = { color: colorOf(bgX, ctx) ?? (/<p:bgRef\b[\s\S]*?<\/p:bgRef>/.test(bgX ?? '') ? colorOf(/<p:bgRef\b[\s\S]*?<\/p:bgRef>/.exec(bgX)[0], ctx) : null), img: bgImg ? bgRels?.get(bgImg) : null }
83
+ const items = []
84
+ const tree = /<p:spTree>[\s\S]*<\/p:spTree>/.exec(x)?.[0] ?? ''
85
+ // 组合形状:子元素的坐标按组的 chOff/chExt 换算
86
+ const walk = (xml, tf) => {
87
+ for (const m of xml.matchAll(/<p:grpSp>([\s\S]*?)<\/p:grpSp>|<p:sp>([\s\S]*?)<\/p:sp>|<p:sp\b[^>]*>([\s\S]*?)<\/p:sp>|<p:pic>([\s\S]*?)<\/p:pic>|<p:pic\b[^>]*>([\s\S]*?)<\/p:pic>|<p:graphicFrame>([\s\S]*?)<\/p:graphicFrame>|<p:graphicFrame\b[^>]*>([\s\S]*?)<\/p:graphicFrame>/g)) {
88
+ if (items.length > 120) return
89
+ const at = (xf) => (xf ? { x: tf.ox + (xf.x - tf.cx) * tf.sx, y: tf.oy + (xf.y - tf.cy) * tf.sy, w: xf.w * tf.sx, h: xf.h * tf.sy } : null)
90
+ if (m[1] != null) {
91
+ const g = /<p:grpSpPr>[\s\S]*?<\/p:grpSpPr>/.exec(m[1])?.[0] ?? '', off = xfrmOf(g), ch = /<a:chOff x="(-?\d+)" y="(-?\d+)"\/>[\s\S]*?<a:chExt cx="(\d+)" cy="(\d+)"/.exec(g)
92
+ const inner = m[1].replace(/^[\s\S]*?<\/p:grpSpPr>/, '')
93
+ if (off && ch) { const o = at(off); walk(inner, { ox: o.x, oy: o.y, cx: +ch[1], cy: +ch[2], sx: o.w / (+ch[3] || 1), sy: o.h / (+ch[4] || 1) }) } else walk(inner, tf)
94
+ continue
95
+ }
96
+ const sp = m[2] ?? m[3], pic = m[4] ?? m[5], gf = m[6] ?? m[7]
97
+ if (pic != null) { const xf = at(xfrmOf(/<p:spPr\b[\s\S]*?<\/p:spPr>/.exec(pic)?.[0] ?? '')), e = /r:embed="([^"]+)"/.exec(pic)?.[1], src = e && r.get(e); if (xf && src && /\.(png|jpe?g|gif|webp|bmp)$/i.test(src)) items.push({ type: 'img', ...xf, src }); continue }
98
+ if (gf != null) { const xf = at(xfrmOf(/<p:xfrm>[\s\S]*?<\/p:xfrm>/.exec(gf)?.[0] ?? '')); const tbl = /<a:tbl>[\s\S]*?<\/a:tbl>/.exec(gf)?.[0]; if (xf && tbl) items.push({ type: 'table', ...xf, rows: [...tbl.matchAll(/<a:tr\b[\s\S]*?<\/a:tr>/g)].slice(0, 40).map((row) => [...row[0].matchAll(/<a:tc\b[\s\S]*?<\/a:tc>/g)].map((c) => [...c[0].matchAll(/<a:t>([\s\S]*?)<\/a:t>/g)].map((q) => unxml(q[1])).join(''))) }); continue }
99
+ if (sp == null) continue
100
+ const ph = phOf(sp), base = ph ? findPh(ph) : null
101
+ if (ph && /^(sldNum|dt|ftr|hdr)$/.test(ph.type)) continue
102
+ const spPr = /<p:spPr\b[\s\S]*?<\/p:spPr>/.exec(sp)?.[0] ?? '', xf = at(xfrmOf(spPr) ?? base?.xf ?? null); if (!xf) continue
103
+ const fill = /<a:noFill\/>/.test(spPr) ? null : colorOf(/<a:solidFill>[\s\S]*?<\/a:solidFill>/.exec(spPr.replace(/<a:ln\b[\s\S]*?<\/a:ln>/, ''))?.[0], ctx)
104
+ const line = colorOf(/<a:ln\b[\s\S]*?<\/a:ln>/.exec(spPr)?.[0], ctx), round = /prstGeom prst="(roundRect|ellipse)"/.exec(spPr)?.[1]
105
+ const isTitle = ph && /title|ctrTitle/i.test(ph.type), defSz = base?.sz ?? (isTitle ? titleSz : ph ? bodySz : 1800)
106
+ const body = /<p:txBody>[\s\S]*?<\/p:txBody>/.exec(sp)?.[0] ?? '', bodyPr = /<a:bodyPr\b[^>]*\/?>/.exec(body)?.[0] ?? '', scale = +(/<a:normAutofit fontScale="(\d+)"/.exec(body)?.[1] ?? 100000) / 100000
107
+ const paras = [...body.matchAll(/<a:p>([\s\S]*?)<\/a:p>|<a:p\/>/g)].map((p) => {
108
+ const pp = p[1] ?? '', pPr = /<a:pPr\b[^>]*\/?>(?:[\s\S]*?<\/a:pPr>)?/.exec(pp)?.[0] ?? ''
109
+ const runs = [...pp.matchAll(/<a:r>([\s\S]*?)<\/a:r>|<a:br\/>|<a:fld\b[\s\S]*?<\/a:fld>/g)].map((q) => {
110
+ if (q[0] === '<a:br/>') return { t: '\n' }
111
+ const rPr = /<a:rPr\b[^>]*\/?>(?:[\s\S]*?<\/a:rPr>)?/.exec(q[0])?.[0] ?? ''
112
+ return { t: unxml(/<a:t>([\s\S]*?)<\/a:t>/.exec(q[0])?.[1] ?? ''), sz: Math.round((+(attr(rPr, 'sz') ?? 0) || defSz) * scale), b: attr(rPr, 'b') === '1' || undefined, i: attr(rPr, 'i') === '1' || undefined, u: attr(rPr, 'u') && attr(rPr, 'u') !== 'none' || undefined, color: colorOf(rPr, ctx) ?? undefined }
113
+ })
114
+ return { algn: attr(pPr, 'algn') ?? base?.algn, lvl: +(attr(pPr, 'lvl') ?? 0), bullet: /<a:buNone\/>/.test(pPr) ? false : /<a:buChar\b|<a:buAutoNum\b/.test(pPr) || (ph && !isTitle && ph.type !== 'subTitle' && ph.type !== 'ctrTitle' ? true : false), runs, sz: Math.round(defSz * scale) }
115
+ })
116
+ if (!fill && !line && !paras.some((p) => p.runs.some((q) => q.t.trim()))) continue
117
+ items.push({ type: 'text', ...xf, fill, line, round, anchor: attr(bodyPr, 'anchor') ?? (isTitle ? 'ctr' : 't'), vert: /vert="(vert|eaVert)"/.test(bodyPr) || undefined, color: base?.color ?? (isTitle || ph ? colorOf('<a:schemeClr val="tx1"/>', ctx) : null), paras })
118
+ }
119
+ }
120
+ walk(tree, { ox: 0, oy: 0, cx: 0, cy: 0, sx: 1, sy: 1 })
121
+ return { w: ctx.w, h: ctx.h, bg, items }
122
+ }
123
+ /** Word:段落(标题级别、列表)、表格、图片 */
124
+ function docx(z) {
125
+ const x = z.read('word/document.xml')?.toString('utf8'); if (!x) throw new Error('Word 文件里没有正文')
126
+ const r = rels(z, 'word/document.xml'), blocks = []
127
+ const body = x.slice(x.indexOf('<w:body'))
128
+ for (const m of body.matchAll(/<w:tbl>[\s\S]*?<\/w:tbl>|<w:p\b[\s\S]*?<\/w:p>/g)) {
129
+ if (blocks.length > 3000) break
130
+ if (m[0].startsWith('<w:tbl')) { blocks.push({ table: [...m[0].matchAll(/<w:tr\b[\s\S]*?<\/w:tr>/g)].slice(0, 200).map((row) => [...row[0].matchAll(/<w:tc\b[\s\S]*?<\/w:tc>/g)].map((c) => [...c[0].matchAll(/<w:t(?: [^>]*)?>([\s\S]*?)<\/w:t>/g)].map((t) => unxml(t[1])).join(''))) }); continue }
131
+ const t = [...m[0].matchAll(/<w:t(?: [^>]*)?>([\s\S]*?)<\/w:t>|<w:tab\/>|<w:br\/>/g)].map((q) => (q[1] != null ? unxml(q[1]) : q[0] === '<w:tab/>' ? '\t' : '\n')).join('')
132
+ const style = /<w:pStyle w:val="([^"]+)"/.exec(m[0])?.[1] ?? '', h = /^(Heading|heading|标题)\s?(\d)$/.exec(style)?.[2] ?? (/^Title$/i.test(style) ? '1' : null)
133
+ const img = [...m[0].matchAll(/r:embed="([^"]+)"/g)].map((q) => r.get(q[1])).filter(Boolean)
134
+ if (t.trim() || img.length) blocks.push({ t, h: h ? +h : 0, list: /<w:numPr>/.test(m[0]), images: img })
135
+ }
136
+ return { kind: 'docx', blocks }
137
+ }
138
+ /** Excel:每张表的前 300 行、40 列 */
139
+ function xlsx(z) {
140
+ const ss = z.read('xl/sharedStrings.xml')?.toString('utf8') ?? '', strs = [...ss.matchAll(/<si>([\s\S]*?)<\/si>/g)].map((m) => [...m[1].matchAll(/<t(?: [^>]*)?>([\s\S]*?)<\/t>/g)].map((t) => unxml(t[1])).join(''))
141
+ const wb = z.read('xl/workbook.xml')?.toString('utf8') ?? '', wr = rels(z, 'xl/workbook.xml')
142
+ const sheets = [...wb.matchAll(/<sheet\b[^>]*>/g)].map((m) => ({ name: unxml(/name="([^"]+)"/.exec(m[0])?.[1] ?? ''), file: wr.get(/r:id="([^"]+)"/.exec(m[0])?.[1]) })).filter((s) => s.file).slice(0, 20)
143
+ const col = (ref) => { let n = 0; for (const ch of /^[A-Z]+/.exec(ref)?.[0] ?? 'A') n = n * 26 + ch.charCodeAt(0) - 64; return n - 1 }
144
+ return { kind: 'xlsx', sheets: sheets.map((s) => {
145
+ const x = z.read(s.file)?.toString('utf8') ?? '', rows = []
146
+ for (const r of x.matchAll(/<row\b[^>]*>([\s\S]*?)<\/row>/g)) {
147
+ if (rows.length >= 300) break
148
+ const row = []
149
+ for (const c of r[1].matchAll(/<c\b([^>]*?)(?:\/>|>([\s\S]*?)<\/c>)/g)) {
150
+ const ref = /r="([A-Z]+\d+)"/.exec(c[1])?.[1], t = /t="([^"]+)"/.exec(c[1])?.[1], v = /<v>([\s\S]*?)<\/v>/.exec(c[2] ?? '')?.[1], is = /<is>([\s\S]*?)<\/is>/.exec(c[2] ?? '')?.[1]
151
+ const i = ref ? col(ref) : row.length; if (i >= 40) continue
152
+ row[i] = t === 's' ? strs[+v] ?? '' : t === 'inlineStr' ? unxml((is ?? '').replace(/<[^>]+>/g, '')) : t === 'b' ? (v === '1' ? 'TRUE' : 'FALSE') : unxml(v ?? '')
153
+ }
154
+ rows.push(Array.from(row, (x) => x ?? ''))
155
+ }
156
+ return { name: s.name, rows }
157
+ }) }
158
+ }
159
+
160
+ /** 给手机上的预览用:pptx / docx / xlsx 读成结构化的内容 */
161
+ export function previewOffice(file) {
162
+ const ext = file.toLowerCase().split('.').pop(), z = openZip(file)
163
+ if (ext === 'pptx') return pptx(z)
164
+ if (ext === 'docx') return docx(z)
165
+ if (ext === 'xlsx') return xlsx(z)
166
+ throw new Error('不认识的格式')
167
+ }
168
+ /** 取包里的一张图(PPT、Word 里的图片) */
169
+ export function zipImage(file, entry) {
170
+ if (!/^(ppt|word|xl)\/media\/[^/]+\.(png|jpe?g|gif|webp|bmp)$/i.test(entry)) return null
171
+ return openZip(file).read(entry)
172
+ }
@@ -0,0 +1,134 @@
1
+ // 打洞直连(12-03):两台设备不在一个局域网时,用 WebRTC 数据通道直接传文件,文件不经过服务器。
2
+ // · 信令(连接信息)走现成的端到端加密消息(type: 'file.rtc'),中继只转这几条小消息
3
+ // · 打洞用服务器上的 STUN;打不通(两边都是对称 NAT,比如很多手机流量网络)才走服务器的 TURN 中转——服务器那边限速、限量
4
+ // · 通行证(TURN 用户名 / 密码)一次一小时,向号码服务要(只给领过号的身份)
5
+ // · 一次传输开一条,传完就关;不常驻在线
6
+ // 通道上跑一个很小的“请求 / 回答”:
7
+ // 文字消息 = JSON { r: 请求号, ... };二进制消息 = [请求号 4 字节][第几片 4 字节][共几片 4 字节] + 内容(大块切成 64 KB 一片,SCTP 一条消息不能太大)
8
+ // 注意:node-datachannel 的通道对象要一直有人引用着,不然会被回收、通道悄悄断掉(12-03 实测)
9
+ const PART = 64 * 1024
10
+ const HIGH = 4 << 20, LOW = 1 << 20
11
+
12
+ let NDC = null, ndcErr = null
13
+ async function lib() {
14
+ if (NDC || ndcErr) return NDC
15
+ try { NDC = (await import('node-datachannel')).default } catch (e) { ndcErr = e }
16
+ return NDC
17
+ }
18
+ /** 这台机器能不能打洞(装没装上 node-datachannel) */
19
+ export async function p2pAvailable() { return !!(await lib()) }
20
+ /** 没装上时的原因(手机日志里要看得到真实报错,不然只能猜) */
21
+ export function p2pError() { return ndcErr ? String(ndcErr?.message ?? ndcErr).slice(0, 300) : null }
22
+
23
+ function frame(r, idx, total, body) { const h = Buffer.alloc(12); h.writeUInt32BE(r >>> 0, 0); h.writeUInt32BE(idx, 4); h.writeUInt32BE(total, 8); return Buffer.concat([h, body]) }
24
+
25
+ /** 包一条打开的数据通道:request(头, 内容?) → { head, body };onRequest((头, 内容) → { head, body }) */
26
+ function wrapChannel(dc, pc, log) {
27
+ let nextR = 1, closed = false
28
+ const pending = new Map(), parts = new Map(), waitingBody = new Map()
29
+ let handler = null, onClose = []
30
+ const drained = []
31
+ dc.setBufferedAmountLowThreshold(LOW)
32
+ dc.onBufferedAmountLow(() => { while (drained.length && dc.bufferedAmount() < HIGH) drained.shift()() })
33
+ const room = () => (dc.bufferedAmount() < HIGH ? Promise.resolve() : new Promise((ok) => drained.push(ok)))
34
+ async function sendBody(r, body) {
35
+ const total = Math.max(1, Math.ceil(body.length / PART))
36
+ for (let i = 0; i < total; i++) { await room(); if (closed) throw new Error('直连断了'); dc.sendMessageBinary(frame(r, i, total, body.subarray(i * PART, (i + 1) * PART))) }
37
+ }
38
+ function gotBody(r, buf) {
39
+ const idx = buf.readUInt32BE(4), total = buf.readUInt32BE(8), p = parts.get(r) ?? { n: 0, a: new Array(total) }
40
+ p.a[idx] = buf.subarray(12); p.n++; parts.set(r, p)
41
+ if (p.n < total) return
42
+ parts.delete(r); const body = Buffer.concat(p.a)
43
+ const w = waitingBody.get(r); if (w) { waitingBody.delete(r); w(body) }
44
+ }
45
+ const bodyOf = (r) => new Promise((ok) => waitingBody.set(r, ok))
46
+ dc.onMessage(async (m) => {
47
+ if (typeof m === 'string') {
48
+ let j; try { j = JSON.parse(m) } catch { return }
49
+ if (j.resp) { const p = pending.get(j.r); if (!p) return; pending.delete(j.r); p(j.hasBody ? { head: j, body: await bodyOf(j.r) } : { head: j, body: null }); return }
50
+ // 对方来的请求:有内容的先等内容到齐
51
+ const body = j.hasBody ? await bodyOf(j.r) : null
52
+ let out
53
+ try { out = handler ? await handler(j, body) : { head: { code: 404 } } } catch (e) { out = { head: { code: 500, error: String(e?.message ?? e) } } }
54
+ if (closed) return
55
+ dc.sendMessage(JSON.stringify({ ...out.head, r: j.r, resp: 1, hasBody: !!out.body }))
56
+ if (out.body) sendBody(j.r, out.body).catch(() => {})
57
+ return
58
+ }
59
+ const buf = Buffer.isBuffer(m) ? m : Buffer.from(m)
60
+ gotBody(buf.readUInt32BE(0), buf) // 通道是有序的:内容总在它的请求 / 回答后面到,那时已经登记了“等内容”
61
+ })
62
+ const shutdown = () => { if (closed) return; closed = true; for (const p of pending.values()) p({ head: { code: 499, error: '直连断了' }, body: null }); pending.clear(); drained.splice(0).forEach((f) => f()); onClose.splice(0).forEach((f) => f()) }
63
+ dc.onClosed(shutdown)
64
+ return {
65
+ get route() { const p = pc.getSelectedCandidatePair?.(); const t = p?.local?.type; return t === 'relay' || p?.remote?.type === 'relay' ? 'relay' : t === 'host' && p?.remote?.type === 'host' ? 'host' : 'direct' },
66
+ async request(head, body = null, ms = 60_000) {
67
+ if (closed) throw new Error('直连断了')
68
+ const r = nextR++
69
+ const res = new Promise((ok, no) => { const t = setTimeout(() => { pending.delete(r); no(new Error('直连没回话')) }, ms); pending.set(r, (x) => { clearTimeout(t); ok(x) }) })
70
+ dc.sendMessage(JSON.stringify({ ...head, r, hasBody: !!body }))
71
+ if (body) await sendBody(r, body)
72
+ return res
73
+ },
74
+ onRequest(fn) { handler = fn },
75
+ onClose(fn) { onClose.push(fn) },
76
+ close() { try { dc.close() } catch {} try { pc.close() } catch {} shutdown() },
77
+ }
78
+ }
79
+
80
+ /**
81
+ * 打洞直连。send(对方公钥, 消息) 发信令;iceServers() 返回 { iceServers: [...], username, credential }(可以为空:那就只用公共 STUN)
82
+ * 发起:await open(对方公钥) → 通道;接听:onSignal(对方公钥, 消息, (通道) => {...})
83
+ */
84
+ export function createP2PLink({ send, iceServers = async () => null, log = () => {} }) {
85
+ const sessions = new Map() // sid → { pc, dc, peer, resolve, reject, link }
86
+ const keep = new Set()
87
+ const PUBLIC_STUN = ['stun:stun.miwifi.com:3478', 'stun:stun.qq.com:3478']
88
+ async function config() {
89
+ let c = null; try { c = await iceServers() } catch (e) { log('[直连] 没拿到打洞通行证:', e?.message) }
90
+ const enc = encodeURIComponent
91
+ const list = (c?.iceServers ?? []).map((u) => (u.startsWith('turn:') && c.username ? u.replace('turn:', 'turn:' + enc(c.username) + ':' + enc(c.credential) + '@') : u))
92
+ return { iceServers: [...list, ...PUBLIC_STUN] }
93
+ }
94
+ function wire(sid, peer, pc) {
95
+ pc.onLocalDescription((sdp, type) => send(peer, { type: 'file.rtc', sid, k: 'sdp', sdp, t: type }).catch?.(() => {}))
96
+ pc.onLocalCandidate((c, mid) => send(peer, { type: 'file.rtc', sid, k: 'cand', c, mid }).catch?.(() => {}))
97
+ pc.onStateChange((st) => { if (st === 'failed' || st === 'closed') { const s = sessions.get(sid); s?.reject?.(new Error('打洞没打通')); cleanup(sid) } })
98
+ }
99
+ function cleanup(sid) { const s = sessions.get(sid); if (!s) return; sessions.delete(sid); keep.delete(s.pc); keep.delete(s.dc) }
100
+ /** 发起一条直连;ms 内没打通就放弃 */
101
+ async function open(peer, ms = 20_000) {
102
+ const N = await lib(); if (!N) throw new Error('这台设备不能打洞直连(缺少组件)')
103
+ const sid = Math.random().toString(36).slice(2, 12)
104
+ const pc = new N.PeerConnection('yu-' + sid, await config()); keep.add(pc)
105
+ const s = { pc, peer }; sessions.set(sid, s)
106
+ wire(sid, peer, pc)
107
+ return await new Promise((ok, no) => {
108
+ const t = setTimeout(() => { no(new Error('打洞没打通(20 秒)')); try { pc.close() } catch {} cleanup(sid) }, ms)
109
+ s.reject = (e) => { clearTimeout(t); no(e) }
110
+ const dc = pc.createDataChannel('yusho-file', { ordered: true }); s.dc = dc; keep.add(dc)
111
+ dc.onOpen(() => { clearTimeout(t); const link = wrapChannel(dc, pc, log); link.onClose(() => cleanup(sid)); s.link = link; log('[直连] 打通了:' + link.route); ok(link) })
112
+ })
113
+ }
114
+ /** 收到对方的信令(file.rtc)。onLink:对方发起的通道打开时交给它 */
115
+ async function onSignal(peer, m, onLink) {
116
+ const sid = String(m.sid ?? ''); if (!/^[a-z0-9]{6,16}$/.test(sid)) return
117
+ let s = sessions.get(sid)
118
+ if (!s) {
119
+ if (m.k !== 'sdp' || m.t !== 'offer') return
120
+ const N = await lib(); if (!N) { send(peer, { type: 'file.rtc', sid, k: 'nope', reason: '对方不能打洞直连' }).catch?.(() => {}); return }
121
+ const pc = new N.PeerConnection('yu-' + sid, await config()); keep.add(pc)
122
+ s = { pc, peer }; sessions.set(sid, s); wire(sid, peer, pc)
123
+ pc.onDataChannel((dc) => { s.dc = dc; keep.add(dc); const link = wrapChannel(dc, pc, log); link.onClose(() => cleanup(sid)); s.link = link; onLink?.(link) })
124
+ setTimeout(() => { if (!s.link) { try { pc.close() } catch {} cleanup(sid) } }, 30_000)
125
+ }
126
+ if (s.peer !== peer) return
127
+ if (m.k === 'nope') { s.reject?.(new Error(String(m.reason ?? '对方不能打洞直连'))); return }
128
+ try {
129
+ if (m.k === 'sdp') s.pc.setRemoteDescription(String(m.sdp), String(m.t))
130
+ else if (m.k === 'cand') s.pc.addRemoteCandidate(String(m.c), String(m.mid ?? '0'))
131
+ } catch (e) { log('[直连] 信令出错:', e?.message) }
132
+ }
133
+ return { open, onSignal, available: p2pAvailable }
134
+ }
@@ -0,0 +1,55 @@
1
+ // 电脑版(Windows EXE)自己的更新(12-03)。只在电脑版加载(launcher.mjs 里动态 import),手机不用。
2
+ // 服务器:https://yusho.chat/update/pc/latest.json = { version, channel, url, sha256, size, notes, betaNumbers? }(deploy/yusho-ops/release-pc.mjs 写)
3
+ // 有比自己新的版本 → 后台下到 <数据目录>/update/yusho-pc-<版本>.exe,边下边算 SHA-256,对不上就删掉;
4
+ // 下好了界面显示“重启并更新”,外壳(YuSho.exe)只认这个目录里这个名字的文件,静默安装后自己重新打开
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import crypto from 'node:crypto'
8
+
9
+ const verNum = (v) => String(v ?? '').split('.').map((x) => Number(x) || 0).reduce((a, x) => a * 1000 + x, 0)
10
+
11
+ export function createPcUpdater({ dir, version, channel = 'beta', number = () => '', url = 'https://yusho.chat/update/pc/latest.json', allowHttp = false, log = () => {}, notify = () => {} }) {
12
+ const D = path.join(dir, 'update')
13
+ let s = { state: 'idle' } // idle 没新版 / downloading 在下 / ready 下好了 / failed 没下成
14
+ const okUrl = (u) => /^https:\/\//.test(String(u ?? '')) || (allowHttp && /^http:\/\/127\.0\.0\.1[:/]/.test(String(u ?? '')))
15
+ const view = () => ({ edition: 'pc', current: version, ...s, file: s.state === 'ready' ? s.file : null })
16
+ async function download(j) {
17
+ const name = 'yusho-pc-' + j.version + '.exe', file = path.join(D, name), part = file + '.part'
18
+ fs.mkdirSync(D, { recursive: true })
19
+ if (fs.existsSync(file)) {
20
+ const h = crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')
21
+ if (h === j.sha256) { s = { ...s, state: 'ready', file, done: j.size }; return }
22
+ fs.rmSync(file, { force: true })
23
+ }
24
+ s = { ...s, state: 'downloading', done: 0 }
25
+ try {
26
+ const r = await fetch(j.url, { signal: AbortSignal.timeout(30 * 60_000) }); if (!r.ok || !r.body) throw new Error('下载失败 HTTP ' + r.status)
27
+ const out = fs.createWriteStream(part), h = crypto.createHash('sha256'); let done = 0
28
+ for await (const chunk of r.body) { h.update(chunk); done += chunk.length; if (!out.write(chunk)) await new Promise((ok) => out.once('drain', ok)); s.done = done }
29
+ await new Promise((ok, no) => out.end((e) => (e ? no(e) : ok())))
30
+ if (h.digest('hex') !== j.sha256) { fs.rmSync(part, { force: true }); throw new Error('下载的安装包校验不对,过一会儿再试') }
31
+ fs.renameSync(part, file)
32
+ for (const f of fs.readdirSync(D)) if (f !== name && /^yusho-pc-.*\.exe(\.part)?$/.test(f)) fs.rmSync(path.join(D, f), { force: true }) // 旧版本的安装包清掉
33
+ s = { ...s, state: 'ready', file, done: j.size }; log('电脑版新版本下好了:' + j.version)
34
+ notify({ kind: 'update', title: '鱼Sho 电脑版 ' + j.version + ' 下好了', body: '在 设置 › 关于鱼Sho 点“重启并更新”' })
35
+ } catch (e) { s = { ...s, state: 'failed', error: String(e?.message ?? e) }; log('电脑版更新没下成:', s.error) }
36
+ }
37
+ let running = null
38
+ async function check() {
39
+ try {
40
+ const r = await fetch(url, { signal: AbortSignal.timeout(10000), cache: 'no-store' })
41
+ if (!r.ok) { s = { ...s, checkedAt: Date.now() }; return view() }
42
+ const j = await r.json(), myNo = String(number() ?? '')
43
+ const okCh = Array.isArray(j.betaNumbers) && j.betaNumbers.length ? j.betaNumbers.includes(myNo) : j.channel === 'release' || channel === 'beta'
44
+ const newer = /^\d+\.\d+\.\d+$/.test(String(j.version ?? '')) && verNum(j.version) > verNum(version)
45
+ const ok = newer && okCh && okUrl(j.url) && /^[0-9a-f]{64}$/.test(String(j.sha256 ?? '')) && Number(j.size) > 0
46
+ if (!ok) { s = { state: 'idle', checkedAt: Date.now(), latest: j.version ?? null }; return view() }
47
+ if (s.latest !== j.version || s.state === 'idle' || s.state === 'failed') {
48
+ s = { state: 'idle', checkedAt: Date.now(), latest: j.version, channel: j.channel ?? 'beta', notes: String(j.notes ?? '').slice(0, 2000), size: Number(j.size), sha256: j.sha256 }
49
+ running = download(j).catch(() => {}).finally(() => { running = null })
50
+ } else s.checkedAt = Date.now()
51
+ } catch (e) { log('电脑版查更新没成:', e?.message); s = { ...s, checkedAt: Date.now() } }
52
+ return view()
53
+ }
54
+ return { check, view, wait: () => running ?? Promise.resolve() }
55
+ }
package/app/plans.mjs ADDED
@@ -0,0 +1,126 @@
1
+ // 计划:工作秘书想派活给电脑时,不直接派,先列一张“计划卡”(拆成几件、各交给谁),用户点“开始执行”才派。
2
+ // 开始后 3 秒内能撤销(还没真正发出去);派出后能“全部叫停”;某一件出问题能重试、换别的 Agent 接手(带上进度);
3
+ // 在做的时候用户又补充了要求,记下来,这件做完后接着让同一个 Agent 按补充改;全部做完由启动器转告一次总结。
4
+ // 计划存在 App 目录的 plans.json(最近 50 个)。任务本身(进度、审批、结果、产物)还是 net.mjs 管,这里只记“哪件对应哪个任务”。
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { randomBytes } from 'node:crypto'
8
+
9
+ const HOLD_MS = 3000
10
+ const FINAL = new Set(['done', 'failed'])
11
+
12
+ export function createPlans({ dir, net, log = () => {}, changed = () => {} }) {
13
+ const file = path.join(dir, 'plans.json')
14
+ let plans = []; try { plans = JSON.parse(fs.readFileSync(file, 'utf8')) } catch {}
15
+ const save = () => { fs.writeFileSync(file, JSON.stringify(plans.slice(-50))); changed() }
16
+ const get = (id) => plans.find((p) => p.id === id)
17
+ const task = (tid) => tid && net.tasks().find((t) => t.id === tid)
18
+ const holds = new Map()
19
+
20
+ // App 重启时还在“3 秒等待”里的:直接派出去(用户已经点了开始)
21
+ for (const p of plans) if (p.status === 'starting') { p.status = 'proposed'; delete p.holdUntil }
22
+
23
+ function propose({ title, jobs, lane = 'work' }) {
24
+ const js = (jobs ?? []).map((j) => ({ agent: String(j.agent ?? '').trim().toLowerCase(), title: String(j.title ?? '').trim().slice(0, 40), instruction: String(j.instruction ?? '').trim().slice(0, 8000), ...(/^[\w-]{4,40}$/.test(String(j.continue_task ?? '')) ? { continueTask: String(j.continue_task) } : {}) })).filter((j) => j.agent && j.instruction).slice(0, 6)
25
+ if (!js.length) throw new Error('计划里没有要做的事')
26
+ const agents = new Set(net.members().flatMap((m) => m.agents))
27
+ const bad = js.filter((j) => !agents.has(j.agent)).map((j) => j.agent)
28
+ if (bad.length) throw new Error(`连上的电脑里没有:${[...new Set(bad)].join('、')};能派给:${[...agents].join('、') || '(还没连上电脑)'}`)
29
+ const p = { id: 'p_' + Date.now().toString(36) + randomBytes(2).toString('hex'), title: String(title ?? '').trim().slice(0, 40) || js[0].title || '一件活', lane, jobs: js.map((j) => ({ ...j, title: j.title || j.instruction.slice(0, 20), tasks: [], followups: [] })), status: 'proposed', at: Date.now() }
30
+ plans.push(p); save(); return p
31
+ }
32
+
33
+ async function sendJob(p, j, instruction) {
34
+ j.sending = true // 新任务记到计划里之前,别让“全部做完了没有”的检查看到上一个任务就判做完
35
+ // 同一件活的补充、重试,以及助理说“接着之前那件改”的:都在电脑上同一个会话里接着做
36
+ if (!j.thread) { const prev = j.continueTask ? net.tasks().find((x) => x.id === j.continueTask && x.agent === j.agent) : null; j.thread = prev?.thread ?? prev?.id ?? null }
37
+ try { const t = await net.dispatch({ agent: j.agent, instruction, title: j.title, thread: j.thread ?? undefined }); t.planId = p.id; j.tasks.push(t.id); if (!j.thread) j.thread = t.thread }
38
+ catch (e) { j.error = String(e?.message ?? e) }
39
+ finally { delete j.sending }
40
+ }
41
+ async function launch(id) {
42
+ const p = get(id); holds.delete(id)
43
+ if (!p || p.status !== 'starting') return
44
+ p.status = 'running'; p.startAt = Date.now(); delete p.holdUntil; save()
45
+ for (const j of p.jobs) await sendJob(p, j, j.instruction)
46
+ save(); log('计划派出去了:' + p.title)
47
+ }
48
+ function start(id) {
49
+ const p = get(id); if (!p) throw new Error('没有这个计划')
50
+ if (p.status !== 'proposed') throw new Error('这个计划已经' + (p.status === 'dropped' ? '不做了' : '开始了'))
51
+ p.status = 'starting'; p.holdUntil = Date.now() + HOLD_MS; save()
52
+ holds.set(id, setTimeout(() => launch(id).catch((e) => log('派计划出错:', e?.message)), HOLD_MS))
53
+ return p
54
+ }
55
+ function undo(id) {
56
+ const p = get(id); if (!p || p.status !== 'starting') throw new Error('已经派出去了,撤不回来;可以“全部叫停”')
57
+ clearTimeout(holds.get(id)); holds.delete(id); p.status = 'proposed'; delete p.holdUntil; save(); return p
58
+ }
59
+ function drop(id) {
60
+ const p = get(id); if (!p) throw new Error('没有这个计划')
61
+ if (p.status === 'starting') undo(id)
62
+ if (p.status !== 'proposed') throw new Error('已经开始了,要停就点“全部叫停”')
63
+ p.status = 'dropped'; save(); return p
64
+ }
65
+ async function stop(id) {
66
+ const p = get(id); if (!p) throw new Error('没有这个计划')
67
+ if (p.status === 'starting') return undo(id)
68
+ for (const j of p.jobs) { j.followups = []; const t = task(j.tasks.at(-1)); if (t && !FINAL.has(t.status)) await net.cancel(t.id).catch(() => {}) }
69
+ p.stopped = Date.now(); save(); return p
70
+ }
71
+ /** 某一件重做:agent 不填就还交给原来的;换人时把上一个做到哪、说了什么带过去 */
72
+ async function redo(id, i, agent) {
73
+ const p = get(id), j = p?.jobs[i]; if (!j) throw new Error('没有这一件')
74
+ j.sending = true; p.status = 'running'; delete p.reported; delete p.endAt // 先标“在重派”:取消旧任务引起的检查不会把计划判成做完
75
+ const prev = task(j.tasks.at(-1))
76
+ if (prev && !FINAL.has(prev.status)) await net.cancel(prev.id).catch(() => {})
77
+ const to = String(agent || j.agent).toLowerCase()
78
+ const ctx = prev ? [`[这件活之前交给过 ${prev.agent},${prev.status === 'failed' ? '没做成:' + (prev.reason ?? '') : '没做完'}。`,
79
+ prev.lines?.length ? '它做到的地方(最近几步):\n' + prev.lines.slice(-8).join('\n') : '', prev.text ? '它最后说:' + String(prev.text).slice(0, 1500) : '',
80
+ '请接着把它做完,已经做好的部分不用重做。]'].filter(Boolean).join('\n') : ''
81
+ j.agent = to; delete j.error; p.status = 'running'; delete p.reported; delete p.endAt; delete p.stopped
82
+ await sendJob(p, j, ctx ? j.instruction + '\n\n' + ctx : j.instruction); save(); return p
83
+ }
84
+ /** 在做的时候用户补充的要求:等这件做完,接着交给同一个 Agent 按补充改 */
85
+ function addFollowup(id, i, text) {
86
+ const p = get(id), j = p?.jobs[i]; if (!j) throw new Error('没有这一件')
87
+ j.followups.push(String(text).trim().slice(0, 4000)); save(); return p
88
+ }
89
+
90
+ // 任务有变化:补充的要求接着派;全部到头了就把计划标成做完(启动器看到 done 且没 reported 就转告总结)
91
+ let busy = false, again = false
92
+ net.onChange(async function check() {
93
+ if (busy) { again = true; return } busy = true; again = false
94
+ let dirty = false
95
+ try {
96
+ for (const p of plans) {
97
+ if (p.status !== 'running') continue
98
+ for (const j of p.jobs) {
99
+ const t = task(j.tasks.at(-1))
100
+ if (t?.status === 'done' && t.settled && j.followups.length && !p.stopped) {
101
+ const more = j.followups.splice(0); dirty = true; j.applied = [...(j.applied ?? []), ...more]
102
+ await sendJob(p, j, `[接着你刚做完的「${j.title}」改。你上次交回的:${String(t.text ?? '').slice(0, 1500)}]\n\n用户补充的要求:\n${more.map((x) => '- ' + x).join('\n')}`)
103
+ }
104
+ }
105
+ const last = p.jobs.map((j) => task(j.tasks.at(-1)))
106
+ const over = p.jobs.every((j, k) => !j.sending && (j.error || (last[k] && FINAL.has(last[k].status) && last[k].settled && !j.followups.length)))
107
+ if (over) { p.status = 'done'; p.endAt = Date.now(); dirty = true }
108
+ }
109
+ if (dirty) save()
110
+ } finally { busy = false; if (again) check() } // 检查时又有变化:再查一遍,免得漏掉最后一次
111
+ })
112
+
113
+ /** 给界面看:计划加上每件的当前任务(状态、最近一步、多久没动静、交回的文件) */
114
+ function view() {
115
+ return plans.filter((p) => p.status !== 'dropped' || Date.now() - p.at < 86400000).map((p) => ({ ...p, jobs: p.jobs.map((j) => {
116
+ const t = task(j.tasks.at(-1))
117
+ return { agent: j.agent, title: j.title, instruction: j.instruction, error: j.error ?? null, followups: j.followups.length, tries: j.tasks.length, tasks: j.tasks, applied: j.applied ?? [],
118
+ task: t ? { id: t.id, status: t.status, computer: t.computer, line: t.lines?.at(-1) ?? null, updated: t.updated, at: t.at, endAt: t.endAt ?? null, seconds: t.seconds ?? null, reason: t.reason ?? null, text: t.status === 'done' ? String(t.text ?? '').slice(0, 600) : null, approval: !!t.approval, artifacts: (t.artifacts ?? []).map(({ name, saved, size, type, error }) => ({ name, saved, size, type, error })) } : null }
119
+ }) }))
120
+ }
121
+ /** 全部做完:给助理的总结材料 */
122
+ function facts(p) { return p.jobs.map((j, k) => { const t = task(j.tasks.at(-1)); return `${k + 1}. ${j.title}(${j.agent}):` + (j.applied?.length ? '(用户在做的过程中补充过要求,已经交给它按补充改了:' + j.applied.join(';') + ')' : '') + (j.error ? '没派出去:' + j.error : t ? net.report(t) : '没有任务') }).join('\n\n') }
123
+ function markReported(id) { const p = get(id); if (p) { p.reported = true; save() } }
124
+
125
+ return { propose, start, undo, drop, stop, redo, addFollowup, view, get, facts, markReported, list: () => plans }
126
+ }
@@ -0,0 +1,79 @@
1
+ // 插件(DSH 插件):列出随 App 带的(按类别),装 / 删第三方插件。
2
+ // 第三方插件用内置 Linux 里的 npm 装到 App 的 plugins 目录(国内源 npmmirror),写进 plugins.patch.yml,重启内核后生效。
3
+ // 插件 import 的 @deepseek-ai/*(cordis、DSH 的接口)指回内核自己的那份,不另装一套:同一套类,插件才挂得上。
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
7
+
8
+ const CATS = [
9
+ ['model', '模型', /llm|model|provider|credential|token-meter|pi-ai|openai|anthropic|reasoning/],
10
+ ['tool', '工具', /tool-|web-|^web$|fs|shell|bash|pwsh|todo|ptc|browser|image|office|search|fetch/],
11
+ ['memory', '记忆与上下文', /compaction|memory|context|session|history|title|prompt/],
12
+ ['task', '定时、计划和子 Agent', /schedule|jobs|goal|plan|subagent|workflow|cron/],
13
+ ['safety', '权限与安全', /permission|sandbox|approval|policy|redact|guard/],
14
+ ['ui', '界面与连接', /client|webserver|web-app|ui-|host|remote|connection|upload/],
15
+ ]
16
+ const catOf = (name) => (CATS.find(([, , re]) => re.test(name)) ?? ['other', '其他'])[0]
17
+ export const PLUGIN_CATS = Object.fromEntries([...CATS.map(([k, l]) => [k, l]), ['other', '其他']])
18
+
19
+ export function createPlugins({ appDir, kernelDir, linux, log = () => {} }) {
20
+ const DIR = path.join(appDir, 'plugins'), PATCH = path.join(DIR, 'plugins.patch.yml'), LIST = path.join(DIR, 'installed.json')
21
+ const NM = path.join(kernelDir, 'node_modules')
22
+ const readList = () => { try { return JSON.parse(fs.readFileSync(LIST, 'utf8')) } catch { return [] } }
23
+ function writePatch(list) {
24
+ fs.mkdirSync(DIR, { recursive: true })
25
+ const on = list.filter((p) => p.enabled !== false)
26
+ fs.writeFileSync(PATCH, '# 你装的第三方 DSH 插件(App 自动生成,别手改)\n' + (on.length ? '- insert:\n' + on.map((p) => ` - id: ${p.id}\n name: '${entryUrl(p.pkg)}'\n`).join('') : ''))
27
+ fs.writeFileSync(LIST, JSON.stringify(list, null, 1))
28
+ }
29
+ /** 插件包的入口文件(package.json 的 exports / main)→ file:// 地址。DSH 按内核目录找插件名,找不到 App 里装的,所以直接写绝对地址 */
30
+ function entryUrl(pkg) {
31
+ const dir = path.join(DIR, 'node_modules', ...pkg.split('/')), pj = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'))
32
+ const ex = typeof pj.exports === 'string' ? pj.exports : pj.exports?.['.']
33
+ const rel = typeof ex === 'string' ? ex : ex?.import ?? ex?.default ?? pj.module ?? pj.main ?? 'index.js'
34
+ return pathToFileURL(path.join(dir, typeof rel === 'string' ? rel : 'index.js')).href
35
+ }
36
+ /** 随 App 带的插件:从打包时记下的清单读(stage.mjs 生成 assets/plugins.json),读不到就扫 node_modules */
37
+ function builtin() {
38
+ let names = []
39
+ try { names = JSON.parse(fs.readFileSync(path.join(kernelDir, 'assets', 'plugins.json'), 'utf8')) } catch { try { names = fs.readdirSync(path.join(NM, '@deepseek-ai')).filter((n) => n.startsWith('dsh-')).map((n) => '@deepseek-ai/' + n) } catch {} }
40
+ return names.map((pkg) => { let desc = ''; try { desc = JSON.parse(fs.readFileSync(path.join(NM, pkg, 'package.json'), 'utf8')).description ?? '' } catch {} const short = pkg.replace(/^@deepseek-ai\/dsh-/, ''); return { pkg, name: short, category: catOf(short), desc: String(desc).slice(0, 160) } })
41
+ }
42
+ /** 让 plugins/node_modules/@deepseek-ai 指回内核的那份(插件和内核用同一套 cordis) */
43
+ function linkCore() {
44
+ const dst = path.join(DIR, 'node_modules', '@deepseek-ai'), src = path.join(NM, '@deepseek-ai')
45
+ fs.mkdirSync(path.dirname(dst), { recursive: true })
46
+ try { const st = fs.lstatSync(dst); if (st.isSymbolicLink()) return; fs.rmSync(dst, { recursive: true, force: true }) } catch {}
47
+ fs.symlinkSync(src, dst, 'dir')
48
+ }
49
+ async function install(spec) {
50
+ spec = String(spec ?? '').trim()
51
+ if (!/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=*-]+)?$/i.test(spec) && !/^https:\/\/(github\.com|codeload\.github\.com|registry\.npmmirror\.com|registry\.npmjs\.org)\/\S+$/.test(spec)) throw new Error('填 npm 包名(比如 dsh-plugin-xxx 或 @作者/xxx),或者 GitHub 链接')
52
+ if (!linux.supported()) throw new Error('这台设备上用不了内置 Linux,装不了插件')
53
+ await linux.ensure()
54
+ fs.mkdirSync(DIR, { recursive: true })
55
+ if (!fs.existsSync(path.join(DIR, 'package.json'))) fs.writeFileSync(path.join(DIR, 'package.json'), JSON.stringify({ name: 'yusho-user-plugins', private: true, type: 'module' }))
56
+ // 先把指向内核的链接拿掉,免得 npm 往内核目录里写;装完再接回来
57
+ try { fs.rmSync(path.join(DIR, 'node_modules', '@deepseek-ai'), { force: true, recursive: false }) } catch {}
58
+ const before = new Set(Object.keys(JSON.parse(fs.readFileSync(path.join(DIR, 'package.json'), 'utf8')).dependencies ?? {}))
59
+ const r = await linux.exec(`cd '${DIR}' && npm install --no-audit --no-fund --legacy-peer-deps --omit=peer --ignore-scripts --registry=https://registry.npmmirror.com '${spec.replace(/'/g, '')}' 2>&1 | tail -20`, { binds: [DIR], timeoutMs: 600_000 })
60
+ linkCore()
61
+ const deps = JSON.parse(fs.readFileSync(path.join(DIR, 'package.json'), 'utf8')).dependencies ?? {}
62
+ const pkg = Object.keys(deps).find((k) => !before.has(k)) ?? Object.keys(deps).find((k) => spec.startsWith(k))
63
+ if (r.code !== 0 || !pkg) throw new Error('没装上:' + r.out.trim().split('\n').slice(-3).join(' ').slice(0, 300))
64
+ const pj = JSON.parse(fs.readFileSync(path.join(DIR, 'node_modules', pkg, 'package.json'), 'utf8'))
65
+ const list = readList().filter((p) => p.pkg !== pkg)
66
+ list.push({ id: 'user-' + pkg.replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '').toLowerCase(), pkg, version: pj.version ?? '', desc: String(pj.description ?? '').slice(0, 160), category: catOf(pkg), at: Date.now(), enabled: true })
67
+ writePatch(list); log('装了插件 ' + pkg + '@' + (pj.version ?? ''))
68
+ return { pkg, version: pj.version ?? '', restart: true }
69
+ }
70
+ function remove(pkg) {
71
+ const list = readList(); if (!list.some((p) => p.pkg === pkg)) throw new Error('没装这个插件')
72
+ writePatch(list.filter((p) => p.pkg !== pkg))
73
+ fs.rmSync(path.join(DIR, 'node_modules', ...pkg.split('/')), { recursive: true, force: true })
74
+ try { const pj = JSON.parse(fs.readFileSync(path.join(DIR, 'package.json'), 'utf8')); delete pj.dependencies?.[pkg]; fs.writeFileSync(path.join(DIR, 'package.json'), JSON.stringify(pj)) } catch {}
75
+ return { restart: true }
76
+ }
77
+ function setEnabled(pkg, on) { const list = readList(); const p = list.find((x) => x.pkg === pkg); if (!p) throw new Error('没装这个插件'); p.enabled = !!on; writePatch(list); return { restart: true } }
78
+ return { view: () => ({ builtin: builtin(), user: readList(), cats: PLUGIN_CATS, linux: linux.supported() }), install, remove, setEnabled, patchFile: () => (fs.existsSync(PATCH) ? PATCH : null) }
79
+ }