dsh-mobile-plugin 0.5.33 → 0.5.35

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 (142) hide show
  1. package/README.md +17 -2
  2. package/dsh-mobile-credentials/lib/credentials.js +49 -2
  3. package/extensions/README.md +25 -21
  4. package/host.js +16 -1
  5. package/lib/git/pr.js +375 -0
  6. package/lib/git/read.js +1 -0
  7. package/lib/host-capabilities.cjs +67 -0
  8. package/lib/http/routing.js +25 -0
  9. package/lib/impl.js +34 -26
  10. package/lib/mirror/history-blob.cjs +184 -0
  11. package/lib/mirror/pusher.cjs +276 -1
  12. package/lib/mobile/approval-facts.js +439 -0
  13. package/lib/mobile/approval-memory.js +199 -0
  14. package/lib/mobile/approvals.js +596 -30
  15. package/lib/mobile/auto-review-log.js +160 -0
  16. package/lib/mobile/auto-review.js +172 -0
  17. package/lib/mobile/credential-upgrade.js +14 -0
  18. package/lib/mobile/device-permissions.js +86 -0
  19. package/lib/mobile/directory-browse.js +23 -8
  20. package/lib/mobile/events.js +9 -1
  21. package/lib/mobile/extension-catalog.js +106 -44
  22. package/lib/mobile/extension-data.js +6 -0
  23. package/lib/mobile/file-ops.js +89 -76
  24. package/lib/mobile/git.js +108 -2
  25. package/lib/mobile/live-steps.js +107 -4
  26. package/lib/mobile/mail.js +621 -0
  27. package/lib/mobile/monitor.js +6 -0
  28. package/lib/mobile/notification-prefs.js +205 -0
  29. package/lib/mobile/pairing.js +15 -2
  30. package/lib/mobile/permissions.js +433 -0
  31. package/lib/mobile/project-write-queue.js +115 -0
  32. package/lib/mobile/project-writes.js +61 -0
  33. package/lib/mobile/push-notify.js +293 -13
  34. package/lib/mobile/questions.js +20 -3
  35. package/lib/mobile/recent-failures.js +48 -0
  36. package/lib/mobile/relay-control.js +5 -0
  37. package/lib/mobile/session-cache.js +50 -0
  38. package/lib/mobile/session-last-turn.js +24 -22
  39. package/lib/mobile/session-new.js +205 -0
  40. package/lib/mobile/session-send.js +0 -1
  41. package/lib/mobile/sessions.js +12 -84
  42. package/lib/mobile/skill-write.js +549 -0
  43. package/lib/mobile/stats-collect.cjs +33 -3
  44. package/lib/mobile/stats-ledger.cjs +39 -2
  45. package/lib/mobile/stream.js +24 -3
  46. package/lib/mobile/supervisor-broadcast.js +58 -11
  47. package/lib/mobile/supervisor-tools.js +1 -1
  48. package/lib/mobile/third-party-extensions.js +158 -0
  49. package/lib/mobile/uploads.js +30 -14
  50. package/lib/mobile/worktree-isolation.js +479 -0
  51. package/lib/mobile/worktree-lifecycle.js +79 -0
  52. package/lib/p2p/wiring.cjs +41 -16
  53. package/lib/panel/index.html +15 -15
  54. package/lib/read-receipt.cjs +89 -5
  55. package/lib/relay/core.js +25 -1
  56. package/lib/relay/lan-proxy.js +6 -1
  57. package/lib/relay/preview.js +21 -1
  58. package/lib/relay/protocol.js +1 -0
  59. package/lib/relay/status.js +6 -0
  60. package/lib/relay/tunnel-forwarder.cjs +178 -0
  61. package/lib/routes/control-plane.js +35 -1
  62. package/lib/routes/mobile-api.js +105 -52
  63. package/lib/shared/via-header.js +15 -2
  64. package/lib/sidecar-facade-worker.cjs +15 -2
  65. package/lib/sidecar-facade.cjs +5 -0
  66. package/lib/tailcat/host-process.cjs +1 -1
  67. package/lib/tailcat/ingress.cjs +2 -2
  68. package/lib/tailcat/wiring.cjs +34 -13
  69. package/package.json +11 -3
  70. package/assets/pets/README.md +0 -9
  71. package/assets/pets/deepy-whale/attention.gif +0 -0
  72. package/assets/pets/deepy-whale/done.gif +0 -0
  73. package/assets/pets/deepy-whale/error.gif +0 -0
  74. package/assets/pets/deepy-whale/idle.gif +0 -0
  75. package/assets/pets/deepy-whale/pack.json +0 -54
  76. package/assets/pets/deepy-whale/sleeping.gif +0 -0
  77. package/assets/pets/deepy-whale/working-3.gif +0 -0
  78. package/assets/pets/deepy-whale/working.gif +0 -0
  79. package/knowledge/apps/alipay.md +0 -30
  80. package/knowledge/apps/android-settings.md +0 -30
  81. package/knowledge/apps/baijiahao.md +0 -30
  82. package/knowledge/apps/bilibili.md +0 -31
  83. package/knowledge/apps/boss-zhipin.md +0 -32
  84. package/knowledge/apps/dedao.md +0 -33
  85. package/knowledge/apps/douyin.md +0 -32
  86. package/knowledge/apps/feishu.md +0 -35
  87. package/knowledge/apps/gmail.md +0 -33
  88. package/knowledge/apps/jike.md +0 -31
  89. package/knowledge/apps/kuaishou.md +0 -34
  90. package/knowledge/apps/linkedin.md +0 -33
  91. package/knowledge/apps/qqmail.md +0 -30
  92. package/knowledge/apps/taobao.md +0 -33
  93. package/knowledge/apps/telegram.md +0 -27
  94. package/knowledge/apps/toutiao.md +0 -32
  95. package/knowledge/apps/uber-eats.md +0 -26
  96. package/knowledge/apps/uber.md +0 -27
  97. package/knowledge/apps/wechat.md +0 -33
  98. package/knowledge/apps/weibo.md +0 -31
  99. package/knowledge/apps/whatsapp.md +0 -27
  100. package/knowledge/apps/x.md +0 -32
  101. package/knowledge/apps/xiaohongshu.md +0 -30
  102. package/knowledge/apps/zhihu.md +0 -31
  103. package/knowledge/sites/bilibili.com/SITE.md +0 -50
  104. package/knowledge/sites/bilibili.com/references/view-fields.md +0 -17
  105. package/knowledge/sites/github.com/SITE.md +0 -51
  106. package/knowledge/sites/github.com/references/repo-fields.md +0 -13
  107. package/knowledge/sites/x.com/SITE.md +0 -47
  108. package/knowledge/sites/xiaohongshu.com/SITE.md +0 -48
  109. package/knowledge/sites/xiaohongshu.com/references/note-fields.md +0 -18
  110. package/knowledge/sites/youtube.com/SITE.md +0 -49
  111. package/knowledge/sites/youtube.com/references/innertube-fields.md +0 -14
  112. package/knowledge/sites/zhihu.com/SITE.md +0 -47
  113. package/knowledge/sites/zhihu.com/references/api-fields.md +0 -21
  114. package/lib/mobile/pet-tools.js +0 -261
  115. package/lib/mobile/pets.js +0 -755
  116. package/lib/mobile/phone/access.js +0 -85
  117. package/lib/mobile/phone/binding.js +0 -247
  118. package/lib/mobile/phone/confirm.js +0 -189
  119. package/lib/mobile/phone/evidence.js +0 -228
  120. package/lib/mobile/phone/gate.js +0 -290
  121. package/lib/mobile/phone/grounding.js +0 -314
  122. package/lib/mobile/phone/guard.js +0 -465
  123. package/lib/mobile/phone/index.js +0 -83
  124. package/lib/mobile/phone/irreversible.js +0 -226
  125. package/lib/mobile/phone/knowledge-tools.js +0 -665
  126. package/lib/mobile/phone/learn.js +0 -329
  127. package/lib/mobile/phone/pacing.js +0 -173
  128. package/lib/mobile/phone/redact.js +0 -237
  129. package/lib/mobile/phone/risk.js +0 -95
  130. package/lib/mobile/phone/route-hint.js +0 -164
  131. package/lib/mobile/phone/routes-memory.js +0 -133
  132. package/lib/mobile/phone/routes.js +0 -279
  133. package/lib/mobile/phone/service.js +0 -500
  134. package/lib/mobile/phone/site-commands.js +0 -271
  135. package/lib/mobile/phone/step-summary.js +0 -201
  136. package/lib/mobile/phone/stop-summary.js +0 -235
  137. package/lib/mobile/phone/tool-groups.js +0 -125
  138. package/lib/mobile/phone/tools.js +0 -2282
  139. package/lib/mobile/phone/untrusted.js +0 -65
  140. package/lib/mobile/phone-knowledge.js +0 -317
  141. package/lib/mobile/wechat-tools.js +0 -257
  142. package/lib/mobile/wechat.js +0 -514
@@ -1,271 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 站点知识里的只读脚本:声明格式、清单与调用参数校验。
5
- *
6
- * 一条命令就是站点目录下的 `scripts/<name>.js`,文件以一段块注释开头(MARK 见下),后面是
7
- * async 函数体,参数从 `args` 取。name 必须与文件名一致。头部一行一项:
8
- *
9
- * - `name: list_jobs`
10
- * - `description: 列出当前搜索结果里的职位`
11
- * - `arg: limit integer - 最多几条`
12
- * - `arg: query string required - 只保留标题含这段字的`
13
- * - `returns: [{title, company, salary, url}]`
14
- * - `readOnly: true`(可选;站点命令只能是 true)
15
- *
16
- * 真正的页面内执行由原生侧做(真实页面、读取世界、同源只读),这个模块**不碰网络、不执行
17
- * 任何代码**,只做两件事:把站点目录里的命令声明列出来,以及在调用前按声明校验参数。
18
- *
19
- * ## 执行契约(原生侧遵守,这里只定义,不在 JS 里强制执行)
20
- *
21
- * - 只读:脚本只能读 DOM 与页面已加载的数据,不得点击、输入、导航或改动页面状态。
22
- * - 同源:只允许当前页面同源的 GET,禁止跨域请求。
23
- * - 禁网:除同源只读外不得主动发起网络请求,不发 POST、不调站点的写接口。
24
- * - 密码打码:返回值若来自密码 / 验证码等敏感输入,一律以 `***` 代替。
25
- */
26
-
27
- const fs = require('node:fs');
28
- const path = require('node:path');
29
-
30
- /** 命令头的起始标记。与 Mika 的 `/* mika-command` 同构,换成我们自己的名字。 */
31
- const COMMAND_MARK = '/* dsh-command';
32
- /** 命令名的字符集:小写字母开头,字母数字下划线,至多 40 个。 */
33
- const NAME_RE = /^[a-z][a-z0-9_]{0,39}$/;
34
- /** 参数类型白名单。 */
35
- const TYPES = ['string', 'integer', 'number', 'boolean'];
36
- /** 说明文字上限。 */
37
- const DESCRIPTION_LIMIT = 120;
38
- /** 脚本正文上限(字符)。太长说明该拆,不放进一块。 */
39
- const BODY_LIMIT = 12_000;
40
-
41
- /**
42
- * 站点知识里 `commands` 的字段规格(给写知识的人看,也给校验用)。
43
- * 每条命令恒定只读。
44
- */
45
- const COMMAND_SCHEMA = {
46
- name: '小写字母开头,字母 / 数字 / 下划线,至多 40,必须与文件名 scripts/<name>.js 一致',
47
- description: `一句话说清这条命令取什么,至多 ${DESCRIPTION_LIMIT} 字`,
48
- readOnly: '恒为 true:站点命令只能读,不得写页面或改状态',
49
- returns: '返回的字段说明,例如 [{title, url}]',
50
- args: '[{ name, type: string|integer|number|boolean, required?, description? }]',
51
- };
52
-
53
- /** 执行契约的文字版(给知识注入与原生实现对齐用)。 */
54
- const EXECUTION_CONTRACT = {
55
- readOnly: true,
56
- sameOrigin: true,
57
- network: false,
58
- redactPasswords: true,
59
- summary:
60
- '只读、同源、禁网、密码打码:脚本只读当前页面同源数据,不点击不输入不改页面,'
61
- + '不主动发网络请求(含写接口),敏感输入一律打码后返回。',
62
- };
63
-
64
- const ARG_RE = /^([a-z][A-Za-z0-9_]{0,39})\s+(string|integer|number|boolean)(\s+required)?(?:\s+-\s+(.+))?$/;
65
-
66
- /** 去掉 BOM、统一换行、去掉开头空白,便于认头部。 */
67
- function clean(text) {
68
- return String(text || '').replace(/^\uFEFF/, '').replace(/\r\n/g, '\n').replace(/^\s+/, '');
69
- }
70
-
71
- /** 这段文本是不是一条站点命令(以命令头开头)。 */
72
- function isCommand(text) {
73
- return clean(text).startsWith(COMMAND_MARK);
74
- }
75
-
76
- /**
77
- * 解析一条站点命令文件。
78
- *
79
- * 返回 `{ decl, body, errors }`:`decl` 只在 `errors` 为空时给出,形状为
80
- * `{ name, description, readOnly: true, returns, args, file }`;`body` 是头部之后的脚本正文。
81
- *
82
- * @param {string} file 站点目录下的相对路径,如 `scripts/list_jobs.js`
83
- * @param {string} text 文件全文
84
- */
85
- function parseCommand(file, text) {
86
- const t = clean(text);
87
- if (!t.startsWith(COMMAND_MARK)) {
88
- return { decl: null, body: '', errors: [`文件要以 \`${COMMAND_MARK}\` 开头`] };
89
- }
90
- const end = t.indexOf('*/');
91
- if (end < 0) return { decl: null, body: '', errors: ['命令头没有用 `*/` 结束'] };
92
-
93
- const body = t.slice(end + 2).trim();
94
- const errors = [];
95
- let name = null;
96
- let description = null;
97
- let returns = null;
98
- let readOnly = null;
99
- const args = [];
100
-
101
- for (const raw of t.slice(COMMAND_MARK.length, end).split('\n')) {
102
- // 头部每行可能带一个多余的 `*` 前缀,去掉它再按 key: value 解析。
103
- const line = raw.trim().replace(/^\*\s?/, '');
104
- if (!line) continue;
105
- const idx = line.indexOf(':');
106
- if (idx <= 0) {
107
- errors.push(`头部这一行看不懂:${line}`);
108
- continue;
109
- }
110
- const key = line.slice(0, idx).trim();
111
- const value = line.slice(idx + 1).trim();
112
- switch (key) {
113
- case 'name':
114
- name = value;
115
- break;
116
- case 'description':
117
- description = value;
118
- break;
119
- case 'returns':
120
- returns = value;
121
- break;
122
- case 'readOnly':
123
- case 'readonly':
124
- readOnly = value.toLowerCase() === 'true';
125
- break;
126
- case 'arg':
127
- {
128
- const m = ARG_RE.exec(value);
129
- if (m) {
130
- args.push({
131
- name: m[1],
132
- type: m[2],
133
- required: Boolean(m[3]),
134
- description: (m[4] || '').trim(),
135
- });
136
- } else {
137
- errors.push(`arg 要写作「名字 类型 [required] [- 说明]」,类型是 ${TYPES.join('/')}:${value}`);
138
- }
139
- }
140
- break;
141
- default:
142
- errors.push(`头部有不认得的键 ${key}`);
143
- }
144
- }
145
-
146
- const base = path.basename(file).replace(/\.js$/i, '');
147
- if (name == null) errors.push('缺少 name');
148
- else if (!NAME_RE.test(name)) errors.push('name 只能用小写字母、数字与下划线,以字母开头,至多 40 个字符');
149
- else if (name !== base) errors.push(`name(${name})必须与文件名(${base}.js)一致`);
150
- if (description == null || description === '') errors.push('缺少 description');
151
- else if ([...description].length > DESCRIPTION_LIMIT) errors.push(`description 超过 ${DESCRIPTION_LIMIT} 字`);
152
- if (returns == null || returns === '') errors.push('缺少 returns');
153
- if (readOnly === false) errors.push('站点命令只能只读,readOnly 不能是 false');
154
- const dupNames = args.map((a) => a.name).filter((n, i, arr) => arr.indexOf(n) !== i);
155
- for (const dup of new Set(dupNames)) errors.push(`arg ${dup} 重复`);
156
- if (body === '') errors.push('脚本正文为空');
157
- if (body.length > BODY_LIMIT) errors.push(`脚本正文 ${body.length} 字,超过 ${BODY_LIMIT}`);
158
-
159
- const decl = errors.length === 0
160
- ? { name, description, readOnly: true, returns, args, file }
161
- : null;
162
- return { decl, body, errors };
163
- }
164
-
165
- /** 值是否符合声明的类型。 */
166
- function fitsType(value, type) {
167
- switch (type) {
168
- case 'string':
169
- return typeof value === 'string';
170
- case 'boolean':
171
- return typeof value === 'boolean';
172
- case 'integer':
173
- return typeof value === 'number' && Number.isInteger(value);
174
- case 'number':
175
- return typeof value === 'number' && Number.isFinite(value);
176
- default:
177
- return false;
178
- }
179
- }
180
-
181
- /**
182
- * 按声明校验一次调用的参数。没问题返回 null,有问题返回一句中文说明。
183
- *
184
- * @param {object} decl parseCommand 给出的命令声明
185
- * @param {object} args 模型 / 调用方给的参数(名字 → 值)
186
- */
187
- function validateCommand(decl, args) {
188
- if (!decl || typeof decl !== 'object') return '命令声明无效';
189
- const given = args && typeof args === 'object' && !Array.isArray(args) ? args : {};
190
- const declared = new Map((decl.args || []).map((a) => [a.name, a]));
191
- for (const key of Object.keys(given)) {
192
- if (!declared.has(key)) {
193
- const takes = (decl.args || []).map((a) => a.name).join('、') || '无参数';
194
- return `'${key}' 不是 ${decl.name} 的参数;它接受 ${takes}`;
195
- }
196
- }
197
- for (const arg of decl.args || []) {
198
- const value = given[arg.name];
199
- const missing = value === undefined || value === null;
200
- if (missing) {
201
- if (arg.required) return `${decl.name} 需要参数 '${arg.name}'(${arg.type})`;
202
- continue;
203
- }
204
- if (!fitsType(value, arg.type)) return `参数 '${arg.name}' 必须是 ${arg.type}`;
205
- }
206
- return null;
207
- }
208
-
209
- /**
210
- * 读一个站点目录下的 `scripts/*.js`,把带命令头的解析成声明清单。
211
- *
212
- * 返回 `{ commands, errors }`:`commands` 是合法声明(按名字排序),`errors` 收下坏掉的命令
213
- * 及其具体问题。目录不存在或某文件读坏了都只跳过,不抛。
214
- *
215
- * @param {string} siteDir 站点知识目录,如 `knowledge/sites/github.com`
216
- */
217
- function listCommands(siteDir) {
218
- const dir = path.join(String(siteDir || ''), 'scripts');
219
- let entries;
220
- try {
221
- entries = fs.readdirSync(dir, { withFileTypes: true });
222
- } catch {
223
- return { commands: [], errors: [] };
224
- }
225
- const commands = [];
226
- const errors = [];
227
- for (const entry of entries) {
228
- if (!entry.isFile() || !entry.name.endsWith('.js')) continue;
229
- let text;
230
- try {
231
- text = fs.readFileSync(path.join(dir, entry.name), 'utf8');
232
- } catch {
233
- continue;
234
- }
235
- if (!isCommand(text)) continue;
236
- const rel = `scripts/${entry.name}`;
237
- const parsed = parseCommand(rel, text);
238
- if (parsed.decl) commands.push(parsed.decl);
239
- else errors.push({ file: rel, errors: parsed.errors });
240
- }
241
- commands.sort((a, b) => a.name.localeCompare(b.name));
242
- return { commands, errors };
243
- }
244
-
245
- /** 把一条命令声明写成知识块里的一行(供站点正文注入)。 */
246
- function formatCommandLine(decl) {
247
- const sig = (decl.args || [])
248
- .map((a) => `${a.name}${a.required ? '' : '?'}: ${a.type}`)
249
- .join(', ');
250
- const notes = (decl.args || [])
251
- .filter((a) => a.description)
252
- .map((a) => `${a.name} ${a.description}`)
253
- .join('; ');
254
- return `- ${decl.name}(${sig}): ${decl.description}。返回 ${decl.returns}`
255
- + (notes ? `。参数:${notes}` : '');
256
- }
257
-
258
- module.exports = {
259
- COMMAND_MARK,
260
- NAME_RE,
261
- TYPES,
262
- DESCRIPTION_LIMIT,
263
- BODY_LIMIT,
264
- COMMAND_SCHEMA,
265
- EXECUTION_CONTRACT,
266
- isCommand,
267
- parseCommand,
268
- validateCommand,
269
- listCommands,
270
- formatCommandLine,
271
- };
@@ -1,201 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * 压缩时的**结构化步骤摘要**:目标 / 已确认事实(按种类去重)/ 进展行 / 更早结局计数 / 最后打算。
5
- *
6
- * 全从原话、工具结果与模型说过的话里**确定性**地取,**不调模型**。理由和 Mika 一样直白:
7
- * 压缩每次都要重算摘要,调一次模型既多一次往返,同样的历史还可能得出不同的摘要——请求前缀
8
- * 就不稳,缓存命中率跟着掉。摘要稳 = 前缀稳 = 省钱。
9
- *
10
- * 各段都有上限(事实每类 `MAX_FACT_VALUES` 个、进展 `MAX_PROGRESS` 行、更早结局 `MAX_EARLIER_KINDS`
11
- * 种、单项截到 `CLIP` 字),步数再多摘要也不会无限变长。
12
- *
13
- * 输入沿用直播 / 历史清单的形状(`{ key, step }` 或裸 step 数组,step 里带
14
- * `kind` / `name` / `summary` / `state`,可选 `args` / 结构化事实字段)。`render()` 产出的
15
- * 是给模型读的确定性文本,可直接当压缩时折叠段的头。
16
- */
17
-
18
- const MAX_FACT_VALUES = 4;
19
- const MAX_PROGRESS = 15;
20
- const MAX_EARLIER_KINDS = 5;
21
- const CLIP = 100;
22
- const OTHER = '其他';
23
-
24
- /** 结果里能当事实记下的短字段 → 事实种类(对齐 Mika StepSummary 的 FACT_KEYS)。 */
25
- const FACT_KEYS = [
26
- ['currentApp', '去过的应用'],
27
- ['app', '去过的应用'],
28
- ['packageName', '去过的应用'],
29
- ['url', '打开的页面'],
30
- ['path', '读写的文件'],
31
- ['file_path', '读写的文件'],
32
- ];
33
-
34
- function clip(text, max = CLIP) {
35
- const one = String(text == null ? '' : text).replace(/\s+/g, ' ').trim();
36
- if (one.length <= max) return one;
37
- return `${one.slice(0, max - 1)}…`;
38
- }
39
-
40
- function normalizeEntry(entry) {
41
- if (!entry || typeof entry !== 'object') return {};
42
- return entry.step && typeof entry.step === 'object'
43
- ? { key: entry.key, ...entry.step }
44
- : entry;
45
- }
46
-
47
- function toStepList(run) {
48
- const list = Array.isArray(run)
49
- ? run
50
- : (run && typeof run === 'object' && Array.isArray(run.steps) ? run.steps : null);
51
- return list ? list.map(normalizeEntry) : [];
52
- }
53
-
54
- function labelOf(step) {
55
- if (!step || typeof step !== 'object') return '';
56
- if (typeof step.summary === 'string' && step.summary.trim() !== '') return clip(step.summary);
57
- const args = step.args && typeof step.args === 'object' ? step.args : {};
58
- for (const key of ['target', 'text', 'description', 'query', 'command', 'file_path', 'path', 'ref', 'packageName', 'url']) {
59
- if (typeof args[key] === 'string' && args[key].trim() !== '') return clip(args[key]);
60
- }
61
- return clip(step.name || step.kind || '');
62
- }
63
-
64
- /** 状态 → 进展行末尾的结局词。 */
65
- function outcomeOf(step) {
66
- const state = step && typeof step.state === 'string' ? step.state : '';
67
- if (state === 'ok') return '成功';
68
- if (state === 'error') return '失败';
69
- if (state === 'stopped') return '中断';
70
- if (state === 'running') return '未完成';
71
- return '完成';
72
- }
73
-
74
- /** 工具名 → 从它这一步能确认的事实(路径 / 网址 / 应用)。 */
75
- function factsFromStep(step, out) {
76
- if (!step || typeof step !== 'object') return;
77
- // 优先用步骤/结果里已经结构化好的字段。
78
- for (const [key, kind] of FACT_KEYS) {
79
- const value = step[key] != null ? step[key]
80
- : (step.result && typeof step.result === 'object' ? step.result[key] : undefined);
81
- if (typeof value === 'string' && value.trim() !== '') {
82
- pushFact(out, kind, value.trim());
83
- }
84
- }
85
- // 退一步:从工具摘要里认(读写/编辑给的是路径,web_fetch 给的是网址)。
86
- const args = step.args && typeof step.args === 'object' ? step.args : {};
87
- if (step.name === 'web_fetch' && typeof args.url === 'string') pushFact(out, '打开的页面', args.url.trim());
88
- if (['read', 'read_image', 'write', 'edit', 'str_replace_editor'].includes(step.name)) {
89
- const path = args.file_path || args.path;
90
- if (typeof path === 'string' && path.trim() !== '') pushFact(out, '读写的文件', path.trim());
91
- }
92
- if (step.name === 'phone_open_app' && typeof args.packageName === 'string') pushFact(out, '去过的应用', args.packageName.trim());
93
- }
94
-
95
- function pushFact(out, kind, value) {
96
- const clipped = clip(value);
97
- if (!clipped) return;
98
- const list = out[kind] || [];
99
- const next = list.filter((v) => v !== clipped).concat(clipped).slice(-MAX_FACT_VALUES);
100
- out[kind] = next;
101
- }
102
-
103
- /**
104
- * 生成结构化步骤摘要。
105
- *
106
- * @param {object|Array} steps 步骤流(见文件头)
107
- * @param {{goal?:string, intent?:string}} [opts] 目标;`intent` 不传就从最后一段有内容的思考取
108
- * @returns {{
109
- * goal:string, facts:Object<string,string[]>, progress:string[],
110
- * earlier:Object<string,number>, intent:string,
111
- * render:(header?:string)=>string
112
- * }}
113
- */
114
- function summarizeSteps(steps, opts) {
115
- const list = toStepList(steps);
116
- const goal = opts && typeof opts.goal === 'string' ? clip(opts.goal, 200) : '';
117
-
118
- const facts = {};
119
- const progress = [];
120
- let lastThought = '';
121
-
122
- for (const step of list) {
123
- if (!step || typeof step !== 'object') continue;
124
- if (step.kind === 'think') {
125
- const label = labelOf(step);
126
- if (label) lastThought = label;
127
- continue;
128
- }
129
- const label = labelOf(step);
130
- if (!label && !step.name) continue;
131
- factsFromStep(step, facts);
132
- progress.push(`${label || step.name} → ${outcomeOf(step)}`);
133
- }
134
-
135
- // 进展行超上限:最早的几行并进「更早结局计数」。
136
- const earlier = {};
137
- let p = progress;
138
- while (p.length > MAX_PROGRESS) {
139
- const out = p[0].substring(p[0].lastIndexOf('→ ') + 2).trim() || OTHER;
140
- const key = (out in earlier || Object.keys(earlier).length < MAX_EARLIER_KINDS) ? out : OTHER;
141
- earlier[key] = (earlier[key] || 0) + 1;
142
- p = p.slice(1);
143
- }
144
-
145
- const intent = opts && typeof opts.intent === 'string' && opts.intent.trim() !== ''
146
- ? clip(opts.intent)
147
- : lastThought;
148
-
149
- const summary = {
150
- goal,
151
- facts,
152
- progress: p,
153
- earlier,
154
- intent,
155
- };
156
- summary.render = (header) => render(summary, header);
157
- return summary;
158
- }
159
-
160
- /** 把摘要渲染成给模型读的确定性文本(无时间戳,保证前缀稳定)。 */
161
- function render(summary, header) {
162
- const lines = [];
163
- lines.push(typeof header === 'string' && header.trim() !== '' ? header.trim() : '【本轮进度摘要】');
164
- lines.push('只有最新的用户消息是当前任务,工具仍然可用;更早的用户消息只作参考。');
165
- lines.push(`目标:${summary.goal || '(未记录)'}`);
166
- lines.push('已确认:');
167
- const kinds = Object.keys(summary.facts);
168
- if (kinds.length === 0) {
169
- lines.push('- (暂无)');
170
- } else {
171
- for (const kind of kinds) lines.push(`- ${kind}:${summary.facts[kind].join('、')}`);
172
- }
173
- lines.push('进展:');
174
- const earlierKeys = Object.keys(summary.earlier);
175
- if (earlierKeys.length > 0) {
176
- const total = earlierKeys.reduce((sum, k) => sum + summary.earlier[k], 0);
177
- lines.push(`- 更早 ${total} 步:${earlierKeys.map((k) => `${k} ${summary.earlier[k]}`).join(',')}`);
178
- }
179
- if (summary.progress.length === 0) {
180
- lines.push('- (暂无)');
181
- } else {
182
- for (const line of summary.progress) lines.push(`- ${line}`);
183
- }
184
- lines.push(summary.intent
185
- ? `下一步:从下面保留的最近几步接着做(折叠前的最后打算:${summary.intent})`
186
- : '下一步:从下面保留的最近几步接着做');
187
- return lines.join('\n');
188
- }
189
-
190
- module.exports = {
191
- summarizeSteps,
192
- render,
193
- // 纯函数与小常量:
194
- labelOf,
195
- outcomeOf,
196
- factsFromStep,
197
- MAX_FACT_VALUES,
198
- MAX_PROGRESS,
199
- MAX_EARLIER_KINDS,
200
- CLIP,
201
- };