dsh-timeback 0.0.0-stage → 0.6.0

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/index.js ADDED
@@ -0,0 +1,579 @@
1
+ /**
2
+ * Timeback — Host half.
3
+ *
4
+ * Records a workspace snapshot for every conversation turn, keeps the branch
5
+ * tree, and rewinds a conversation and its files together: the conversation is
6
+ * forked at the chosen turn (the append-only Session log is never rewritten)
7
+ * while the work tree is restored from the snapshot captured at that turn.
8
+ *
9
+ * Adds:
10
+ * - the `timeback_*` model-facing tools,
11
+ * - `GET /timeback/api/health` and `GET /timeback/api/tree`,
12
+ * - `POST /timeback/api/action` for the Web panel,
13
+ * - turn/event hooks that drive snapshot capture.
14
+ */
15
+
16
+ import { readFileSync } from 'node:fs'
17
+ import os from 'node:os'
18
+ import path from 'node:path'
19
+ import { GitRunner } from './src/git-runner.js'
20
+ import { SnapshotStore } from './src/snapshots.js'
21
+ import { CheckpointRegistry } from './src/registry.js'
22
+ import { NotesStore } from './src/notes.js'
23
+ import { TimebackService, TimebackError } from './src/service.js'
24
+
25
+ export const name = 'timeback'
26
+ export const inject = ['webServer', 'subprocess', 'tools', 'sessionController']
27
+
28
+ const JSON_HEADERS = {
29
+ 'content-type': 'application/json; charset=utf-8',
30
+ 'cache-control': 'no-store',
31
+ 'x-content-type-options': 'nosniff',
32
+ }
33
+ const BODY_LIMIT = 256 * 1024
34
+ const RENDER_LIMIT = 12_000
35
+
36
+ /** Plugin package version, used by the browser half to detect a stale bundle. */
37
+ const PLUGIN_VERSION = (() => {
38
+ try {
39
+ return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version ?? '0.0.0'
40
+ } catch {
41
+ return '0.0.0'
42
+ }
43
+ })()
44
+
45
+ /**
46
+ * Resolve the snapshot/registry directory.
47
+ * @param ctx - Host context used to locate the profile when the environment omits DSH_HOME.
48
+ * @param configured - explicit `dataDir` configuration, when present.
49
+ * @returns {string} absolute data directory.
50
+ */
51
+ function resolveDataDir(ctx, configured) {
52
+ if (typeof configured === 'string' && configured.trim() !== '') {
53
+ const value = configured.trim()
54
+ return path.resolve(value.startsWith('~/') ? path.join(os.homedir(), value.slice(2)) : value)
55
+ }
56
+ if (process.env.DSH_HOME) return path.join(process.env.DSH_HOME, 'timeback')
57
+ const profileDir = optionalService(ctx, 'profileContext')?.dir
58
+ if (typeof profileDir === 'string' && profileDir !== '') {
59
+ // <home>/profiles/<name> → keep snapshots beside the profiles directory,
60
+ // so recreating the profile from a default template does not orphan them.
61
+ const match = /^(.*)[\\/]profiles[\\/][^\\/]+$/.exec(profileDir)
62
+ return path.join(match ? match[1] : profileDir, 'timeback')
63
+ }
64
+ return path.join(os.homedir(), '.dsh', 'timeback')
65
+ }
66
+
67
+ /** Resolve the effective plugin configuration. */
68
+ function resolveConfig(ctx, raw) {
69
+ const input = raw && typeof raw === 'object' ? raw : {}
70
+ const dataDir = resolveDataDir(ctx, input.dataDir)
71
+ const exclude = Array.isArray(input.exclude)
72
+ ? input.exclude.filter((entry) => typeof entry === 'string' && entry.trim() !== '')
73
+ : undefined
74
+ return {
75
+ dataDir,
76
+ version: PLUGIN_VERSION,
77
+ capture: normalizeCapture(input.capture),
78
+ timeoutMs: Number.isSafeInteger(input.timeoutMs) && input.timeoutMs >= 1000 ? input.timeoutMs : 30_000,
79
+ maxBytes: Number.isSafeInteger(input.maxBytes) && input.maxBytes >= 65_536 ? input.maxBytes : 8 * 1024 * 1024,
80
+ maxCheckpoints: Number.isSafeInteger(input.maxCheckpoints) && input.maxCheckpoints >= 20 ? input.maxCheckpoints : 400,
81
+ maxFiles: Number.isSafeInteger(input.maxFiles) && input.maxFiles >= 100 ? input.maxFiles : 20_000,
82
+ probeTimeoutMs: Number.isSafeInteger(input.probeTimeoutMs) && input.probeTimeoutMs >= 1_000 ? input.probeTimeoutMs : 8_000,
83
+ restoreDeletesExtra: input.restoreDeletesExtra !== false,
84
+ routePath: normalizePath(input.routePath ?? '/timeback'),
85
+ ...(exclude && exclude.length > 0 ? { exclude } : {}),
86
+ }
87
+ }
88
+
89
+ /** Resolve the automatic-capture mode. */
90
+ function normalizeCapture(value) {
91
+ if (value === 'off') return 'off'
92
+ if (value === 'all' || value === 'turn') return 'all'
93
+ return 'workspace'
94
+ }
95
+
96
+ /** Normalize an HTTP mount path. */
97
+ function normalizePath(value) {
98
+ const withSlash = String(value).startsWith('/') ? String(value) : `/${String(value)}`
99
+ return withSlash.length > 1 && withSlash.endsWith('/') ? withSlash.slice(0, -1) : withSlash
100
+ }
101
+
102
+ /** Best-effort access to an optional Host service. */
103
+ function optionalService(ctx, serviceName) {
104
+ try {
105
+ return ctx.get(serviceName) ?? null
106
+ } catch {
107
+ return null
108
+ }
109
+ }
110
+
111
+ /** Write one JSON response. */
112
+ function writeJson(res, status, value, req) {
113
+ const body = JSON.stringify(value)
114
+ res.statusCode = status
115
+ for (const [key, header] of Object.entries(JSON_HEADERS)) res.setHeader(key, header)
116
+ res.setHeader('content-length', Buffer.byteLength(body))
117
+ if (req?.method === 'HEAD') {
118
+ res.end()
119
+ return
120
+ }
121
+ res.end(body)
122
+ }
123
+
124
+ /** Apply the Web Connection origin trust policy when the service is composed. */
125
+ function requestRejection(ctx, req) {
126
+ const connection = optionalService(ctx, 'connection')
127
+ if (!connection?.requestRejection) return 0
128
+ try {
129
+ return connection.requestRejection({ headers: req.headers }) || 0
130
+ } catch {
131
+ return 0
132
+ }
133
+ }
134
+
135
+ /** Browser-session credential admission on top of the origin check. */
136
+ function requestAdmission(ctx, req) {
137
+ const connection = optionalService(ctx, 'connection')
138
+ if (!connection?.admit) return 0
139
+ try {
140
+ const admission = connection.admit({ headers: req.headers })
141
+ return admission && typeof admission === 'object' && 'rejection' in admission ? admission.rejection : 0
142
+ } catch {
143
+ return 0
144
+ }
145
+ }
146
+
147
+ /** Parse a bounded JSON request body. */
148
+ async function readJsonBody(req) {
149
+ const chunks = []
150
+ let total = 0
151
+ for await (const chunk of req) {
152
+ total += chunk.length
153
+ if (total > BODY_LIMIT) throw new TimebackError('请求体过大', 'timeback/body-too-large')
154
+ chunks.push(chunk)
155
+ }
156
+ if (total === 0) return {}
157
+ try {
158
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
159
+ } catch {
160
+ throw new TimebackError('请求体不是合法 JSON', 'timeback/body-invalid')
161
+ }
162
+ }
163
+
164
+ /** Strip non-JSON values (undefined object members) from a tool result. */
165
+ function toLossless(value) {
166
+ try {
167
+ return JSON.parse(JSON.stringify(value))
168
+ } catch {
169
+ return value
170
+ }
171
+ }
172
+
173
+ /** Render a JSON tool result as bounded text. */
174
+ function renderValue(value) {
175
+ let text
176
+ try {
177
+ text = JSON.stringify(value, null, 2)
178
+ } catch {
179
+ text = String(value)
180
+ }
181
+ return [{ type: 'text', text: text.length <= RENDER_LIMIT ? text : `${text.slice(0, RENDER_LIMIT)}\n…(已截断)` }]
182
+ }
183
+
184
+ /** Build one model-facing tool definition. */
185
+ function tool(name, description, properties, required, execute) {
186
+ return {
187
+ name,
188
+ description,
189
+ parameters: { type: 'object', properties, required, additionalProperties: false },
190
+ output: { schema: { type: 'object', additionalProperties: true }, render: (_args, value) => renderValue(value) },
191
+ async execute(args, exec) {
192
+ try {
193
+ return toLossless(await execute(args, exec))
194
+ } catch (error) {
195
+ if (error instanceof TimebackError) return { ok: false, code: error.code, error: error.message }
196
+ throw error
197
+ }
198
+ },
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Host plugin entry point.
204
+ * @param ctx - Host context.
205
+ * @param rawConfig - row configuration from the bundle patch.
206
+ */
207
+ export function apply(ctx, rawConfig) {
208
+ const config = resolveConfig(ctx, rawConfig)
209
+ const logger = ctx.logger ?? console
210
+ const lifetime = new AbortController()
211
+ ctx.effect(() => () => lifetime.abort(), 'timeback: plugin lifetime')
212
+
213
+ const runner = new GitRunner(ctx.subprocess, {
214
+ timeoutMs: config.timeoutMs,
215
+ maxBytes: config.maxBytes,
216
+ lifetime,
217
+ logger,
218
+ })
219
+ const protectedPaths = [config.dataDir]
220
+ if (process.env.DSH_HOME) protectedPaths.push(process.env.DSH_HOME)
221
+ const profileDir = optionalService(ctx, 'profileContext')?.dir
222
+ if (typeof profileDir === 'string' && profileDir !== '') protectedPaths.push(profileDir)
223
+ const store = new SnapshotStore({
224
+ dataDir: config.dataDir,
225
+ runner,
226
+ exclude: config.exclude,
227
+ logger,
228
+ protectedPaths,
229
+ maxFiles: config.maxFiles,
230
+ probeTimeoutMs: config.probeTimeoutMs,
231
+ })
232
+ const notes = new NotesStore({ dataDir: config.dataDir, logger })
233
+ const registry = new CheckpointRegistry({
234
+ dataDir: config.dataDir,
235
+ maxCheckpoints: config.maxCheckpoints,
236
+ logger,
237
+ onDrop: (sessionId, dropped) => store.dropCheckpointRefs(sessionId, dropped.map((checkpoint) => checkpoint.id)),
238
+ })
239
+ const service = new TimebackService({
240
+ ctx,
241
+ config,
242
+ store,
243
+ registry,
244
+ notes,
245
+ logger,
246
+ lifetime,
247
+ sessionController: ctx.sessionController,
248
+ workingDirectory: optionalService(ctx, 'workingDirectory'),
249
+ sessions: optionalService(ctx, 'sessions'),
250
+ sessionTitle: optionalService(ctx, 'sessionTitle'),
251
+ workspaceRegistry: optionalService(ctx, 'workspaceRegistry'),
252
+ })
253
+ service.start().catch((error) => logger.warn?.(`timeback: initialization failed: ${error?.message ?? error}`))
254
+
255
+ /* ---------------------------------------------------------------- */
256
+ /* capture hooks */
257
+ /* ---------------------------------------------------------------- */
258
+ if (config.capture !== 'off') {
259
+ ctx.on('session/event', (session, event) => {
260
+ if (!event || !session) return
261
+ if (event.type === 'turn/start') service.onTurnStart(session, event.data?.turn)
262
+ else if (event.type === 'user/message') service.onUserMessage(session, event)
263
+ else if (event.type === 'turn/end') service.onTurnEnd(session, event.data?.turn, event.seq)
264
+ })
265
+ ctx.on('agent/turn-stopping', async (payload) => {
266
+ const session = payload?.agent?.session
267
+ if (session) await service.onTurnStopping(session, payload.turn)
268
+ })
269
+ ctx.on('tools/pre-execute', async (exec, next) => {
270
+ await service.gateTool(exec)
271
+ return next()
272
+ })
273
+ }
274
+ ctx.on('session/disposed', (session) => {
275
+ service.onSessionDisposed(session)
276
+ })
277
+
278
+ /* ---------------------------------------------------------------- */
279
+ /* HTTP routes for the Web panel */
280
+ /* ---------------------------------------------------------------- */
281
+ const actionRoutes = new Set([
282
+ 'rewind',
283
+ 'restore-files',
284
+ 'checkpoint',
285
+ 'status',
286
+ 'set-workspace',
287
+ 'workspaces',
288
+ 'prune',
289
+ 'notes-list',
290
+ 'note-save',
291
+ 'note-delete',
292
+ 'card-note',
293
+ ])
294
+ const handler = async (req, res) => {
295
+ try {
296
+ const url = new URL(req.url || '/', 'http://localhost')
297
+ const method = req.method || 'GET'
298
+ const rejection = requestRejection(ctx, req)
299
+ if (rejection) {
300
+ writeJson(res, rejection, { ok: false, code: 'timeback/untrusted', error: '请求来源不受信任' }, req)
301
+ return
302
+ }
303
+ const admission = requestAdmission(ctx, req)
304
+ if (admission) {
305
+ writeJson(res, admission, { ok: false, code: 'timeback/unauthenticated', error: '浏览器会话未认证' }, req)
306
+ return
307
+ }
308
+ const pathname = url.pathname
309
+ if (method === 'GET' || method === 'HEAD') {
310
+ if (pathname === `${config.routePath}/api/health`) {
311
+ writeJson(res, 200, await service.status(), req)
312
+ return
313
+ }
314
+ if (pathname === `${config.routePath}/api/notes`) {
315
+ writeJson(res, 200, { ok: true, board: await service.board() }, req)
316
+ return
317
+ }
318
+ if (pathname === `${config.routePath}/api/tree`) {
319
+ const sessionId = url.searchParams.get('session')
320
+ if (!sessionId) throw new TimebackError('缺少 session 参数', 'timeback/session-required')
321
+ const includeFiles = url.searchParams.get('files') === '1'
322
+ writeJson(res, 200, await service.tree({ sessionId, includeFiles }), req)
323
+ return
324
+ }
325
+ writeJson(res, 404, { ok: false, code: 'timeback/not-found', error: `未知路由 ${pathname}` }, req)
326
+ return
327
+ }
328
+ if (method !== 'POST' || pathname !== `${config.routePath}/api/action`) {
329
+ writeJson(res, 405, { ok: false, code: 'timeback/method', error: '不支持的请求方法或路由' }, req)
330
+ return
331
+ }
332
+ const body = await readJsonBody(req)
333
+ const action = typeof body.action === 'string' ? body.action : ''
334
+ if (!actionRoutes.has(action)) throw new TimebackError(`未知操作:${action}`, 'timeback/action-unknown')
335
+ if (action === 'status') {
336
+ writeJson(res, 200, await service.status(), req)
337
+ return
338
+ }
339
+ if (action === 'workspaces') {
340
+ writeJson(
341
+ res,
342
+ 200,
343
+ {
344
+ ok: true,
345
+ ...(await service.listWorkspaces({
346
+ sessionId: typeof body.sessionId === 'string' && body.sessionId !== '' ? body.sessionId : undefined,
347
+ cwd: typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : undefined,
348
+ })),
349
+ },
350
+ req,
351
+ )
352
+ return
353
+ }
354
+ if (action === 'set-workspace') {
355
+ writeJson(
356
+ res,
357
+ 200,
358
+ {
359
+ ok: true,
360
+ ...(await service.setWorkspace({
361
+ sessionId: typeof body.sessionId === 'string' && body.sessionId !== '' ? body.sessionId : undefined,
362
+ cwd: typeof body.cwd === 'string' && body.cwd !== '' ? body.cwd : undefined,
363
+ enabled: body.enabled !== false,
364
+ })),
365
+ },
366
+ req,
367
+ )
368
+ return
369
+ }
370
+ if (action === 'notes-list') {
371
+ writeJson(res, 200, { ok: true, board: await service.board() }, req)
372
+ return
373
+ }
374
+ if (action === 'note-save') {
375
+ writeJson(
376
+ res,
377
+ 200,
378
+ await service.saveBoardNote(
379
+ {
380
+ id: typeof body.id === 'string' ? body.id : undefined,
381
+ title: typeof body.title === 'string' ? body.title : '',
382
+ body: typeof body.body === 'string' ? body.body : '',
383
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : undefined,
384
+ cwd: typeof body.cwd === 'string' ? body.cwd : undefined,
385
+ },
386
+ 'user',
387
+ ),
388
+ req,
389
+ )
390
+ return
391
+ }
392
+ if (action === 'note-delete') {
393
+ writeJson(res, 200, await service.deleteBoardNote(typeof body.id === 'string' ? body.id : ''), req)
394
+ return
395
+ }
396
+ if (action === 'card-note') {
397
+ writeJson(
398
+ res,
399
+ 200,
400
+ await service.saveCardNote({
401
+ sessionId: typeof body.sessionId === 'string' ? body.sessionId : '',
402
+ checkpointId: typeof body.checkpointId === 'string' ? body.checkpointId : undefined,
403
+ note: typeof body.note === 'string' ? body.note : '',
404
+ }),
405
+ req,
406
+ )
407
+ return
408
+ }
409
+ const sessionId = typeof body.sessionId === 'string' ? body.sessionId : ''
410
+ if (action === 'checkpoint') {
411
+ if (!sessionId) throw new TimebackError('缺少 sessionId', 'timeback/session-required')
412
+ const label = typeof body.label === 'string' && body.label.trim() !== '' ? body.label.trim().slice(0, 120) : '手动检查点'
413
+ writeJson(res, 200, { ok: true, ...(await service.createCheckpoint({ sessionId, label })) }, req)
414
+ return
415
+ }
416
+ const checkpointId = typeof body.checkpointId === 'string' ? body.checkpointId : ''
417
+ if (!checkpointId) throw new TimebackError('缺少 checkpointId', 'timeback/checkpoint-required')
418
+ if (action === 'prune') {
419
+ writeJson(
420
+ res,
421
+ 200,
422
+ await service.prune({
423
+ sessionId: sessionId || undefined,
424
+ checkpointId,
425
+ mode: body.mode === 'branch-only' ? 'branch-only' : 'branch-and-files',
426
+ childSessionId: typeof body.childSessionId === 'string' && body.childSessionId !== '' ? body.childSessionId : undefined,
427
+ }),
428
+ req,
429
+ )
430
+ return
431
+ }
432
+ const mode = action === 'restore-files' ? 'files-only' : body.mode === 'branch-only' ? 'branch-only' : 'branch-and-files'
433
+ writeJson(res, 200, await service.rewind({ sessionId: sessionId || undefined, checkpointId, mode }), req)
434
+ } catch (error) {
435
+ const status = error instanceof TimebackError ? 400 : 500
436
+ const payload = {
437
+ ok: false,
438
+ code: error?.code ?? 'timeback/internal',
439
+ error: error?.message ? String(error.message) : String(error),
440
+ ...(error instanceof TimebackError ? { details: error.details } : {}),
441
+ }
442
+ if (status === 500) logger.warn?.(`timeback: request failed: ${payload.error}`)
443
+ writeJson(res, status, payload, req)
444
+ }
445
+ }
446
+ ctx.effect(
447
+ () => ctx.webServer.register({ kind: 'prefix', path: config.routePath, handler }),
448
+ 'timeback: browser routes',
449
+ )
450
+
451
+ /* ---------------------------------------------------------------- */
452
+ /* model-facing tools */
453
+ /* ---------------------------------------------------------------- */
454
+ const disposers = []
455
+ const sessionIdParam = { type: 'string', description: '会话 id;省略时使用当前会话' }
456
+ const resolveSessionId = (args, exec) => {
457
+ const sessionId = typeof args.sessionId === 'string' && args.sessionId !== '' ? args.sessionId : exec?.agent?.session?.id
458
+ if (!sessionId) throw new TimebackError('当前没有可用的会话', 'timeback/session-required')
459
+ return String(sessionId)
460
+ }
461
+ disposers.push(
462
+ ctx.tools.register(
463
+ tool(
464
+ 'timeback_tree',
465
+ '列出当前会话的 timeback 分支树和检查点。只有用户在工作区里手动开启记录后,每个回合才会有开始前/结束后的文件快照;返回值里的 workspace 说明当前工作区是否开启。可用 timeback_rewind 回到某个检查点。',
466
+ {
467
+ sessionId: sessionIdParam,
468
+ includeFiles: { type: 'boolean', description: '是否包含每个检查点的变更文件路径列表' },
469
+ },
470
+ [],
471
+ async (args, exec) => service.tree({ sessionId: resolveSessionId(args, exec), includeFiles: args.includeFiles === true }),
472
+ ),
473
+ ),
474
+ )
475
+ disposers.push(
476
+ ctx.tools.register(
477
+ tool(
478
+ 'timeback_checkpoint',
479
+ '为当前会话立即创建一个手动检查点(对话位置 + 工作区文件快照)。之后可用 timeback_rewind 回到这里。',
480
+ { label: { type: 'string', description: '检查点标签,省略时使用本地化的默认标签' }, sessionId: sessionIdParam },
481
+ [],
482
+ async (args, exec) =>
483
+ service.createCheckpoint({ sessionId: resolveSessionId(args, exec), label: args.label }),
484
+ ),
485
+ ),
486
+ )
487
+ disposers.push(
488
+ ctx.tools.register(
489
+ tool(
490
+ 'timeback_note',
491
+ '在时间回溯的全局 Markdown 记录板上读写记录。记录板与工作区无关、所有会话共享;回溯到某个检查点时,记录板也会一起恢复到该检查点时的状态。action=list 查看;create 新建(title/body,body 为 Markdown);update 修改(id/title/body);delete 删除(id)。用户让你记录笔记、决策、进展或结论时使用它。',
492
+ {
493
+ action: { type: 'string', enum: ['list', 'create', 'update', 'delete'], description: 'list/create/update/delete' },
494
+ id: { type: 'string', description: 'update/delete 的记录 id(nt-…)' },
495
+ title: { type: 'string', description: '记录标题(create/update,可选)' },
496
+ body: { type: 'string', description: '记录正文,Markdown 文本' },
497
+ sessionId: sessionIdParam,
498
+ },
499
+ ['action'],
500
+ async (args, exec) => {
501
+ if (args.action === 'list') {
502
+ const sessionId = typeof args.sessionId === 'string' && args.sessionId !== '' ? args.sessionId : exec?.agent?.session?.id
503
+ return { ok: true, ...(await service.board()), sessionId: sessionId ?? null }
504
+ }
505
+ if (args.action === 'create') {
506
+ const sessionId = typeof args.sessionId === 'string' && args.sessionId !== '' ? args.sessionId : exec?.agent?.session?.id
507
+ return service.saveBoardNote({ title: args.title, body: args.body, sessionId }, 'agent')
508
+ }
509
+ if (args.action === 'update') return service.saveBoardNote({ id: args.id, title: args.title, body: args.body }, 'agent')
510
+ if (args.action === 'delete') return service.deleteBoardNote(String(args.id ?? ''))
511
+ throw new TimebackError(`未知操作:${String(args.action)}`, 'timeback/action-unknown')
512
+ },
513
+ ),
514
+ ),
515
+ )
516
+ disposers.push(
517
+ ctx.tools.register(
518
+ tool(
519
+ 'timeback_rewind',
520
+ '回到某个 timeback 检查点:在检查点的对话位置创建一个新分支会话,并把工作区文件恢复成该检查点的快照。原来的会话与历史不会被删除,随时可以切回。',
521
+ {
522
+ checkpointId: { type: 'string', description: 'timeback_tree 返回的检查点 id(cp-…)' },
523
+ mode: {
524
+ type: 'string',
525
+ enum: ['branch-and-files', 'branch-only', 'files-only'],
526
+ description: 'branch-and-files:分支并恢复文件(默认);branch-only:只分支;files-only:只恢复文件、不新建会话',
527
+ },
528
+ sessionId: sessionIdParam,
529
+ },
530
+ ['checkpointId'],
531
+ async (args, exec) =>
532
+ service.rewind({
533
+ sessionId: resolveSessionId(args, exec),
534
+ checkpointId: String(args.checkpointId),
535
+ mode: args.mode,
536
+ }),
537
+ ),
538
+ ),
539
+ )
540
+ disposers.push(
541
+ ctx.tools.register(
542
+ tool(
543
+ 'timeback_workspace',
544
+ '查看或修改 timeback 的工作区记录开关。默认所有工作区都不记录;只有显式开启过的工作区目录(含其子目录)才会在每回合保存文件快照;子目录可以单独关闭以覆盖父目录的继承。只有用户明确要求开启/关闭时才调用 enable/disable,不要自行开启记录。',
545
+ {
546
+ action: { type: 'string', enum: ['list', 'enable', 'disable'], description: 'list 查看状态;enable/disable 修改记录开关' },
547
+ cwd: { type: 'string', description: '工作区目录(绝对路径);省略时使用当前会话的工作目录' },
548
+ sessionId: sessionIdParam,
549
+ },
550
+ ['action'],
551
+ async (args, exec) => {
552
+ const sessionId = typeof args.sessionId === 'string' && args.sessionId !== '' ? args.sessionId : exec?.agent?.session?.id
553
+ const explicitCwd = typeof args.cwd === 'string' && args.cwd !== ''
554
+ const input = explicitCwd
555
+ ? { cwd: args.cwd }
556
+ : sessionId
557
+ ? { sessionId: String(sessionId) }
558
+ : {}
559
+ if (args.action === 'list') return { ok: true, ...(await service.listWorkspaces(input)) }
560
+ if (args.action === 'enable' || args.action === 'disable') {
561
+ return { ok: true, ...(await service.setWorkspace({ ...input, enabled: args.action === 'enable' })) }
562
+ }
563
+ throw new TimebackError(`未知操作:${String(args.action)}`, 'timeback/action-unknown')
564
+ },
565
+ ),
566
+ ),
567
+ )
568
+ ctx.effect(() => () => {
569
+ for (const dispose of disposers) {
570
+ try {
571
+ dispose?.()
572
+ } catch {
573
+ // Already disposed by the owning context.
574
+ }
575
+ }
576
+ }, 'timeback: tools')
577
+ }
578
+
579
+ export default { name, inject, apply }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Timeback",
4
+ "description": "Conversation tree with per-turn workspace snapshots. Recording is opt-in per workspace: tick the switch in the Timeback panel and each following turn saves a checkpoint of the workspace; rewinding then creates a new branch at that turn and restores the files as they were, so a mistake can be undone without losing history or dragging the whole context along.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "时间回溯",
4
+ "description": "带逐轮文件快照的对话树。记录按工作区单独开启:在时间回溯面板里勾选后,之后每个回合都会保存该工作区的检查点;回溯时在该回合处创建新分支并把文件恢复成当时的样子——既不会丢失历史,也只需携带到该回合为止的上下文。",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "dsh-timeback",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.0",
4
+ "description": "Conversation tree with per-turn workspace snapshots for DeepSeek Harness: branch at any checkpoint and restore the files that turn had.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "keywords": [
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "deepseek-harness",
11
+ "conversation-tree",
12
+ "branch",
13
+ "checkpoint",
14
+ "rewind",
15
+ "rollback",
16
+ "time-travel"
17
+ ],
18
+ "engines": {
19
+ "dsh": ">=0.2.2-rc.1 <0.3.0-0",
20
+ "node": ">=24.9.0"
21
+ },
22
+ "exports": {
23
+ ".": "./index.js",
24
+ "./client": "./client.js",
25
+ "./locale/*.json": "./locale/*.json",
26
+ "./icon": "./icon.svg"
27
+ },
28
+ "files": [
29
+ "index.js",
30
+ "client.js",
31
+ "src",
32
+ "cordis.patch.yml",
33
+ "locale/*.json",
34
+ "icon.svg",
35
+ "docs",
36
+ "README.md",
37
+ "LICENSE",
38
+ "ACKNOWLEDGEMENTS.md"
39
+ ],
40
+ "scripts": {
41
+ "test": "node --test test/*.test.js",
42
+ "market:index": "node scripts/build-market-index.mjs"
43
+ },
44
+ "dsh": {
45
+ "bundle": {
46
+ "patch": "./cordis.patch.yml"
47
+ },
48
+ "client": {
49
+ "platform": "web",
50
+ "immediately": true,
51
+ "inject": [
52
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
53
+ "@deepseek-ai/dsh-client-ui-conversation",
54
+ "@deepseek-ai/dsh-client-ui-session",
55
+ "@deepseek-ai/dsh-client-ui-workspace",
56
+ "@deepseek-ai/dsh-client-ui-layout",
57
+ "@deepseek-ai/dsh-client-ui-context-menu"
58
+ ]
59
+ }
60
+ },
61
+ "repository": {
62
+ "type": "git",
63
+ "url": "https://github.com/ppmchen/dsh-timeback.git"
64
+ },
65
+ "homepage": "https://github.com/ppmchen/dsh-timeback#readme",
66
+ "bugs": {
67
+ "url": "https://github.com/ppmchen/dsh-timeback/issues"
68
+ },
69
+ "publishConfig": {
70
+ "registry": "https://registry.npmjs.org/"
71
+ }
72
+ }