@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,485 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
/**
|
|
3
|
+
* 鱼Sho 手机版的“派活”工具:手机上的助理用它把活交给已连上的电脑上的 Agent(Codex、Claude Code、DSH)。
|
|
4
|
+
* 网络(身份、中继、配对、任务状态)在启动器的 net.mjs 里,同一个进程,通过 globalThis.__shoalNet 拿到。
|
|
5
|
+
* 这里只把它包成模型能调用的工具。审批不经过模型:电脑上的 Agent 要权限时,请求直接出现在手机页面上,由用户本人点。
|
|
6
|
+
*/
|
|
7
|
+
export const name = 'shoal-mobile'
|
|
8
|
+
export const inject = ['tools']
|
|
9
|
+
|
|
10
|
+
const TEXT = { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: String(v) }] }
|
|
11
|
+
const net = () => globalThis.__shoalNet
|
|
12
|
+
|
|
13
|
+
// 小应用图标:只收简单的矢量图形。界面用 <img> 显示(本来就不会执行脚本),这里再按白名单查一遍
|
|
14
|
+
const SVG_TAGS = new Set(['svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon', 'lineargradient', 'radialgradient', 'stop', 'defs'])
|
|
15
|
+
export function safeSvg(src) {
|
|
16
|
+
const svg = String(src ?? '').trim()
|
|
17
|
+
if (svg.length > 6000) return { error: '超过 6 KB' }
|
|
18
|
+
if (!/^<svg[\s>]/i.test(svg) || !/<\/svg>$/i.test(svg)) return { error: '要是一个完整的 <svg>…</svg>' }
|
|
19
|
+
if (/<!|<\?/.test(svg)) return { error: '不能有注释、DOCTYPE 或 CDATA' }
|
|
20
|
+
for (const m of svg.matchAll(/<\/?\s*([a-zA-Z][\w:-]*)([^>]*)>/g)) {
|
|
21
|
+
if (!SVG_TAGS.has(m[1].toLowerCase())) return { error: '不能用 <' + m[1] + '>' }
|
|
22
|
+
if (/\son\w+\s*=|href\s*=|\sstyle\s*=|url\(\s*['"]?(?!#)/i.test(m[2])) return { error: '不能有事件、链接、style 或外部引用' }
|
|
23
|
+
}
|
|
24
|
+
return { svg: /xmlns=/.test(svg.slice(0, 200)) ? svg : svg.replace(/^<svg/i, '<svg xmlns="http://www.w3.org/2000/svg"') }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function membersText() {
|
|
28
|
+
const n = net()
|
|
29
|
+
if (!n) return '派活功能没有启动。'
|
|
30
|
+
const ms = n.members()
|
|
31
|
+
if (!ms.length) return '还没有连上电脑。请用户在电脑上装鱼Sho 连接器(对电脑上的 Claude Code / Codex 说“按 yusho.chat/connect.md 帮我连上鱼Sho”;或者自己装:npm install -g @yusho/dsh-yusho-connect --registry=https://registry.npmmirror.com),再在 App 的 圈子 →“+”→ 接入电脑上的 Agent 里扫码。'
|
|
32
|
+
return ms.map((m) => `${m.name}:可以派给 ${m.agents.join('、')}${n.online() ? '' : '(手机现在连不上中继)'}`).join('\n')
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function apply(ctx) {
|
|
36
|
+
// 边写边显示:DSH 每收到模型的一小段(正文、思考)就发一个 agent/assistant-stream;JSON-RPC 不转发它,所以在这里(同一个进程)接住交给启动器
|
|
37
|
+
// 调试用:现在登记了哪些工具(看助理到底拿不拿得到)
|
|
38
|
+
globalThis.__shoalToolNames = () => { try { return ctx.tools.definitions().map((d) => d.name) } catch (e) { return ['ERR ' + (e?.message ?? e)] } }
|
|
39
|
+
ctx.on('agent/assistant-stream', (e) => { try { globalThis.__shoalStream?.(e?.frame) } catch {} })
|
|
40
|
+
// 老的安卓网页视图(Chrome 119 以前,比如 113)没有 Promise.withResolvers、AbortSignal.any(116 起才有):DSH 网页的启动脚本和连接层都用它,
|
|
41
|
+
// 缺了就报错、连接层一直断开重连。在页面最前面补上(新的网页视图本来就有,这段什么也不做)
|
|
42
|
+
ctx.inject(['webServer'], (c) => {
|
|
43
|
+
// 老网页视图(安卓 10 自带 Chrome 74 一类)缺的函数,见 polyfill.js;所有脚本前面先补上
|
|
44
|
+
const POLYFILL = '<script>' + fs.readFileSync(new URL('./polyfill.js', import.meta.url), 'utf8').replace(/<\/script/gi, '<\\/script') + '</script>'
|
|
45
|
+
c.effect(() => c.webServer.tapIndex((html) => { const m = /<head(?:\s[^>]*)?>/i.exec(html); return m ? html.slice(0, m.index + m[0].length) + POLYFILL + html.slice(m.index + m[0].length) : POLYFILL + html }), 'shoal-mobile: 老网页视图补 Promise.withResolvers')
|
|
46
|
+
})
|
|
47
|
+
// 定时(提醒、定时任务):DSH 的 schedule 服务。交给启动器给界面用:列出全部、删一个、暂停 / 恢复
|
|
48
|
+
// DeepSeek 官方账号(DSH 自带的账号登录):内核用它查状态、登录、退出、查余额
|
|
49
|
+
ctx.inject(['deepseekAccount'], (c) => {
|
|
50
|
+
c.effect(() => { globalThis.__shoalDsAcc = c.deepseekAccount; return () => { if (globalThis.__shoalDsAcc === c.deepseekAccount) globalThis.__shoalDsAcc = null } })
|
|
51
|
+
})
|
|
52
|
+
// 电脑版:读 DSH 会话(左栏“任务”)这一轮的结果——“发给…”“做完发到手机”用。wait 在会话停下来(或超时)时返回最近的助理消息
|
|
53
|
+
ctx.inject(['sessionController'], (c) => {
|
|
54
|
+
c.effect(() => {
|
|
55
|
+
globalThis.__shoalDshWait = (sessionId, timeoutMs = 1000, afterSeq, maxMessages = 1) => c.sessionController.wait({ sessionId, timeoutMs, maxMessages, ...(afterSeq != null ? { afterSeq } : {}) }, AbortSignal.timeout(timeoutMs + 10_000))
|
|
56
|
+
return () => { delete globalThis.__shoalDshWait }
|
|
57
|
+
}, 'shoal-mobile: 读会话结果')
|
|
58
|
+
})
|
|
59
|
+
// 电脑版:定时 / 工作流用“每次开一件新任务”时,新会话是 DSH 网页版的会话控制器建的,建好就有一个活着的 Agent 占着写入;
|
|
60
|
+
// 我们插进来的 SDK 服务(给鱼Sho 内核用)抢着再打开同一个会话就会报“already owned by an active write handle”。
|
|
61
|
+
// 排在它前面:已经有活着的 Agent 就直接用它(审批、提问照 DSH 网页的做法),没有才交给 SDK 服务。手机上不登记,照旧
|
|
62
|
+
if (process.env.SHOAL_PLATFORM === 'pc') ctx.inject(['agents'], (c) => {
|
|
63
|
+
c.on('schedule/resolve-agent', (sessionId, next) => c.agents.get(sessionId) ?? next(), true)
|
|
64
|
+
})
|
|
65
|
+
// 电脑版接单:手机派给“这台电脑的 DSH”的活,开成网页版左栏里看得到的一件任务(默认工作区、工作秘书预设),把活发进去。
|
|
66
|
+
// 这件任务里要你批的事:网页上照常弹,同时交给连接器发到手机,哪边先批算哪边(__shoalDshApproval 由内核登记)
|
|
67
|
+
if (process.env.SHOAL_PLATFORM === 'pc') ctx.inject(['sessionController'], (c) => {
|
|
68
|
+
c.effect(() => {
|
|
69
|
+
globalThis.__shoalDshRun = {
|
|
70
|
+
async create(cwd, agentPreset) {
|
|
71
|
+
const r = await c.sessionController.create({ cwd, ...(agentPreset ? { agentPreset } : {}) })
|
|
72
|
+
try { await (await c.get('workspaceRegistry')?.resolveByPath(cwd))?.attachSession(r.sessionId) } catch {}
|
|
73
|
+
return r.sessionId
|
|
74
|
+
},
|
|
75
|
+
prompt: (sessionId, text, o) => c.sessionController.prompt({ requestId: (o?.local ? 'req-' : 'req-yph-') + crypto.randomUUID() /* yph = 手机派来的:电脑版在这条用户消息上标“从手机发的” */, sessionId, mode: 'queue', content: [{ type: 'text', text }] }, AbortSignal.timeout(60_000)),
|
|
76
|
+
cancel: (sessionId) => c.sessionController.cancel({ sessionId }),
|
|
77
|
+
// 这件任务叫起来的子 Agent(它们的会话记着父任务),还在不在做
|
|
78
|
+
async kids(sessionId) { const v = await c.sessionController.list({}); return (v?.items ?? []).filter((x) => x.parentSessionId === sessionId).map((x) => ({ id: x.sessionId, running: !!x.running })) },
|
|
79
|
+
}
|
|
80
|
+
return () => { delete globalThis.__shoalDshRun }
|
|
81
|
+
}, 'shoal-mobile: 电脑版接单开任务')
|
|
82
|
+
c.on('approval/request', (req, next) => {
|
|
83
|
+
const sid = req?.agent?.session?.id, hook = globalThis.__shoalDshApproval
|
|
84
|
+
const phone = sid && hook ? hook(sid, req) : null
|
|
85
|
+
if (!phone) return next()
|
|
86
|
+
// 手机先批了:网页上那张“要你批”也要收起——给这次请求挂一个我们能触发的取消信号,网页那边看到取消就撤掉
|
|
87
|
+
const ac = new AbortController()
|
|
88
|
+
try { Object.defineProperty(req, 'signal', { value: req.signal ? AbortSignal.any([req.signal, ac.signal]) : ac.signal, configurable: true, writable: true }) } catch {}
|
|
89
|
+
const web = next()
|
|
90
|
+
return Promise.race([web.then((o) => { phone.done(o === 'allowed-once' ? 'allow' : 'reject'); return o }), phone.answer.then((a) => { if (a) ac.abort(); return a === 'allow' ? 'allowed-once' : a === 'reject' ? 'rejected' : web })])
|
|
91
|
+
}, true)
|
|
92
|
+
})
|
|
93
|
+
ctx.inject(['schedule'], (c) => {
|
|
94
|
+
c.effect(() => {
|
|
95
|
+
globalThis.__shoalSchedule = {
|
|
96
|
+
list: () => c.schedule.catalog(),
|
|
97
|
+
remove: (id) => c.schedule.remoteEdit({ id, action: 'delete' }),
|
|
98
|
+
update: (id, patch) => c.schedule.remoteEdit({ id, action: 'update', patch }),
|
|
99
|
+
// 电脑版工作流:新建、马上跑一次、运行记录
|
|
100
|
+
create: (req) => c.schedule.remoteCreate(req),
|
|
101
|
+
run: (id) => c.schedule.run({ id }),
|
|
102
|
+
history: (id, limit = 8) => c.schedule.history({ id, limit }),
|
|
103
|
+
}
|
|
104
|
+
return () => { delete globalThis.__shoalSchedule }
|
|
105
|
+
}, 'shoal-mobile: 定时交给界面')
|
|
106
|
+
})
|
|
107
|
+
// DSH 网页前端的连接层一打开就订阅宿主的“转发事件”流($events)。完整 DSH 由 dsh-api-remotes 提供这个流,
|
|
108
|
+
// 它会把审批、提问转发给网页——手机上审批和提问走启动器(SDK),不能让网页抢走。这里登记一个永远不发事件的空流:
|
|
109
|
+
// 网页的连接握手能完成,不再每隔几秒断开重连(以前控制台里一直是 connection lost, retry #N)
|
|
110
|
+
// 电脑版(完整 DSH 网页版):审批、提问要照 DSH 自己的做法交给网页(接管输入框),所以不登记这个空流;手机上照旧
|
|
111
|
+
if (process.env.SHOAL_PLATFORM !== 'pc') ctx.inject(['typertGateway'], (c) => {
|
|
112
|
+
c.effect(() => c.typertGateway.registerRemoteEvents((signal) => ({
|
|
113
|
+
async *[Symbol.asyncIterator]() { if (!signal.aborted) await new Promise((ok) => signal.addEventListener('abort', ok, { once: true })) },
|
|
114
|
+
}), { home: process.env.HOME || process.cwd() }), 'shoal-mobile: 空的转发事件流')
|
|
115
|
+
})
|
|
116
|
+
// 界面(DSH 网页宿主里的鱼Sho 前端插件)调启动器的接口:只开一个 /api/yusho,经 DSH 的登录保护转给启动器。
|
|
117
|
+
// 请求体 { method, path, body };回原样的状态码和内容。没有网页宿主(比如电脑上只跑 SDK)时这段不启用
|
|
118
|
+
ctx.inject(['connection'], (c) => {
|
|
119
|
+
c.effect(() => c.connection.fetch.register({
|
|
120
|
+
path: '/api/yusho', methods: ['POST'], requestBody: 'buffered',
|
|
121
|
+
fetch: async (request) => {
|
|
122
|
+
let b = {}; try { b = await request.json() } catch {}
|
|
123
|
+
const p = String(b.path ?? '')
|
|
124
|
+
if (!p.startsWith('/api/') || typeof globalThis.__shoalApi !== 'function') return new Response(JSON.stringify({ error: '不支持' }), { status: 400, headers: { 'content-type': 'application/json; charset=utf-8' } })
|
|
125
|
+
const r = await globalThis.__shoalApi(String(b.method || 'GET').toUpperCase(), p, b.body === undefined ? '' : JSON.stringify(b.body))
|
|
126
|
+
return new Response(r.body, { status: r.status, headers: r.headers })
|
|
127
|
+
},
|
|
128
|
+
}), 'shoal-mobile: /api/yusho')
|
|
129
|
+
// 发给电脑的文件(相册、系统文件管理里选的,可能几个 GB):流式写进 App 的临时目录,交给直连传完就删
|
|
130
|
+
c.effect(() => c.connection.fetch.register({
|
|
131
|
+
path: '/api/yusho-up', methods: ['POST'], requestBody: 'streaming',
|
|
132
|
+
fetch: async (request) => {
|
|
133
|
+
const j = (s, b) => new Response(JSON.stringify(b), { status: s, headers: { 'content-type': 'application/json; charset=utf-8' } })
|
|
134
|
+
if (typeof globalThis.__shoalUpload !== 'function') return j(400, { error: '不支持' })
|
|
135
|
+
const u = new URL(request.url)
|
|
136
|
+
async function* chunks(body) { if (!body) return; const r = body.getReader(); try { for (;;) { const c = await r.read(); if (c.done) return; yield c.value } } finally { r.releaseLock() } }
|
|
137
|
+
try { return j(200, await globalThis.__shoalUpload({ name: u.searchParams.get('name') ?? '', size: Number(u.searchParams.get('size') ?? 0), chunks: chunks(request.body), signal: request.signal })) } catch (e) { return j(400, { error: String(e?.message || e) }) }
|
|
138
|
+
},
|
|
139
|
+
}), 'shoal-mobile: /api/yusho-up')
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
// 列文件:完整 DSH 的文件搜索(glob / grep)要调用 ripgrep(开子进程),手机上用不了;这里用纯 JS 列目录,只限 App 的工作目录
|
|
143
|
+
ctx.effect(() => ctx.tools.register({
|
|
144
|
+
name: 'list_files',
|
|
145
|
+
description: '列出 App 工作目录里的文件和文件夹(手机上没有命令行,用这个代替 ls / glob)。path 是相对工作目录的子目录,默认根目录;pattern 可选,按文件名过滤,支持 * 和 ?(例如 *.md);recursive 为 true 时包含子目录。最多返回 500 项。',
|
|
146
|
+
parameters: { type: 'object', properties: { path: { type: 'string' }, pattern: { type: 'string' }, recursive: { type: 'boolean' } }, additionalProperties: false },
|
|
147
|
+
output: TEXT,
|
|
148
|
+
timeoutMs: 15000,
|
|
149
|
+
async execute(args) {
|
|
150
|
+
const fs = await import('node:fs'), path = await import('node:path')
|
|
151
|
+
const root = path.resolve(process.env.SHOAL_WORKSPACE || process.cwd())
|
|
152
|
+
const dir = path.resolve(root, String(args?.path ?? '.'))
|
|
153
|
+
if (dir !== root && !dir.startsWith(root + path.sep)) return '只能列 App 工作目录里的东西。'
|
|
154
|
+
if (!fs.existsSync(dir)) return `没有这个目录:${path.relative(root, dir) || '.'}`
|
|
155
|
+
const re = args?.pattern ? new RegExp('^' + String(args.pattern).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + '$', 'i') : null
|
|
156
|
+
const out = []
|
|
157
|
+
const walk = (d) => {
|
|
158
|
+
for (const e of fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
159
|
+
if (out.length >= 500) return
|
|
160
|
+
const p = path.join(d, e.name), rel = path.relative(root, p).split(path.sep).join('/')
|
|
161
|
+
if (!re || re.test(e.name)) out.push(e.isDirectory() ? rel + '/' : `${rel}(${fs.statSync(p).size} 字节)`)
|
|
162
|
+
if (e.isDirectory() && args?.recursive) walk(p)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
walk(dir)
|
|
166
|
+
return out.length ? out.join('\n') + (out.length >= 500 ? '\n(只列了前 500 项)' : '') : '(空的)'
|
|
167
|
+
},
|
|
168
|
+
}))
|
|
169
|
+
|
|
170
|
+
// 小应用:用户说“做一个学日语的小应用”,助理写一个单文件网页,放进 App。用户先试、再启用。
|
|
171
|
+
// 小应用跑在隔离的沙盒里(不能联网、读不到对话和钥匙),只能用声明过、用户同意了的能力:问 AI(ai)、存自己的数据(storage)
|
|
172
|
+
ctx.effect(() => ctx.tools.register({
|
|
173
|
+
name: 'make_mini_app',
|
|
174
|
+
description: [
|
|
175
|
+
'做(或改)一个 App 里的“小应用”:一个单文件网页(HTML,CSS 和 JS 都写在里面),用户在 App 里点开就能用,比如学日语卡片、记账、番茄钟。',
|
|
176
|
+
'同一个 id 再调用就是改版。做完告诉用户:到“助理 → 小应用”里试一下,满意了点“启用”。',
|
|
177
|
+
'限制:不能联网(不能引用外部的脚本、样式、图片、字体,也不能 fetch),所有东西写在这一个文件里;手机竖屏,字号不小于 16px,按钮至少 44px 高。',
|
|
178
|
+
'能用的接口(在页面里直接用全局对象 yusho,都返回 Promise):',
|
|
179
|
+
'await yusho.ai("问题"):让 AI 回答(要在 permissions 里声明 "ai");',
|
|
180
|
+
'await yusho.storage.get("键")、await yusho.storage.set("键", 值):存取这个小应用自己的数据,值可以是任何 JSON(要声明 "storage");',
|
|
181
|
+
'await yusho.speak("文字", "语言"):朗读出声(App 负责:先用免费的在线朗读,没网时用手机的系统语音),语言用 BCP-47,例如 "ja-JP"、"en-US"、"zh-CN"(要声明 "speak")。朗读一律用 yusho.speak,不要用浏览器的 speechSynthesis(小应用里没有);',
|
|
182
|
+
'await yusho.card.set({ title: "标题", lines: ["一行字", …] }):在 App 的副屏放一张小卡片(标题 20 字内、最多 4 行、每行 60 字内),显示这个小应用的近况,比如“今天背了 12 个词”“本月支出 ¥1,280”;状态变了就再调一次,yusho.card.set(null) 撤掉(要声明 "card")。',
|
|
183
|
+
'不要声明用不到的权限。图标:从 glyph 的列表里挑一个最能代表它的线条图标,tone 按用途选颜色(学习语言 blue、时间效率 coral、钱 green、健康运动 teal、生活心情 amber、游戏娱乐 violet、恋爱社交 pink、思考工具 indigo、提醒紧急 red)。图标由 App 统一画,不用自己画。',
|
|
184
|
+
].join(''),
|
|
185
|
+
parameters: {
|
|
186
|
+
type: 'object',
|
|
187
|
+
properties: {
|
|
188
|
+
id: { type: 'string', description: '英文小写、数字和 -,例如 learn-japanese' },
|
|
189
|
+
title: { type: 'string', description: '给用户看的名字,例如“学日语”' },
|
|
190
|
+
description: { type: 'string', description: '一句话说明它能干什么' },
|
|
191
|
+
icon: { type: 'string', description: '一个 emoji,例如 🗾(SVG 图标用不了时显示)' },
|
|
192
|
+
glyph: { type: 'string', description: '图标,只能从这些里选一个:timer alarm-clock hourglass calendar-days calendar-check list-checks notebook-pen sticky-note book-open-text book-heart languages graduation-cap brain lightbulb calculator sigma wallet piggy-bank receipt chart-pie chart-line coins shopping-cart gift dumbbell heart-pulse footprints bike apple salad utensils coffee cup-soda droplets pill bed moon-star sun cloud-sun thermometer leaf flower-2 sprout trees dog cat fish paw-print music headphones mic-vocal film camera image palette brush pen-tool gamepad-2 dice-5 puzzle trophy target party-popper smile heart star sparkles zap flame map map-pin plane car house shirt baby message-circle-heart quote globe compass key-round shield-check bell clock' },
|
|
193
|
+
tone: { type: 'string', enum: ['blue', 'coral', 'green', 'teal', 'amber', 'violet', 'pink', 'indigo', 'red'], description: '图标颜色:学习语言 blue、时间效率 coral、钱 green、健康运动 teal、生活心情 amber、游戏娱乐 violet、恋爱社交 pink、思考工具 indigo、提醒紧急 red' },
|
|
194
|
+
permissions: { type: 'array', items: { type: 'string', enum: ['ai', 'storage', 'speak', 'card'] } },
|
|
195
|
+
html: { type: 'string', description: '完整的单文件 HTML' },
|
|
196
|
+
},
|
|
197
|
+
required: ['id', 'title', 'html'],
|
|
198
|
+
additionalProperties: false,
|
|
199
|
+
},
|
|
200
|
+
output: TEXT,
|
|
201
|
+
timeoutMs: 30000,
|
|
202
|
+
async execute(args) {
|
|
203
|
+
const fs = await import('node:fs'), path = await import('node:path')
|
|
204
|
+
const id = String(args?.id ?? '').trim().toLowerCase()
|
|
205
|
+
if (!/^[a-z0-9][a-z0-9-]{1,40}$/.test(id)) return 'id 只能用英文小写、数字和 -,2 到 41 个字。'
|
|
206
|
+
const html = String(args?.html ?? '')
|
|
207
|
+
if (!/<(html|body|div|script)/i.test(html)) return 'html 看起来不是网页。'
|
|
208
|
+
if (html.length > 400_000) return '太大了(超过 400 KB),精简一下。'
|
|
209
|
+
// 自动审计(技能 make-app 的“安全”和规范里能机器查的部分):不过就退回,按提示改好再交
|
|
210
|
+
const bad = [], warn = []
|
|
211
|
+
const noComments = html.replace(/<!--[\s\S]*?-->/g, '')
|
|
212
|
+
if (/\b(fetch|XMLHttpRequest|WebSocket|EventSource|navigator\.sendBeacon)\s*\(/.test(noComments) || /new\s+(XMLHttpRequest|WebSocket|EventSource)\b/.test(noComments)) bad.push('有联网的代码(fetch / XMLHttpRequest / WebSocket / EventSource / sendBeacon):小应用不能联网,要 AI 用 yusho.ai')
|
|
213
|
+
if (/<(script|link|img|iframe|audio|video|source|embed|object)\b[^>]*\b(src|href)\s*=\s*["']?\s*(https?:)?\/\//i.test(noComments) || /url\(\s*["']?\s*(https?:)?\/\//i.test(noComments) || /@import\s+(url\()?\s*["']?(https?:)?\/\//i.test(noComments)) bad.push('引用了外部的脚本 / 样式 / 图片 / 字体:所有东西都要写在这一个文件里')
|
|
214
|
+
if (/\beval\s*\(|new\s+Function\s*\(|document\.write\s*\(/.test(noComments)) bad.push('用了 eval / new Function / document.write:换成普通写法')
|
|
215
|
+
if (/\blocalStorage\b|\bsessionStorage\b|\bindexedDB\b/.test(noComments)) bad.push('用了 localStorage / sessionStorage / indexedDB:数据要用 yusho.storage(并在 permissions 里声明 "storage")')
|
|
216
|
+
const used = { ai: /yusho\.ai\s*\(/.test(noComments), storage: /yusho\.storage\./.test(noComments), speak: /yusho\.speak\s*\(/.test(noComments), card: /yusho\.card\./.test(noComments) }
|
|
217
|
+
const decl = new Set(args?.permissions ?? [])
|
|
218
|
+
for (const [k, u] of Object.entries(used)) if (u && !decl.has(k)) bad.push(`代码里用了 yusho.${k},但 permissions 里没声明 "${k}"`)
|
|
219
|
+
for (const k of decl) if (used[k] === false) warn.push(`声明了 "${k}" 但代码里没用到:去掉这个权限`)
|
|
220
|
+
if (!/<meta[^>]+name=["']?viewport/i.test(html)) bad.push('缺少 <meta name="viewport" content="width=device-width, initial-scale=1">,手机上会缩成一小块')
|
|
221
|
+
if (/font-size\s*:\s*(1[0-3]|[0-9])px/i.test(noComments)) warn.push('有小于 14px 的字:正文至少 16px,辅助文字至少 13–14px')
|
|
222
|
+
if (/\.innerHTML\s*[+]?=\s*[^;]*\b(value|input|text)\b/.test(noComments)) warn.push('可能把用户输入直接塞进了 innerHTML:用户内容用 textContent 或先转义')
|
|
223
|
+
if (bad.length) return '自动审计没通过,改好再交:\n- ' + bad.join('\n- ') + (warn.length ? '\n另外建议:\n- ' + warn.join('\n- ') : '')
|
|
224
|
+
const dir = path.join(process.env.SHOAL_APPS_DIR || 'apps', id)
|
|
225
|
+
fs.mkdirSync(dir, { recursive: true })
|
|
226
|
+
let old = {}; try { old = JSON.parse(fs.readFileSync(path.join(dir, 'app.json'), 'utf8')) } catch {}
|
|
227
|
+
const perms = [...new Set((args?.permissions ?? []).filter((p) => p === 'ai' || p === 'storage' || p === 'speak' || p === 'card'))]
|
|
228
|
+
// 模型偶尔把工具调用的格式漏进参数里(比如标题后面跟着 </title><parameter=…),只取第一个尖括号之前的字
|
|
229
|
+
const clean = (v, n) => String(v ?? '').split('<')[0].replace(/[\u0000-\u001f]/g, ' ').trim().slice(0, n)
|
|
230
|
+
const icon = [...clean(args?.icon, 16)].slice(0, 2).join('') || old.icon || ''
|
|
231
|
+
let iconSvg = old.iconSvg || ''
|
|
232
|
+
if (args?.icon_svg) { const r = safeSvg(args.icon_svg); if (r.error) return '图标不合格:' + r.error + '。按技能 app-icon 的规格重画,再调用一次。'; iconSvg = r.svg }
|
|
233
|
+
// 改版保留置顶的意愿;要重新启用后才显示在会话页
|
|
234
|
+
const glyph = /^[a-z0-9-]{2,30}$/.test(String(args?.glyph ?? '')) ? String(args.glyph) : old.glyph || null
|
|
235
|
+
const tone = ['blue', 'coral', 'green', 'teal', 'amber', 'violet', 'pink', 'indigo', 'red'].includes(args?.tone) ? args.tone : old.tone || null
|
|
236
|
+
const meta = { id, title: clean(args?.title, 30) || id, description: clean(args?.description, 200), icon, iconSvg, glyph, tone, permissions: perms, version: (old.version ?? 0) + 1, updatedAt: Date.now(), createdAt: old.createdAt ?? Date.now(), enabled: false, granted: [], pinned: !!old.pinned, pinnedAt: old.pinnedAt ?? null }
|
|
237
|
+
// 改版后要用户重新确认:权限变了、代码变了,都重新试过再启用
|
|
238
|
+
fs.writeFileSync(path.join(dir, 'index.html'), html)
|
|
239
|
+
fs.writeFileSync(path.join(dir, 'app.json'), JSON.stringify(meta))
|
|
240
|
+
return (warn.length ? '(自动审计通过,另有建议:' + warn.join(';') + ')\n' : '(自动审计通过)\n') + `小应用「${meta.title}」第 ${meta.version} 版做好了(id: ${id},权限:${perms.join('、') || '无'})。请告诉用户:到“助理 → 小应用”里点开试一下,满意了点“启用”${old.version ? '(改版后要重新启用)' : ''}。`
|
|
241
|
+
},
|
|
242
|
+
}))
|
|
243
|
+
|
|
244
|
+
// 助理页的 Sho 酱(生活线)看工作那边:最近聊了什么、派给电脑的活怎么样。只读,不碰生活线的记录
|
|
245
|
+
// 助理替用户做事:看好友和群、给好友 / 群发消息(按审批设置,可能要用户点同意)、把事交给工作秘书
|
|
246
|
+
// 她在助理页左上角显示的状态(心情、在做什么)
|
|
247
|
+
ctx.effect(() => ctx.tools.register({
|
|
248
|
+
name: 'set_status',
|
|
249
|
+
description: '换你在助理页左上角显示的状态。可以从这些里选:心情很好、开心、很想你、在忙、工作中、有点烦、有点低落、难过、烦躁、困了、饿了;也可以自己写,6 个字以内。心情或在做的事变了就换,不用每轮都换。传空字符串表示不显示自己设的状态。',
|
|
250
|
+
parameters: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false },
|
|
251
|
+
output: TEXT, timeoutMs: 5000,
|
|
252
|
+
async execute(a) { const t = globalThis.__shoalSetStatus?.(a?.text); return t ? '状态换成了“' + t + '”。' : '不显示自己设的状态了。' },
|
|
253
|
+
}))
|
|
254
|
+
// 她自己的日记本和人设:只读。想起以前写过什么、用户问“你日记里写了什么”“你是什么性格”时用
|
|
255
|
+
ctx.effect(() => ctx.tools.register({
|
|
256
|
+
name: 'my_diary',
|
|
257
|
+
description: '看你自己的日记(最近写的几篇,带日期)和你自己的人设。what:diary(默认)只看日记、persona 只看人设、both 都看。只读。',
|
|
258
|
+
parameters: { type: 'object', properties: { what: { type: 'string', enum: ['diary', 'persona', 'both'] }, count: { type: 'number' } }, additionalProperties: false },
|
|
259
|
+
output: TEXT, timeoutMs: 5000,
|
|
260
|
+
async execute(a) { const r = globalThis.__shoalMyDiary?.(a?.what ?? 'diary', a?.count ?? 5); return r || '看不到。' },
|
|
261
|
+
}))
|
|
262
|
+
ctx.effect(() => ctx.tools.register({
|
|
263
|
+
name: 'contacts_list',
|
|
264
|
+
description: '看用户的好友和群(名字、鱼Sho号、在不在线)。用户让你联系某人、给谁发消息前先用这个找对人。只读。',
|
|
265
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
266
|
+
output: TEXT, timeoutMs: 10000,
|
|
267
|
+
async execute(_a, exec) { const c = globalThis.__shoalAssist?.contacts(exec?.agent?.session?.id); if (!c) return '看不到。'; if (c.error) return c.error; return (c.friends ? '好友(' + c.friends.length + '):' + (c.friends.map((f) => f.name + (f.number ? '(' + f.number + ')' : '') + (f.starred ? '★' : '') + (f.tags?.length ? '[' + f.tags.join('/') + ']' : '') + (f.online ? '·在线' : '')).join('、') || '没有') : '') + (c.groups ? '\n群和兴趣圈(' + c.groups.length + '):' + (c.groups.map((g) => g.name + (g.circle ? '(兴趣圈)' : '') + (g.muted ? '·免打扰' : '')).join('、') || '没有') : '') + (c.why ? '\n' + c.why : '') },
|
|
268
|
+
}))
|
|
269
|
+
ctx.effect(() => ctx.tools.register({
|
|
270
|
+
name: 'send_message',
|
|
271
|
+
description: '替用户给好友或群发一条消息(用户明确让你发时才用)。to 是好友的备注、名字或鱼Sho号,或者群名(这时 group 填 true)。会按用户的审批设置先问用户同不同意。消息用用户的口吻还是你的口吻,按用户说的来;没说就写成“XX 让我转告你:…”。',
|
|
272
|
+
parameters: { type: 'object', properties: { to: { type: 'string' }, text: { type: 'string' }, group: { type: 'boolean' } }, required: ['to', 'text'], additionalProperties: false },
|
|
273
|
+
output: TEXT, timeoutMs: 11 * 60_000,
|
|
274
|
+
async execute(a, exec) { try { return await globalThis.__shoalAssist.send(a ?? {}, exec?.agent?.session?.id) } catch (e) { return '没发成:' + (e?.message ?? e) } },
|
|
275
|
+
}))
|
|
276
|
+
ctx.effect(() => ctx.tools.register({
|
|
277
|
+
name: 'ask_secretary',
|
|
278
|
+
description: '把一件工作上的事交给会话页的工作秘书去做(比如查资料、整理文件、设定时、派活给电脑上的 Claude Code / Codex)。它做完会在会话页回用户。适合你自己不方便做、或者要用到电脑的事。',
|
|
279
|
+
parameters: { type: 'object', properties: { instruction: { type: 'string', description: '要它做什么,写清楚' } }, required: ['instruction'], additionalProperties: false },
|
|
280
|
+
output: TEXT, timeoutMs: 10000,
|
|
281
|
+
async execute(a, exec) { return globalThis.__shoalAssist?.askSecretary(a?.instruction, exec?.agent?.session?.id) ?? '工作秘书不在。' },
|
|
282
|
+
}))
|
|
283
|
+
|
|
284
|
+
// ── 看、管:按 设置 › 权限与审批 里给助理 / 工作秘书的权限(看不到 / 只读 / 可管理);管的操作按审批设置先问用户
|
|
285
|
+
const P = (o) => ({ type: 'object', properties: o, additionalProperties: false })
|
|
286
|
+
const tool = (name, description, parameters, fn, timeoutMs = 11 * 60_000) => ctx.effect(() => ctx.tools.register({ name, description, parameters, output: TEXT, timeoutMs, async execute(a, exec) { try { return await fn(a ?? {}, exec?.agent?.session?.id) } catch (e) { return '没成:' + (e?.message ?? e) } } }))
|
|
287
|
+
tool('read_chat', '看用户和某个好友、某个群、或电脑上某个 Agent(codex、claude、dsh)最近的聊天记录。with 填好友的备注 / 名字 / 鱼Sho号、群名或 Agent 名;看群时 group 填 true。要有“聊天记录”的只读权限。', { ...P({ with: { type: 'string' }, group: { type: 'boolean' }, limit: { type: 'number' } }), required: ['with'] }, (a, sid) => globalThis.__shoalAssist.readChat(a, sid), 10000)
|
|
288
|
+
tool('agents_list', '看连着的电脑上有哪些 Agent、各用什么模型、有没有在做事。', P({}), (a, sid) => globalThis.__shoalAssist.agents(sid), 10000)
|
|
289
|
+
tool('manage_friend', '管理好友:改备注(remark)、加 / 取消星标(star)、改标签(tags)。用户明确要求时才用。要“好友”的管理权限,会按审批设置先问用户。', { ...P({ who: { type: 'string' }, remark: { type: 'string' }, star: { type: 'boolean' }, tags: { type: 'array', items: { type: 'string' } } }), required: ['who'] }, (a, sid) => globalThis.__shoalAssist.manageFriend(a, sid))
|
|
290
|
+
tool('manage_group', '管理群:设 / 取消免打扰(mute),改群名(name,要是群主)。用户明确要求时才用。要“群”的管理权限,会按审批设置先问用户。', { ...P({ group: { type: 'string' }, mute: { type: 'boolean' }, name: { type: 'string' } }), required: ['group'] }, (a, sid) => globalThis.__shoalAssist.manageGroup(a, sid))
|
|
291
|
+
tool('set_setting', '改 App 的设置。能改的 key:language(zh/en)、compact(长对话压缩:save/balance/full)、quiet(勿扰:off 或 23:00-08:00)、presence(用户的在线状态:online/busy/invisible)。别的设置告诉用户去哪改。要“设置”的管理权限,会按审批设置先问用户。', { ...P({ key: { type: 'string' }, value: { type: 'string' } }), required: ['key', 'value'] }, (a, sid) => globalThis.__shoalAssist.setSetting(a, sid))
|
|
292
|
+
tool('set_agent_model', '给电脑上的某个 Agent(codex、claude)换以后派活用的模型(model)和思考等级(thought)。不知道能选什么先用 agents_list 或直接调用,它会列出来。要“电脑和 Agent”的管理权限,会按审批设置先问用户。', { ...P({ agent: { type: 'string' }, model: { type: 'string' }, thought: { type: 'string' } }), required: ['agent'] }, (a, sid) => globalThis.__shoalAssist.setAgentModel(a, sid))
|
|
293
|
+
|
|
294
|
+
// 读 App 现在的设置(只读,不含密钥):用户问“我现在用的什么模型 / 声音”“在哪改”时用
|
|
295
|
+
ctx.effect(() => ctx.tools.register({
|
|
296
|
+
name: 'app_settings',
|
|
297
|
+
description: '看鱼Sho App 现在的设置(只读,不含任何密钥):在用的模型和思考深度、声音、语言、长对话压缩、勿扰时段、主动找用户的设置、连着的电脑等,以及每一项在 App 里的哪儿改。用户问起 App 的设置、或者想改什么时先看这个,再告诉用户去哪改。你不能替用户改设置。',
|
|
298
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
299
|
+
output: TEXT,
|
|
300
|
+
timeoutMs: 10000,
|
|
301
|
+
async execute(_a, exec) {
|
|
302
|
+
const s = globalThis.__shoalSettings?.(exec?.agent?.session?.id ?? null); if (!s) return '读不到设置。'
|
|
303
|
+
return Object.entries(s).map(([k, v]) => '- ' + k + ':' + v).join('\n')
|
|
304
|
+
},
|
|
305
|
+
}))
|
|
306
|
+
|
|
307
|
+
ctx.effect(() => ctx.tools.register({
|
|
308
|
+
name: 'work_overview',
|
|
309
|
+
description: '看“工作秘书”(会话页)那边最近在忙什么:最近的工作对话(问和答的摘要)、交给电脑的活和状态、此刻是否在做事。只读。用户问起工作、或你想关心用户最近忙不忙时用。',
|
|
310
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
311
|
+
output: TEXT,
|
|
312
|
+
timeoutMs: 10000,
|
|
313
|
+
async execute() {
|
|
314
|
+
const w = globalThis.__shoalWork?.(); if (!w) return '看不到工作那边。'
|
|
315
|
+
const lines = []
|
|
316
|
+
if (w.working) lines.push('工作秘书此刻在做:' + w.working.text + '(' + w.working.since + ' 开始)')
|
|
317
|
+
lines.push('最近的工作对话:' + (w.recent.length ? '\n' + w.recent.map((x) => '- ' + x.at + ' ' + (x.q ? '用户:' + x.q + ' → ' : x.title ? '[' + x.title + '] ' : '') + x.a).join('\n') : '没有'))
|
|
318
|
+
lines.push('交给电脑的活:' + (w.tasks.length ? '\n' + w.tasks.map((t) => '- ' + t.at + ' ' + t.title + '(' + t.agent + ',' + t.status + ')').join('\n') : '没有'))
|
|
319
|
+
return lines.join('\n\n')
|
|
320
|
+
},
|
|
321
|
+
}))
|
|
322
|
+
|
|
323
|
+
ctx.effect(() => ctx.tools.register({
|
|
324
|
+
name: 'remember_about_user',
|
|
325
|
+
description: [
|
|
326
|
+
'想记住关于用户的事时用:他的喜好、习惯、常用的称呼和说法、重要的人和日子、工作上的固定安排。',
|
|
327
|
+
'不会马上记住:手机上会出现“助理想记住这几件事”,用户本人点“记住”才算数;记住的以后每一轮都会附给你。',
|
|
328
|
+
'只记对以后有用、用户自己说过的事;一次 1 到 5 条,每条一句话,写成“用户……”。不要记密码、身份证号、银行卡这类敏感信息。',
|
|
329
|
+
'调用后不用特意告诉用户,正常回话就行。',
|
|
330
|
+
].join(''),
|
|
331
|
+
parameters: { type: 'object', properties: { items: { type: 'array', minItems: 1, maxItems: 5, items: { type: 'string' } } }, required: ['items'], additionalProperties: false },
|
|
332
|
+
output: TEXT,
|
|
333
|
+
timeoutMs: 10000,
|
|
334
|
+
async execute(args) {
|
|
335
|
+
const M = globalThis.__shoalMemory
|
|
336
|
+
if (!M) return '记忆功能没有启动。'
|
|
337
|
+
const k = M.propose(args?.items ?? [], 'assistant')
|
|
338
|
+
return k ? '已经提给用户确认(' + k + ' 条),等他点“记住”。' : '这些已经记过或在等确认了。'
|
|
339
|
+
},
|
|
340
|
+
}))
|
|
341
|
+
|
|
342
|
+
ctx.effect(() => ctx.tools.register({
|
|
343
|
+
name: 'long_task_start',
|
|
344
|
+
description: [
|
|
345
|
+
'开一件长任务:要花几小时到几天、需要隔一阵做一次的事。例如“接下来一周每天早上收集 AI 新闻发我”“盯着这台显示器的价格,降到 1500 以下告诉我”“三天内帮我把去日本的行程一点点排好”。',
|
|
346
|
+
'开了以后 App 会每隔 every_hours 小时叫你做下一步,你每次做一点、写下进展;有新东西才通知用户,到 days 天后(或你说做完了)写总结交给用户。',
|
|
347
|
+
'和 schedule_create(定时)怎么选:有个期限、做完要给用户一个结果或总结的事(收集几天的新闻、盯到某个条件、慢慢把一件事做完),用 long_task_start,不要用 schedule_create;没有尽头、每次只是提醒一句的(每天 8 点提醒喝水),才用 schedule_create。',
|
|
348
|
+
'一次性能马上做完的事不要用这个,直接做。用户已经说清楚要做什么、多久做一次、做多久的,直接开;没说清的先问一句。',
|
|
349
|
+
].join(''),
|
|
350
|
+
parameters: { type: 'object', properties: {
|
|
351
|
+
goal: { type: 'string', description: '要做成什么,一两句话,写清楚交付什么' },
|
|
352
|
+
every_hours: { type: 'number', description: '多久做一次,小时(0.5–72,默认 6)' },
|
|
353
|
+
days: { type: 'number', description: '一共做多久,天(0.1–60,默认 3)' },
|
|
354
|
+
plan: { type: 'string', description: '打算怎么做,分几步(可不填)' },
|
|
355
|
+
}, required: ['goal'], additionalProperties: false },
|
|
356
|
+
output: TEXT,
|
|
357
|
+
timeoutMs: 10000,
|
|
358
|
+
async execute(args) {
|
|
359
|
+
const L = globalThis.__shoalLongTasks
|
|
360
|
+
if (!L) return '长任务功能没有启动。'
|
|
361
|
+
const t = L.start(args ?? {})
|
|
362
|
+
if (t.error) return '没开成:' + t.error
|
|
363
|
+
return '开好了长任务:' + t.goal + '。每 ' + t.every + ' 小时做一次,到 ' + new Date(t.until).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }) + ' 为止;第一步大约一分钟后开始。告诉用户在“任务”页能看到进度、能暂停或结束。'
|
|
364
|
+
},
|
|
365
|
+
}))
|
|
366
|
+
|
|
367
|
+
// 整理工作目录:只扫明显的垃圾(临时文件、空文件、空文件夹、编译缓存、重复文件);挪进回收站(7 天内能找回),不直接删
|
|
368
|
+
// 自定义皮肤:先读技能 make-skin,按用户说的风格(或用户发的参考图)配一套外观变量
|
|
369
|
+
ctx.effect(() => ctx.tools.register({
|
|
370
|
+
name: 'make_skin',
|
|
371
|
+
description: '给 App 做一套新的外观皮肤(用户说“做个樱花粉的皮肤”“照这张图的配色做个皮肤”时用)。先读技能 make-skin,按它的规则配色、检查对比度,再调用。vars 是 CSS 变量到值的对照,只能用技能里列的变量,值只能是颜色、渐变、长度、阴影;--page、--text、--brand、--bg-2 必须给。做好后告诉用户:到 设置 › 外观 里点它就能用,不喜欢可以删。',
|
|
372
|
+
parameters: { type: 'object', properties: {
|
|
373
|
+
name: { type: 'string', description: '皮肤名字,16 字以内,例如“樱花雨”' },
|
|
374
|
+
dark: { type: 'boolean', description: '是不是深色皮肤(深底浅字)' },
|
|
375
|
+
vars: { type: 'object', additionalProperties: { type: 'string' }, description: '例如 {"--page":"#FFF5F8","--text":"#3A1F2B","--brand":"#E0517F",…}' },
|
|
376
|
+
note: { type: 'string', description: '一句话说明风格,给用户看' },
|
|
377
|
+
}, required: ['name', 'vars'], additionalProperties: false },
|
|
378
|
+
output: TEXT,
|
|
379
|
+
timeoutMs: 10000,
|
|
380
|
+
async execute(args) {
|
|
381
|
+
const K = globalThis.__shoalSkins; if (!K) return '皮肤功能没有启动。'
|
|
382
|
+
try { const sk = K.save(args ?? {}); return '皮肤「' + sk.name + '」做好了(' + Object.keys(sk.vars).length + ' 个变量)。告诉用户:设置 › 外观 里点它就换上;不喜欢可以删。' } catch (e) { return '没存成:' + e.message + '。按技能 make-skin 改好再调用一次。' }
|
|
383
|
+
},
|
|
384
|
+
}))
|
|
385
|
+
|
|
386
|
+
ctx.effect(() => ctx.tools.register({
|
|
387
|
+
name: 'workspace_junk_scan',
|
|
388
|
+
description: '扫一遍 App 工作目录里的垃圾文件:临时文件、备份残留、空文件、空文件夹、编译缓存、一模一样的重复文件(留最新的那份)。只读,不删东西。用户让你清理、整理工作目录或者存储快满时用;扫完把清单(路径、原因、大小)列给用户看。',
|
|
389
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
390
|
+
output: TEXT,
|
|
391
|
+
timeoutMs: 60000,
|
|
392
|
+
async execute() {
|
|
393
|
+
const S = globalThis.__shoalStorage; if (!S) return '存储管理没有启动。'
|
|
394
|
+
const r = S.scanJunk(), kb = (n) => (n < 1024 ? n + ' B' : n < 1048576 ? (n / 1024).toFixed(1) + ' KB' : (n / 1048576).toFixed(1) + ' MB')
|
|
395
|
+
if (!r.items.length) return '工作目录里没扫到垃圾文件。'
|
|
396
|
+
return '扫到 ' + r.items.length + ' 项,共 ' + kb(r.bytes) + ':\n' + r.items.slice(0, 80).map((x) => '- ' + x.path + '(' + x.why + ',' + kb(x.bytes) + ')').join('\n') + (r.items.length > 80 ? '\n(只列了前 80 项)' : '') + '\n\n先把清单给用户看,用户同意了再用 workspace_junk_to_trash 挪进回收站。'
|
|
397
|
+
},
|
|
398
|
+
}))
|
|
399
|
+
ctx.effect(() => ctx.tools.register({
|
|
400
|
+
name: 'workspace_junk_to_trash',
|
|
401
|
+
description: '把 workspace_junk_scan 刚扫出来的垃圾挪进回收站(不是删除:7 天内用户能在 设置 › 存储 › 回收站 找回)。只能挪上一次扫描清单里的路径,别的文件一律拒绝。一定要用户看过清单、说了同意才调用。',
|
|
402
|
+
parameters: { type: 'object', properties: { paths: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 200 } }, required: ['paths'], additionalProperties: false },
|
|
403
|
+
output: TEXT,
|
|
404
|
+
timeoutMs: 30000,
|
|
405
|
+
async execute(args) {
|
|
406
|
+
const S = globalThis.__shoalStorage; if (!S) return '存储管理没有启动。'
|
|
407
|
+
const r = S.trashJunk(args?.paths ?? [])
|
|
408
|
+
return '挪进回收站 ' + r.moved.length + ' 项' + (r.refused.length ? ';' + r.refused.length + ' 项不在扫描清单里,没动:' + r.refused.slice(0, 10).join('、') : '') + '。告诉用户:7 天内可以在 设置 › 存储 › 回收站 里找回。'
|
|
409
|
+
},
|
|
410
|
+
}))
|
|
411
|
+
|
|
412
|
+
ctx.effect(() => ctx.tools.register({
|
|
413
|
+
name: 'computer_members',
|
|
414
|
+
description: '查看用户连上了哪些电脑、每台电脑上能派活的 Agent(例如 codex、claude、dsh)。派活前不确定有哪些 Agent 时先调用。只读。',
|
|
415
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
416
|
+
output: TEXT,
|
|
417
|
+
timeoutMs: 10000,
|
|
418
|
+
async execute() { return membersText() },
|
|
419
|
+
}))
|
|
420
|
+
|
|
421
|
+
ctx.effect(() => ctx.tools.register({
|
|
422
|
+
name: 'dispatch_to_computer',
|
|
423
|
+
description: [
|
|
424
|
+
'把活交给用户电脑上的 Agent 去做。调用后不会马上派:手机上会出现一张“计划卡”,列出拆成哪几件、各交给谁,用户本人点“开始执行”才真正派出去。',
|
|
425
|
+
'所以调用后告诉用户“计划列好了,看一下,没问题点开始执行”,不要说已经交出去、更不要编结果。用户说要改计划,就按他说的重新调用一次(旧的那张他会自己放弃)。',
|
|
426
|
+
'一件大事可以拆成几件(jobs 里 1 到 6 件,能同时做的才拆开;有先后依赖的写成一件),每件交给最合适的 Agent。做完的结果会自动送回这段对话。',
|
|
427
|
+
'适合手机上做不了的事:写代码、改项目里的文件、跑测试、在电脑上整理文件。手机上自己能做的(上网查、记待办、读写 App 里的笔记)不要派。',
|
|
428
|
+
'agent 从 computer_members 返回的名字里选;不确定就用 codex。instruction 写清楚要做什么、做完要交回什么。',
|
|
429
|
+
'用户给出的原话——要写进文件的内容、文件名、名字、数字、引号里的字——必须一字不改地照抄进 instruction,不要改写、润色或换说法。',
|
|
430
|
+
'你的工作目录、文件路径都在手机上,电脑上没有,绝不要写进 instruction。用户说“它的工作目录”“工作目录里”指的是电脑上那个 Agent 自己的工作目录:照样写“在你的工作目录里”,由电脑决定具体在哪。',
|
|
431
|
+
'电脑上的 Agent 要权限(比如改文件)时,会在用户手机上弹出“需要你”,由用户本人允许或拒绝,你不用、也不能替用户批。',
|
|
432
|
+
'要派给别人的东西会离开这部手机,只派用户要你做的事。',
|
|
433
|
+
].join(''),
|
|
434
|
+
parameters: {
|
|
435
|
+
type: 'object',
|
|
436
|
+
properties: {
|
|
437
|
+
title: { type: 'string', description: '整件事给用户看的标题,10 个字左右,例如“修好计算器并补测试”' },
|
|
438
|
+
jobs: {
|
|
439
|
+
type: 'array', minItems: 1, maxItems: 6,
|
|
440
|
+
items: {
|
|
441
|
+
type: 'object',
|
|
442
|
+
properties: {
|
|
443
|
+
agent: { type: 'string', description: 'Agent 名字,例如 codex、claude、dsh' },
|
|
444
|
+
title: { type: 'string', description: '这一件给用户看的一句话,10 个字左右' },
|
|
445
|
+
instruction: { type: 'string', description: '交给它的指令(中文即可),写清楚要做什么、交回什么' },
|
|
446
|
+
continue_task: { type: 'string', description: '只在“接着之前交给电脑的某件活改”时填:那件活的 task_id(computer_task_status 查得到)。填了,电脑上同一个 Agent 会在原来的会话里接着做,记得前面做过什么。新的活不要填。' },
|
|
447
|
+
},
|
|
448
|
+
required: ['agent', 'instruction'],
|
|
449
|
+
additionalProperties: false,
|
|
450
|
+
},
|
|
451
|
+
},
|
|
452
|
+
},
|
|
453
|
+
required: ['jobs'],
|
|
454
|
+
additionalProperties: false,
|
|
455
|
+
},
|
|
456
|
+
output: TEXT,
|
|
457
|
+
timeoutMs: 20000,
|
|
458
|
+
async execute(args) {
|
|
459
|
+
const n = net(), P = globalThis.__shoalPlans
|
|
460
|
+
if (!n || !P) return '派活功能没有启动。'
|
|
461
|
+
if (!n.members().length) return membersText()
|
|
462
|
+
try {
|
|
463
|
+
const p = P.propose({ title: args?.title, jobs: args?.jobs })
|
|
464
|
+
const js = p.jobs.length + ' 件:' + p.jobs.map((j) => j.title + '→' + j.agent).join(';')
|
|
465
|
+
if (p.auto) return '计划卡已经显示在用户手机上(' + js + ')。计划设成了直接开始,5 秒后自动派出(这 5 秒里可以撤销)。直接对用户说一句已经开始做了、做完会告诉他(用“你”称呼,别说“用户”,也别提设置)。'
|
|
466
|
+
return '计划卡已经显示在用户手机上(' + js + ')。还没有派出去,要等用户点“开始执行”。告诉用户看一下计划,没问题就点开始;想改就直接说。'
|
|
467
|
+
} catch (e) { return '计划没列成:' + (e?.message ?? e) }
|
|
468
|
+
},
|
|
469
|
+
}))
|
|
470
|
+
|
|
471
|
+
ctx.effect(() => ctx.tools.register({
|
|
472
|
+
name: 'computer_task_status',
|
|
473
|
+
description: '查交给电脑的活现在怎么样了:在做、等用户批、做完了、没做成,以及结果和交回的文件。用户问“做得怎么样了”时用。不填 task_id 就列出最近几件。只读。',
|
|
474
|
+
parameters: { type: 'object', properties: { task_id: { type: 'string' } }, additionalProperties: false },
|
|
475
|
+
output: TEXT,
|
|
476
|
+
timeoutMs: 10000,
|
|
477
|
+
async execute(args) {
|
|
478
|
+
const n = net()
|
|
479
|
+
if (!n) return '派活功能没有启动。'
|
|
480
|
+
const id = String(args?.task_id ?? '').trim()
|
|
481
|
+
const ts = id ? n.tasks().filter((t) => t.id === id) : n.tasks().slice(-5).reverse()
|
|
482
|
+
return ts.length ? ts.map((t) => n.report(t)).join('\n\n---\n\n') : (id ? `没有任务 ${id}。` : '还没有交给电脑的活。')
|
|
483
|
+
},
|
|
484
|
+
}))
|
|
485
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/* 老网页视图(安卓 10 自带的 Chrome 74 一类)缺的函数:在所有脚本之前补上。只补没有的,新手机上什么都不做。写成 ES5,老浏览器也能解析 */
|
|
2
|
+
(function () {
|
|
3
|
+
var def = function (o, k, v) { if (o && !(k in o)) Object.defineProperty(o, k, { value: v, writable: true, configurable: true }) }
|
|
4
|
+
if (!Promise.withResolvers) Promise.withResolvers = function () { var a, b; var p = new this(function (r, j) { a = r; b = j }); return { promise: p, resolve: a, reject: b } }
|
|
5
|
+
var at = function (i) { i = Math.trunc ? Math.trunc(i) || 0 : (i | 0); if (i < 0) i += this.length; return i < 0 || i >= this.length ? undefined : this[i] }
|
|
6
|
+
def(Array.prototype, 'at', at); def(String.prototype, 'at', function (i) { var s = String(this); i = Math.trunc(i) || 0; if (i < 0) i += s.length; return i < 0 || i >= s.length ? undefined : s.charAt(i) })
|
|
7
|
+
try { var TA = Object.getPrototypeOf(Int8Array.prototype); def(TA, 'at', at) } catch (e) {}
|
|
8
|
+
def(Array.prototype, 'findLast', function (f, t) { for (var i = this.length - 1; i >= 0; i--) if (f.call(t, this[i], i, this)) return this[i] })
|
|
9
|
+
def(Array.prototype, 'findLastIndex', function (f, t) { for (var i = this.length - 1; i >= 0; i--) if (f.call(t, this[i], i, this)) return i; return -1 })
|
|
10
|
+
def(Array.prototype, 'toSorted', function (c) { return this.slice().sort(c) })
|
|
11
|
+
def(Array.prototype, 'toReversed', function () { return this.slice().reverse() })
|
|
12
|
+
def(Array.prototype, 'toSpliced', function () { var a = this.slice(); a.splice.apply(a, arguments); return a })
|
|
13
|
+
def(Array.prototype, 'with', function (i, v) { var a = this.slice(); if (i < 0) i += a.length; a[i] = v; return a })
|
|
14
|
+
def(Object, 'hasOwn', function (o, k) { return Object.prototype.hasOwnProperty.call(o, k) })
|
|
15
|
+
def(Object, 'groupBy', function (xs, f) { var o = Object.create(null), i = 0; Array.from(xs).forEach(function (x) { var k = f(x, i++); (o[k] = o[k] || []).push(x) }); return o })
|
|
16
|
+
if (typeof Map !== 'undefined') def(Map, 'groupBy', function (xs, f) { var m = new Map(), i = 0; Array.from(xs).forEach(function (x) { var k = f(x, i++); if (!m.has(k)) m.set(k, []); m.get(k).push(x) }); return m })
|
|
17
|
+
def(String.prototype, 'replaceAll', function (a, b) { if (a instanceof RegExp) { if (!a.global) throw new TypeError('replaceAll needs a global RegExp'); return this.replace(a, b) } return this.split(String(a)).join(typeof b === 'function' ? b(a) : b) })
|
|
18
|
+
if (!Promise.allSettled) Promise.allSettled = function (ps) { return Promise.all(Array.from(ps).map(function (p) { return Promise.resolve(p).then(function (v) { return { status: 'fulfilled', value: v } }, function (r) { return { status: 'rejected', reason: r } }) })) }
|
|
19
|
+
if (typeof AggregateError === 'undefined') { window.AggregateError = function (errs, msg) { var e = new Error(msg || 'All promises were rejected'); e.name = 'AggregateError'; e.errors = errs; return e } }
|
|
20
|
+
if (!Promise.any) Promise.any = function (ps) { return new Promise(function (ok, no) { var arr = Array.from(ps), n = arr.length, errs = []; if (!n) return no(new AggregateError([])); arr.forEach(function (p, i) { Promise.resolve(p).then(ok, function (e) { errs[i] = e; if (--n === 0) no(new AggregateError(errs)) }) }) }) }
|
|
21
|
+
if (typeof structuredClone === 'undefined') window.structuredClone = function clone(v, seen) {
|
|
22
|
+
seen = seen || new Map(); if (v === null || typeof v !== 'object') return v; if (seen.has(v)) return seen.get(v)
|
|
23
|
+
var out; if (v instanceof Date) return new Date(v.getTime()); if (v instanceof RegExp) return new RegExp(v.source, v.flags)
|
|
24
|
+
if (ArrayBuffer.isView(v)) return v.slice ? v.slice() : new v.constructor(v); if (v instanceof ArrayBuffer) return v.slice(0)
|
|
25
|
+
if (v instanceof Map) { out = new Map(); seen.set(v, out); v.forEach(function (x, k) { out.set(clone(k, seen), clone(x, seen)) }); return out }
|
|
26
|
+
if (v instanceof Set) { out = new Set(); seen.set(v, out); v.forEach(function (x) { out.add(clone(x, seen)) }); return out }
|
|
27
|
+
out = Array.isArray(v) ? [] : {}; seen.set(v, out); Object.keys(v).forEach(function (k) { out[k] = clone(v[k], seen) }); return out
|
|
28
|
+
}
|
|
29
|
+
if (window.crypto && !crypto.randomUUID && crypto.getRandomValues) crypto.randomUUID = function () { var b = crypto.getRandomValues(new Uint8Array(16)); b[6] = (b[6] & 15) | 64; b[8] = (b[8] & 63) | 128; var h = Array.prototype.map.call(b, function (x) { return (x + 256).toString(16).slice(1) }).join(''); return h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20) }
|
|
30
|
+
if (typeof AbortSignal !== 'undefined') {
|
|
31
|
+
if (!AbortSignal.timeout) AbortSignal.timeout = function (ms) { var c = new AbortController(); setTimeout(function () { try { c.abort(new DOMException('signal timed out', 'TimeoutError')) } catch (e) { c.abort() } }, ms); return c.signal }
|
|
32
|
+
if (!AbortSignal.any) AbortSignal.any = function (ss) { var c = new AbortController(); for (var i = 0; i < ss.length; i++) { var s = ss[i]; if (s.aborted) { c.abort(s.reason); return c.signal } s.addEventListener('abort', function (e) { c.abort(e.target.reason) }, { once: true }) } return c.signal }
|
|
33
|
+
def(AbortSignal.prototype, 'throwIfAborted', function () { if (this.aborted) throw this.reason || new DOMException('aborted', 'AbortError') })
|
|
34
|
+
}
|
|
35
|
+
if (typeof Element !== 'undefined') def(Element.prototype, 'replaceChildren', function () { while (this.firstChild) this.removeChild(this.firstChild); for (var i = 0; i < arguments.length; i++) this.append(arguments[i]) })
|
|
36
|
+
if (typeof queueMicrotask === 'undefined') window.queueMicrotask = function (f) { Promise.resolve().then(f) }
|
|
37
|
+
// Chrome 84 起才有:弱引用(这里换成普通引用,只是少回收一点内存)、回收通知(什么都不做)
|
|
38
|
+
if (typeof WeakRef === 'undefined') { window.WeakRef = function (t) { this._t = t }; window.WeakRef.prototype.deref = function () { return this._t } }
|
|
39
|
+
if (typeof FinalizationRegistry === 'undefined') { window.FinalizationRegistry = function () {}; window.FinalizationRegistry.prototype.register = function () {}; window.FinalizationRegistry.prototype.unregister = function () { return false } }
|
|
40
|
+
def(Object, 'fromEntries', function (it) { var o = {}; Array.from(it).forEach(function (kv) { o[kv[0]] = kv[1] }); return o })
|
|
41
|
+
def(String.prototype, 'trimStart', String.prototype.trimLeft); def(String.prototype, 'trimEnd', String.prototype.trimRight)
|
|
42
|
+
if (typeof globalThis === 'undefined') window.globalThis = window
|
|
43
|
+
if (typeof ResizeObserver === 'undefined') { window.ResizeObserver = function (cb) { this._cb = cb }; window.ResizeObserver.prototype.observe = function () {}; window.ResizeObserver.prototype.unobserve = function () {}; window.ResizeObserver.prototype.disconnect = function () {} }
|
|
44
|
+
// Chrome 84 起 flex 布局才认 gap(我们的界面到处用它排间距):老网页视图上给 flex 容器的子元素补上同样大小的外边距
|
|
45
|
+
if (typeof document !== 'undefined' && typeof MutationObserver !== 'undefined') {
|
|
46
|
+
var probe = function () { var d = document.createElement('div'); d.style.cssText = 'display:flex;flex-direction:column;row-gap:1px;position:absolute;visibility:hidden'; d.appendChild(document.createElement('div')); d.appendChild(document.createElement('div')); document.body.appendChild(d); var ok = d.scrollHeight === 1; d.remove(); return ok }
|
|
47
|
+
var start = function () {
|
|
48
|
+
if (probe()) return
|
|
49
|
+
document.documentElement.classList.add('no-flexgap')
|
|
50
|
+
var px = function (v) { var n = parseFloat(v); return isNaN(n) ? 0 : n }
|
|
51
|
+
var fix = function (el) {
|
|
52
|
+
var cs = getComputedStyle(el); if (cs.display !== 'flex' && cs.display !== 'inline-flex') return
|
|
53
|
+
var rg = px(cs.rowGap), cg = px(cs.columnGap); if (!rg && !cg) return
|
|
54
|
+
var col = cs.flexDirection.indexOf('column') === 0, wrap = cs.flexWrap !== 'nowrap', first = true
|
|
55
|
+
for (var c = el.firstElementChild; c; c = c.nextElementSibling) {
|
|
56
|
+
if (getComputedStyle(c).position === 'absolute' || c.hidden) continue
|
|
57
|
+
if (wrap) { c.style.marginRight = cg + 'px'; c.style.marginBottom = rg + 'px' }
|
|
58
|
+
else if (!first) { if (col) c.style.marginTop = rg + 'px'; else c.style.marginLeft = cg + 'px' }
|
|
59
|
+
first = false
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
var queued = false, pending = []
|
|
63
|
+
var flush = function () { queued = false; var list = pending; pending = []; list.forEach(function (n) { if (n.nodeType !== 1 || !n.isConnected) return; fix(n); var all = n.querySelectorAll('*'); for (var i = 0; i < all.length; i++) fix(all[i]) }) }
|
|
64
|
+
var add = function (n) { pending.push(n); if (!queued) { queued = true; requestAnimationFrame(flush) } }
|
|
65
|
+
new MutationObserver(function (ms) { ms.forEach(function (m) { if (m.type === 'childList') { add(m.target); m.addedNodes.forEach(function (n) { if (n.nodeType === 1) add(n) }) } else if (m.type === 'attributes') add(m.target) }) }).observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['class'] })
|
|
66
|
+
add(document.body)
|
|
67
|
+
}
|
|
68
|
+
if (document.body) start(); else document.addEventListener('DOMContentLoaded', start)
|
|
69
|
+
}
|
|
70
|
+
// Chrome 87 起才有:按“字”切文字。老手机上按码点切(emoji 组合会被拆开,但不影响用)
|
|
71
|
+
if (typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'undefined') {
|
|
72
|
+
Intl.Segmenter = function (loc, opt) { this.g = (opt && opt.granularity) || 'grapheme' }
|
|
73
|
+
Intl.Segmenter.prototype.segment = function (s) {
|
|
74
|
+
s = String(s); var parts = [], i = 0
|
|
75
|
+
if (this.g === 'grapheme') Array.from(s).forEach(function (c) { parts.push({ segment: c, index: i, input: s }); i += c.length })
|
|
76
|
+
else s.split(/(\s+|[ -〿-]|[^\s -〿-]+)/).forEach(function (c) { if (c) { parts.push({ segment: c, index: i, input: s, isWordLike: /\S/.test(c) }); i += c.length } })
|
|
77
|
+
parts[Symbol.iterator] = Array.prototype[Symbol.iterator]
|
|
78
|
+
parts.containing = function (k) { for (var j = 0; j < parts.length; j++) if (k >= parts[j].index && k < parts[j].index + parts[j].segment.length) return parts[j] }
|
|
79
|
+
return parts
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
})();
|