zcode-app-cli 3.3.5-1

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 (169) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +642 -0
  3. package/bin/zcode.js +848 -0
  4. package/config.example.json +110 -0
  5. package/package.json +81 -0
  6. package/vendor/.node-bundle-meta.json +6 -0
  7. package/vendor/extraction.json +11 -0
  8. package/vendor/node_modules/@zcode/tui/dist/index.js +161875 -0
  9. package/vendor/node_modules/@zcode/tui/package.json +14 -0
  10. package/vendor/packages/android-emulator-plugin/.mcp.json +19 -0
  11. package/vendor/packages/android-emulator-plugin/.zcode-plugin/plugin.json +63 -0
  12. package/vendor/packages/android-emulator-plugin/README.md +134 -0
  13. package/vendor/packages/android-emulator-plugin/commands/android-dev.md +11 -0
  14. package/vendor/packages/android-emulator-plugin/dist/lib/path.d.ts +4 -0
  15. package/vendor/packages/android-emulator-plugin/dist/lib/path.js +17 -0
  16. package/vendor/packages/android-emulator-plugin/dist/lib/result.d.ts +5 -0
  17. package/vendor/packages/android-emulator-plugin/dist/lib/result.js +22 -0
  18. package/vendor/packages/android-emulator-plugin/dist/lib/run.d.ts +18 -0
  19. package/vendor/packages/android-emulator-plugin/dist/lib/run.js +99 -0
  20. package/vendor/packages/android-emulator-plugin/dist/mcp/server.d.ts +3 -0
  21. package/vendor/packages/android-emulator-plugin/dist/mcp/server.js +47607 -0
  22. package/vendor/packages/android-emulator-plugin/dist/providers/app.d.ts +39 -0
  23. package/vendor/packages/android-emulator-plugin/dist/providers/app.js +50 -0
  24. package/vendor/packages/android-emulator-plugin/dist/providers/avd.d.ts +37 -0
  25. package/vendor/packages/android-emulator-plugin/dist/providers/avd.js +185 -0
  26. package/vendor/packages/android-emulator-plugin/dist/providers/build.d.ts +68 -0
  27. package/vendor/packages/android-emulator-plugin/dist/providers/build.js +131 -0
  28. package/vendor/packages/android-emulator-plugin/dist/providers/config.d.ts +7 -0
  29. package/vendor/packages/android-emulator-plugin/dist/providers/config.js +29 -0
  30. package/vendor/packages/android-emulator-plugin/dist/providers/device.d.ts +20 -0
  31. package/vendor/packages/android-emulator-plugin/dist/providers/device.js +91 -0
  32. package/vendor/packages/android-emulator-plugin/dist/providers/logs.d.ts +15 -0
  33. package/vendor/packages/android-emulator-plugin/dist/providers/logs.js +31 -0
  34. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.d.ts +15 -0
  35. package/vendor/packages/android-emulator-plugin/dist/providers/preflight.js +123 -0
  36. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.d.ts +13 -0
  37. package/vendor/packages/android-emulator-plugin/dist/providers/project-template.js +211 -0
  38. package/vendor/packages/android-emulator-plugin/dist/providers/project.d.ts +33 -0
  39. package/vendor/packages/android-emulator-plugin/dist/providers/project.js +195 -0
  40. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.d.ts +14 -0
  41. package/vendor/packages/android-emulator-plugin/dist/providers/screenshot.js +73 -0
  42. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.d.ts +14 -0
  43. package/vendor/packages/android-emulator-plugin/dist/providers/sdk.js +185 -0
  44. package/vendor/packages/android-emulator-plugin/dist/providers/ui.d.ts +92 -0
  45. package/vendor/packages/android-emulator-plugin/dist/providers/ui.js +146 -0
  46. package/vendor/packages/android-emulator-plugin/hooks/hooks.json +3 -0
  47. package/vendor/packages/android-emulator-plugin/package.json +35 -0
  48. package/vendor/packages/android-emulator-plugin/skills/android-dev/INSTALL_ENVIRONMENT.md +357 -0
  49. package/vendor/packages/android-emulator-plugin/skills/android-dev/SKILL.md +73 -0
  50. package/vendor/packages/android-emulator-plugin/templates/compose-app/README.md +5 -0
  51. package/vendor/packages/document-skills-plugin/.zcode-plugin/plugin.json +8 -0
  52. package/vendor/packages/document-skills-plugin/package.json +8 -0
  53. package/vendor/packages/document-skills-plugin/skills/docx/LICENSE.txt +13 -0
  54. package/vendor/packages/document-skills-plugin/skills/docx/SKILL.md +201 -0
  55. package/vendor/packages/document-skills-plugin/skills/docx/references/chart-templates.md +386 -0
  56. package/vendor/packages/document-skills-plugin/skills/docx/references/common-rules.md +419 -0
  57. package/vendor/packages/document-skills-plugin/skills/docx/references/decorations.md +537 -0
  58. package/vendor/packages/document-skills-plugin/skills/docx/references/design-system.md +1797 -0
  59. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-advanced.md +257 -0
  60. package/vendor/packages/document-skills-plugin/skills/docx/references/docx-js-core.md +332 -0
  61. package/vendor/packages/document-skills-plugin/skills/docx/references/faq.md +323 -0
  62. package/vendor/packages/document-skills-plugin/skills/docx/references/math-formulas.md +276 -0
  63. package/vendor/packages/document-skills-plugin/skills/docx/references/ooxml.md +222 -0
  64. package/vendor/packages/document-skills-plugin/skills/docx/references/toc.md +264 -0
  65. package/vendor/packages/document-skills-plugin/skills/docx/routes/comment.md +88 -0
  66. package/vendor/packages/document-skills-plugin/skills/docx/routes/create.md +207 -0
  67. package/vendor/packages/document-skills-plugin/skills/docx/routes/edit.md +115 -0
  68. package/vendor/packages/document-skills-plugin/skills/docx/routes/format.md +120 -0
  69. package/vendor/packages/document-skills-plugin/skills/docx/routes/read.md +114 -0
  70. package/vendor/packages/document-skills-plugin/skills/docx/scenes/academic.md +783 -0
  71. package/vendor/packages/document-skills-plugin/skills/docx/scenes/contract.md +463 -0
  72. package/vendor/packages/document-skills-plugin/skills/docx/scenes/copywriting.md +139 -0
  73. package/vendor/packages/document-skills-plugin/skills/docx/scenes/exam.md +698 -0
  74. package/vendor/packages/document-skills-plugin/skills/docx/scenes/official-doc.md +411 -0
  75. package/vendor/packages/document-skills-plugin/skills/docx/scenes/report.md +340 -0
  76. package/vendor/packages/document-skills-plugin/skills/docx/scenes/resume.md +534 -0
  77. package/vendor/packages/document-skills-plugin/skills/docx/scripts/__init__.py +1 -0
  78. package/vendor/packages/document-skills-plugin/skills/docx/scripts/add_toc_placeholders.py +749 -0
  79. package/vendor/packages/document-skills-plugin/skills/docx/scripts/document.py +1333 -0
  80. package/vendor/packages/document-skills-plugin/skills/docx/scripts/postcheck.py +807 -0
  81. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/comments.xml +3 -0
  82. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtended.xml +3 -0
  83. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsExtensible.xml +3 -0
  84. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/commentsIds.xml +3 -0
  85. package/vendor/packages/document-skills-plugin/skills/docx/scripts/templates/people.xml +3 -0
  86. package/vendor/packages/document-skills-plugin/skills/docx/scripts/utilities.py +374 -0
  87. package/vendor/packages/document-skills-plugin/skills/docx/setup.sh +177 -0
  88. package/vendor/packages/document-skills-plugin/skills/pdf/LICENSE.txt +13 -0
  89. package/vendor/packages/document-skills-plugin/skills/pdf/SKILL.md +919 -0
  90. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/academic.md +1058 -0
  91. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/creative.md +770 -0
  92. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/poster.md +702 -0
  93. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process-advanced.md +284 -0
  94. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/process.md +319 -0
  95. package/vendor/packages/document-skills-plugin/skills/pdf/briefs/report.md +1659 -0
  96. package/vendor/packages/document-skills-plugin/skills/pdf/configs/components.md +153 -0
  97. package/vendor/packages/document-skills-plugin/skills/pdf/configs/fonts.md +93 -0
  98. package/vendor/packages/document-skills-plugin/skills/pdf/configs/visual_framework.md +263 -0
  99. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-academic.tex +130 -0
  100. package/vendor/packages/document-skills-plugin/skills/pdf/references/resume-altacv.tex +190 -0
  101. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/cover_validate.js +367 -0
  102. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/design_engine.py +2816 -0
  103. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2pdf-next.js +754 -0
  104. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/html2poster.js +256 -0
  105. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf.py +2959 -0
  106. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/pdf_qa.py +901 -0
  107. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/poster_validate.py +1337 -0
  108. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/setup.sh +269 -0
  109. package/vendor/packages/document-skills-plugin/skills/pdf/scripts/toc_validate.py +2075 -0
  110. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/charts.md +320 -0
  111. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover-backgrounds.md +384 -0
  112. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/cover.md +1442 -0
  113. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/fill-engine.md +527 -0
  114. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/geometry.md +142 -0
  115. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/overflow.md +630 -0
  116. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/pagination.md +367 -0
  117. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/palette.md +217 -0
  118. package/vendor/packages/document-skills-plugin/skills/pdf/typesetting/typography.md +20 -0
  119. package/vendor/packages/ios-simulator-plugin/.mcp.json +15 -0
  120. package/vendor/packages/ios-simulator-plugin/.zcode-plugin/plugin.json +34 -0
  121. package/vendor/packages/ios-simulator-plugin/README.md +111 -0
  122. package/vendor/packages/ios-simulator-plugin/commands/ios-dev.md +11 -0
  123. package/vendor/packages/ios-simulator-plugin/dist/lib/path.d.ts +4 -0
  124. package/vendor/packages/ios-simulator-plugin/dist/lib/path.js +18 -0
  125. package/vendor/packages/ios-simulator-plugin/dist/lib/result.d.ts +5 -0
  126. package/vendor/packages/ios-simulator-plugin/dist/lib/result.js +20 -0
  127. package/vendor/packages/ios-simulator-plugin/dist/lib/run.d.ts +17 -0
  128. package/vendor/packages/ios-simulator-plugin/dist/lib/run.js +83 -0
  129. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.d.ts +3 -0
  130. package/vendor/packages/ios-simulator-plugin/dist/mcp/server.js +46833 -0
  131. package/vendor/packages/ios-simulator-plugin/dist/providers/build.d.ts +112 -0
  132. package/vendor/packages/ios-simulator-plugin/dist/providers/build.js +99 -0
  133. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.d.ts +21 -0
  134. package/vendor/packages/ios-simulator-plugin/dist/providers/logs.js +26 -0
  135. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.d.ts +12 -0
  136. package/vendor/packages/ios-simulator-plugin/dist/providers/preflight.js +62 -0
  137. package/vendor/packages/ios-simulator-plugin/dist/providers/project.d.ts +35 -0
  138. package/vendor/packages/ios-simulator-plugin/dist/providers/project.js +288 -0
  139. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.d.ts +22 -0
  140. package/vendor/packages/ios-simulator-plugin/dist/providers/screenshot.js +30 -0
  141. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.d.ts +60 -0
  142. package/vendor/packages/ios-simulator-plugin/dist/providers/sim.js +116 -0
  143. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.d.ts +57 -0
  144. package/vendor/packages/ios-simulator-plugin/dist/providers/ui.js +67 -0
  145. package/vendor/packages/ios-simulator-plugin/hooks/hooks.json +3 -0
  146. package/vendor/packages/ios-simulator-plugin/package.json +35 -0
  147. package/vendor/packages/ios-simulator-plugin/skills/ios-dev/SKILL.md +45 -0
  148. package/vendor/packages/ios-simulator-plugin/templates/swiftui-app/README.md +5 -0
  149. package/vendor/packages/restore-legacy-sessions-plugin/.zcode-plugin/plugin.json +9 -0
  150. package/vendor/packages/restore-legacy-sessions-plugin/README.md +35 -0
  151. package/vendor/packages/restore-legacy-sessions-plugin/commands/restore-legacy-sessions.md +11 -0
  152. package/vendor/packages/restore-legacy-sessions-plugin/package.json +8 -0
  153. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/SKILL.md +92 -0
  154. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/restore-conversation.mjs +648 -0
  155. package/vendor/packages/restore-legacy-sessions-plugin/skills/restore-legacy-sessions/scripts/scan-legacy-sessions.mjs +422 -0
  156. package/vendor/packages/skill-creator-plugin/.zcode-plugin/plugin.json +8 -0
  157. package/vendor/packages/skill-creator-plugin/package.json +8 -0
  158. package/vendor/packages/skill-creator-plugin/skills/skill-creator/SKILL.md +159 -0
  159. package/vendor/packages/zcode-guide-plugin/.zcode-plugin/plugin.json +8 -0
  160. package/vendor/packages/zcode-guide-plugin/README.md +22 -0
  161. package/vendor/packages/zcode-guide-plugin/package.json +8 -0
  162. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-commands/SKILL.md +66 -0
  163. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-hooks/SKILL.md +66 -0
  164. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-mcp/SKILL.md +97 -0
  165. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-plugins/SKILL.md +59 -0
  166. package/vendor/packages/zcode-guide-plugin/skills/diagnosing-skills/SKILL.md +61 -0
  167. package/vendor/packages/zcode-guide-plugin/skills/zcode-configuration-guide/SKILL.md +99 -0
  168. package/vendor/zcode.cjs +2926 -0
  169. package/zcode-runtime.lock.json +8 -0
@@ -0,0 +1,648 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Restore a single legacy ACP-era conversation snapshot into the new ZCode stores.
4
+ *
5
+ * Usage:
6
+ * restore-conversation.mjs --snapshot <path> [--task-index <path>] [--cli-db <path>]
7
+ *
8
+ * Options:
9
+ * --snapshot <path> Path to the legacy snapshot JSON file (required)
10
+ * --task-index <path> Task index sqlite path. Default: ~/.zcode/v2/tasks-index.sqlite
11
+ * --cli-db <path> New ZCode session sqlite path. Default: ~/.zcode/cli/db/db.sqlite
12
+ * --dry-run Print what would be done without writing
13
+ */
14
+
15
+ import { copyFileSync, existsSync, readFileSync, statSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { basename, dirname, join } from "node:path";
18
+
19
+ const originalEmitWarning = process.emitWarning;
20
+ process.emitWarning = function filterSqliteExperimentalWarning(warning, ...args) {
21
+ if (String(warning).includes("SQLite is an experimental feature")) return;
22
+ return originalEmitWarning.call(process, warning, ...args);
23
+ };
24
+ const { DatabaseSync } = await import("node:sqlite");
25
+ process.emitWarning = originalEmitWarning;
26
+
27
+ const ZCODE_PROVIDER = "glm";
28
+ const defaultTaskIndexPath = join(homedir(), ".zcode", "v2", "tasks-index.sqlite");
29
+ const defaultCliDbPath = join(homedir(), ".zcode", "cli", "db", "db.sqlite");
30
+
31
+ function parseArgs(argv) {
32
+ const args = {
33
+ snapshot: null,
34
+ taskIndexPath: defaultTaskIndexPath,
35
+ cliDbPath: defaultCliDbPath,
36
+ dryRun: false,
37
+ };
38
+
39
+ for (let i = 0; i < argv.length; i++) {
40
+ const item = argv[i];
41
+ if (item === "--dry-run") {
42
+ args.dryRun = true;
43
+ continue;
44
+ }
45
+
46
+ const next = argv[++i];
47
+ if (!next) throw new Error(`Missing value for ${item}`);
48
+ if (item === "--snapshot") args.snapshot = next;
49
+ else if (item === "--task-index") args.taskIndexPath = next;
50
+ else if (item === "--cli-db") args.cliDbPath = next;
51
+ else throw new Error(`Unknown option: ${item}`);
52
+ }
53
+
54
+ if (!args.snapshot) throw new Error("--snapshot is required");
55
+ if (!existsSync(args.snapshot)) throw new Error(`Snapshot not found: ${args.snapshot}`);
56
+ return args;
57
+ }
58
+
59
+ function ensureExistingDb(path, label) {
60
+ if (!existsSync(path)) throw new Error(`${label} not found: ${path}`);
61
+ const stat = statSync(path);
62
+ if (!stat.isFile() || stat.size === 0) {
63
+ throw new Error(`${label} is not a populated sqlite file: ${path}`);
64
+ }
65
+ }
66
+
67
+ function backupDb(path) {
68
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
69
+ const backupPath = `${path}.bak-${stamp}`;
70
+ copyFileSync(path, backupPath);
71
+ return backupPath;
72
+ }
73
+
74
+ function projectIdFromPath(workspacePath) {
75
+ // 保持和现有 CLI session project_id 约定一致。
76
+ return "proj_" + workspacePath.replace(/^\//, "").replace(/\//g, "-");
77
+ }
78
+
79
+ function workspaceKey(workspacePath, workspaceIdentity) {
80
+ return (workspaceIdentity || "").trim() || workspacePath;
81
+ }
82
+
83
+ function optionalString(value) {
84
+ return typeof value === "string" && value.trim().length > 0 ? value : undefined;
85
+ }
86
+
87
+ function optionalNumber(value) {
88
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
89
+ }
90
+
91
+ function removeUndefined(value) {
92
+ return Object.fromEntries(
93
+ Object.entries(value).filter(([, entryValue]) => entryValue !== undefined),
94
+ );
95
+ }
96
+
97
+ function jsonObject(value) {
98
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
99
+ }
100
+
101
+ function jsonText(value) {
102
+ if (value === undefined || value === null) return "";
103
+ return typeof value === "string" ? value : JSON.stringify(value);
104
+ }
105
+
106
+ function messageContent(message) {
107
+ return typeof message.content === "string"
108
+ ? message.content
109
+ : message.content === undefined || message.content === null
110
+ ? ""
111
+ : String(message.content);
112
+ }
113
+
114
+ function messageCompletedAt(message, messageTimestamp) {
115
+ return typeof message.timestamp === "number"
116
+ ? message.timestamp + (optionalNumber(message.durationMs) ?? 0)
117
+ : messageTimestamp;
118
+ }
119
+
120
+ function legacyToolName(tool) {
121
+ const raw = jsonObject(tool.raw);
122
+ const meta = jsonObject(raw._meta);
123
+ const claudeCode = jsonObject(meta.claudeCode);
124
+ return (
125
+ optionalString(claudeCode.toolName) ||
126
+ optionalString(tool.toolName) ||
127
+ optionalString(tool.name) ||
128
+ optionalString(tool.kind) ||
129
+ optionalString(tool.title) ||
130
+ "legacy_tool"
131
+ );
132
+ }
133
+
134
+ function legacyToolTitle(tool, toolName) {
135
+ return optionalString(tool.title) || toolName;
136
+ }
137
+
138
+ function legacyToolCallId(messageId, toolIndex, tool) {
139
+ return (
140
+ optionalString(tool.id) ||
141
+ optionalString(tool.callID) ||
142
+ optionalString(tool.callId) ||
143
+ `call_legacy_${messageId}_${toolIndex}`
144
+ );
145
+ }
146
+
147
+ function legacyToolMetadata(tool) {
148
+ return removeUndefined({
149
+ legacyRestore: true,
150
+ legacyKind: optionalString(tool.kind),
151
+ legacyStatus: optionalString(tool.status),
152
+ });
153
+ }
154
+
155
+ function buildToolPartData(tool, messageId, toolIndex, messageTimestamp, completedAt) {
156
+ const toolName = legacyToolName(tool);
157
+ const input = jsonObject(tool.input);
158
+ const metadata = legacyToolMetadata(tool);
159
+ const status = optionalString(tool.status) || "completed";
160
+ const startedAt = optionalNumber(tool.startedAt) ?? messageTimestamp;
161
+ const endedAt = optionalNumber(tool.completedAt) ?? completedAt;
162
+ let state;
163
+
164
+ // Bugfix: CLI session-store 持久化的是 contracts 形状,tool 时间必须放在 state.time。
165
+ // 如果直接写 protocol 的 startedAt/completedAt,app-server 映射 session/read 时会读不到 state.time 而失败。
166
+ if (status === "running") {
167
+ state = {
168
+ status: "running",
169
+ input,
170
+ title: legacyToolTitle(tool, toolName),
171
+ metadata,
172
+ time: { start: startedAt },
173
+ };
174
+ } else if (status === "pending") {
175
+ state = {
176
+ status: "pending",
177
+ input,
178
+ raw: jsonText(tool.raw || tool),
179
+ };
180
+ } else if (status === "failed" || status === "error" || status === "denied") {
181
+ state = {
182
+ status: "error",
183
+ input,
184
+ error: jsonText(tool.error || tool.output || status),
185
+ metadata,
186
+ time: { start: startedAt, end: endedAt },
187
+ };
188
+ } else {
189
+ state = {
190
+ status: "completed",
191
+ input,
192
+ output: jsonText(tool.output),
193
+ title: legacyToolTitle(tool, toolName),
194
+ metadata,
195
+ time: { start: startedAt, end: endedAt },
196
+ };
197
+ }
198
+
199
+ return {
200
+ type: "tool",
201
+ callID: legacyToolCallId(messageId, toolIndex, tool),
202
+ tool: toolName,
203
+ state,
204
+ };
205
+ }
206
+
207
+ function buildTextPartData(text, messageTimestamp, completedAt) {
208
+ return {
209
+ type: "text",
210
+ text,
211
+ time: {
212
+ start: messageTimestamp,
213
+ end: completedAt,
214
+ },
215
+ };
216
+ }
217
+
218
+ function buildReasoningPartData(text, messageTimestamp, completedAt) {
219
+ return {
220
+ type: "reasoning",
221
+ text,
222
+ time: {
223
+ start: messageTimestamp,
224
+ end: completedAt,
225
+ },
226
+ };
227
+ }
228
+
229
+ function buildPartDataList(message, messageId, messageTimestamp) {
230
+ const content = messageContent(message);
231
+ const completedAt = messageCompletedAt(message, messageTimestamp);
232
+ const tools = Array.isArray(message.tools) ? message.tools : [];
233
+ const persistedParts = Array.isArray(message.parts) ? message.parts : [];
234
+ const partDataList = [];
235
+
236
+ if (message.role === "assistant" && persistedParts.length > 0) {
237
+ for (const part of persistedParts) {
238
+ if (part?.type === "content" && typeof part.content === "string" && part.content.length > 0) {
239
+ partDataList.push(buildTextPartData(part.content, messageTimestamp, completedAt));
240
+ } else if (
241
+ part?.type === "thought" &&
242
+ typeof part.content === "string" &&
243
+ part.content.length > 0
244
+ ) {
245
+ partDataList.push(buildReasoningPartData(part.content, messageTimestamp, completedAt));
246
+ } else if (part?.type === "tool-call" && Number.isInteger(part.toolIndex)) {
247
+ const tool = tools[part.toolIndex];
248
+ if (tool) {
249
+ partDataList.push(
250
+ buildToolPartData(tool, messageId, part.toolIndex, messageTimestamp, completedAt),
251
+ );
252
+ }
253
+ }
254
+ }
255
+ } else {
256
+ const thought = optionalString(message.thought);
257
+ if (message.role === "assistant" && thought) {
258
+ partDataList.push(buildReasoningPartData(thought, messageTimestamp, completedAt));
259
+ }
260
+ if (content.length > 0) {
261
+ partDataList.push(buildTextPartData(content, messageTimestamp, completedAt));
262
+ }
263
+ for (const [toolIndex, tool] of tools.entries()) {
264
+ partDataList.push(buildToolPartData(tool, messageId, toolIndex, messageTimestamp, completedAt));
265
+ }
266
+ }
267
+
268
+ const hasVisibleText = partDataList.some(
269
+ (part) => (part.type === "text" || part.type === "reasoning") && part.text.length > 0,
270
+ );
271
+ if (!hasVisibleText && content.length > 0) {
272
+ partDataList.push(buildTextPartData(content, messageTimestamp, completedAt));
273
+ }
274
+ return partDataList;
275
+ }
276
+
277
+ function buildRestorePlan(snapshotPath) {
278
+ const raw = JSON.parse(readFileSync(snapshotPath, "utf8"));
279
+ const meta = raw.meta || {};
280
+ const messages = Array.isArray(raw.messages) ? raw.messages : [];
281
+
282
+ const legacyTaskId = String(meta.taskId || basename(snapshotPath, ".json"));
283
+ const acpSessionId = optionalString(meta.acpSessionId) || "";
284
+ const restoredTaskId = acpSessionId || legacyTaskId;
285
+ const workspacePath = optionalString(meta.workspacePath) || "";
286
+ if (!workspacePath) {
287
+ throw new Error(`Snapshot has no workspacePath: ${snapshotPath}`);
288
+ }
289
+
290
+ const workspaceIdentity = optionalString(meta.workspaceIdentity) || "";
291
+ const workspaceHash = basename(dirname(snapshotPath));
292
+ const sourceProvider = optionalString(meta.provider) || "unknown";
293
+ const title = optionalString(meta.title) || "Untitled session";
294
+ const mode = optionalString(meta.mode) || "build";
295
+ const model = optionalString(meta.model) || "";
296
+ const traceId = optionalString(meta.traceId) || `zcode-${restoredTaskId}`;
297
+ const createdAt = optionalNumber(meta.createdAt) ?? Date.now();
298
+ const updatedAt = optionalNumber(meta.updatedAt) ?? createdAt;
299
+
300
+ // 旧 ACP provider 只代表来源。恢复后的新 ZCode 任务必须按 glm 写入,否则任务列表会被过滤掉。
301
+ const normalizedMeta = removeUndefined({
302
+ ...meta,
303
+ taskId: restoredTaskId,
304
+ traceId,
305
+ title,
306
+ workspacePath,
307
+ workspaceIdentity: workspaceIdentity || undefined,
308
+ createdAt,
309
+ updatedAt,
310
+ mode,
311
+ model: model || undefined,
312
+ thoughtLevel: optionalString(meta.thoughtLevel),
313
+ runtimeEpoch: optionalNumber(meta.runtimeEpoch),
314
+ provider: ZCODE_PROVIDER,
315
+ legacyTaskId,
316
+ restoredTaskId,
317
+ workspaceHash,
318
+ messageCount: messages.length,
319
+ migrationSource: undefined,
320
+ });
321
+
322
+ return {
323
+ snapshotPath,
324
+ raw,
325
+ meta,
326
+ messages,
327
+ legacyTaskId,
328
+ restoredTaskId,
329
+ workspacePath,
330
+ workspaceIdentity,
331
+ workspaceHash,
332
+ workspaceKey: workspaceKey(workspacePath, workspaceIdentity),
333
+ projectId: projectIdFromPath(workspacePath),
334
+ sourceProvider,
335
+ title,
336
+ mode,
337
+ model,
338
+ traceId,
339
+ createdAt,
340
+ updatedAt,
341
+ searchableText: messages.map((message) => String(message.content || "")).join("\n"),
342
+ metaJson: JSON.stringify(normalizedMeta),
343
+ };
344
+ }
345
+
346
+ function printPlan(plan, dryRun) {
347
+ console.log("=== Restoring conversation ===");
348
+ console.log(` Title: ${plan.title}`);
349
+ console.log(` SourceProvider: ${plan.sourceProvider}`);
350
+ console.log(` RuntimeProvider: ${ZCODE_PROVIDER}`);
351
+ console.log(` Model: ${plan.model}`);
352
+ console.log(` Workspace: ${plan.workspacePath}`);
353
+ console.log(` Messages: ${plan.messages.length}`);
354
+ console.log(` restoredTaskId: ${plan.restoredTaskId}`);
355
+ console.log(` legacyTaskId: ${plan.legacyTaskId}`);
356
+ console.log(` workspaceHash: ${plan.workspaceHash}`);
357
+ console.log(" migrationSource: <empty>");
358
+ console.log(` Dry run: ${dryRun}`);
359
+ console.log();
360
+ }
361
+
362
+ function writeTaskIndex(taskDb, plan) {
363
+ const upsertTask = taskDb.prepare(`
364
+ INSERT INTO tasks
365
+ (workspace_key, workspace_path, workspace_identity, task_id, title,
366
+ task_status, provider, mode, model, migration_source, forked_from_task_id,
367
+ created_at, updated_at, unread_at, meta_json, searchable_text)
368
+ VALUES
369
+ (@workspace_key, @workspace_path, @workspace_identity, @task_id, @title,
370
+ @task_status, @provider, @mode, @model, NULL, @forked_from_task_id,
371
+ @created_at, @updated_at, @unread_at, @meta_json, @searchable_text)
372
+ ON CONFLICT(workspace_key, task_id) DO UPDATE SET
373
+ workspace_path = excluded.workspace_path,
374
+ workspace_identity = excluded.workspace_identity,
375
+ title = CASE
376
+ WHEN tasks.title_overridden = 1 THEN tasks.title
377
+ ELSE excluded.title
378
+ END,
379
+ task_status = excluded.task_status,
380
+ provider = excluded.provider,
381
+ mode = excluded.mode,
382
+ model = excluded.model,
383
+ migration_source = NULL,
384
+ forked_from_task_id = excluded.forked_from_task_id,
385
+ created_at = MIN(tasks.created_at, excluded.created_at),
386
+ updated_at = MAX(tasks.updated_at, excluded.updated_at),
387
+ unread_at = tasks.unread_at,
388
+ searchable_text = CASE
389
+ WHEN tasks.updated_at > excluded.updated_at THEN tasks.searchable_text
390
+ ELSE excluded.searchable_text
391
+ END,
392
+ meta_json = excluded.meta_json
393
+ `);
394
+
395
+ upsertTask.run({
396
+ workspace_key: plan.workspaceKey,
397
+ workspace_path: plan.workspacePath,
398
+ workspace_identity: plan.workspaceIdentity || null,
399
+ task_id: plan.restoredTaskId,
400
+ title: plan.title,
401
+ task_status: optionalString(plan.meta.status) || null,
402
+ provider: ZCODE_PROVIDER,
403
+ mode: plan.mode,
404
+ model: plan.model || null,
405
+ forked_from_task_id: optionalString(plan.meta.forkedFromTaskId) || null,
406
+ created_at: plan.createdAt,
407
+ updated_at: plan.updatedAt,
408
+ unread_at: optionalNumber(plan.meta.unreadAt) ?? null,
409
+ meta_json: plan.metaJson,
410
+ searchable_text: plan.searchableText,
411
+ });
412
+ }
413
+
414
+ function writeSession(cliDb, plan) {
415
+ const upsertSession = cliDb.prepare(`
416
+ INSERT INTO session
417
+ (id, project_id, workspace_id, slug, directory, path, title, version,
418
+ time_created, time_updated, task_type, title_source, trace_id)
419
+ VALUES
420
+ (@id, @project_id, @workspace_id, @slug, @directory, @path, @title, @version,
421
+ @time_created, @time_updated, @task_type, @title_source, @trace_id)
422
+ ON CONFLICT(id) DO UPDATE SET
423
+ project_id = excluded.project_id,
424
+ workspace_id = excluded.workspace_id,
425
+ slug = excluded.slug,
426
+ directory = excluded.directory,
427
+ path = excluded.path,
428
+ title = CASE
429
+ WHEN session.title_source = 'custom' THEN session.title
430
+ ELSE excluded.title
431
+ END,
432
+ version = excluded.version,
433
+ time_created = MIN(session.time_created, excluded.time_created),
434
+ time_updated = MAX(session.time_updated, excluded.time_updated),
435
+ task_type = excluded.task_type,
436
+ trace_id = COALESCE(session.trace_id, excluded.trace_id)
437
+ `);
438
+
439
+ upsertSession.run({
440
+ id: plan.restoredTaskId,
441
+ project_id: plan.projectId,
442
+ workspace_id: plan.workspaceHash,
443
+ slug: plan.restoredTaskId,
444
+ directory: plan.workspacePath,
445
+ path: plan.workspacePath,
446
+ title: plan.title,
447
+ version: "0.14.5",
448
+ time_created: plan.createdAt,
449
+ time_updated: plan.updatedAt,
450
+ task_type: "interactive",
451
+ title_source: "first_input",
452
+ trace_id: plan.traceId,
453
+ });
454
+ }
455
+
456
+ function writeMessages(cliDb, plan) {
457
+ const insertMessage = cliDb.prepare(`
458
+ INSERT OR REPLACE INTO message
459
+ (id, session_id, time_created, time_updated, data)
460
+ VALUES
461
+ (@id, @session_id, @time_created, @time_updated, @data)
462
+ `);
463
+ const insertPart = cliDb.prepare(`
464
+ INSERT OR REPLACE INTO part
465
+ (id, message_id, session_id, time_created, time_updated, data)
466
+ VALUES
467
+ (@id, @message_id, @session_id, @time_created, @time_updated, @data)
468
+ `);
469
+ const deleteLegacyParts = cliDb.prepare(`
470
+ DELETE FROM part
471
+ WHERE session_id = @session_id AND id LIKE @id_prefix
472
+ `);
473
+
474
+ let partCount = 0;
475
+ let latestUserMessageId = "";
476
+ deleteLegacyParts.run({
477
+ session_id: plan.restoredTaskId,
478
+ id_prefix: `part_legacy_${plan.restoredTaskId}_%`,
479
+ });
480
+ for (const [index, message] of plan.messages.entries()) {
481
+ const messageTimestamp = optionalNumber(message.timestamp) ?? plan.updatedAt;
482
+ const completedAt = messageCompletedAt(message, messageTimestamp);
483
+ const messageId = `msg_legacy_${plan.restoredTaskId}_${index}`;
484
+ const role = message.role === "assistant" ? "assistant" : "user";
485
+ const baseMessageData = {
486
+ role,
487
+ time: removeUndefined({
488
+ created: messageTimestamp,
489
+ completed: role === "assistant" ? completedAt : undefined,
490
+ }),
491
+ agent: "zcode-agent",
492
+ };
493
+ // Bugfix: contracts 里 user message 使用 model 对象,assistant message 使用顶层 modelID/providerID。
494
+ // 两者不能混写,否则 app-server 的 message-mapper 会把用户消息模型解析成 undefined。
495
+ const messageData =
496
+ role === "assistant"
497
+ ? {
498
+ ...baseMessageData,
499
+ content: message.content,
500
+ modelID: message.model || plan.model || undefined,
501
+ providerID: ZCODE_PROVIDER,
502
+ mode: plan.mode,
503
+ path: {
504
+ cwd: plan.workspacePath,
505
+ root: plan.workspacePath,
506
+ },
507
+ cost: 0,
508
+ tokens: {
509
+ input: 0,
510
+ output: 0,
511
+ reasoning: 0,
512
+ cache: { read: 0, write: 0 },
513
+ },
514
+ finish: "stop",
515
+ ...(latestUserMessageId ? { parentID: latestUserMessageId } : {}),
516
+ ...(Array.isArray(message.tools) && message.tools.length > 0
517
+ ? {
518
+ toolCalls: message.tools.map((tool, toolIndex) => ({
519
+ id: `tool_${messageId}_${toolIndex}`,
520
+ toolName: tool.title || "",
521
+ kind: tool.kind || "other",
522
+ status: tool.status || "completed",
523
+ input: tool.input || {},
524
+ output: tool.output || "",
525
+ ...(tool.raw ? { raw: tool.raw } : {}),
526
+ })),
527
+ }
528
+ : {}),
529
+ ...(message.characterCount !== undefined
530
+ ? { characterCount: message.characterCount }
531
+ : {}),
532
+ ...(message.turnIndex !== undefined ? { turnIndex: message.turnIndex } : {}),
533
+ }
534
+ : {
535
+ ...baseMessageData,
536
+ content: message.content,
537
+ model: {
538
+ providerID: ZCODE_PROVIDER,
539
+ modelID: message.model || plan.model || "unknown",
540
+ },
541
+ ...(message.characterCount !== undefined
542
+ ? { characterCount: message.characterCount }
543
+ : {}),
544
+ ...(message.turnIndex !== undefined ? { turnIndex: message.turnIndex } : {}),
545
+ };
546
+
547
+ insertMessage.run({
548
+ id: messageId,
549
+ session_id: plan.restoredTaskId,
550
+ time_created: messageTimestamp,
551
+ time_updated: messageTimestamp,
552
+ data: JSON.stringify(removeUndefined(messageData)),
553
+ });
554
+
555
+ // Bugfix: 详情页从 part 表还原可见正文;只有 message.data.content 会出现任务可打开但历史区空白。
556
+ const partDataList = buildPartDataList(message, messageId, messageTimestamp);
557
+ for (const [partIndex, partData] of partDataList.entries()) {
558
+ const partTimestamp = messageTimestamp + partIndex;
559
+ insertPart.run({
560
+ id: `part_legacy_${plan.restoredTaskId}_${String(index).padStart(4, "0")}_${String(
561
+ partIndex,
562
+ ).padStart(4, "0")}`,
563
+ message_id: messageId,
564
+ session_id: plan.restoredTaskId,
565
+ time_created: partTimestamp,
566
+ time_updated: partTimestamp,
567
+ data: JSON.stringify(partData),
568
+ });
569
+ partCount++;
570
+ }
571
+
572
+ if (role === "user") {
573
+ latestUserMessageId = messageId;
574
+ }
575
+ }
576
+ return { messageCount: plan.messages.length, partCount };
577
+ }
578
+
579
+ function main() {
580
+ const args = parseArgs(process.argv.slice(2));
581
+ const plan = buildRestorePlan(args.snapshot);
582
+ printPlan(plan, args.dryRun);
583
+
584
+ if (args.dryRun) {
585
+ console.log("Dry run mode: no writes performed.");
586
+ return;
587
+ }
588
+
589
+ ensureExistingDb(args.taskIndexPath, "Task index");
590
+ ensureExistingDb(args.cliDbPath, "CLI DB");
591
+ const taskBackupPath = backupDb(args.taskIndexPath);
592
+ const cliBackupPath = backupDb(args.cliDbPath);
593
+ console.log(`Backed up task index: ${taskBackupPath}`);
594
+ console.log(`Backed up CLI DB: ${cliBackupPath}`);
595
+
596
+ const taskDb = new DatabaseSync(args.taskIndexPath);
597
+ const cliDb = new DatabaseSync(args.cliDbPath);
598
+ let taskInTx = false;
599
+ let cliInTx = false;
600
+
601
+ try {
602
+ taskDb.exec("BEGIN IMMEDIATE");
603
+ taskInTx = true;
604
+ cliDb.exec("BEGIN IMMEDIATE");
605
+ cliInTx = true;
606
+
607
+ console.log("[1/2] Writing task index...");
608
+ writeTaskIndex(taskDb, plan);
609
+ console.log(` tasks row ready: ${plan.restoredTaskId}`);
610
+
611
+ console.log("[2/2] Writing CLI session DB...");
612
+ writeSession(cliDb, plan);
613
+ const writeResult = writeMessages(cliDb, plan);
614
+ console.log(` message rows ready: ${writeResult.messageCount}`);
615
+ console.log(` part rows ready: ${writeResult.partCount}`);
616
+
617
+ taskDb.exec("COMMIT");
618
+ taskInTx = false;
619
+ cliDb.exec("COMMIT");
620
+ cliInTx = false;
621
+
622
+ console.log();
623
+ console.log("=== Restore complete ===");
624
+ } catch (error) {
625
+ if (taskInTx) {
626
+ try {
627
+ taskDb.exec("ROLLBACK");
628
+ } catch {}
629
+ }
630
+ if (cliInTx) {
631
+ try {
632
+ cliDb.exec("ROLLBACK");
633
+ } catch {}
634
+ }
635
+ console.error("Restore failed:", error instanceof Error ? error.message : String(error));
636
+ process.exitCode = 1;
637
+ } finally {
638
+ taskDb.close();
639
+ cliDb.close();
640
+ }
641
+ }
642
+
643
+ try {
644
+ main();
645
+ } catch (error) {
646
+ console.error(error instanceof Error ? error.message : String(error));
647
+ process.exitCode = 1;
648
+ }