@anionex/dsh-turn-rewind 0.3.11 → 0.3.13

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.
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto'
2
+ import { readFile } from 'node:fs/promises'
2
3
  import type { Context } from '@deepseek-ai/cordis'
3
4
  import { createDeadline } from './deadline.js'
4
5
  import { ChangeLedgerError, errorMessage } from './errors.js'
@@ -158,6 +159,15 @@ declare module '@deepseek-ai/cordis' {
158
159
  }
159
160
 
160
161
  export const REWIND_HTTP_PATH = '/turn-rewind'
162
+ /**
163
+ * Same-origin route mapping every recorded turn to its opening user-message seq.
164
+ *
165
+ * DSH 0.2.0 removed the per-message chat snapshot from session-scoped slot
166
+ * entries, so the browser half can no longer resolve a rendered message row back
167
+ * to the Session event seq the rewind API anchors on. This read-only endpoint
168
+ * restores that mapping without touching project files or the Session log.
169
+ */
170
+ export const TURNS_HTTP_PATH = '/turn-rewind/turns'
161
171
  const BODY_LIMIT = 64 * 1024
162
172
  const INITIAL_CHANGE_PREVIEW_LIMIT = 8
163
173
  const MAX_CHANGE_PAGE_SIZE = 200
@@ -397,6 +407,132 @@ export function installRewindHttp(
397
407
  path: REWIND_HTTP_PATH,
398
408
  handler: createRewindHttpHandler(ctx, engine, coordinator),
399
409
  }), 'change-ledger.rewindHttp')
410
+ ctx.effect(() => ctx.webServer.register({
411
+ kind: 'exact',
412
+ path: TURNS_HTTP_PATH,
413
+ handler: createTurnsHttpHandler(ctx),
414
+ }), 'change-ledger.turnsHttp')
415
+ }
416
+
417
+ /** Build the read-only turn-anchor handler as a testable unit. */
418
+ export function createTurnsHttpHandler(
419
+ ctx: Pick<Context, 'sessions' | 'sessionQuery'>,
420
+ ): (request: HttpRequestLike, response: HttpResponseLike) => Promise<void> {
421
+ return async (request, response) => {
422
+ try {
423
+ if (request.method !== 'GET') {
424
+ json(response, 405, { error: 'method not allowed' })
425
+ return
426
+ }
427
+ const url = new URL(request.url ?? TURNS_HTTP_PATH, 'http://dsh.local')
428
+ const sessionId = requiredText(url.searchParams.get('sessionId'), 'sessionId')
429
+ json(response, 200, { turns: listTurnAnchors(await readSession(ctx, sessionId)) })
430
+ } catch (error) {
431
+ const status = error instanceof ChangeLedgerError && error.code === 'RESTORE_POINT_NOT_FOUND' ? 404 : 409
432
+ json(response, status, { error: errorMessage(error), code: error instanceof ChangeLedgerError ? error.code : 'REWIND_FAILED' })
433
+ }
434
+ }
435
+ }
436
+
437
+ /** One rewind anchor the browser keys a rendered message row by its turn number. */
438
+ interface TurnAnchorLike {
439
+ readonly turn: number
440
+ readonly userSeq: number
441
+ readonly turnStartSeq: number
442
+ readonly previousTurnEndSeq?: number
443
+ readonly promptText: string
444
+ readonly attachments?: readonly TurnAttachmentLike[]
445
+ }
446
+
447
+ /** One durable `image` / `file` reference distilled for the browser restart dialog. */
448
+ interface TurnAttachmentLike {
449
+ readonly kind: 'image' | 'file'
450
+ readonly attachmentId: string
451
+ readonly name: string
452
+ readonly mediaType: string
453
+ }
454
+
455
+ /**
456
+ * Anchor every recorded turn to its opening direct user message.
457
+ *
458
+ * Mirrors `messageTarget` from the apply path: a turn opens at its first direct
459
+ * `user/message` after `turn/start` and closes at the following `turn/end`. The
460
+ * currently open turn is included; callers gate restoration separately.
461
+ * @param session - live or stored session to scan.
462
+ * @returns clean turns in event order.
463
+ */
464
+ function listTurnAnchors(session: SessionLike): readonly TurnAnchorLike[] {
465
+ const anchors: TurnAnchorLike[] = []
466
+ let turnStart: SessionEventLike | undefined
467
+ let previousTurnEnd: SessionEventLike | undefined
468
+ let opening: SessionEventLike | undefined
469
+ const flush = (): void => {
470
+ if (turnStart === undefined || opening === undefined) return
471
+ const turn = turnStart.data.turn
472
+ if (!Number.isSafeInteger(turn) || (turn as number) < 0) return
473
+ const attachments = turnAttachments(opening.data)
474
+ anchors.push({
475
+ turn: turn as number,
476
+ userSeq: opening.seq,
477
+ turnStartSeq: turnStart.seq,
478
+ ...(previousTurnEnd === undefined ? {} : { previousTurnEndSeq: previousTurnEnd.seq }),
479
+ promptText: turnPromptText(opening.data),
480
+ ...(attachments.length === 0 ? {} : { attachments }),
481
+ })
482
+ }
483
+ for (const event of getSessionEvents(session)) {
484
+ if (event.type === 'turn/start') {
485
+ flush()
486
+ turnStart = event
487
+ opening = undefined
488
+ continue
489
+ }
490
+ if (event.type === 'turn/end') {
491
+ flush()
492
+ turnStart = undefined
493
+ opening = undefined
494
+ previousTurnEnd = event
495
+ continue
496
+ }
497
+ if (turnStart !== undefined && opening === undefined && event.type === 'user/message' && isDirectUserMessage(event)) {
498
+ opening = event
499
+ }
500
+ }
501
+ flush()
502
+ return anchors
503
+ }
504
+
505
+ function turnPromptText(data: Record<string, unknown>): string {
506
+ const content = data.content
507
+ if (!Array.isArray(content)) return ''
508
+ const parts: string[] = []
509
+ for (const block of content) {
510
+ if (block === null || typeof block !== 'object') continue
511
+ const record = block as Record<string, unknown>
512
+ if (record.type === 'text' && typeof record.text === 'string') parts.push(record.text)
513
+ }
514
+ return parts.join('\n')
515
+ }
516
+
517
+ function turnAttachments(data: Record<string, unknown>): readonly TurnAttachmentLike[] {
518
+ const content = data.content
519
+ if (!Array.isArray(content)) return []
520
+ const attachments: TurnAttachmentLike[] = []
521
+ for (const block of content) {
522
+ if (block === null || typeof block !== 'object') continue
523
+ const record = block as Record<string, unknown>
524
+ if (record.type !== 'image' && record.type !== 'file') continue
525
+ const raw = record.attachment
526
+ const attachment = raw !== null && typeof raw === 'object' ? raw as Record<string, unknown> : {}
527
+ const kind = record.type
528
+ attachments.push({
529
+ kind,
530
+ attachmentId: typeof attachment.attachmentId === 'string' ? attachment.attachmentId : '',
531
+ name: typeof attachment.name === 'string' && attachment.name !== '' ? attachment.name : kind,
532
+ mediaType: typeof attachment.mediaType === 'string' && attachment.mediaType !== '' ? attachment.mediaType : 'application/octet-stream',
533
+ })
534
+ }
535
+ return attachments
400
536
  }
401
537
 
402
538
  /** Build the exact-route handler as a testable unit. */
@@ -839,6 +975,93 @@ function json(response: HttpResponseLike, status: number, value: unknown): void
839
975
  response.end(`${JSON.stringify(value)}\n`)
840
976
  }
841
977
 
978
+ /** Same-origin route that replays one stored attachment's bytes to the browser. */
979
+ export const ATTACHMENT_HTTP_PATH = '/turn-rewind/attachment-bytes'
980
+
981
+ /** Shape of a durable attachment reference as stored on a user message. */
982
+ interface AttachmentRefLike {
983
+ readonly attachmentId: string
984
+ readonly name?: string
985
+ readonly mediaType?: string
986
+ }
987
+
988
+ /**
989
+ * Attachment store capability needed to turn a durable reference back into bytes.
990
+ *
991
+ * Both readers are provider-owned: a deployment without a local store rejects
992
+ * them, which this route reports as an unavailable attachment rather than a
993
+ * crash.
994
+ */
995
+ interface AttachmentStoreLike {
996
+ fileHostPath(ref: { readonly attachmentId: string }): string | undefined
997
+ imageHostPath(ref: { readonly attachmentId: string }): string | undefined
998
+ }
999
+
1000
+ /** Register the attachment-bytes route consumed by the rewound composer draft. */
1001
+ export function installAttachmentHttp(ctx: Context): void {
1002
+ ctx.effect(() => (ctx as unknown as { webServer: HttpServerLike }).webServer.register({
1003
+ kind: 'exact',
1004
+ path: ATTACHMENT_HTTP_PATH,
1005
+ handler: createAttachmentHttpHandler(ctx),
1006
+ }), 'change-ledger.attachmentHttp')
1007
+ }
1008
+
1009
+ /**
1010
+ * Build the attachment-bytes route as a testable unit.
1011
+ *
1012
+ * Bytes travel in a JSON envelope shared by Web and Desktop carriers;
1013
+ * the browser rebuilds a `File` from the verified message reference.
1014
+ */
1015
+ export function createAttachmentHttpHandler(
1016
+ ctx: Pick<Context, 'get' | 'sessions' | 'sessionQuery'>,
1017
+ ): (request: HttpRequestLike, response: HttpResponseLike) => Promise<void> {
1018
+ return async (request, response) => {
1019
+ if (request.method !== 'GET') {
1020
+ json(response, 405, { ok: false, error: 'method not allowed' })
1021
+ return
1022
+ }
1023
+ try {
1024
+ const url = new URL(request.url ?? ATTACHMENT_HTTP_PATH, 'http://dsh.local')
1025
+ const attachmentId = requiredText(url.searchParams.get('attachmentId'), 'attachmentId')
1026
+ const sessionId = requiredText(url.searchParams.get('sessionId'), 'sessionId')
1027
+ const messageSeq = Number(url.searchParams.get('messageSeq'))
1028
+ if (!url.searchParams.has('messageSeq') || !Number.isSafeInteger(messageSeq) || messageSeq < 0) throw new Error('invalid messageSeq')
1029
+ const kind = url.searchParams.get('kind')
1030
+ if (kind !== 'image' && kind !== 'file') throw new Error('invalid attachment kind')
1031
+ const session = await readSession(ctx, sessionId)
1032
+ const message = getSessionEvents(session).find(event => event.seq === messageSeq && event.type === 'user/message' && isDirectUserMessage(event))
1033
+ const blocks = Array.isArray(message?.data.content) ? message.data.content : []
1034
+ const block = blocks.find(value => value?.type === kind && value.attachment?.attachmentId === attachmentId)
1035
+ if (block === undefined) {
1036
+ json(response, 404, { ok: false, error: 'attachment is not referenced by the selected message' })
1037
+ return
1038
+ }
1039
+ const store = ctx.get('attachments') as AttachmentStoreLike | undefined
1040
+ if (store === undefined) {
1041
+ json(response, 503, { ok: false, error: 'attachment store is unavailable' })
1042
+ return
1043
+ }
1044
+ const ref = block.attachment as AttachmentRefLike
1045
+ const hostPath = kind === 'image' ? store.imageHostPath(ref) : store.fileHostPath(ref)
1046
+ if (hostPath === undefined) {
1047
+ json(response, 503, { ok: false, error: 'attachment is not available from the local store' })
1048
+ return
1049
+ }
1050
+ const bytes = await readFile(hostPath)
1051
+ json(response, 200, {
1052
+ ok: true,
1053
+ attachmentId,
1054
+ kind,
1055
+ ...(ref.mediaType === undefined ? {} : { mediaType: ref.mediaType }),
1056
+ data: bytes.toString('base64'),
1057
+ })
1058
+ } catch (error) {
1059
+ const message = errorMessage(error)
1060
+ json(response, message.includes('ENOENT') ? 404 : 400, { ok: false, error: 'unable to restore the selected attachment' })
1061
+ }
1062
+ }
1063
+ }
1064
+
842
1065
  export const MANAGE_HTTP_PATH = '/turn-rewind/manage'
843
1066
 
844
1067
  /** Register the same-origin storage-management endpoint consumed by the settings card. */