dsh-tiddlywiki 0.28.7 → 0.28.8

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 (52) hide show
  1. package/README.md +1 -0
  2. package/docs/CHANGELOG.md +1 -0
  3. package/docs/features.md +4 -0
  4. package/docs/usage.md +13 -3
  5. package/lib/client.js +63 -27
  6. package/lib/index.js +10655 -10188
  7. package/lib/index.js.map +1 -1
  8. package/package.json +2 -2
  9. package/src/client/dom.ts +26 -0
  10. package/src/client/index.ts +14 -0
  11. package/src/client/note-widget-draft.ts +154 -0
  12. package/src/client/note-widget-tags.ts +184 -0
  13. package/src/client/note-widget-upload.ts +50 -0
  14. package/src/client/note-widget.ts +19 -348
  15. package/src/client/panel.ts +12 -3
  16. package/src/client/render-fetch.ts +11 -4
  17. package/src/client/scope-seat.ts +117 -0
  18. package/src/client/session-summary.ts +29 -7
  19. package/src/client/settings-icon-picker.ts +238 -0
  20. package/src/client/settings-page-catalog.ts +578 -0
  21. package/src/client/settings-page-config.ts +445 -0
  22. package/src/client/settings-page-runtime.ts +149 -0
  23. package/src/client/settings-page-wikis.ts +432 -0
  24. package/src/client/settings-page.ts +127 -1425
  25. package/src/client/styles.ts +36 -0
  26. package/src/client/tool-views.ts +170 -36
  27. package/src/client/wiki-icon.generated.ts +97 -0
  28. package/src/client/wiki-icon.ts +50 -15
  29. package/src/client/wiki-scope-dock.ts +56 -2
  30. package/src/client/wiki-scope.ts +98 -0
  31. package/src/host/admin-catalog.ts +488 -0
  32. package/src/host/admin-routes.ts +670 -0
  33. package/src/host/admin-secrets.ts +119 -0
  34. package/src/host/admin.ts +3 -1244
  35. package/src/host/clip-bridge.ts +24 -1
  36. package/src/host/config.ts +10 -2
  37. package/src/host/routes-session.ts +617 -0
  38. package/src/host/routes-tw-proxy.ts +390 -0
  39. package/src/host/routes.ts +77 -829
  40. package/src/host/tools-attach.ts +151 -0
  41. package/src/host/tools-git.ts +213 -0
  42. package/src/host/tools-notes.ts +672 -0
  43. package/src/host/tools-read.ts +421 -0
  44. package/src/host/tools-support.ts +513 -0
  45. package/src/host/tools.ts +33 -1814
  46. package/src/host/wiki-registry.ts +25 -4
  47. package/src/host/wiki.ts +55 -5
  48. package/src/index-clip.ts +142 -0
  49. package/src/index-git.ts +196 -0
  50. package/src/index-prompt.ts +139 -0
  51. package/src/index-wikis.ts +353 -0
  52. package/src/index.ts +89 -429
@@ -0,0 +1,151 @@
1
+ /**
2
+ * `tiddlywiki_attach` — the only way an agent can write a binary attachment.
3
+ *
4
+ * Split out of `tools.ts` in v0.28.8 — pure code move, body unchanged.
5
+ *
6
+ * @module dsh-tiddlywiki/host/tools-attach
7
+ */
8
+ import { readFile, stat } from 'node:fs/promises'
9
+ import { basename, extname, isAbsolute } from 'node:path'
10
+ import { defineTool } from '../sdk.ts'
11
+ import { isBinaryType } from './tw-api.ts'
12
+ import { downloadClipImage } from './clip-bridge.ts'
13
+ import { assertNoConflict, buildWriteTiddler } from './write-policy.ts'
14
+ import { MAX_ATTACH_BYTES, sessionIdOf } from './tools-support.ts'
15
+ import type { AttachResult, ToolEnv } from './tools-support.ts'
16
+
17
+ /** Mime types offered by `tiddlywiki_attach` for local files. */
18
+ const ATTACH_MIME_BY_EXT: Record<string, string> = {
19
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
20
+ webp: 'image/webp', svg: 'image/svg+xml', avif: 'image/avif', bmp: 'image/bmp',
21
+ ico: 'image/x-icon', pdf: 'application/pdf', zip: 'application/zip',
22
+ txt: 'text/plain', md: 'text/markdown', json: 'application/json', csv: 'text/csv',
23
+ mp3: 'audio/mpeg', wav: 'audio/wav', ogg: 'audio/ogg', mp4: 'video/mp4',
24
+ epub: 'application/epub+zip',
25
+ }
26
+
27
+ export function attachTool(env: ToolEnv) {
28
+ const { deps, requireWiki } = env
29
+ // ── tiddlywiki_attach ────────────────────────────────────────────────────
30
+ return defineTool({
31
+ name: 'tiddlywiki_attach',
32
+ description: '把一个本机文件或公网 http(s) 地址存成 wiki 的二进制附件 tiddler(图片 / PDF / 压缩包等,type + base64 正文,随 wiki 进 git)。可选把附件嵌入/链接进某篇笔记。这是 agent 唯一能写入二进制附件的途径。',
33
+ parameters: {
34
+ title: { type: 'string', description: '附件 tiddler 标题(同时决定其在 wiki 里的名字)', required: true },
35
+ path: { type: 'string', description: '本机绝对路径(与 url 二选一)' },
36
+ url: { type: 'string', description: '公网 http(s) 地址(与 path 二选一;含 SSRF 守卫,拒绝内网/回环地址)' },
37
+ tags: { type: 'array', items: { type: 'string' }, description: '可选:附件标签' },
38
+ noteTitle: { type: 'string', description: '可选:把该附件嵌入到这篇笔记末尾(图片用 [img[标题]],其它用 [[标题]] 链接)' },
39
+ expectedModified: { type: 'string', description: '可选:乐观并发保护,仅在同名 tiddler 已存在时有意义(传 tiddlywiki_get 读到的 modified)' },
40
+ expectedRevision: { type: 'integer', description: '可选:乐观并发保护的另一种令牌——传 tiddlywiki_get 返回字段里的 revision' },
41
+ force: { type: 'boolean', description: '可选:true 时忽略 expectedModified/expectedRevision,允许覆盖同名 tiddler(默认 false;即便覆盖也会保留其 tags 与自定义字段)' },
42
+ },
43
+ output: {
44
+ render: (_args, value: AttachResult) => {
45
+ const lines = [`已保存附件「${value.title}」(${value.mime},${value.bytes} 字节,base64 约 ${value.chars} 字符)`]
46
+ if (value.source !== null) lines.push(`来源: ${value.source}`)
47
+ if (value.embedInto !== null) lines.push(`已嵌入笔记「${value.embedInto}」`)
48
+ lines.push(`打开: [${value.title}](/dsh-tiddlywiki/tw/#${encodeURIComponent(value.title)})`)
49
+ return [{ type: 'text', text: lines.join('\n') }]
50
+ },
51
+ },
52
+ execute: async (args: { title: string; path?: string; url?: string; tags?: string[]; noteTitle?: string; expectedModified?: string; expectedRevision?: number; force?: boolean }, exec: unknown): Promise<AttachResult> => {
53
+ const wiki = requireWiki(sessionIdOf(exec))
54
+ const title = args.title.trim()
55
+ if (title.length === 0) throw new Error('tiddlywiki_attach: title 不能为空')
56
+ const hasPath = typeof args.path === 'string' && args.path.trim().length > 0
57
+ const hasUrl = typeof args.url === 'string' && args.url.trim().length > 0
58
+ if (hasPath === hasUrl) throw new Error('tiddlywiki_attach: path 与 url 必须且只能提供一个')
59
+ let buffer: Buffer
60
+ let mime: string
61
+ let source: string
62
+ if (hasPath) {
63
+ const filePath = (args.path as string).trim()
64
+ // Absolute only: a relative path would resolve against the DSH process
65
+ // cwd, which is not something the model can reason about.
66
+ if (!isAbsolute(filePath)) throw new Error('tiddlywiki_attach: path 必须是绝对路径')
67
+ const info = await stat(filePath)
68
+ if (!info.isFile()) throw new Error(`tiddlywiki_attach: ${basename(filePath)} 不是普通文件`)
69
+ if (info.size > MAX_ATTACH_BYTES) throw new Error(`tiddlywiki_attach: 文件超过 ${Math.floor(MAX_ATTACH_BYTES / 1024 / 1024)}MB 上限`)
70
+ buffer = await readFile(filePath)
71
+ const ext = extname(filePath).slice(1).toLowerCase()
72
+ mime = ATTACH_MIME_BY_EXT[ext] ?? 'application/octet-stream'
73
+ source = filePath
74
+ } else {
75
+ const imageUrl = (args.url as string).trim()
76
+ const downloaded = await downloadClipImage(imageUrl, '')
77
+ buffer = downloaded.buffer
78
+ const ext = extname(new URL(imageUrl).pathname).slice(1).toLowerCase()
79
+ mime = downloaded.type?.split(';')[0]?.trim() || ATTACH_MIME_BY_EXT[ext] || 'application/octet-stream'
80
+ source = imageUrl
81
+ }
82
+ if (buffer.length === 0) throw new Error('tiddlywiki_attach: 内容为空')
83
+ if (buffer.length > MAX_ATTACH_BYTES) throw new Error(`tiddlywiki_attach: 内容超过 ${Math.floor(MAX_ATTACH_BYTES / 1024 / 1024)}MB 上限`)
84
+ // DATA SAFETY (v0.19.5): this used to `wiki.put({title, type, text})` with
85
+ // no read at all — attaching an image whose title collided with an existing
86
+ // note silently replaced that note (tags, custom fields and body all gone),
87
+ // the exact class the write policy exists to prevent. It also never added
88
+ // the `agent-written` tag every other creating tool adds. Read first (404 =
89
+ // new tiddler; any other failure propagates), then build the PUT from the
90
+ // existing tiddler so a same-named note keeps everything but its body.
91
+ const existing = await wiki.get(title)
92
+ assertNoConflict(title, existing, {
93
+ expectedModified: args.expectedModified,
94
+ expectedRevision: args.expectedRevision,
95
+ force: args.force,
96
+ })
97
+ // An attachment sharing a title with an existing tiddler is almost always
98
+ // a mistake (the old code silently destroyed the note). Require explicit
99
+ // consent: a concurrency token (the caller proved it read the tiddler) or
100
+ // `force: true`. `expectedRevision`/`expectedModified` alone does NOT
101
+ // consent to an overwrite — `assertNoConflict` above only rejects when the
102
+ // tiddler changed since that token, so a stale-but-matching token would
103
+ // still wipe the body.
104
+ if (existing !== undefined && args.force !== true) {
105
+ throw new Error(
106
+ `tiddlywiki_attach: 标题「${title}」已存在(type=${typeof existing.type === 'string' ? existing.type : '?'})。`
107
+ + '为避免静默覆盖既有笔记,请换一个附件标题;确认要覆盖时传 force: true(tags 与自定义字段仍会保留)。',
108
+ )
109
+ }
110
+ const explicitTags = Array.isArray(args.tags)
111
+ ? args.tags.filter((t) => typeof t === 'string' && t.trim().length > 0)
112
+ : undefined
113
+ const { tiddler } = buildWriteTiddler(title, buffer.toString('base64'), {
114
+ existing,
115
+ ...(explicitTags !== undefined && explicitTags.length > 0 ? { tags: explicitTags } : {}),
116
+ fields: {
117
+ type: mime,
118
+ 'attach-source': source,
119
+ 'attach-at': new Date().toISOString(),
120
+ },
121
+ })
122
+ await wiki.put(tiddler)
123
+ let embedInto: string | null = null
124
+ if (typeof args.noteTitle === 'string' && args.noteTitle.trim().length > 0) {
125
+ embedInto = args.noteTitle.trim()
126
+ const note = await wiki.get(embedInto)
127
+ // A binary tiddler holds base64 in `text`: appending an embed line would
128
+ // corrupt it (and `type: image/png` would stay, so the receipt would look
129
+ // fine). Same class `tiddlywiki_put` refuses — refuse here too (v0.25.0).
130
+ if (note !== undefined && isBinaryType(typeof note.type === 'string' ? note.type : undefined)) {
131
+ throw new Error(
132
+ `tiddlywiki_attach: noteTitle「${embedInto}」是二进制附件(type=${String(note.type)}),`
133
+ + '把嵌入链接写进去会写坏附件;请改用普通笔记,或去掉 noteTitle 参数单独保存附件。',
134
+ )
135
+ }
136
+ // `[img[Title]]` breaks if the attachment title itself contains `]]`;
137
+ // fall back to a plain link (which has the same constraint, so strip the
138
+ // sequence) instead of silently producing a broken embed.
139
+ const safeTitle = title.replace(/\]\]/g, '] ]')
140
+ const embed = mime.startsWith('image/') ? `[img[${safeTitle}]]` : `[[${safeTitle}]]`
141
+ const text = note === undefined ? embed : `${(note.text ?? '').replace(/\s+$/, '')}\n\n${embed}`
142
+ // Same read-modify-write policy as everywhere else: preserve the note's
143
+ // tags/custom fields/type, only append the embed.
144
+ const { tiddler: noteTiddler } = buildWriteTiddler(embedInto, text, { existing: note })
145
+ await wiki.put(noteTiddler)
146
+ }
147
+ deps.autoCommit()
148
+ return { ok: true, title, mime, bytes: buffer.length, chars: buffer.toString('base64').length, source, embedInto }
149
+ },
150
+ })
151
+ }
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Git-facing `tiddlywiki_*` tools: git_sync / git_resolve, plus the shared
3
+ * status + receipt renders they use.
4
+ *
5
+ * Split out of `tools.ts` in v0.28.8 — pure code move, bodies unchanged.
6
+ *
7
+ * @module dsh-tiddlywiki/host/tools-git
8
+ */
9
+ import { join } from 'node:path'
10
+ import { defineTool } from '../sdk.ts'
11
+ import { GitConflictStateError } from './git.ts'
12
+ import type { GitStatusView } from './git.ts'
13
+ import { flushPendingWrites } from './seeds.ts'
14
+ import { sessionIdOf } from './tools-support.ts'
15
+ import type { ResolveResult, SyncResult, ToolEnv } from './tools-support.ts'
16
+
17
+ /** One-line 状态 summary: 分支 … 领先 … 落后 … 工作区未提交 … 最近提交. */
18
+ function gitStatusBits(s: GitStatusView): string {
19
+ const bits = [`分支 ${s.branch}`]
20
+ if (s.ahead !== undefined) bits.push(`领先 ${s.ahead}`)
21
+ if (s.behind !== undefined) bits.push(`落后 ${s.behind}`)
22
+ if (s.dirty) bits.push(`工作区有 ${s.dirtyFiles.length} 个未提交改动`)
23
+ if (s.lastCommit !== undefined) bits.push(`最近提交 ${s.lastCommit}`)
24
+ return bits.join(' · ')
25
+ }
26
+
27
+ function renderSync(value: SyncResult): Array<{ type: 'text'; text: string }> {
28
+ const lines = [`git ${value.action}: ${value.ok ? '成功' : '失败'}`]
29
+ lines.push(` ${value.message}`)
30
+ if (value.conflictFiles !== undefined && value.conflictFiles.length > 0) {
31
+ lines.push(`冲突文件(rebase 已 abort,勿自动覆盖):`)
32
+ for (const f of value.conflictFiles) lines.push(` - ${f}`)
33
+ lines.push('处理方式:用 tiddlywiki_git_resolve files=[以上文件] strategy=keep-local|keep-remote 按 tiddler 二选一解决,再重新 sync;也可以直接让用户处理。')
34
+ }
35
+ if (value.commit !== undefined) lines.push(`本地 commit: ${value.commit}`)
36
+ if (value.push !== undefined) lines.push(`远端 push: ${value.push}`)
37
+ if (value.changed === true) {
38
+ lines.push(value.restarted !== undefined && value.restarted.length > 0
39
+ ? `本次 pull 拉取了新内容,已重启:${value.restarted.join('、')}(同端口),其读取/搜索均为最新快照。`
40
+ : '本次 pull 拉取了新内容,但没有正在运行的知识库受影响(无需重启,或改动落在未运行的库里)。')
41
+ }
42
+ if (value.restartFailed !== undefined) {
43
+ for (const item of value.restartFailed) lines.push(`TW 重启失败:${item.id} —— ${item.message}`)
44
+ }
45
+ if (value.status !== undefined) {
46
+ lines.push(`状态: ${gitStatusBits(value.status)}`)
47
+ const s = value.status
48
+ if (s.dirty && s.dirtyFiles.length > 0) lines.push(` 未提交: ${s.dirtyFiles.join(', ')}`)
49
+ }
50
+ return [{ type: 'text', text: lines.join('\n') }]
51
+ }
52
+
53
+ export function gitSyncTool(env: ToolEnv) {
54
+ const { deps, requireWiki } = env
55
+ // ── tiddlywiki_git_sync ──────────────────────────────────────────────────
56
+ return defineTool({
57
+ name: 'tiddlywiki_git_sync',
58
+ description: '对 TiddlyWiki 知识库的 git 仓库做同步:pull(拉取远端并 rebase 本地,冲突则 abort 并报文件)、push(推送本地提交到远端)、sync(pull → commit 本地改动 → push)。未配置 git.remote 时 push 会失败并提示。',
59
+ parameters: {
60
+ action: { type: 'string', enum: ['pull', 'push', 'sync'], description: '要执行的 git 操作', required: true },
61
+ message: { type: 'string', description: 'commit 信息(可选,仅 sync 的本地 commit 使用)' },
62
+ },
63
+ output: {
64
+ render: (_args, value: SyncResult) => renderSync(value),
65
+ },
66
+ execute: async (args: { action: 'pull' | 'push' | 'sync'; message?: string }, exec: unknown): Promise<SyncResult> => {
67
+ const dir = deps.wikiPath()
68
+ /**
69
+ * Restart the RUNNING wikis whose content this pull changed.
70
+ *
71
+ * `changedFiles` is what makes this correct with several knowledge bases in
72
+ * one repository: restarting "the wiki I happened to pull from" would miss
73
+ * the one that actually changed, and would interrupt a wiki nothing
74
+ * happened to (v0.28.0).
75
+ */
76
+ const restartIfChanged = async (pulled: { changed?: boolean; changedFiles?: string[] }): Promise<{ restarted?: string[]; restartFailed?: Array<{ id: string; message: string }> }> => {
77
+ if (pulled.changed !== true) return {}
78
+ if (deps.restartAffected === undefined) return {}
79
+ try {
80
+ // DRAIN THE SYNCER FIRST (v0.19.1, data safety): a PUT answers 204 as
81
+ // soon as the tiddler is in TW's in-memory store; the filesystem
82
+ // syncer writes it ~250ms later. Restarting TW before that flush KILLS
83
+ // the write (the restarted server boots from the old snapshot and the
84
+ // note is gone — not even the git commit that follows can recover it).
85
+ // The agent path is the risky one: `tiddlywiki_put` → `git_sync`
86
+ // back-to-back. Same sentinel trick as seeds.ts / index.ts.
87
+ await flushPendingWrites(requireWiki(sessionIdOf(exec)), join(dir, 'tiddlers')).catch(() => undefined)
88
+ const outcome = await deps.restartAffected(dir, pulled.changedFiles ?? [])
89
+ return {
90
+ ...(outcome.restarted.length > 0 ? { restarted: outcome.restarted } : {}),
91
+ ...(outcome.failed.length > 0 ? { restartFailed: outcome.failed } : {}),
92
+ }
93
+ } catch (err) {
94
+ return { restartFailed: [{ id: '(全部)', message: err instanceof Error ? err.message : String(err) }] }
95
+ }
96
+ }
97
+ switch (args.action) {
98
+ case 'pull': {
99
+ const r = await deps.git.pull(dir)
100
+ const restart = await restartIfChanged(r)
101
+ return { action: args.action, ok: r.ok, message: r.message, ...(r.conflictFiles !== undefined ? { conflictFiles: r.conflictFiles } : {}), ...(r.changed === true ? { changed: true } : {}), ...restart }
102
+ }
103
+ case 'push': {
104
+ const r = await deps.git.push(dir)
105
+ return { action: args.action, ok: r.ok, message: r.message }
106
+ }
107
+ case 'sync': {
108
+ const pulled = await deps.git.pull(dir)
109
+ if (!pulled.ok) return { action: args.action, ok: false, message: pulled.message, ...(pulled.conflictFiles !== undefined ? { conflictFiles: pulled.conflictFiles } : {}) }
110
+ const restart = await restartIfChanged(pulled)
111
+ // The commit guard (v0.23.4) turns a conflicted tree into a structured
112
+ // failure instead of a thrown error: the model must SEE why nothing was
113
+ // committed, otherwise it would report「同步完成」over broken content.
114
+ let committed: { committed: boolean; message: string }
115
+ try {
116
+ committed = await deps.git.commit(dir, args.message ?? `sync ${new Date().toISOString()}`)
117
+ } catch (err) {
118
+ if (err instanceof GitConflictStateError) {
119
+ return { action: args.action, ok: false, message: err.message, conflictFiles: err.files, ...restart }
120
+ }
121
+ throw err
122
+ }
123
+ const pushed = await deps.git.push(dir)
124
+ const status = await deps.git.status(dir)
125
+ return {
126
+ action: args.action,
127
+ ok: pushed.ok,
128
+ message: pushed.ok ? '同步完成' : pushed.message,
129
+ pull: 'ok',
130
+ ...(pulled.changed === true ? { changed: true } : {}),
131
+ ...restart,
132
+ commit: committed.message,
133
+ push: pushed.message,
134
+ status,
135
+ }
136
+ }
137
+ }
138
+ },
139
+ })
140
+ }
141
+
142
+ export function gitResolveTool(env: ToolEnv) {
143
+ const { deps } = env
144
+ // ── tiddlywiki_git_resolve ───────────────────────────────────────────────
145
+ return defineTool({
146
+ name: 'tiddlywiki_git_resolve',
147
+ description: '在 tiddlywiki_git_sync action=pull 冲突(已 abort)后,按 tiddler 二选一解决:keep-local 保留本地版本;keep-remote 用 git fetch 拉取远端并检出远端版本(需已配置 git.remote);list 仅报告当前状态。解决后建议重新 pull/sync 整合其余改动。',
148
+ parameters: {
149
+ strategy: { type: 'string', enum: ['keep-local', 'keep-remote', 'list'], description: 'keep-local=保留本地;keep-remote=改用远端版本;list=仅报告当前 git 状态', required: true },
150
+ files: { type: 'array', items: { type: 'string' }, description: '冲突文件名数组(来自 pull 返回的 conflictFiles;list 时忽略)' },
151
+ },
152
+ output: {
153
+ render: (_args, value: ResolveResult) => {
154
+ const lines = [`git resolve ${value.action}: ${value.ok ? '成功' : '失败'}`]
155
+ lines.push(` ${value.message}`)
156
+ if (value.files !== undefined && value.files.length > 0) lines.push(`涉及文件: ${value.files.join(', ')}`)
157
+ if (value.commit !== undefined) lines.push(`本地 commit: ${value.commit}`)
158
+ if (value.status !== undefined) lines.push(`状态: ${gitStatusBits(value.status)}`)
159
+ return [{ type: 'text', text: lines.join('\n') }]
160
+ },
161
+ },
162
+ execute: async (args: { strategy: 'keep-local' | 'keep-remote' | 'list'; files?: string[] }, exec: unknown): Promise<ResolveResult> => {
163
+ const dir = deps.wikiPath()
164
+ if (args.strategy === 'list') {
165
+ const status = await deps.git.status(dir)
166
+ return { ok: true, action: 'list', message: '当前仓库状态(pull 冲突已 abort,工作区即本地版本,不会残留未合并状态)', status }
167
+ }
168
+ const files = (args.files ?? []).filter((f) => typeof f === 'string' && f.length > 0)
169
+ if (files.length === 0) {
170
+ return { ok: false, action: args.strategy, message: '请提供 conflictFiles(来自 pull 返回)', hint: '可先执行 tiddlywiki_git_sync action=pull 查看冲突文件' }
171
+ }
172
+ if (args.strategy === 'keep-local') {
173
+ const status = await deps.git.status(dir)
174
+ return {
175
+ ok: true,
176
+ action: 'keep-local',
177
+ message: `已保留本地版本(${files.length} 个文件;abort 后本地即为工作区内容)。建议重新 tiddlywiki_git_sync action=sync 整合远端其余改动。`,
178
+ files,
179
+ status,
180
+ }
181
+ }
182
+ const fetched = await deps.git.fetch(dir)
183
+ if (!fetched.ok) {
184
+ return { ok: false, action: 'keep-remote', message: `fetch 失败(可能未配置 git.remote):${fetched.message}` }
185
+ }
186
+ const checked = await deps.git.checkoutFetchHead(dir, files)
187
+ if (!checked.ok) {
188
+ return { ok: false, action: 'keep-remote', message: `从远端检出失败:${checked.message}` }
189
+ }
190
+ // Same guard as git_sync: resolving one file may still leave other
191
+ // conflicted files behind — report that instead of throwing (v0.23.4).
192
+ let committed: { committed: boolean; message: string }
193
+ try {
194
+ committed = await deps.git.commit(dir, `resolve conflict (keep remote) ${new Date().toISOString()}`)
195
+ } catch (err) {
196
+ if (err instanceof GitConflictStateError) {
197
+ return { ok: false, action: 'keep-remote', message: err.message, files: err.files }
198
+ }
199
+ throw err
200
+ }
201
+ deps.autoCommit()
202
+ const status = await deps.git.status(dir)
203
+ return {
204
+ ok: true,
205
+ action: 'keep-remote',
206
+ message: `已把 ${files.length} 个冲突文件改为远端版本并提交。建议继续 tiddlywiki_git_sync action=sync 完成整合与推送。`,
207
+ files,
208
+ commit: committed.message,
209
+ status,
210
+ }
211
+ },
212
+ })
213
+ }