zcode-pro 1.7.0 → 1.8.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.
@@ -0,0 +1,239 @@
1
+ // 四个来源共用的解析工具:读 JSONL、取文件头尾、时间归一、文本提取、工具名映射。
2
+ import { closeSync, createReadStream, openSync, readSync, readdirSync, statSync } from 'node:fs';
3
+ import { createInterface } from 'node:readline';
4
+ import { resolve, sep } from 'node:path';
5
+
6
+ export async function* readJsonl(file) {
7
+ const rl = createInterface({ input: createReadStream(file, { encoding: 'utf8' }), crlfDelay: Infinity });
8
+ try {
9
+ for await (const line of rl) {
10
+ const s = line.trim();
11
+ if (!s) continue;
12
+ try { yield JSON.parse(s); } catch { /* 末尾写了一半的行,跳过 */ }
13
+ }
14
+ } finally {
15
+ rl.close();
16
+ }
17
+ }
18
+
19
+ export async function readJsonlAll(file) {
20
+ const out = [];
21
+ for await (const rec of readJsonl(file)) out.push(rec);
22
+ return out;
23
+ }
24
+
25
+ export function readHead(file, bytes = 262144) {
26
+ const fd = openSync(file, 'r');
27
+ try {
28
+ const buf = Buffer.alloc(bytes);
29
+ const n = readSync(fd, buf, 0, bytes, 0);
30
+ return buf.subarray(0, n).toString('utf8');
31
+ } finally {
32
+ closeSync(fd);
33
+ }
34
+ }
35
+
36
+ export function readTail(file, bytes = 65536) {
37
+ const size = statSync(file).size;
38
+ const start = Math.max(0, size - bytes);
39
+ const fd = openSync(file, 'r');
40
+ try {
41
+ const buf = Buffer.alloc(size - start);
42
+ const n = readSync(fd, buf, 0, buf.length, start);
43
+ return buf.subarray(0, n).toString('utf8');
44
+ } finally {
45
+ closeSync(fd);
46
+ }
47
+ }
48
+
49
+ export function parseTime(v) {
50
+ if (typeof v === 'number' && Number.isFinite(v)) return v < 1e12 ? Math.round(v * 1000) : Math.round(v);
51
+ if (typeof v === 'string' && v) {
52
+ const t = Date.parse(v);
53
+ if (Number.isFinite(t)) return t;
54
+ }
55
+ return 0;
56
+ }
57
+
58
+ export function oneLine(value, max = 200) {
59
+ const s = String(value == null ? '' : value).replace(/\s+/g, ' ').trim();
60
+ return s.length > max ? s.slice(0, max - 1) + '…' : s;
61
+ }
62
+
63
+ export function blockText(block) {
64
+ if (!block || typeof block !== 'object') return '';
65
+ if (typeof block.text === 'string') return block.text;
66
+ if (typeof block.thinking === 'string') return block.thinking;
67
+ if (typeof block.content === 'string') return block.content;
68
+ if (Array.isArray(block.content)) return block.content.map(blockText).filter(Boolean).join('\n');
69
+ return '';
70
+ }
71
+
72
+ export function textOf(value) {
73
+ if (typeof value === 'string') return value;
74
+ if (Array.isArray(value)) return value.map(blockText).filter(Boolean).join('\n');
75
+ return blockText(value);
76
+ }
77
+
78
+ export function isLocalCommandText(text) {
79
+ const s = String(text || '').trim();
80
+ return /^<(?:local-command|command-name|command-message|local-command-stdout)/.test(s);
81
+ }
82
+
83
+ export function stripPiInjections(text) {
84
+ return String(text || '')
85
+ .replace(/<skill>[\s\S]*?<\/skill>/g, '')
86
+ .replace(/<available_skills>[\s\S]*?<\/available_skills>/g, '')
87
+ .trim();
88
+ }
89
+
90
+ export function toDataUrl(mime, data) {
91
+ const raw = String(data || '');
92
+ if (!raw) return '';
93
+ if (raw.startsWith('data:')) return raw;
94
+ return `data:${mime || 'application/octet-stream'};base64,${raw}`;
95
+ }
96
+
97
+ export function dataUrlBytes(url) {
98
+ const comma = String(url || '').indexOf(',');
99
+ if (comma < 0) return 0;
100
+ return Math.round((url.length - comma - 1) * 3 / 4);
101
+ }
102
+
103
+ // 只解图片头部,拿显示尺寸;认不出来就省略,不影响导入。
104
+ export function imageSize(dataUrl) {
105
+ const comma = String(dataUrl || '').indexOf(',');
106
+ if (comma < 0) return null;
107
+ const buf = Buffer.from(dataUrl.slice(comma + 1, comma + 1 + 131072), 'base64');
108
+ if (buf.length >= 24 && buf.readUInt32BE(0) === 0x89504e47) {
109
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
110
+ }
111
+ if (buf.length >= 10 && buf.toString('ascii', 0, 3) === 'GIF') {
112
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };
113
+ }
114
+ if (buf.length >= 4 && buf[0] === 0xff && buf[1] === 0xd8) {
115
+ let p = 2;
116
+ while (p + 9 < buf.length) {
117
+ if (buf[p] !== 0xff) { p++; continue; }
118
+ const marker = buf[p + 1];
119
+ const len = buf.readUInt16BE(p + 2);
120
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
121
+ return { width: buf.readUInt16BE(p + 7), height: buf.readUInt16BE(p + 5) };
122
+ }
123
+ p += 2 + len;
124
+ }
125
+ }
126
+ return null;
127
+ }
128
+
129
+ export function outputText(value) {
130
+ if (value == null) return '';
131
+ if (typeof value === 'string') return value;
132
+ if (Array.isArray(value)) return value.map(blockText).filter(Boolean).join('\n');
133
+ if (typeof value === 'object') {
134
+ const t = blockText(value);
135
+ if (t) return t;
136
+ try { return JSON.stringify(value); } catch { return String(value); }
137
+ }
138
+ return String(value);
139
+ }
140
+
141
+ export function truncateText(value, max, note = '内容过长,已截断') {
142
+ const s = String(value == null ? '' : value);
143
+ if (s.length <= max) return s;
144
+ return s.slice(0, max) + `\n\n[${note},原长 ${s.length} 字符]`;
145
+ }
146
+
147
+ const TOOL_NAMES = {
148
+ bash: 'Bash', shell: 'Bash', exec: 'Bash', run_shell_command: 'Bash', shell_command: 'Bash',
149
+ read: 'Read', read_file: 'Read', readfile: 'Read',
150
+ write: 'Write', write_file: 'Write', writefile: 'Write',
151
+ edit: 'Edit', edit_file: 'Edit', str_replace_editor: 'Edit',
152
+ grep: 'Grep', search: 'Grep',
153
+ glob: 'Glob', find: 'Glob',
154
+ };
155
+
156
+ // 只映射参数形状能对上 ZCode 内置工具的调用;对不上就返回 null,由调用方转成文本块。
157
+ export function mapToolCall(name, input) {
158
+ const mapped = TOOL_NAMES[String(name || '').toLowerCase()];
159
+ if (!mapped) return null;
160
+ const args = input && typeof input === 'object' ? input : {};
161
+ if (mapped === 'Bash') {
162
+ let command = args.command ?? args.cmd ?? args.input;
163
+ if (Array.isArray(command)) command = command.join(' ');
164
+ if (typeof command !== 'string' || !command.trim()) return null;
165
+ return { tool: 'Bash', input: { command } };
166
+ }
167
+ if (mapped === 'Read') {
168
+ const file = args.file_path ?? args.path ?? args.file;
169
+ if (typeof file !== 'string' || !file) return null;
170
+ return { tool: 'Read', input: { file_path: file } };
171
+ }
172
+ if (mapped === 'Write') {
173
+ const file = args.file_path ?? args.path ?? args.file;
174
+ const content = args.content ?? args.text;
175
+ if (typeof file !== 'string' || !file || typeof content !== 'string') return null;
176
+ return { tool: 'Write', input: { file_path: file, content } };
177
+ }
178
+ if (mapped === 'Edit') {
179
+ const file = args.file_path ?? args.path ?? args.file;
180
+ const oldText = args.old_string ?? args.oldText ?? args.search;
181
+ const newText = args.new_string ?? args.newText ?? args.replace;
182
+ if (typeof file !== 'string' || !file || typeof oldText !== 'string' || typeof newText !== 'string') return null;
183
+ return { tool: 'Edit', input: { file_path: file, old_string: oldText, new_string: newText } };
184
+ }
185
+ if (mapped === 'Grep') {
186
+ const pattern = args.pattern ?? args.query;
187
+ if (typeof pattern !== 'string' || !pattern) return null;
188
+ const path = args.path ?? args.cwd ?? args.directory;
189
+ const out = { pattern };
190
+ if (typeof path === 'string' && path) out.path = path;
191
+ return { tool: 'Grep', input: out };
192
+ }
193
+ if (mapped === 'Glob') {
194
+ const pattern = args.pattern ?? args.glob ?? args.query;
195
+ if (typeof pattern !== 'string' || !pattern) return null;
196
+ const path = args.path ?? args.cwd ?? args.directory;
197
+ const out = { pattern };
198
+ if (typeof path === 'string' && path) out.path = path;
199
+ return { tool: 'Glob', input: out };
200
+ }
201
+ return null;
202
+ }
203
+
204
+ export function walkFiles(dir, accept, depth = 6) {
205
+ const out = [];
206
+ const visit = (current, level) => {
207
+ let entries;
208
+ try { entries = readdirSync(current, { withFileTypes: true }); } catch { return; }
209
+ for (const entry of entries) {
210
+ const full = resolve(current, entry.name);
211
+ if (entry.isDirectory()) {
212
+ if (level < depth) visit(full, level + 1);
213
+ } else if (entry.isFile() && accept(full, entry.name)) {
214
+ out.push(full);
215
+ }
216
+ }
217
+ };
218
+ visit(dir, 0);
219
+ return out;
220
+ }
221
+
222
+ export function normalizeRoots(roots) {
223
+ const seen = new Set();
224
+ const out = [];
225
+ for (const root of Array.isArray(roots) ? roots : []) {
226
+ if (typeof root !== 'string' || !root) continue;
227
+ const p = resolve(root);
228
+ if (p === sep || seen.has(p)) continue;
229
+ seen.add(p);
230
+ out.push(p);
231
+ }
232
+ return out;
233
+ }
234
+
235
+ export function isUnder(file, roots) {
236
+ if (!file) return false;
237
+ const p = resolve(file);
238
+ return roots.some((root) => p === root || p.startsWith(root.endsWith(sep) ? root : root + sep));
239
+ }
@@ -0,0 +1,405 @@
1
+ // 导入写入:会话库(session/message/part)与任务索引(tasks + 分组记账)双写,
2
+ // 以及来源登记文件和已导入状态查询。
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { join, resolve } from 'node:path';
6
+ import { mapToolCall, oneLine, truncateText } from './util.mjs';
7
+
8
+ // 按需加载:旧版 Node 没有 node:sqlite,不能让整个 helper 启动失败。
9
+ let DatabaseSync = null;
10
+ try { ({ DatabaseSync } = await import('node:sqlite')); } catch { DatabaseSync = null; }
11
+
12
+ const BUSY_TIMEOUT_MS = 5000;
13
+ const MAX_TOOL_CHARS = 100000;
14
+ const MAX_TOOL_FALLBACK = 20000;
15
+ const MAX_SEARCHABLE = 200000;
16
+
17
+ function openDb(file, readOnly = false) {
18
+ if (!DatabaseSync) {
19
+ throw Object.assign(new Error('当前 Node 不支持内置 SQLite,无法写入 ZCode 数据'), { code: 'sqlite-unavailable' });
20
+ }
21
+ const db = new DatabaseSync(file, readOnly ? { readOnly: true } : {});
22
+ db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
23
+ return db;
24
+ }
25
+
26
+ function tx(db, fn) {
27
+ db.exec('BEGIN IMMEDIATE');
28
+ try {
29
+ fn();
30
+ db.exec('COMMIT');
31
+ } catch (err) {
32
+ try { db.exec('ROLLBACK'); } catch { /* 已回滚 */ }
33
+ throw err;
34
+ }
35
+ }
36
+
37
+ function dbFile(dataRoot) {
38
+ return join(dataRoot, 'cli', 'db', 'db.sqlite');
39
+ }
40
+
41
+ function indexFile(dataRoot) {
42
+ return join(dataRoot, 'v2', 'tasks-index.sqlite');
43
+ }
44
+
45
+ function projectIdOf(workspace) {
46
+ return 'proj_' + String(workspace).replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-+|-+$/g, '');
47
+ }
48
+
49
+ // 官方 Claude 迁移用的来源标记是 claudeCode,这里保持一致,其他来源用来源 id。
50
+ function migrationSourceOf(source) {
51
+ return source === 'claude' ? 'claudeCode' : source;
52
+ }
53
+
54
+ export function registryPath(dataRoot) {
55
+ return join(dataRoot, 'zcodepro-imports.json');
56
+ }
57
+
58
+ export function readRegistry(dataRoot) {
59
+ try {
60
+ const data = JSON.parse(readFileSync(registryPath(dataRoot), 'utf8'));
61
+ if (data && typeof data === 'object' && data.imports && typeof data.imports === 'object') {
62
+ return { version: 1, imports: data.imports };
63
+ }
64
+ } catch { /* 没有或损坏就重建 */ }
65
+ return { version: 1, imports: {} };
66
+ }
67
+
68
+ export function writeRegistry(dataRoot, registry) {
69
+ mkdirSync(dataRoot, { recursive: true });
70
+ const file = registryPath(dataRoot);
71
+ const tmp = `${file}.${process.pid}.tmp`;
72
+ writeFileSync(tmp, JSON.stringify(registry, null, 2));
73
+ renameSync(tmp, file);
74
+ }
75
+
76
+ export function sourceKey(source, sessionId) {
77
+ return `${source}:${sessionId}`;
78
+ }
79
+
80
+ // 一次读出还活着的任务(tasks 未删 + 会话未软删),并带上归档状态,
81
+ // 用于列表页判断“已导入”和提示“任务已归档”。
82
+ export function aliveTaskStates(dataRoot) {
83
+ const states = new Map();
84
+ const tasksDb = indexFile(dataRoot);
85
+ const cliDb = dbFile(dataRoot);
86
+ const tasks = new Map();
87
+ const sessions = new Set();
88
+ try {
89
+ if (existsSync(tasksDb)) {
90
+ const db = openDb(tasksDb, true);
91
+ try {
92
+ for (const row of db.prepare('SELECT task_id, archived FROM tasks WHERE deleted = 0 AND coalesce(cli_deleted, 0) = 0').all()) {
93
+ tasks.set(String(row.task_id), { archived: Number(row.archived) === 1 });
94
+ }
95
+ } finally { db.close(); }
96
+ }
97
+ } catch { /* 库读不到就不标已导入 */ }
98
+ try {
99
+ if (existsSync(cliDb)) {
100
+ const db = openDb(cliDb, true);
101
+ try {
102
+ for (const row of db.prepare('SELECT id FROM session WHERE time_deleted IS NULL').all()) {
103
+ sessions.add(String(row.id));
104
+ }
105
+ } finally { db.close(); }
106
+ }
107
+ } catch { /* 同上 */ }
108
+ for (const [id, state] of tasks) if (sessions.has(id)) states.set(id, state);
109
+ return states;
110
+ }
111
+
112
+ export function aliveTaskIds(dataRoot) {
113
+ return new Set(aliveTaskStates(dataRoot).keys());
114
+ }
115
+
116
+ export function getProject(dataRoot, projectId) {
117
+ const file = indexFile(dataRoot);
118
+ if (!existsSync(file)) throw Object.assign(new Error('任务索引不存在'), { code: 'index-missing' });
119
+ const db = openDb(file, true);
120
+ try {
121
+ const row = db.prepare('SELECT project_id, name FROM projects WHERE project_id = ? AND deleted = 0').get(projectId);
122
+ if (!row) return null;
123
+ const roots = db.prepare('SELECT root_path, is_primary FROM project_roots WHERE project_id = ? ORDER BY is_primary DESC, position').all(projectId)
124
+ .map((r) => ({ path: String(r.root_path || ''), primary: Number(r.is_primary) === 1 }))
125
+ .filter((r) => r.path);
126
+ return { id: String(row.project_id), name: String(row.name || ''), roots };
127
+ } finally {
128
+ db.close();
129
+ }
130
+ }
131
+
132
+ function latestValue(db, sql, fallback) {
133
+ try {
134
+ const row = db.prepare(sql).get();
135
+ return row ? Object.values(row)[0] : fallback;
136
+ } catch {
137
+ return fallback;
138
+ }
139
+ }
140
+
141
+ const modelCaches = new Map();
142
+
143
+ function modelContext(db, cliFile) {
144
+ const cached = modelCaches.get(cliFile);
145
+ if (cached && Date.now() - cached.at < 30000) return cached.value;
146
+ let modelSelection = null;
147
+ let modelId = '';
148
+ let providerId = '';
149
+ try {
150
+ const row = db.prepare("SELECT data FROM message WHERE json_extract(data, '$.role') = 'user' AND json_extract(data, '$.modelSelection') IS NOT NULL ORDER BY time_created DESC LIMIT 1").get();
151
+ if (row) modelSelection = JSON.parse(row.data).modelSelection || null;
152
+ } catch { /* ignore */ }
153
+ try {
154
+ const row = db.prepare("SELECT data FROM message WHERE json_extract(data, '$.role') = 'assistant' ORDER BY time_created DESC LIMIT 1").get();
155
+ if (row) {
156
+ const data = JSON.parse(row.data);
157
+ modelId = data.modelId || '';
158
+ providerId = data.providerId || '';
159
+ }
160
+ } catch { /* ignore */ }
161
+ const value = { modelSelection, modelId, providerId };
162
+ modelCaches.set(cliFile, { at: Date.now(), value });
163
+ return value;
164
+ }
165
+
166
+ function userMessageData(time, migrationSource, modelSelection) {
167
+ const data = {
168
+ role: 'user',
169
+ time: { created: time },
170
+ agent: 'zcode-agent',
171
+ metadata: { migrationSource },
172
+ semantics: {
173
+ origin: 'real_user', kind: 'user_prompt',
174
+ uiVisibility: 'visible', providerVisibility: 'visible', transcriptVisibility: 'visible',
175
+ },
176
+ };
177
+ if (modelSelection) data.modelSelection = modelSelection;
178
+ return data;
179
+ }
180
+
181
+ function assistantMessageData(time, parentID, ctx) {
182
+ const data = {
183
+ role: 'assistant',
184
+ time: { created: time, completed: time },
185
+ parentID: parentID || null,
186
+ mode: 'build',
187
+ planEnabled: false,
188
+ agent: 'zcode-agent',
189
+ path: { cwd: ctx.workspace, root: ctx.workspace },
190
+ cost: 0,
191
+ tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
192
+ finish: 'completed',
193
+ semantics: {
194
+ origin: 'agent_runtime', kind: 'assistant_response',
195
+ uiVisibility: 'visible', providerVisibility: 'visible', transcriptVisibility: 'visible',
196
+ },
197
+ };
198
+ if (ctx.modelId) data.modelId = ctx.modelId;
199
+ if (ctx.providerId) data.providerId = ctx.providerId;
200
+ return data;
201
+ }
202
+
203
+ function partData(part, time, declIndex) {
204
+ const start = Number(part.start) || time;
205
+ const end = Number(part.end) || start;
206
+ if (part.type === 'text') {
207
+ return { type: 'text', text: String(part.text || ''), time: { start, end: start } };
208
+ }
209
+ if (part.type === 'reasoning') {
210
+ return { type: 'reasoning', text: String(part.text || ''), time: { start, end: start } };
211
+ }
212
+ if (part.type === 'file') {
213
+ const out = { type: 'file', mime: part.mime, url: part.url, metadata: part.metadata || {} };
214
+ if (part.filename) out.filename = part.filename;
215
+ return out;
216
+ }
217
+ if (part.type === 'tool') {
218
+ const output = truncateText(part.output, MAX_TOOL_CHARS, '工具输出过长,已截断');
219
+ const mapped = mapToolCall(part.tool, part.input);
220
+ if (mapped) {
221
+ return {
222
+ type: 'tool',
223
+ callID: String(part.callID || `import_tool_${declIndex}`),
224
+ declarationIndex: declIndex,
225
+ tool: mapped.tool,
226
+ metadata: {},
227
+ state: {
228
+ status: part.isError ? 'error' : 'completed',
229
+ input: mapped.input,
230
+ ...(part.isError ? { error: output || '工具执行失败' } : { output }),
231
+ title: mapped.tool,
232
+ metadata: { schemaVersion: 1 },
233
+ time: { start, end },
234
+ },
235
+ };
236
+ }
237
+ const input = (() => {
238
+ try { return JSON.stringify(part.input); } catch { return String(part.input); }
239
+ })();
240
+ return {
241
+ type: 'text',
242
+ text: `[工具 ${part.tool}]\n参数:${input}\n结果:${truncateText(output, MAX_TOOL_FALLBACK, '工具输出过长,已截断')}`,
243
+ time: { start, end: start },
244
+ };
245
+ }
246
+ return null;
247
+ }
248
+
249
+ function searchableText(messages) {
250
+ const lines = [];
251
+ for (const msg of messages) {
252
+ for (const part of msg.parts) {
253
+ if (part.type === 'text' && part.text) lines.push(String(part.text));
254
+ }
255
+ }
256
+ return truncateText(lines.join('\n'), MAX_SEARCHABLE, '搜索文本过长,已截断');
257
+ }
258
+
259
+ function purgeCliSession(db, sessionId) {
260
+ tx(db, () => {
261
+ db.prepare('DELETE FROM part WHERE session_id = ?').run(sessionId);
262
+ db.prepare('DELETE FROM message WHERE session_id = ?').run(sessionId);
263
+ try { db.prepare('DELETE FROM session_entry WHERE session_id = ?').run(sessionId); } catch { /* 旧库没有该表 */ }
264
+ try { db.prepare('DELETE FROM todo WHERE session_id = ?').run(sessionId); } catch { /* 旧库没有该表 */ }
265
+ db.prepare('DELETE FROM session WHERE id = ?').run(sessionId);
266
+ });
267
+ }
268
+
269
+ export function writeImportedSession({ dataRoot, source, parsed, workspace, projectId }) {
270
+ const cliDb = dbFile(dataRoot);
271
+ const idxDb = indexFile(dataRoot);
272
+ if (!existsSync(cliDb) || !existsSync(idxDb)) {
273
+ throw Object.assign(new Error('ZCode 的会话库或任务索引不存在'), { code: 'db-missing' });
274
+ }
275
+ const sessionId = `sess_${randomUUID()}`;
276
+ const migrationSource = migrationSourceOf(source);
277
+ const title = oneLine(parsed.title || '导入的会话', 120) || '导入的会话';
278
+ const createdAt = Math.max(1, Number(parsed.createdAt) || Date.now());
279
+ // 侧边栏按 cli_updated_at 倒序;导入的任务用导入时间,才能在“任务”和项目
280
+ // 列表里排到最上面。源会话的创建时间仍写进 cli_created_at。
281
+ const importedAt = Math.max(createdAt, Date.now());
282
+ const traceId = randomUUID();
283
+ const messages = Array.isArray(parsed.messages) ? parsed.messages : [];
284
+ if (!messages.length) {
285
+ throw Object.assign(new Error('会话里没有可导入的消息'), { code: 'empty-session' });
286
+ }
287
+
288
+ let cli = null;
289
+ let idx = null;
290
+ try {
291
+ cli = openDb(cliDb);
292
+ const version = latestValue(cli, 'SELECT version FROM session ORDER BY time_updated DESC LIMIT 1', '0.0.0');
293
+ const model = modelContext(cli, cliDb);
294
+ const userInsert = cli.prepare('INSERT INTO message (id, session_id, time_created, time_updated, data, sequence) VALUES (?, ?, ?, ?, ?, ?)');
295
+ const partInsert = cli.prepare('INSERT INTO part (id, message_id, session_id, time_created, time_updated, data, sequence) VALUES (?, ?, ?, ?, ?, ?, ?)');
296
+
297
+ tx(cli, () => {
298
+ cli.prepare(`INSERT INTO session
299
+ (id, project_id, workspace_id, parent_id, slug, directory, path, title, version, permission,
300
+ time_created, time_updated, task_type, title_source, trace_id, last_outcome)
301
+ VALUES (?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?, ?, ?, 'interactive', 'custom', ?, 'completed')`)
302
+ .run(
303
+ sessionId, projectIdOf(workspace), sessionId, workspace, workspace, title, String(version || '0.0.0'),
304
+ JSON.stringify({ mode: 'build' }), createdAt, importedAt, traceId
305
+ );
306
+
307
+ let lastUserId = null;
308
+ messages.forEach((msg, index) => {
309
+ const time = Math.max(1, Number(msg.time) || createdAt);
310
+ const messageId = `${sessionId}_import_${index}`;
311
+ const data = msg.role === 'user'
312
+ ? userMessageData(time, migrationSource, model.modelSelection)
313
+ : assistantMessageData(time, lastUserId, { ...model, workspace });
314
+ userInsert.run(messageId, sessionId, time, time, JSON.stringify(data), index + 1);
315
+ msg.parts.forEach((part, partIndex) => {
316
+ const body = partData(part, time, partIndex);
317
+ if (!body) return;
318
+ partInsert.run(
319
+ `${messageId}_p${partIndex}`, messageId, sessionId,
320
+ Number(part.start) || time, Number(part.end) || time,
321
+ JSON.stringify(body), partIndex + 1
322
+ );
323
+ });
324
+ if (msg.role === 'user') lastUserId = messageId;
325
+ });
326
+ });
327
+
328
+ idx = openDb(idxDb);
329
+ const meta = {
330
+ taskId: sessionId,
331
+ traceId,
332
+ title,
333
+ titleOverridden: true,
334
+ workspacePath: workspace,
335
+ createdAt,
336
+ updatedAt: importedAt,
337
+ mode: 'build',
338
+ provider: 'glm',
339
+ status: 'completed',
340
+ migrationSource,
341
+ unreadAt: importedAt,
342
+ };
343
+ tx(idx, () => {
344
+ idx.prepare(`INSERT INTO tasks
345
+ (workspace_key, workspace_path, task_id, title, task_status, provider, mode, migration_source,
346
+ created_at, updated_at, unread_at, pinned, archived, deleted, title_overridden, meta_json, searchable_text,
347
+ last_unread_at, root_path, project_id, cli_title, handoff_pending, cli_title_source,
348
+ cli_created_at, cli_updated_at, cli_last_outcome, cli_deleted, host_id)
349
+ VALUES (?, ?, ?, ?, 'completed', 'glm', 'build', ?, ?, ?, ?, 0, 0, 0, 1, ?, ?, ?, ?, ?, ?, 0, 'custom', ?, ?, 'completed', 0, 'local')`)
350
+ .run(
351
+ workspace, workspace, sessionId, title, migrationSource, createdAt, importedAt, importedAt,
352
+ JSON.stringify(meta), searchableText(messages), importedAt, workspace, projectId || null,
353
+ title, createdAt, importedAt
354
+ );
355
+ idx.prepare(`INSERT OR IGNORE INTO task_group_admissions
356
+ (workspace_key, task_id, system_kind, user_organized, creation_id) VALUES (?, ?, NULL, 0, NULL)`)
357
+ .run(workspace, sessionId);
358
+ const min = idx.prepare('SELECT coalesce(min(sort_order), 0) - 1 AS n FROM task_group_view_node_orders').get();
359
+ const now = Date.now();
360
+ idx.prepare(`INSERT OR IGNORE INTO task_group_view_node_orders
361
+ (node_type, node_key, sort_order, created_at, updated_at) VALUES ('task', ?, ?, ?, ?)`)
362
+ .run(JSON.stringify([workspace, sessionId]), Number(min?.n) || 0, now, now);
363
+ });
364
+ } catch (err) {
365
+ if (cli) {
366
+ try { purgeCliSession(cli, sessionId); } catch { /* 清理失败也不掩盖原错误 */ }
367
+ }
368
+ throw err;
369
+ } finally {
370
+ try { if (cli) cli.close(); } catch { /* ignore */ }
371
+ try { if (idx) idx.close(); } catch { /* ignore */ }
372
+ }
373
+
374
+ return { taskId: sessionId, title, createdAt, updatedAt: importedAt, messageCount: messages.length };
375
+ }
376
+
377
+ export function purgeImportedTask(dataRoot, taskId) {
378
+ const tasksDb = indexFile(dataRoot);
379
+ const cliDb = dbFile(dataRoot);
380
+ if (existsSync(tasksDb)) {
381
+ const db = openDb(tasksDb);
382
+ try {
383
+ tx(db, () => {
384
+ const row = db.prepare('SELECT workspace_key FROM tasks WHERE task_id = ?').get(taskId);
385
+ const workspace = row ? String(row.workspace_key) : '';
386
+ db.prepare('DELETE FROM task_group_view_node_orders WHERE node_type = \'task\' AND node_key = ?')
387
+ .run(JSON.stringify([workspace, taskId]));
388
+ db.prepare('DELETE FROM task_group_admissions WHERE task_id = ?').run(taskId);
389
+ db.prepare('DELETE FROM tasks WHERE task_id = ?').run(taskId);
390
+ });
391
+ } finally { db.close(); }
392
+ }
393
+ if (existsSync(cliDb)) {
394
+ const db = openDb(cliDb);
395
+ try { purgeCliSession(db, taskId); } finally { db.close(); }
396
+ }
397
+ }
398
+
399
+ export function workspaceForImport({ cwd, projectRoot }) {
400
+ for (const candidate of [cwd, projectRoot]) {
401
+ if (!candidate) continue;
402
+ try { if (statSync(candidate).isDirectory()) return resolve(candidate); } catch { /* 不存在就试下一个 */ }
403
+ }
404
+ return null;
405
+ }