dsh-seal-scripts 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/core/tool.js CHANGED
@@ -40,7 +40,7 @@ export const WRITE_TOOL_NAME = 'session_mem_write'
40
40
  */
41
41
  export function resolveMemoryFile(dshHome, cwd, file) {
42
42
  const dir = memoryDir(dshHome, cwd)
43
- const abs = assertInside(dir, file, { label: '本工作区的回顾目录' })
43
+ const abs = assertInside(dir, file, { label: 'this workspace\'s review directory' })
44
44
  return assertMarkdown(abs, file)
45
45
  }
46
46
 
@@ -58,7 +58,7 @@ export async function readMemorySection({ dshHome, cwd, file }) {
58
58
  const abs = resolveMemoryFile(dshHome, cwd, file)
59
59
  const text = await fsp.readFile(abs, 'utf8')
60
60
  const parsed = parseMemory(text)
61
- if (!parsed.id) throw new Error('这份文件没有回顾分区标记,不是回顾文件:' + file)
61
+ if (!parsed.id) throw new Error('this file has no review section markers, so it is not a review file: ' + file)
62
62
  return { file: path.basename(abs), path: abs, text: dialogueOnly(parsed.sections.body) }
63
63
  }
64
64
 
@@ -76,10 +76,10 @@ export function estimateTokens(text) {
76
76
  */
77
77
  function diaryTooLongMessage(file, diaryTokens, sumTokens) {
78
78
  return [
79
- '【日记没有写进去】日记比摘要还长,已拒绝。',
80
- '文件:' + file,
81
- '现状:日记约 ' + diaryTokens + ' token,摘要约 ' + sumTokens + ' token;日记不得超过摘要。',
82
- '处理:把日记压到摘要以内再写——只留下次能接上的要点,细节本来就留在原文里。'
79
+ '【Diary not written】the diary is longer than the summary, so it was rejected.',
80
+ 'File: ' + file,
81
+ 'Now: the diary is about ' + diaryTokens + ' tokens, the summary about ' + sumTokens + '; the diary must not exceed the summary.',
82
+ 'Fix: trim the diary below the summary length and write again — keep only what the next pass needs; the details stay in the original text.'
83
83
  ].join('\n')
84
84
  }
85
85
 
@@ -88,10 +88,10 @@ function diaryTooLongMessage(file, diaryTokens, sumTokens) {
88
88
  */
89
89
  function keywordsTooLongMessage(file, keyTokens, diaryTokens) {
90
90
  return [
91
- '【关键词没有写进去】关键词的 token 不少于日记,已拒绝。',
92
- '文件:' + file,
93
- '现状:关键词约 ' + keyTokens + ' token,日记约 ' + diaryTokens + ' token;关键词必须少于日记。',
94
- '处理:从原文另做一遍摘要,用更少的 token 讲同一件事——它要当检索用的索引,不是第二份日记。'
91
+ '【Keywords not written】the keywords cost at least as many tokens as the diary, so they were rejected.',
92
+ 'File: ' + file,
93
+ 'Now: the keywords are about ' + keyTokens + ' tokens, the diary about ' + diaryTokens + '; the keywords must cost fewer tokens than the diary.',
94
+ 'Fix: summarize the original again in fewer tokens for the same content — this is a retrieval index, not a second diary.'
95
95
  ].join('\n')
96
96
  }
97
97
 
@@ -107,7 +107,7 @@ function keywordsTooLongMessage(file, keyTokens, diaryTokens) {
107
107
  export function applyWrite(before, { file, keywords, diary }) {
108
108
  const hasKeywords = Array.isArray(keywords)
109
109
  const hasDiary = typeof diary === 'string'
110
- if (!hasKeywords && !hasDiary) throw new Error('keywords 与 diary 至少给一个')
110
+ if (!hasKeywords && !hasDiary) throw new Error('pass at least one of keywords or diary')
111
111
 
112
112
  const parsed = parseMemory(before)
113
113
  const oldDiary = String(parsed.sections.diary ?? '').trim()
@@ -116,7 +116,7 @@ export function applyWrite(before, { file, keywords, diary }) {
116
116
  let keyLine = null
117
117
  if (hasKeywords) {
118
118
  const words = keywords.map((w) => String(w).trim()).filter(Boolean)
119
- if (words.length === 0) throw new Error('keywords 不能是空数组')
119
+ if (words.length === 0) throw new Error('keywords must not be an empty array')
120
120
  keyLine = words.join(' · ')
121
121
  }
122
122
  const nextDiary = hasDiary ? String(diary).trim() : oldDiary
@@ -143,20 +143,20 @@ export function applyWrite(before, { file, keywords, diary }) {
143
143
  const changed = []
144
144
  if (hasKeywords) {
145
145
  const updated = setField(next, 'keywords', keyLine)
146
- if (updated === null) throw new Error('这份文件没有「关键词」字段')
146
+ if (updated === null) throw new Error('this file has no keywords field')
147
147
  next = updated
148
- changed.push('关键词')
148
+ changed.push('keywords')
149
149
  }
150
150
  if (hasDiary) {
151
151
  const updated = setSection(next, 'diary', diary)
152
- if (updated === null) throw new Error('这份文件没有日记分区')
152
+ if (updated === null) throw new Error('this file has no diary section')
153
153
  next = updated
154
- changed.push('日记')
154
+ changed.push('diary')
155
155
  }
156
156
 
157
157
  const check = parseMemory(next)
158
158
  const ok = check.id && ['sum', 'body', 'diary'].every((k) => typeof check.sections[k] === 'string')
159
- if (!ok) throw new Error('写入后校验失败:' + file)
159
+ if (!ok) throw new Error('post-write verification failed: ' + file)
160
160
  return { next, changed, diary: check.sections.diary, keywords: readField(check.meta, 'keywords') }
161
161
  }
162
162
 
@@ -182,16 +182,16 @@ const fileIO = {
182
182
  * @returns {Promise<{items:Array<{file:string, path:string, changed:string, diary:string, keywords:string}>}>}
183
183
  */
184
184
  export async function writeMemories({ dshHome, cwd, items, io = fileIO }) {
185
- if (!Array.isArray(items) || items.length === 0) throw new Error('一次至少写一份')
185
+ if (!Array.isArray(items) || items.length === 0) throw new Error('write at least one item at a time')
186
186
  const staged = []
187
187
  const seen = new Set()
188
188
  for (const item of items) {
189
189
  const abs = resolveMemoryFile(dshHome, cwd, item.file)
190
- if (seen.has(abs)) throw new Error('同一份写了两次:' + path.basename(abs))
190
+ if (seen.has(abs)) throw new Error('the same file was written twice: ' + path.basename(abs))
191
191
  seen.add(abs)
192
192
  const before = await fsp.readFile(abs, 'utf8')
193
193
  const parsed = parseMemory(before)
194
- if (!parsed.id) throw new Error('这份文件没有回顾分区标记,不是回顾文件:' + item.file)
194
+ if (!parsed.id) throw new Error('this file has no review section markers, so it is not a review file: ' + item.file)
195
195
  const applied = applyWrite(before, { file: path.basename(abs), keywords: item.keywords, diary: item.diary })
196
196
  staged.push({ abs, before, ...applied })
197
197
  }
@@ -215,15 +215,15 @@ export async function writeMemories({ dshHome, cwd, items, io = fileIO }) {
215
215
  try {
216
216
  await io.writeAtomic(s.abs, s.before)
217
217
  const back = await fsp.readFile(s.abs, 'utf8')
218
- if (back !== s.before) rollback.push(path.basename(s.abs) + '(回滚后内容不一致)')
218
+ if (back !== s.before) rollback.push(path.basename(s.abs) + ' (content differs after rollback)')
219
219
  } catch (e) {
220
- rollback.push(path.basename(s.abs) + '(回滚失败:' + (e?.message ?? e) + ')')
220
+ rollback.push(path.basename(s.abs) + ' (rollback failed: ' + (e?.message ?? e) + ')')
221
221
  }
222
222
  }
223
223
  // 失败必须说清「哪些没回滚回去」——用户得知道哪一份停在半新半旧。
224
224
  const detail = rollback.length > 0
225
- ? '\n以下是没能回滚的,请手工核对:\n · ' + rollback.join('\n · ')
226
- : '\n所有已写入的文件都已还原。'
225
+ ? '\nThese could not be rolled back; check them by hand:\n · ' + rollback.join('\n · ')
226
+ : '\nEvery written file has been restored.'
227
227
  throw new Error((err?.message ?? String(err)) + detail)
228
228
  } finally {
229
229
  for (const tmp of temps) await fsp.rm(tmp, { force: true }).catch(() => {})
@@ -261,17 +261,17 @@ export function localDayOf(compactedAt) {
261
261
  */
262
262
  export async function resolveMemoryByDay({ dshHome, cwd, date, nth }) {
263
263
  const day = String(date ?? '').trim()
264
- if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new Error('date 要写成 YYYY-MM-DD(本地日期):' + day)
264
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(day)) throw new Error('date must be YYYY-MM-DD (local date): ' + day)
265
265
  const { entries } = await listMemories(dshHome, cwd)
266
266
  const same = entries
267
267
  .filter((e) => e && typeof e.compactedAt === 'string' && localDayOf(e.compactedAt) === day)
268
268
  .sort((a, b) => String(a.compactedAt).localeCompare(String(b.compactedAt)))
269
269
  if (same.length === 0) {
270
270
  const days = [...new Set(entries.map((e) => localDayOf(e.compactedAt)).filter(Boolean))].sort()
271
- throw new Error('这一天没有回顾:' + day + (days.length > 0 ? '(有回顾的日期:' + days.join('、') + ')' : '(这个工作区还没有任何回顾)'))
271
+ throw new Error('no review on that day: ' + day + (days.length > 0 ? ' (days with reviews: ' + days.join(', ') + ')' : ' (this workspace has no reviews at all)'))
272
272
  }
273
273
  if (nth > same.length) {
274
- throw new Error('这一天只有 ' + same.length + ' 份:' + day + ' 没有第 ' + nth + ' 份')
274
+ throw new Error('that day only has ' + same.length + ' review(s): ' + day + ' has no #' + nth)
275
275
  }
276
276
  return same[nth - 1].file
277
277
  }
@@ -285,18 +285,18 @@ export async function listMemories(dshHome, cwd) {
285
285
 
286
286
  /** 读工具的入参校验:一个线索(need),可选跳过清单与跨区许可。 */
287
287
  function validateReadArgs(args) {
288
- if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
288
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('arguments must be an object')
289
289
  if (typeof args.need !== 'string' || args.need.trim() === '') {
290
- throw new Error('need 不能为空:用一句话说清你在找什么')
290
+ throw new Error('need must not be empty: say in one sentence what you are looking for')
291
291
  }
292
292
  if (args.skip !== undefined && (!Array.isArray(args.skip) || args.skip.some((s) => typeof s !== 'string'))) {
293
- throw new Error('skip 必须是字符串数组(已经读过的回顾文件名)')
293
+ throw new Error('skip must be an array of strings (review files already read)')
294
294
  }
295
295
  if (args.allowOuter !== undefined && typeof args.allowOuter !== 'boolean') {
296
- throw new Error('allowOuter 必须是布尔值(用户允许才能搜索其他工作区)')
296
+ throw new Error('allowOuter must be a boolean (the user must allow searching other workspaces)')
297
297
  }
298
298
  if (args.query !== undefined || args.file !== undefined) {
299
- throw new Error('这个工具只收 need(可选 skip / allowOuter):要看某一份的原文用 ' + WRITE_TOOL_NAME)
299
+ throw new Error('this tool only takes need (optionally skip / allowOuter); to read one review original use ' + WRITE_TOOL_NAME)
300
300
  }
301
301
  }
302
302
 
@@ -304,28 +304,28 @@ function validateReadArgs(args) {
304
304
  function validatePosition(args, where = '') {
305
305
  const hasFile = typeof args.file === 'string' && args.file.trim() !== ''
306
306
  const hasDate = args.date !== undefined
307
- if (hasFile && hasDate) throw new Error(where + 'file 与 date 只能给一个:给了 file 就不用再给 date / nth')
308
- if (!hasFile && !hasDate) throw new Error(where + '要么给 file,要么给 date(默认那天的第 1 份)来定位哪一份回顾')
307
+ if (hasFile && hasDate) throw new Error(where + 'file and date are mutually exclusive: with file you do not need date / nth')
308
+ if (!hasFile && !hasDate) throw new Error(where + 'pass file, or date (the first review of that day) to locate a review')
309
309
  if (hasDate && !/^\d{4}-\d{2}-\d{2}$/.test(String(args.date).trim())) {
310
- throw new Error(where + 'date 要写成 YYYY-MM-DD(本地日期):' + String(args.date))
310
+ throw new Error(where + 'date must be YYYY-MM-DD (local date): ' + String(args.date))
311
311
  }
312
312
  if (args.date === undefined && args.nth !== undefined) {
313
- throw new Error(where + 'nth 要配 date 一起用:date 是哪天,nth 是那天第几份(从 1 起)')
313
+ throw new Error(where + 'nth goes together with date: date picks the day, nth picks which review of that day (from 1)')
314
314
  }
315
315
  if (args.nth !== undefined && (!Number.isInteger(args.nth) || args.nth < 1)) {
316
- throw new Error(where + 'nth 必须是 1 起的整数(那天的第几份,按压缩时刻从早到晚)')
316
+ throw new Error(where + 'nth must be an integer starting at 1 (which review of that day, oldest first)')
317
317
  }
318
318
  }
319
319
 
320
320
  /** 批量里的一项:定位 + 至少要写 keywords 或 diary。 */
321
321
  function validateWriteItem(item, idx) {
322
322
  const where = 'writes[' + idx + ']:'
323
- if (item === null || typeof item !== 'object' || Array.isArray(item)) throw new Error(where + '必须是对象')
323
+ if (item === null || typeof item !== 'object' || Array.isArray(item)) throw new Error(where + 'must be an object')
324
324
  validatePosition(item, where)
325
- if (item.keywords !== undefined && !Array.isArray(item.keywords)) throw new Error(where + 'keywords 必须是字符串数组')
326
- if (item.diary !== undefined && typeof item.diary !== 'string') throw new Error(where + 'diary 必须是字符串')
327
- if (item.keywords === undefined && item.diary === undefined) throw new Error(where + '至少要给 keywords 或 diary 一项')
328
- if (item.query !== undefined) throw new Error('搜索请用 ' + READ_TOOL_NAME)
325
+ if (item.keywords !== undefined && !Array.isArray(item.keywords)) throw new Error(where + 'keywords must be an array of strings')
326
+ if (item.diary !== undefined && typeof item.diary !== 'string') throw new Error(where + 'diary must be a string')
327
+ if (item.keywords === undefined && item.diary === undefined) throw new Error(where + 'pass at least one of keywords or diary')
328
+ if (item.query !== undefined) throw new Error('use ' + READ_TOOL_NAME + ' to search')
329
329
  }
330
330
 
331
331
  /**
@@ -334,25 +334,25 @@ function validateWriteItem(item, idx) {
334
334
  * - 批量:writes 数组,每一项自带定位与要写的内容;不能再混顶层定位。
335
335
  */
336
336
  function validateWriteArgs(args) {
337
- if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('参数必须是对象')
337
+ if (args === null || typeof args !== 'object' || Array.isArray(args)) throw new Error('arguments must be an object')
338
338
  if (args.writes !== undefined) {
339
- if (!Array.isArray(args.writes)) throw new Error('writes 必须是数组(一份一项)')
340
- if (args.writes.length === 0) throw new Error('writes 不能是空数组')
339
+ if (!Array.isArray(args.writes)) throw new Error('writes must be an array (one item per review)')
340
+ if (args.writes.length === 0) throw new Error('writes must not be an empty array')
341
341
  for (const key of ['file', 'date', 'nth', 'keywords', 'diary']) {
342
- if (args[key] !== undefined) throw new Error('给了 writes 就别再给顶层 ' + key + ':每一项都放进 writes 里')
342
+ if (args[key] !== undefined) throw new Error('with writes, do not also pass top-level ' + key + ': put every item inside writes')
343
343
  }
344
344
  args.writes.forEach((item, i) => validateWriteItem(item, i))
345
345
  return
346
346
  }
347
347
  validatePosition(args)
348
- if (args.query !== undefined) throw new Error('搜索请用 ' + READ_TOOL_NAME)
349
- if (args.keywords !== undefined && !Array.isArray(args.keywords)) throw new Error('keywords 必须是字符串数组')
350
- if (args.diary !== undefined && typeof args.diary !== 'string') throw new Error('diary 必须是字符串')
348
+ if (args.query !== undefined) throw new Error('use ' + READ_TOOL_NAME + ' to search')
349
+ if (args.keywords !== undefined && !Array.isArray(args.keywords)) throw new Error('keywords must be an array of strings')
350
+ if (args.diary !== undefined && typeof args.diary !== 'string') throw new Error('diary must be a string')
351
351
  }
352
352
 
353
353
  /** 命中在哪一轮、在哪一层工作区,说人话。 */
354
- const LEVEL_LABEL = { keywords: '关键词', sum: '摘要', body: '原文' }
355
- const WHERE_LABEL = { self: '本工作区', child: '子工作区', sibling: '平级工作区', outer: '上级/外圈' }
354
+ const LEVEL_LABEL = { keywords: 'keywords', sum: 'summary', body: 'transcript' }
355
+ const WHERE_LABEL = { self: 'this workspace', child: 'child workspace', sibling: 'sibling workspace', outer: 'parent/outer' }
356
356
 
357
357
  /**
358
358
  * 读工具定义(直接给 ctx.tools.register 用)。一次只交给模型一条命中的回顾。
@@ -397,7 +397,7 @@ export function buildReadToolDefinition({ dshHome, onHit }) {
397
397
  async execute(args, exec) {
398
398
  validateReadArgs(args)
399
399
  const cwd = exec?.agent?.session?.header?.cwd
400
- if (typeof cwd !== 'string' || cwd === '') throw new Error(READ_TOOL_NAME + ' 需要知道当前工作区')
400
+ if (typeof cwd !== 'string' || cwd === '') throw new Error(READ_TOOL_NAME + ' needs to know the current workspace')
401
401
  const allowOuter = args.allowOuter === true
402
402
  const skip = new Set((args.skip ?? []).map((s) => String(s)))
403
403
  const picked = await listCandidates({ dshHome, cwd, need: args.need, allowOuter })
@@ -412,8 +412,8 @@ export function buildReadToolDefinition({ dshHome, onHit }) {
412
412
  await onHit({ local: true, workspace: cwd, hitCount: 1, hits: [{ file: one.file }] })
413
413
  }
414
414
  const text = [
415
- '读到 ' + one.file + '(' + (WHERE_LABEL[one.scope] || one.scope) + ')· 命中「' + (LEVEL_LABEL[one.level] || one.level) + '」',
416
- '还有 ' + (rest.length - 1) + ' 条没读;这条不对,就把它放进 skip 再调一次。',
415
+ 'Read ' + one.file + ' (' + (WHERE_LABEL[one.scope] || one.scope) + ') · matched "' + (LEVEL_LABEL[one.level] || one.level) + '"',
416
+ ' ' + (rest.length - 1) + ' more not read; if this one is wrong, put it in skip and call again.',
417
417
  '',
418
418
  one.content
419
419
  ].join('\n')
@@ -434,13 +434,13 @@ export function buildReadToolDefinition({ dshHome, onHit }) {
434
434
  /** 读完了:没找到就明说,并给出下一步(换说法 / 问许可)。 */
435
435
  function exhausted({ need, allowOuter, blocked, read }) {
436
436
  const lines = []
437
- if (read === 0) lines.push('这个范围里没有一条回顾提到「' + need + '」。')
438
- else lines.push('这个范围里的 ' + read + ' 条都读过了,没有更符合的。')
437
+ if (read === 0) lines.push('No review in this scope mentions "' + need + '".')
438
+ else lines.push('All ' + read + ' review(s) in this scope were read; nothing fits better.')
439
439
  if (!allowOuter && blocked > 0) {
440
- lines.push('外圈还有 ' + blocked + ' 份回顾没看,但要用户点头才能搜。')
441
- lines.push('先告诉用户你没想起来或没记清,请他换个说法;他还坚持的话,再问他能不能搜其他工作区。')
440
+ lines.push(blocked + ' more review(s) outside are unread, but searching them needs the user\'s go-ahead.')
441
+ lines.push('Tell the user you do not recall or are unsure and ask them to rephrase; if they insist, ask whether you may search other workspaces.')
442
442
  } else {
443
- lines.push('先告诉用户你没想起来或没记清,请他换个说法再试。')
443
+ lines.push('Tell the user you do not recall or are unsure and ask them to rephrase.')
444
444
  }
445
445
  return { mode: 'exhausted', file: '', workspace: '', level: '', remaining: 0, text: lines.join('\n') }
446
446
  }
@@ -519,31 +519,31 @@ export function buildWriteToolDefinition({ dshHome }) {
519
519
  if (value.mode === 'read') {
520
520
  return [{
521
521
  type: 'text',
522
- text: '原文(只含对话,不含工具调用)· ' + value.file + '(' + (value.path ?? '') + ')\n\n' + (value.text ?? '')
522
+ text: 'Original (dialogue only, tool calls excluded) · ' + value.file + ' (' + (value.path ?? '') + ')\n\n' + (value.text ?? '')
523
523
  }]
524
524
  }
525
525
  if (Array.isArray(value.items) && value.items.length > 0) {
526
526
  return [{
527
527
  type: 'text',
528
- text: '已更新 ' + value.items.length + ' 份:\n' + value.items
528
+ text: 'Updated ' + value.items.length + ' review(s):\n' + value.items
529
529
  .map((it) => '· ' + it.file + ':' + it.changed +
530
- (typeof it.diary === 'string' && it.diary !== '' ? '\n 日记现在是:\n ' + it.diary : '') +
531
- (typeof it.keywords === 'string' && it.keywords !== '' ? '\n 关键词现在是:' + it.keywords : ''))
530
+ (typeof it.diary === 'string' && it.diary !== '' ? '\n diary is now:\n ' + it.diary : '') +
531
+ (typeof it.keywords === 'string' && it.keywords !== '' ? '\n keywords are now: ' + it.keywords : ''))
532
532
  .join('\n')
533
533
  }]
534
534
  }
535
535
  return [{
536
536
  type: 'text',
537
- text: '已更新 ' + value.file + '(' + (value.path ?? '') + '):' + value.changed +
538
- (typeof value.diary === 'string' && value.diary !== '' ? '\n\n日记现在是:\n' + value.diary : '') +
539
- (typeof value.keywords === 'string' && value.keywords !== '' ? '\n关键词现在是:' + value.keywords : '')
537
+ text: 'Updated ' + value.file + ' (' + (value.path ?? '') + '): ' + value.changed +
538
+ (typeof value.diary === 'string' && value.diary !== '' ? '\n\ndiary is now:\n' + value.diary : '') +
539
+ (typeof value.keywords === 'string' && value.keywords !== '' ? '\nkeywords are now: ' + value.keywords : '')
540
540
  }]
541
541
  }
542
542
  },
543
543
  async execute(args, exec) {
544
544
  validateWriteArgs(args)
545
545
  const cwd = exec?.agent?.session?.header?.cwd
546
- if (typeof cwd !== 'string' || cwd === '') throw new Error(WRITE_TOOL_NAME + ' 需要知道当前工作区')
546
+ if (typeof cwd !== 'string' || cwd === '') throw new Error(WRITE_TOOL_NAME + ' needs to know the current workspace')
547
547
 
548
548
  // 批量:每一项先定位(date 翻成文件名),再一起交给 writeMemories——全部合格才落盘。
549
549
  if (Array.isArray(args.writes)) {
@@ -564,8 +564,8 @@ export function buildWriteToolDefinition({ dshHome }) {
564
564
  mode: 'write',
565
565
  items: res.items.map((one) => ({
566
566
  file: one.file, path: one.path, changed: one.changed,
567
- diary: one.changed.includes('日记') ? one.diary : '',
568
- keywords: one.changed.includes('关键词') ? one.keywords : ''
567
+ diary: one.changed.includes('diary') ? one.diary : '',
568
+ keywords: one.changed.includes('keywords') ? one.keywords : ''
569
569
  }))
570
570
  }
571
571
  }
@@ -583,8 +583,8 @@ export function buildWriteToolDefinition({ dshHome }) {
583
583
  const res = await writeMemory({ dshHome, cwd, file, keywords: args.keywords, diary: args.diary })
584
584
  return {
585
585
  file: res.file, path: res.path, mode: 'write', changed: res.changed,
586
- diary: res.changed.includes('日记') ? res.diary : '',
587
- keywords: res.changed.includes('关键词') ? res.keywords : ''
586
+ diary: res.changed.includes('diary') ? res.diary : '',
587
+ keywords: res.changed.includes('keywords') ? res.keywords : ''
588
588
  }
589
589
  }
590
590
  const res = await readMemorySection({ dshHome, cwd, file })
package/lib/core/zip.js CHANGED
@@ -82,7 +82,7 @@ export function buildZip(entries) {
82
82
 
83
83
  for (const entry of entries) {
84
84
  const name = String(entry.name).split('\\').join('/')
85
- if (name === '') throw new Error('zip 条目名不能为空')
85
+ if (name === '') throw new Error('zip entry name must not be empty')
86
86
  const isDir = name.endsWith('/')
87
87
  const body = isDir
88
88
  ? Buffer.alloc(0)
@@ -158,23 +158,23 @@ function findEocd(buf) {
158
158
  */
159
159
  export function readZip(buf) {
160
160
  if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
161
- if (buf.length < 22) throw new Error('不是 zip:文件太短')
161
+ if (buf.length < 22) throw new Error('not a zip: file too short')
162
162
  const eocd = findEocd(buf)
163
- if (eocd < 0) throw new Error('不是 zip:找不到中央目录(可能只是改了扩展名的普通文件)')
163
+ if (eocd < 0) throw new Error('not a zip: no central directory found (maybe just a renamed ordinary file)')
164
164
  const count = buf.readUInt16LE(eocd + 10)
165
165
  const cdSize = buf.readUInt32LE(eocd + 12)
166
166
  const cdOffset = buf.readUInt32LE(eocd + 16)
167
167
  if (cdOffset === 0xFFFFFFFF || cdSize === 0xFFFFFFFF || count === 0xFFFF) {
168
- throw new Error('不支持 zip64 包;重新导出一个普通 zip 再试')
168
+ throw new Error('zip64 archives are not supported; export a normal zip and try again')
169
169
  }
170
- if (cdOffset + cdSize > buf.length) throw new Error('zip 损坏:中央目录越界')
170
+ if (cdOffset + cdSize > buf.length) throw new Error('corrupt zip: central directory out of range')
171
171
 
172
172
  const out = []
173
173
  let total = 0
174
174
  let p = cdOffset
175
175
  for (let n = 0; n < count; n++) {
176
176
  if (p + 46 > buf.length || buf.readUInt32LE(p) !== SIG_CENTRAL) {
177
- throw new Error('zip 损坏:中央目录第 ' + (n + 1) + ' 项读不出来')
177
+ throw new Error('corrupt zip: cannot read central directory entry ' + (n + 1))
178
178
  }
179
179
  const flags = buf.readUInt16LE(p + 8)
180
180
  const method = buf.readUInt16LE(p + 10)
@@ -188,28 +188,28 @@ export function readZip(buf) {
188
188
  const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8').split('\\').join('/')
189
189
  p += 46 + nameLen + extraLen + commentLen
190
190
 
191
- if (compSize === 0xFFFFFFFF || uncompSize === 0xFFFFFFFF) throw new Error('不支持 zip64 包:' + name)
192
- if ((flags & 0x01) === 0x01) throw new Error('不支持加密的 zip:' + name)
191
+ if (compSize === 0xFFFFFFFF || uncompSize === 0xFFFFFFFF) throw new Error('zip64 archives are not supported: ' + name)
192
+ if ((flags & 0x01) === 0x01) throw new Error('encrypted zips are not supported: ' + name)
193
193
 
194
194
  const isDir = name.endsWith('/')
195
195
  if (isDir) { out.push({ name, isDir: true, data: Buffer.alloc(0), method, crc }); continue }
196
196
 
197
197
  if (localOffset + 30 > buf.length || buf.readUInt32LE(localOffset) !== SIG_LOCAL) {
198
- throw new Error('zip 损坏:找不到 ' + name + ' 的本地头')
198
+ throw new Error('corrupt zip: no local header for ' + name)
199
199
  }
200
200
  const lNameLen = buf.readUInt16LE(localOffset + 26)
201
201
  const lExtraLen = buf.readUInt16LE(localOffset + 28)
202
202
  const dataStart = localOffset + 30 + lNameLen + lExtraLen
203
- if (dataStart + compSize > buf.length) throw new Error('zip 损坏:' + name + ' 的数据越界')
203
+ if (dataStart + compSize > buf.length) throw new Error('corrupt zip: data for ' + name + ' is out of range')
204
204
  const raw = buf.subarray(dataStart, dataStart + compSize)
205
205
 
206
206
  let data
207
207
  if (method === 0) data = Buffer.from(raw)
208
208
  else if (method === 8) data = inflateRawSync(raw)
209
- else throw new Error('不支持的压缩方法 ' + method + '(' + name + ');只认 store / deflate')
209
+ else throw new Error('unsupported compression method ' + method + ' (' + name + '); only store / deflate are accepted')
210
210
 
211
211
  total += data.length
212
- if (data.length !== uncompSize) throw new Error('zip 损坏:' + name + ' 解出来的长度对不上')
212
+ if (data.length !== uncompSize) throw new Error('corrupt zip: unpacked length mismatch for ' + name)
213
213
  out.push({ name, isDir: false, data, method, crc })
214
214
  }
215
215
  return out
@@ -224,12 +224,12 @@ export function readZip(buf) {
224
224
  */
225
225
  export function safeEntryName(raw) {
226
226
  const text = String(raw === undefined || raw === null ? '' : raw).split('\\').join('/').replace(/\/+$/, '')
227
- if (text === '') throw new Error('包里有空文件名的条目')
228
- if (text.startsWith('/')) throw new Error('包里有绝对路径:' + raw)
229
- if (/^[A-Za-z]:/.test(text)) throw new Error('包里有盘符路径:' + raw)
227
+ if (text === '') throw new Error('the archive has an entry with an empty name')
228
+ if (text.startsWith('/')) throw new Error('the archive has an absolute path: ' + raw)
229
+ if (/^[A-Za-z]:/.test(text)) throw new Error('the archive has a drive-letter path: ' + raw)
230
230
  const parts = text.split('/')
231
231
  for (const part of parts) {
232
- if (part === '' || part === '.' || part === '..') throw new Error('包里有越界路径:' + raw)
232
+ if (part === '' || part === '.' || part === '..') throw new Error('the archive has an out-of-range path: ' + raw)
233
233
  }
234
234
  return parts.join('/')
235
235
  }
@@ -267,7 +267,7 @@ export async function writeZipFile(file, entries) {
267
267
  try {
268
268
  for (const entry of entries) {
269
269
  const name = String(entry.name).split('\\').join('/')
270
- if (name === '') throw new Error('zip 条目名不能为空')
270
+ if (name === '') throw new Error('zip entry name must not be empty')
271
271
  const isDir = name.endsWith('/')
272
272
  const nameBuf = Buffer.from(name, 'utf8')
273
273
  const stamp = dosDateTime(entry.mtime)
@@ -368,22 +368,22 @@ export async function writeZipFile(file, entries) {
368
368
  */
369
369
  export function zipUncompressedTotal(buf) {
370
370
  if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
371
- if (buf.length < 22) throw new Error('不是 zip:文件太短')
371
+ if (buf.length < 22) throw new Error('not a zip: file too short')
372
372
  const eocd = findEocd(buf)
373
- if (eocd < 0) throw new Error('不是 zip:找不到中央目录(可能只是改了扩展名的普通文件)')
373
+ if (eocd < 0) throw new Error('not a zip: no central directory found (maybe just a renamed ordinary file)')
374
374
  const count = buf.readUInt16LE(eocd + 10)
375
375
  const cdSize = buf.readUInt32LE(eocd + 12)
376
376
  const cdOffset = buf.readUInt32LE(eocd + 16)
377
377
  if (cdOffset === 0xFFFFFFFF || cdSize === 0xFFFFFFFF || count === 0xFFFF) {
378
- throw new Error('不支持 zip64 包;重新导出一个普通 zip 再试')
378
+ throw new Error('zip64 archives are not supported; export a normal zip and try again')
379
379
  }
380
- if (cdOffset + cdSize > buf.length) throw new Error('zip 损坏:中央目录越界')
380
+ if (cdOffset + cdSize > buf.length) throw new Error('corrupt zip: central directory out of range')
381
381
  let bytes = 0
382
382
  let files = 0
383
383
  let p = cdOffset
384
384
  for (let n = 0; n < count; n++) {
385
385
  if (p + 46 > buf.length || buf.readUInt32LE(p) !== SIG_CENTRAL) {
386
- throw new Error('zip 损坏:中央目录第 ' + (n + 1) + ' 项读不出来')
386
+ throw new Error('corrupt zip: cannot read central directory entry ' + (n + 1))
387
387
  }
388
388
  const uncompSize = buf.readUInt32LE(p + 24)
389
389
  const nameLen = buf.readUInt16LE(p + 28)
@@ -391,7 +391,7 @@ export function zipUncompressedTotal(buf) {
391
391
  const commentLen = buf.readUInt16LE(p + 32)
392
392
  const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8')
393
393
  p += 46 + nameLen + extraLen + commentLen
394
- if (uncompSize === 0xFFFFFFFF) throw new Error('不支持 zip64 包:' + name)
394
+ if (uncompSize === 0xFFFFFFFF) throw new Error('zip64 archives are not supported: ' + name)
395
395
  if (name.endsWith('/')) continue
396
396
  bytes += uncompSize
397
397
  files++
@@ -423,26 +423,26 @@ export async function readZipCentralFromFile(file) {
423
423
  const handle = await fsp.open(file, 'r')
424
424
  try {
425
425
  const { size } = await handle.stat()
426
- if (size < 22) throw new Error('不是 zip:文件太短')
426
+ if (size < 22) throw new Error('not a zip: file too short')
427
427
  const tailLen = Math.min(size, 22 + 0xFFFF)
428
428
  const tail = Buffer.alloc(tailLen)
429
429
  await handle.read(tail, 0, tailLen, size - tailLen)
430
430
  const eocd = findEocd(tail)
431
- if (eocd < 0) throw new Error('不是 zip:找不到中央目录(可能只是改了扩展名的普通文件)')
431
+ if (eocd < 0) throw new Error('not a zip: no central directory found (maybe just a renamed ordinary file)')
432
432
  const count = tail.readUInt16LE(eocd + 10)
433
433
  const cdSize = tail.readUInt32LE(eocd + 12)
434
434
  const cdOffset = tail.readUInt32LE(eocd + 16)
435
435
  if (cdOffset === 0xFFFFFFFF || cdSize === 0xFFFFFFFF || count === 0xFFFF) {
436
- throw new Error('不支持 zip64 包;重新导出一个普通 zip 再试')
436
+ throw new Error('zip64 archives are not supported; export a normal zip and try again')
437
437
  }
438
- if (cdOffset + cdSize > size) throw new Error('zip 损坏:中央目录越界')
438
+ if (cdOffset + cdSize > size) throw new Error('corrupt zip: central directory out of range')
439
439
  const cd = Buffer.alloc(cdSize)
440
440
  await handle.read(cd, 0, cdSize, cdOffset)
441
441
  const entries = []
442
442
  let p = 0
443
443
  for (let n = 0; n < count; n++) {
444
444
  if (p + 46 > cd.length || cd.readUInt32LE(p) !== SIG_CENTRAL) {
445
- throw new Error('zip 损坏:中央目录第 ' + (n + 1) + ' 项读不出来')
445
+ throw new Error('corrupt zip: cannot read central directory entry ' + (n + 1))
446
446
  }
447
447
  const flags = cd.readUInt16LE(p + 8)
448
448
  const method = cd.readUInt16LE(p + 10)
@@ -455,8 +455,8 @@ export async function readZipCentralFromFile(file) {
455
455
  const localOffset = cd.readUInt32LE(p + 42)
456
456
  const name = cd.subarray(p + 46, p + 46 + nameLen).toString('utf8').split('\\').join('/')
457
457
  p += 46 + nameLen + extraLen + commentLen
458
- if (compSize === 0xFFFFFFFF || uncompSize === 0xFFFFFFFF) throw new Error('不支持 zip64 包:' + name)
459
- if ((flags & 0x01) === 0x01) throw new Error('不支持加密的 zip:' + name)
458
+ if (compSize === 0xFFFFFFFF || uncompSize === 0xFFFFFFFF) throw new Error('zip64 archives are not supported: ' + name)
459
+ if ((flags & 0x01) === 0x01) throw new Error('encrypted zips are not supported: ' + name)
460
460
  entries.push({ name, isDir: name.endsWith('/'), method, crc, compSize, uncompSize, localOffset })
461
461
  }
462
462
  return entries
@@ -486,12 +486,12 @@ export async function forEachZipEntry(file, visit) {
486
486
  }
487
487
  const head = Buffer.alloc(30)
488
488
  await handle.read(head, 0, 30, e.localOffset)
489
- if (head.readUInt32LE(0) !== SIG_LOCAL) throw new Error('zip 损坏:找不到 ' + e.name + ' 的本地头')
489
+ if (head.readUInt32LE(0) !== SIG_LOCAL) throw new Error('corrupt zip: no local header for ' + e.name)
490
490
  const lNameLen = head.readUInt16LE(26)
491
491
  const lExtraLen = head.readUInt16LE(28)
492
492
  const dataStart = e.localOffset + 30 + lNameLen + lExtraLen
493
493
  const dataEnd = dataStart + e.compSize
494
- if (dataEnd > size) throw new Error('zip 损坏:' + e.name + ' 的数据越界')
494
+ if (dataEnd > size) throw new Error('corrupt zip: data for ' + e.name + ' is out of range')
495
495
 
496
496
  const rawChunks = async function* () {
497
497
  let pos = dataStart
@@ -530,12 +530,12 @@ export async function forEachZipEntry(file, visit) {
530
530
  inflater.destroy()
531
531
  }
532
532
  } else {
533
- throw new Error('不支持的压缩方法 ' + e.method + '(' + e.name + ');只认 store / deflate')
533
+ throw new Error('unsupported compression method ' + e.method + ' (' + e.name + '); only store / deflate are accepted')
534
534
  }
535
535
  if (total !== e.uncompSize) {
536
- throw new Error('zip 损坏:' + e.name + ' 解出来的长度对不上(' + total + ' != ' + e.uncompSize + ')')
536
+ throw new Error('corrupt zip: unpacked length mismatch for ' + e.name + ' (' + total + ' != ' + e.uncompSize + ')')
537
537
  }
538
- if (((state ^ -1) >>> 0) !== e.crc) throw new Error('zip 损坏:' + e.name + ' 的 crc 对不上')
538
+ if (((state ^ -1) >>> 0) !== e.crc) throw new Error('corrupt zip: crc mismatch for ' + e.name)
539
539
  }
540
540
 
541
541
  await visit({ name: e.name, isDir: false, method: e.method, uncompSize: e.uncompSize, read: () => read() })