dsh-seal-scripts 0.6.0 → 0.6.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.
package/README.en.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - [Install](#sec-install)
21
21
  - [Quick start](#sec-quickstart)
22
22
  - [Sealed scripts](#sec-tools)
23
+ - [Session management](#sec-sessions)
23
24
  - [Reviews](#sec-reviews)
24
25
  - [Configuration and settings page](#sec-config)
25
26
  - [Data and backup](#sec-data)
@@ -190,6 +191,40 @@ Two clicks (the first only changes the button label):
190
191
  - Only "valid id + `.bak-` + digits" directories count; a staged import package is skipped.
191
192
  - One entry that cannot be removed does not abort the run; the receipt reports counts and bytes.
192
193
 
194
+ <a name="sec-sessions"></a>
195
+
196
+ ## Session management
197
+
198
+ The Sessions tab lists this machine's sessions grouped by workspace and manages each one: import a package, delete it, or delete it after producing a review.
199
+
200
+ #### The list
201
+
202
+ - **Grouped by workspace**: one block per workspace that has sessions, headed by the workspace path; empty workspaces take no space.
203
+ - **One row each**: the session title (the id in grey while a title does not exist yet), with an **Archived** badge when the session is archived.
204
+ - **Unreadable logs are named**: when a log cannot be decoded the list says so at the top instead of showing it as an empty session.
205
+
206
+ #### Import
207
+
208
+ - **One button**: the leftmost **Import** in the footer takes a `dsh-session-<id>.zip`; no hand-built directories. When the host cannot write zstd the button is disabled and says why.
209
+ - **Preview first**: the dry run says whether the id will be renamed and whether it hangs under that session as a branch; nothing is written until you confirm.
210
+ - **Openable immediately**: the log is packed the way DSH stores it (a one-line header frame plus a body frame) and then `attachSession` registers it; images and files land under the attachment store by sha256; the host is told the list gained a session, so the main window shows it at once, with no restart.
211
+ - **Collisions are not forced**: an id that already exists anywhere on this machine gets a new id and the original stays untouched; a same-workspace collision also hangs under that session as a branch (`parentSession`), another workspace gets a plain rename. A session that carries inherited history (`isSeeded:true`) records its real inherited count and still opens and branches.
212
+ - **Backed up first**: the workspace roster and projection cache are copied into `会话导入备份-<time>/` inside the target workspace before writing.
213
+
214
+ #### Delete
215
+
216
+ - **Two taps**: the first tap only turns the button into Confirm; the second deletes.
217
+ - **Live sessions are closed first**: cancel → wait idle → flush → release the write handle, then remove the directory; if it cannot be closed, the delete is refused and the log is kept.
218
+ - **Removed from the list**: the directory is deleted and the session is detached from its workspace, so it leaves the list at once.
219
+ - **Leftovers are reported**: when the engine still holds a reference, the receipt says so ("it may be remembered until restart") instead of pretending it is clean.
220
+
221
+ #### Delete + review
222
+
223
+ - **Review first, then delete**: compact, wait for the review to be split out, validate, and only then delete.
224
+ - **No delete on failure**: any failing step keeps the session; the worst case is "compaction succeeded, split failed, session still there", and that compaction is irreversible.
225
+ - **Log**: each failing step writes a line to `session-memory/_compact-delete.log`, otherwise only one English error remains.
226
+ - **Result**: the review it produces shows up on the Reviews tab and decays by calendar day.
227
+
193
228
  <a name="sec-reviews"></a>
194
229
 
195
230
  ## Reviews and context memory
package/README.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - [安装](#sec-install)
21
21
  - [快速开始](#sec-quickstart)
22
22
  - [脚本固存](#sec-tools)
23
+ - [会话管理](#sec-sessions)
23
24
  - [回顾](#sec-reviews)
24
25
  - [配置与设置页](#sec-config)
25
26
  - [数据位置与备份](#sec-data)
@@ -190,6 +191,40 @@ $DSH_HOME/session-memory/toolSequence/
190
191
  - 只认「合法 id + `.bak-` + 纯数字」的目录;进行中的导入临时包跳过。
191
192
  - 单项删不掉不中断整轮,回执报数量与字节。
192
193
 
194
+ <a name="sec-sessions"></a>
195
+
196
+ ## 会话管理
197
+
198
+ 会话页按工作区分组列出本机会话,一条一条管:整包导入、删除、删除并回顾。列表读的是落盘日志,不用打开会话也能看。
199
+
200
+ #### 列表
201
+
202
+ - **按工作区分组**:每个有会话的工作区一段,段头是工作区路径;空工作区不占位置。
203
+ - **每条一行**:会话标题(还没有标题时用 id 占位、灰色显示),归档的会话带「已归档」徽章。
204
+ - **读不出来就说**:日志解不开时列表顶上一句说明,不把读不出的会话显示成「空会话」。
205
+
206
+ #### 导入
207
+
208
+ - **一个按键**:页脚最左边「导入」,选 `dsh-session-<id>.zip` 即可,不用手搓目录;宿主写不了 zstd 时这个按钮直接禁用并说明原因。
209
+ - **先看后装**:选包先预演(会不会换新 id、要不要挂分支),确认才落盘。
210
+ - **写完就能开**:日志按 DSH 的格式压成「首帧户口本 + 正文帧」,再 `attachSession` 登记;图与文件按 sha256 落到附件库;落盘后通知宿主列表新增,主界面左侧立刻出现,不用重启。
211
+ - **撞号不硬来**:同 id 撞上本机任何已有会话就换新 id,原来那条一个字节都不动;同工作区的撞号还会挂成原会话的分支(`parentSession`),别的工作区只换号。带继承历史的会话(`isSeeded:true`)按包内实际条数记,照样能开、能挂分支。
212
+ - **写盘前先备份**:`workspace.json` 与目录册备份到目标工作区的 `会话导入备份-<时间>/`。
213
+
214
+ #### 删除
215
+
216
+ - **二次确认**:第一次点只把按钮变成「确认」,再点才真删。
217
+ - **活的先关**:会话还在内存里时先 cancel → 等闲 → flush → 释放句柄,再删目录;关不掉就拒绝,日志原样保留。
218
+ - **删完摘牌**:目录删掉后从工作区里摘掉,列表里同时消失。
219
+ - **残留会说**:引擎里还留着引用时,回执会明说「重启前可能还记着它」,不假装干净。
220
+
221
+ #### 删除并回顾
222
+
223
+ - **先留档再删**:先压缩出回顾、等拆出、校验通过,才删会话。
224
+ - **失败不删**:任何一步失败都不删,最坏情况是「压缩成功、拆失败、会话还在」;这一步不可逆。
225
+ - **日志**:每一步失败都写一行到 `session-memory/_compact-delete.log`,不然只剩一句英文报错。
226
+ - **产物**:生成的回顾出现在「回顾」页,按自然日衰减。
227
+
193
228
  <a name="sec-reviews"></a>
194
229
 
195
230
  ## 回顾(上下文记忆)
@@ -264,7 +299,7 @@ $DSH_HOME/session-memory/toolSequence/
264
299
  | 标签 | 内容 |
265
300
  |---|---|
266
301
  | 自创工具 | 工具路径、注入的提示词原文、清单开关与刷新时刻、导入 / 导出 / 清除缓存 |
267
- | 会话 | 按工作区分组的会话列表;删除、删除并回顾(二次确认) |
302
+ | 会话 | 按工作区分组的会话列表;导入会话包、删除、删除并回顾(后两者二次确认) |
268
303
  | 回顾 | 日历筛选、回顾列表(深度徽章)、注入预览、删除单条 |
269
304
  | 选项 | 四组:工具固存、回顾注入、回顾内容、回顾深度 |
270
305
 
package/lib/client.js CHANGED
@@ -262,7 +262,20 @@ window.__ModuleLoader__.load({
262
262
  'help.injectGroup': '回顾划分为四级深度,载入内容分别为:3级,载入原对话文本;2级,载入压缩概述;1级,载入模型总结;0级,仅载入关键词作为索引。\n回顾深度降低点分别为第二天、第三天、第二十八天及以后,在被用户指出模型内容记忆有误时,模型自身会调用session_mem_read直接读取回顾文件的原会话对话文本,并且对对应回顾加权并锁定载入内容。使用过程中出现深度为1级、0级的空回顾时,这是正常现象,插件会通过注入提醒来让模型调用session_mem_write写总结与提取关键词,上下文侧与系统提示词侧的遵守程度不同,请根据实际情况选用。\n不建议开启“全量加载”,关键节点建议直接使用DSH自带的分支功能。',
263
263
  'opt.auto': '自动回顾',
264
264
  'opt.auto.desc': '开启时维持原来的行为:压缩后创建回顾文件,并按下面的设置将回顾注入上下文,将提醒注入到选择的位置。关闭后停止创建与注入,下面所有选项变为不可改。',
265
- 'opt.auto.off': '未开启回顾功能,已停止回顾文件的创建与注入,如果你没有其他记忆插件或者回顾工作流系统,建议开启本项。'
265
+ 'opt.auto.off': '未开启回顾功能,已停止回顾文件的创建与注入,如果你没有其他记忆插件或者回顾工作流系统,建议开启本项。',
266
+ 'si.import': '导入',
267
+ 'si.target': '目标工作区',
268
+ 'si.preview': function (id, cwd) { return '包内会话:' + id + '\n工作目录:' + cwd },
269
+ 'si.previewTarget': function (title, path) { return '将导入到:' + (title || path) + '(' + path + ')' },
270
+ 'si.branchWarn': '同 id 已在目标工作区:导入会换成新 id,并挂成那条会话的分支;原来那条一个字都不动。',
271
+ 'si.renameWarn': '同 id 已在别的工作区,导入时会换成新 id;原来那条一个字节都不动。',
272
+ 'si.counts': function (m, f, s) { return '包内有图片 ' + m + ' 张、文件 ' + f + ' 个、子代理 ' + s + ' 条。' },
273
+ 'si.confirm': '确认导入',
274
+ 'si.cancel': '取消',
275
+ 'si.done': function (id, m, f) { return '已导入 ' + id + ';图片 ' + m + ' 张,文件 ' + f + ' 个。' },
276
+ 'si.doneRenamed': function (id, old) { return '已导入,id 换成 ' + id + '(原 ' + old + ');原来那条没动。' },
277
+ 'si.noTarget': '没有可选的工作区:先在 DSH 里建一个。',
278
+ 'si.noZstd': '这台机器的 Node 没有 zstdCompress,写不了会话日志,导入暂不可用。'
266
279
  },
267
280
  en: {
268
281
  'app.title': 'Tool (script) manager',
@@ -394,7 +407,20 @@ window.__ModuleLoader__.load({
394
407
  'help.injectGroup': 'A review has four depths, each loading something different: level 3, the original transcript; level 2, the compaction summary; level 1, the model’s own summary; level 0, keywords only, used as an index.\nDepths drop on the second day, the third day, and the twenty-eighth day onward. When you point out that the model misremembers something, the model itself calls session_mem_read to read that review’s original transcript, then weights and locks the loaded content of that review. An empty review at depth 1 or 0 is normal: the plugin injects a reminder telling the model to call session_mem_write with a summary and keywords. Compliance differs between the context channel and the system-prompt channel, so pick whichever fits.\nTurning on “Full load” is not recommended; for important checkpoints, use DSH’s own branching instead.',
395
408
  'opt.auto': 'Auto review',
396
409
  'opt.auto.desc': 'When on, behaviour stays as before: a review is created on every compaction and injected into the context and system prompt per the options below. When off, creation and injection stop and every option below becomes read-only.',
397
- 'opt.auto.off': 'Review is off, so review files are neither created nor injected. If you have no other memory plugin or review workflow, turn this on.'
410
+ 'opt.auto.off': 'Review is off, so review files are neither created nor injected. If you have no other memory plugin or review workflow, turn this on.',
411
+ 'si.import': 'Import',
412
+ 'si.target': 'Target workspace',
413
+ 'si.preview': function (id, cwd) { return 'Session in the package: ' + id + '\nWorking directory: ' + cwd },
414
+ 'si.previewTarget': function (title, path) { return 'Import into: ' + (title || path) + ' (' + path + ')' },
415
+ 'si.branchWarn': 'This id already exists in the target workspace: the import will use a new id and attach it under that session as a branch, leaving the original untouched.',
416
+ 'si.renameWarn': 'This id already lives in another workspace; the import will use a new id and leave the original untouched.',
417
+ 'si.counts': function (m, f, s) { return 'The package holds ' + m + ' image(s), ' + f + ' file(s) and ' + s + ' subagent session(s).' },
418
+ 'si.confirm': 'Import',
419
+ 'si.cancel': 'Cancel',
420
+ 'si.done': function (id, m, f) { return 'Imported ' + id + '; ' + m + ' image(s), ' + f + ' file(s).' },
421
+ 'si.doneRenamed': function (id, old) { return 'Imported with a new id ' + id + ' (was ' + old + '); the original was left alone.' },
422
+ 'si.noTarget': 'No workspace to import into: create one in DSH first.',
423
+ 'si.noZstd': 'This host runs a Node without zstdCompress, so session logs cannot be written; import is unavailable.'
398
424
  },
399
425
  ja: {
400
426
  'app.title': 'ツール(スクリプト)管理',
@@ -524,7 +550,20 @@ window.__ModuleLoader__.load({
524
550
  'help.injectGroup': 'レビューは 4 段階の深度に分かれ、読み込む内容が異なります:レベル 3 は元の会話文、レベル 2 は圧縮要約、レベル 1 はモデル自身のまとめ、レベル 0 はキーワードのみ(索引として使う)。\n深度は 2 日目、3 日目、28 日目以降に下がります。モデルの記憶違いを指摘すると、モデルは session_mem_read を呼んでそのレビューの原文を読み直し、該当レビューの重みを上げて読み込み内容をロックします。レベル 1・0 の空レビューは正常で、プラグインは注入リマインダーでモデルに session_mem_write でまとめとキーワードを書かせます。コンテキスト側とシステムプロンプト側で遵守度が異なるため、状況に応じて選んでください。\n「全量読み込み」は推奨しません。重要な区切りでは DSH 標準のブランチ機能を使ってください。',
525
551
  'opt.auto': '自動レビュー',
526
552
  'opt.auto.desc': 'オンにすると従来どおり:圧縮のたびにレビューファイルを作り、以下の設定でレビューをコンテキストとシステムプロンプトに注入し、リマインダーを選択位置に注入します。オフにすると作成と注入を停止し、以下の設定はすべて変更できなくなります。',
527
- 'opt.auto.off': 'レビュー機能はオフです。レビューファイルの作成も注入も停止しています。他の記憶プラグインやレビュー運用がない場合はこの項目をオンにしてください。'
553
+ 'opt.auto.off': 'レビュー機能はオフです。レビューファイルの作成も注入も停止しています。他の記憶プラグインやレビュー運用がない場合はこの項目をオンにしてください。',
554
+ 'si.import': 'インポート',
555
+ 'si.target': '対象ワークスペース',
556
+ 'si.preview': function (id, cwd) { return 'パッケージ内のセッション:' + id + '\n作業ディレクトリ:' + cwd },
557
+ 'si.previewTarget': function (title, path) { return 'インポート先:' + (title || path) + '(' + path + ')' },
558
+ 'si.branchWarn': '同じ id が対象ワークスペースにあります。インポートは新しい id を使い、そのセッションのブランチとして追加します。元のセッションは変更しません。',
559
+ 'si.renameWarn': '同じ id が他のワークスペースにあります。インポート時は新しい id を使い、元のセッションは変更しません。',
560
+ 'si.counts': function (m, f, s) { return 'パッケージ内:画像 ' + m + ' 枚、ファイル ' + f + ' 個、サブエージェント ' + s + ' 件。' },
561
+ 'si.confirm': 'インポート',
562
+ 'si.cancel': 'キャンセル',
563
+ 'si.done': function (id, m, f) { return id + ' をインポートしました(画像 ' + m + ' 枚、ファイル ' + f + ' 個)。' },
564
+ 'si.doneRenamed': function (id, old) { return 'インポートしました。id は ' + id + '(元は ' + old + ')。元のセッションは変更していません。' },
565
+ 'si.noTarget': 'インポート先のワークスペースがありません。先に DSH で作成してください。',
566
+ 'si.noZstd': 'この Node には zstdCompress がないためセッションログを書き込めません。インポートは使えません。'
528
567
  },
529
568
  es: {
530
569
  'app.title': 'Gestor de herramientas (scripts)',
@@ -656,7 +695,20 @@ window.__ModuleLoader__.load({
656
695
  'help.injectGroup': 'Una revisión tiene cuatro profundidades, cada una carga algo distinto: nivel 3, la transcripción original; nivel 2, el resumen de la compactación; nivel 1, el resumen del propio modelo; nivel 0, solo palabras clave, como índice.\nLa profundidad baja al segundo día, al tercer día y del vigésimo octavo en adelante. Cuando señalas que el modelo recuerda algo mal, el propio modelo llama a session_mem_read para leer la transcripción de esa revisión y luego pondera y bloquea su contenido cargado. Una revisión vacía en nivel 1 o 0 es normal: el plugin inyecta un recordatorio para que el modelo llame a session_mem_write con un resumen y palabras clave. El cumplimiento difiere entre el canal de contexto y el del prompt del sistema, así que elige el que mejor te funcione.\nNo se recomienda activar «Carga completa»; para hitos importantes usa las ramas propias de DSH.',
657
696
  'opt.auto': 'Revisión automática',
658
697
  'opt.auto.desc': 'Cuando está activada, el comportamiento es el de siempre: se crea una revisión en cada compactación y se inyecta en el contexto y el prompt del sistema según las opciones de abajo. Al desactivarla, se detienen la creación y la inyección y todas las opciones de abajo quedan de solo lectura.',
659
- 'opt.auto.off': 'La revisión está desactivada, así que no se crean ni se inyectan archivos de revisión. Si no tienes otro plugin de memoria ni un flujo de revisiones, actívala.'
698
+ 'opt.auto.off': 'La revisión está desactivada, así que no se crean ni se inyectan archivos de revisión. Si no tienes otro plugin de memoria ni un flujo de revisiones, actívala.',
699
+ 'si.import': 'Importar',
700
+ 'si.target': 'Espacio de trabajo destino',
701
+ 'si.preview': function (id, cwd) { return 'Sesión del paquete: ' + id + '\nDirectorio de trabajo: ' + cwd },
702
+ 'si.previewTarget': function (title, path) { return 'Se importará en: ' + (title || path) + ' (' + path + ')' },
703
+ 'si.branchWarn': 'El mismo id ya existe en el espacio de trabajo destino: la importación usará un id nuevo y la colgará como rama de esa sesión, sin tocar la original.',
704
+ 'si.renameWarn': 'El mismo id ya está en otro espacio de trabajo: la importación usará un id nuevo y no tocará el original.',
705
+ 'si.counts': function (m, f, s) { return 'El paquete contiene ' + m + ' imagen(es), ' + f + ' archivo(s) y ' + s + ' sesión(es) de subagente.' },
706
+ 'si.confirm': 'Importar',
707
+ 'si.cancel': 'Cancelar',
708
+ 'si.done': function (id, m, f) { return 'Importado ' + id + '; ' + m + ' imagen(es), ' + f + ' archivo(s).' },
709
+ 'si.doneRenamed': function (id, old) { return 'Importado con id nuevo ' + id + ' (antes ' + old + '); el original no se tocó.' },
710
+ 'si.noTarget': 'No hay espacio de trabajo destino: crea uno en DSH primero.',
711
+ 'si.noZstd': 'Este Node no tiene zstdCompress; no se pueden escribir registros de sesión y la importación no está disponible.'
660
712
  },
661
713
  fr: {
662
714
  'app.title': 'Gestion des outils (scripts)',
@@ -788,7 +840,20 @@ window.__ModuleLoader__.load({
788
840
  'help.injectGroup': 'Une revue a quatre profondeurs, chacune chargeant un contenu différent : niveau 3, la transcription d’origine ; niveau 2, le résumé de compaction ; niveau 1, le résumé du modèle lui-même ; niveau 0, les mots-clés seuls, comme index.\nLa profondeur baisse le deuxième jour, le troisième jour, puis à partir du vingt-huitième. Quand vous signalez un souvenir erroné, le modèle appelle lui-même session_mem_read pour relire la transcription de cette revue, puis pondère et verrouille son contenu chargé. Une revue vide en niveau 1 ou 0 est normale : le plugin injecte un rappel demandant au modèle d’appeler session_mem_write avec un résumé et des mots-clés. Le respect varie entre le canal contexte et le canal prompt système : choisissez celui qui vous convient.\nActiver « Chargement complet » n’est pas recommandé ; pour les étapes importantes, utilisez les branches natives de DSH.',
789
841
  'opt.auto': 'Revue automatique',
790
842
  'opt.auto.desc': 'Quand c’est activé, le comportement reste le même : une revue est créée à chaque compaction et injectée dans le contexte et le prompt système selon les options ci-dessous. Désactivé, la création et l’injection s’arrêtent et toutes les options ci-dessous deviennent en lecture seule.',
791
- 'opt.auto.off': 'La revue est désactivée : les fichiers de revue ne sont ni créés ni injectés. Si vous n’avez pas d’autre plugin de mémoire ni d’enchaînement de revues, activez cette option.'
843
+ 'opt.auto.off': 'La revue est désactivée : les fichiers de revue ne sont ni créés ni injectés. Si vous n’avez pas d’autre plugin de mémoire ni d’enchaînement de revues, activez cette option.',
844
+ 'si.import': 'Importer',
845
+ 'si.target': 'Espace de travail cible',
846
+ 'si.preview': function (id, cwd) { return 'Session du paquet : ' + id + '\nRépertoire de travail : ' + cwd },
847
+ 'si.previewTarget': function (title, path) { return 'Importer vers : ' + (title || path) + ' (' + path + ')' },
848
+ 'si.branchWarn': 'Cet id existe déjà dans l’espace de travail cible : l’import utilisera un nouvel id et le rattachera comme branche de cette session, sans toucher à l’original.',
849
+ 'si.renameWarn': 'Cet id existe déjà dans un autre espace de travail : l’import utilisera un nouvel id et ne touchera pas l’original.',
850
+ 'si.counts': function (m, f, s) { return 'Le paquet contient ' + m + ' image(s), ' + f + ' fichier(s) et ' + s + ' session(s) de sous-agent.' },
851
+ 'si.confirm': 'Importer',
852
+ 'si.cancel': 'Annuler',
853
+ 'si.done': function (id, m, f) { return id + ' importé ; ' + m + ' image(s), ' + f + ' fichier(s).' },
854
+ 'si.doneRenamed': function (id, old) { return 'Importé sous le nouvel id ' + id + ' (ancien : ' + old + ') ; l’original est intact.' },
855
+ 'si.noTarget': 'Aucun espace de travail cible : créez-en un dans DSH.',
856
+ 'si.noZstd': 'Ce Node n’a pas zstdCompress : impossible d’écrire les journaux de session, l’import est indisponible.'
792
857
  },
793
858
  de: {
794
859
  'app.title': 'Werkzeug- (Skript-)Verwaltung',
@@ -920,7 +985,20 @@ window.__ModuleLoader__.load({
920
985
  'help.injectGroup': 'Eine Review hat vier Tiefen, die jeweils etwas anderes laden: Stufe 3 das ursprüngliche Transkript, Stufe 2 die Kompressions-Zusammenfassung, Stufe 1 die eigene Zusammenfassung des Modells, Stufe 0 nur Stichwörter als Index.\nDie Tiefe sinkt am zweiten Tag, am dritten Tag und ab dem achtundzwanzigsten. Wenn du dem Modell eine falsche Erinnerung nachweist, ruft es selbst session_mem_read auf, liest das Transkript dieser Review und gewichtet und sperrt danach den geladenen Inhalt. Eine leere Review auf Stufe 1 oder 0 ist normal: Das Plugin injiziert eine Erinnerung, damit das Modell session_mem_write mit Zusammenfassung und Stichwörtern aufruft. Die Befolgung unterscheidet sich zwischen Kontext- und System-Prompt-Kanal, wähle je nach Bedarf.\n„Vollständig laden“ ist nicht empfehlenswert; nutze für wichtige Punkte die Branches von DSH.',
921
986
  'opt.auto': 'Automatische Review',
922
987
  'opt.auto.desc': 'Wenn ein, bleibt das Verhalten wie bisher: Bei jeder Kompression wird eine Review angelegt und gemäß den Optionen unten in Kontext und System-Prompt injiziert. Wenn aus, stoppen Anlegen und Injizieren und alle Optionen unten werden schreibgeschützt.',
923
- 'opt.auto.off': 'Die Review ist aus, es werden weder Review-Dateien angelegt noch injiziert. Wenn du kein anderes Speicher-Plugin oder keinen Review-Ablauf hast, schalte dies ein.'
988
+ 'opt.auto.off': 'Die Review ist aus, es werden weder Review-Dateien angelegt noch injiziert. Wenn du kein anderes Speicher-Plugin oder keinen Review-Ablauf hast, schalte dies ein.',
989
+ 'si.import': 'Importieren',
990
+ 'si.target': 'Ziel-Workspace',
991
+ 'si.preview': function (id, cwd) { return 'Session im Paket: ' + id + '\nArbeitsverzeichnis: ' + cwd },
992
+ 'si.previewTarget': function (title, path) { return 'Import nach: ' + (title || path) + ' (' + path + ')' },
993
+ 'si.branchWarn': 'Diese id existiert im Ziel-Workspace bereits: der Import nutzt eine neue id und hängt sie als Branch unter diese Session, das Original bleibt unangetastet.',
994
+ 'si.renameWarn': 'Diese id liegt bereits in einem anderen Workspace: der Import nutzt eine neue id und lässt das Original unangetastet.',
995
+ 'si.counts': function (m, f, s) { return 'Das Paket enthält ' + m + ' Bild(er), ' + f + ' Datei(en) und ' + s + ' Subagent-Session(s).' },
996
+ 'si.confirm': 'Importieren',
997
+ 'si.cancel': 'Abbrechen',
998
+ 'si.done': function (id, m, f) { return id + ' importiert; ' + m + ' Bild(er), ' + f + ' Datei(en).' },
999
+ 'si.doneRenamed': function (id, old) { return 'Importiert mit neuer id ' + id + ' (vorher ' + old + '); das Original blieb unverändert.' },
1000
+ 'si.noTarget': 'Kein Ziel-Workspace vorhanden: lege zuerst einen in DSH an.',
1001
+ 'si.noZstd': 'Dieses Node hat kein zstdCompress; Session-Logs lassen sich nicht schreiben, der Import ist nicht verfügbar.'
924
1002
  },
925
1003
  ru: {
926
1004
  'app.title': 'Управление инструментами (скриптами)',
@@ -1052,7 +1130,20 @@ window.__ModuleLoader__.load({
1052
1130
  'help.injectGroup': 'У обзора четыре глубины, каждая загружает своё: уровень 3 — исходная расшифровка; уровень 2 — итог сжатия; уровень 1 — собственный итог модели; уровень 0 — только ключевые слова как индекс.\nГлубина снижается на второй день, на третий и начиная с двадцать восьмого. Когда вы указываете модели на ошибку в памяти, она сама вызывает session_mem_read, читает расшифровку этого обзора, затем повышает вес и закрепляет загруженное содержимое. Пустой обзор на уровне 1 или 0 — это нормально: плагин вставляет напоминание, чтобы модель вызвала session_mem_write с итогом и ключевыми словами. Соблюдение различается для канала контекста и канала системного промпта, выбирайте по ситуации.\nВключать «Полную загрузку» не рекомендуется; для важных точек используйте ветвления самого DSH.',
1053
1131
  'opt.auto': 'Автоматический обзор',
1054
1132
  'opt.auto.desc': 'Когда включено, поведение прежнее: при каждом сжатии создаётся обзор и вставляется в контекст и системный промпт согласно параметрам ниже. Когда выключено, создание и вставка останавливаются, а все параметры ниже становятся только для чтения.',
1055
- 'opt.auto.off': 'Обзоры выключены, файлы обзоров не создаются и не вставляются. Если у вас нет другого плагина памяти или процесса обзоров, включите этот параметр.'
1133
+ 'opt.auto.off': 'Обзоры выключены, файлы обзоров не создаются и не вставляются. Если у вас нет другого плагина памяти или процесса обзоров, включите этот параметр.',
1134
+ 'si.import': 'Импорт',
1135
+ 'si.target': 'Целевое рабочее пространство',
1136
+ 'si.preview': function (id, cwd) { return 'Сессия в пакете: ' + id + '\nРабочий каталог: ' + cwd },
1137
+ 'si.previewTarget': function (title, path) { return 'Импорт в: ' + (title || path) + ' (' + path + ')' },
1138
+ 'si.branchWarn': 'Этот id уже есть в целевом пространстве: импорт возьмёт новый id и повесит её ветвью под эту сессию, оригинал останется нетронутым.',
1139
+ 'si.renameWarn': 'Этот id уже есть в другом рабочем пространстве: импорт возьмёт новый id, оригинал останется нетронутым.',
1140
+ 'si.counts': function (m, f, s) { return 'В пакете: изображений ' + m + ', файлов ' + f + ', субагентских сессий ' + s + '.' },
1141
+ 'si.confirm': 'Импортировать',
1142
+ 'si.cancel': 'Отмена',
1143
+ 'si.done': function (id, m, f) { return 'Импортировано ' + id + '; изображений ' + m + ', файлов ' + f + '.' },
1144
+ 'si.doneRenamed': function (id, old) { return 'Импортировано с новым id ' + id + ' (был ' + old + '); оригинал не тронут.' },
1145
+ 'si.noTarget': 'Нет целевого рабочего пространства: сначала создайте его в DSH.',
1146
+ 'si.noZstd': 'В этом Node нет zstdCompress; журналы сессий записать нельзя, импорт недоступен.'
1056
1147
  },
1057
1148
  pt: {
1058
1149
  'app.title': 'Gerenciador de ferramentas (scripts)',
@@ -1184,7 +1275,20 @@ window.__ModuleLoader__.load({
1184
1275
  'help.injectGroup': 'Uma revisão tem quatro profundidades, cada uma carregando algo diferente: nível 3, a transcrição original; nível 2, o resumo da compactação; nível 1, o resumo do próprio modelo; nível 0, apenas palavras-chave como índice.\nA profundidade cai no segundo dia, no terceiro dia e a partir do vigésimo oitavo. Quando você aponta que o modelo lembra algo errado, o próprio modelo chama session_mem_read para reler a transcrição dessa revisão e então pondera e trava o conteúdo carregado. Uma revisão vazia em nível 1 ou 0 é normal: o plugin injeta um lembrete para o modelo chamar session_mem_write com resumo e palavras-chave. O cumprimento difere entre o canal de contexto e o do prompt do sistema, escolha conforme o caso.\nAtivar “Carga completa” não é recomendado; para marcos importantes use as ramificações do próprio DSH.',
1185
1276
  'opt.auto': 'Revisão automática',
1186
1277
  'opt.auto.desc': 'Quando ligado, o comportamento é o de sempre: uma revisão é criada a cada compactação e injetada no contexto e no prompt do sistema conforme as opções abaixo. Quando desligado, criação e injeção param e todas as opções abaixo ficam somente leitura.',
1187
- 'opt.auto.off': 'A revisão está desligada, então arquivos de revisão não são criados nem injetados. Se você não tem outro plugin de memória nem um fluxo de revisões, ligue esta opção.'
1278
+ 'opt.auto.off': 'A revisão está desligada, então arquivos de revisão não são criados nem injetados. Se você não tem outro plugin de memória nem um fluxo de revisões, ligue esta opção.',
1279
+ 'si.import': 'Importar',
1280
+ 'si.target': 'Workspace de destino',
1281
+ 'si.preview': function (id, cwd) { return 'Sessão no pacote: ' + id + '\nDiretório de trabalho: ' + cwd },
1282
+ 'si.previewTarget': function (title, path) { return 'Importar para: ' + (title || path) + ' (' + path + ')' },
1283
+ 'si.branchWarn': 'Este id já existe no workspace de destino: a importação usará um id novo e a pendurará como ramo dessa sessão, sem tocar na original.',
1284
+ 'si.renameWarn': 'Este id já está em outro workspace: a importação usa um id novo e não toca no original.',
1285
+ 'si.counts': function (m, f, s) { return 'O pacote tem ' + m + ' imagem(ns), ' + f + ' arquivo(s) e ' + s + ' sessão(ões) de subagente.' },
1286
+ 'si.confirm': 'Importar',
1287
+ 'si.cancel': 'Cancelar',
1288
+ 'si.done': function (id, m, f) { return 'Importado ' + id + '; ' + m + ' imagem(ns), ' + f + ' arquivo(s).' },
1289
+ 'si.doneRenamed': function (id, old) { return 'Importado com id novo ' + id + ' (antes ' + old + '); o original ficou intacto.' },
1290
+ 'si.noTarget': 'Nenhum workspace de destino: crie um no DSH primeiro.',
1291
+ 'si.noZstd': 'Este Node não tem zstdCompress; não dá para gravar logs de sessão, a importação está indisponível.'
1188
1292
  }
1189
1293
  }
1190
1294
 
@@ -1542,7 +1646,10 @@ window.__ModuleLoader__.load({
1542
1646
  // 回执(0.5.1):带上它属于哪个标签。以前是一条全页共享的字符串,而那一行
1543
1647
  // 渲染在标签内容区外面,所以在「选项」页存完设置、切到别的页也能看见「已保存」。
1544
1648
  var nt = React.useState(null); var note = nt[0], setNote = nt[1]
1545
- var err = React.useState(''); var setErr = err[1]
1649
+ // 报错只属于产生它的那一页(0.6.1):以前它是全页一条字符串、渲染在标签内容区外面,
1650
+ // 于是「会话」页的报错在四个页都显示。现在带上标签,切过去就看不见别人的错。
1651
+ var err = React.useState(null); var errState = err[0]
1652
+ function setErr(text) { err[1](text ? { tab: tab, text: String(text) } : null) }
1546
1653
  var ldi = React.useState(null); var loadInfo = ldi[0], setLoadInfo = ldi[1]
1547
1654
  var op = React.useState(false); var open = op[0], setOpen = op[1]
1548
1655
  var mp = React.useState(null); var memPick = mp[0], setMemPick = mp[1]
@@ -1571,13 +1678,20 @@ window.__ModuleLoader__.load({
1571
1678
  var cca = React.useState(false); var clearArmed = cca[0], setClearArmed = cca[1]
1572
1679
  var ccn = React.useState(''); var cacheNote = ccn[0], setCacheNote = ccn[1]
1573
1680
  var fileInput = React.useRef(null)
1681
+ // 「会话导入」(0.6.1):会话页最左边那颗按钮。包、预演结果、目标工作区、回执。
1682
+ var sif = React.useState(null); var sessionFile = sif[0], setSessionFile = sif[1]
1683
+ var sip = React.useState(null); var sessionPlan = sip[0], setSessionPlan = sip[1]
1684
+ var sit = React.useState(''); var sessionTarget = sit[0], setSessionTarget = sit[1]
1685
+ var sin = React.useState(''); var sessionNote = sin[0], setSessionNote = sin[1]
1686
+ var sib = React.useState(false); var sessionBusy = sib[0], setSessionBusy = sib[1]
1687
+ var sessionFileInput = React.useRef(null)
1574
1688
 
1575
1689
  var load = React.useCallback(async function () {
1576
1690
  try {
1577
1691
  var res = await fetch(API + 'state')
1578
1692
  var json = await res.json()
1579
1693
  if (!res.ok) throw new Error((json.error && json.error.message) || ('HTTP ' + res.status))
1580
- setData({ loading: false, error: '', workspaces: json.workspaces || [], capabilities: json.capabilities || null })
1694
+ setData({ loading: false, error: '', workspaces: json.workspaces || [], targets: json.targets || [], capabilities: json.capabilities || null })
1581
1695
  if (json.options) setOptions(json.options)
1582
1696
  return json
1583
1697
  } catch (e) {
@@ -1589,6 +1703,7 @@ window.__ModuleLoader__.load({
1589
1703
  React.useEffect(function () { load() }, [])
1590
1704
 
1591
1705
  // 切标签就把上一页的回执和「举刀」状态收掉:它们只属于生成它们的那一页(0.5.1)。
1706
+ // 报错按页留着(0.6.1):切走看不见,切回来还在——它不是回执,是「这页哪一步坏了」。
1592
1707
  React.useEffect(function () { setNote(null); setClearArmed(false) }, [tab])
1593
1708
 
1594
1709
  var selectedWorkspace = selected
@@ -1726,6 +1841,96 @@ window.__ModuleLoader__.load({
1726
1841
  } finally { setBusy(false) }
1727
1842
  }
1728
1843
 
1844
+ /* ── 会话导入(0.6.1)──────────────────────────────────────
1845
+ 会话页最左边的「导入」:选一个 dsh-session-<id>.zip,先预演(不写盘),
1846
+ 确认之后才真装。目标工作区用 id 传,服务端只信 id、不信界面上的路径。 */
1847
+
1848
+ function importTargetsOf() { return Array.isArray(data.targets) ? data.targets : [] }
1849
+
1850
+ /** 默认目标:当前会话所在的工作区 > 第一个。 */
1851
+ function defaultImportTarget() {
1852
+ var list = importTargetsOf()
1853
+ if (list.length === 0) return ''
1854
+ var cur = currentWorkspace && currentWorkspace.cwd
1855
+ for (var i = 0; i < list.length; i++) if (list[i].path === cur) return list[i].id
1856
+ return list[0].id
1857
+ }
1858
+
1859
+ function sessionImportUrl(dryRun, target) {
1860
+ return API + 'session-import?workspaceId=' + encodeURIComponent(target || '') + (dryRun ? '&dryRun=1' : '')
1861
+ }
1862
+
1863
+ /** 预演:只报会碰到谁、要不要换 id,一个字节都不写。 */
1864
+ async function previewSessionImport(entry, target) {
1865
+ var res = await fetch(sessionImportUrl(true, target), {
1866
+ method: 'POST',
1867
+ headers: { 'Content-Type': 'application/zip' },
1868
+ body: entry.file
1869
+ })
1870
+ var json = await res.json()
1871
+ if (!res.ok) throw new Error((json.error && json.error.message) || ('HTTP ' + res.status))
1872
+ setSessionPlan(json)
1873
+ }
1874
+
1875
+ function pickSessionZip() {
1876
+ if (isBusy || sessionBusy) return
1877
+ setErr(''); setSessionNote(''); setSessionPlan(null); setSessionFile(null)
1878
+ var target = sessionTarget || defaultImportTarget()
1879
+ setSessionTarget(target)
1880
+ if (target === '') { setErr(tr('si.noTarget')); return }
1881
+ var el = sessionFileInput.current
1882
+ if (el) { el.value = ''; el.click() }
1883
+ }
1884
+
1885
+ async function onSessionZipChosen(ev) {
1886
+ var file = ev && ev.target && ev.target.files && ev.target.files[0]
1887
+ if (!file) return
1888
+ setSessionBusy(true); setErr(''); setSessionNote(''); setSessionPlan(null)
1889
+ var entry = { name: file.name, file: file }
1890
+ setSessionFile(entry)
1891
+ try { await previewSessionImport(entry, sessionTarget) }
1892
+ catch (e) { setSessionFile(null); setErr(String(e.message || e)) }
1893
+ finally { setSessionBusy(false) }
1894
+ }
1895
+
1896
+ /** 换目标工作区:撞号结果跟着目标变,重新预演一遍。 */
1897
+ async function onSessionTargetChange(id) {
1898
+ setSessionTarget(id)
1899
+ if (!sessionFile) return
1900
+ setSessionBusy(true); setErr('')
1901
+ try { await previewSessionImport(sessionFile, id) }
1902
+ catch (e) { setSessionPlan(null); setErr(String(e.message || e)) }
1903
+ finally { setSessionBusy(false) }
1904
+ }
1905
+
1906
+ async function confirmSessionImport() {
1907
+ if (sessionBusy || !sessionFile || !sessionPlan) return
1908
+ var plan = sessionPlan
1909
+ setSessionBusy(true); setErr(''); setSessionNote('')
1910
+ try {
1911
+ var res = await fetch(sessionImportUrl(false, sessionTarget), {
1912
+ method: 'POST',
1913
+ headers: { 'Content-Type': 'application/zip' },
1914
+ body: sessionFile.file
1915
+ })
1916
+ var json = await res.json()
1917
+ if (!res.ok) throw new Error((json.error && json.error.message) || ('HTTP ' + res.status))
1918
+ var got = json.session || {}
1919
+ setSessionNote(got.renamed
1920
+ ? tr('si.doneRenamed', got.id, got.originalId)
1921
+ : tr('si.done', got.id, (json.counts && json.counts.media) || 0, (json.counts && json.counts.files) || 0))
1922
+ setSessionPlan(null); setSessionFile(null)
1923
+ await load()
1924
+ if (got.id) setSelected({ id: got.id, cwd: got.cwd || plan.workspace.path })
1925
+ } catch (e) { setErr(String(e.message || e)) }
1926
+ finally { setSessionBusy(false) }
1927
+ }
1928
+
1929
+ function closeSessionDialog() {
1930
+ if (sessionBusy) return
1931
+ setSessionPlan(null); setSessionFile(null)
1932
+ }
1933
+
1729
1934
  /**
1730
1935
  * 导出:让宿主把 toolSequence.zip 直接写进当前会话所在的工作区文件夹。
1731
1936
  * 落点由宿主算(它拿得到真实路径),界面只负责把它念出来。
@@ -1837,6 +2042,53 @@ window.__ModuleLoader__.load({
1837
2042
  )
1838
2043
  }
1839
2044
 
2045
+ // Esc 关会话导入弹窗(0.6.1):和工具导入一样只认 Esc,不劫持遮罩点击。
2046
+ React.useEffect(function () {
2047
+ if (sessionPlan === null) return undefined
2048
+ if (typeof document === 'undefined' || typeof document.addEventListener !== 'function') return undefined
2049
+ function onKey(e) { if (e && e.key === 'Escape') closeSessionDialog() }
2050
+ document.addEventListener('keydown', onKey)
2051
+ return function () { document.removeEventListener('keydown', onKey) }
2052
+ }, [sessionPlan, sessionBusy])
2053
+
2054
+ /** 会话导入的确认弹窗(0.6.1):结构照工具导入那张,多一个目标工作区下拉。 */
2055
+ function sessionImportDialogView() {
2056
+ if (sessionPlan === null) return null
2057
+ var list = importTargetsOf()
2058
+ var plan = sessionPlan
2059
+ var busyNow = sessionBusy
2060
+ var options = list.map(function (w) { return [w.id, w.title || w.path] })
2061
+ return h('div', { style: S.modalOverlay, 'data-session-import-dialog': '1' },
2062
+ h('div', { style: S.modalBox, role: 'dialog', 'aria-modal': 'true' },
2063
+ h('p', { style: S.modalBody }, tr('si.preview', plan.session.originalId, plan.session.cwd)),
2064
+ list.length > 1
2065
+ ? h('div', { style: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' } },
2066
+ h('span', { style: S.optLabel }, tr('si.target')),
2067
+ h(Select, { value: sessionTarget, options: options, onChange: onSessionTargetChange }))
2068
+ : null,
2069
+ h('p', { style: S.modalBody }, tr('si.previewTarget', plan.workspace.title || '', plan.workspace.path)),
2070
+ plan.session.willBranch ? h('p', { style: S.modalBody }, tr('si.branchWarn')) : null,
2071
+ plan.session.willRename && !plan.session.willBranch ? h('p', { style: S.modalBody }, tr('si.renameWarn')) : null,
2072
+ h('p', { style: S.modalBody }, tr('si.counts', plan.counts.media, plan.counts.files, plan.counts.subagents)),
2073
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end', flexWrap: 'wrap' } },
2074
+ h('button', {
2075
+ type: 'button',
2076
+ style: busyNow ? S.btnOff : S.btnPrimary,
2077
+ disabled: busyNow,
2078
+ 'data-confirm-action': 'primary',
2079
+ onClick: confirmSessionImport
2080
+ }, tr('si.confirm')),
2081
+ h('button', {
2082
+ type: 'button',
2083
+ style: busyNow ? S.btnOff : S.btnGhost,
2084
+ disabled: busyNow,
2085
+ 'data-confirm-action': 'cancel',
2086
+ onClick: closeSessionDialog
2087
+ }, tr('si.cancel')))
2088
+ )
2089
+ )
2090
+ }
2091
+
1840
2092
  /**
1841
2093
  * 改一个或多个选项。落盘后把回顾页的预览与深度徽章全部作废重取:
1842
2094
  * 选项只改载入时的装配,不改载入文件里记下的深度,所以重取就能看到新内容。
@@ -2286,7 +2538,16 @@ window.__ModuleLoader__.load({
2286
2538
  body)
2287
2539
  }
2288
2540
 
2541
+ // 「导入」在最左(0.6.1):删除 / 删除并回顾 这一行从左边加一颗按钮。
2542
+ // 宿主 Node 写不了 zstd 时这颗按钮明确变灰,并在会话页里说明原因。
2543
+ var canImport = !(data.capabilities && data.capabilities.table && data.capabilities.table['zstd.compress'] === false)
2289
2544
  var footer = tab === 'sessions' ? h('div', { style: S.footer },
2545
+ h('button', {
2546
+ style: (isBusy || sessionBusy || !canImport) ? S.btnOff : S.btn,
2547
+ disabled: isBusy || sessionBusy || !canImport,
2548
+ 'data-session-import': '1',
2549
+ onClick: pickSessionZip
2550
+ }, tr('si.import')),
2290
2551
  h('button', { style: !selected || isBusy ? S.btnOff : S.btnDanger, disabled: !selected || isBusy, onClick: doDelete },
2291
2552
  confirming === 'delete' ? tr('btn.confirm') : tr('btn.delete')),
2292
2553
  h('button', { style: !selected || isBusy ? S.btnOff : S.btn, disabled: !selected || isBusy, onClick: doCompactDelete },
@@ -2295,9 +2556,16 @@ window.__ModuleLoader__.load({
2295
2556
 
2296
2557
  // 会话、回顾两页内容可能很长,仍走 .recall-scroll;选项页只四行,不要滚动框。
2297
2558
  // 0.4.3:自创工具页多了导入/导出一块,整页不再保证一屏装得下,跟着一起滚。
2559
+ // 会话页自己的回执、弹窗与能力说明都挂在页面里面:切到别页就一起消失。
2560
+ var pageInner = tab === 'sessions'
2561
+ ? h('div', null, body,
2562
+ canImport ? null : h('div', { style: S.note, 'data-session-import-off': '1' }, tr('si.noZstd')),
2563
+ sessionNote ? h('div', { style: S.note, 'data-session-import-note': '1' }, sessionNote) : null,
2564
+ sessionImportDialogView())
2565
+ : body
2298
2566
  var pageBox = tab === 'options'
2299
- ? h('div', { style: S.pageFlat }, body)
2300
- : h('div', { className: 'recall-scroll', style: S.page }, body)
2567
+ ? h('div', { style: S.pageFlat }, pageInner)
2568
+ : h('div', { className: 'recall-scroll', style: S.page }, pageInner)
2301
2569
 
2302
2570
  // E1:宿主能力不全时,在每页顶部都说清缺了什么、哪块被关了。
2303
2571
  var missingCaps = data.capabilities && data.capabilities.ok === false
@@ -2309,7 +2577,14 @@ window.__ModuleLoader__.load({
2309
2577
  return h('div', { style: S.wrap },
2310
2578
  head, tabs, capWarn, pageBox, footer,
2311
2579
  note && note.tab === tab ? h('div', { style: S.note }, note.text) : null,
2312
- err[0] ? h('div', { style: S.err }, err[0]) : null
2580
+ errState && errState.tab === tab ? h('div', { style: S.err }, errState.text) : null,
2581
+ h('input', {
2582
+ type: 'file',
2583
+ accept: '.zip,application/zip',
2584
+ style: { display: 'none' },
2585
+ ref: sessionFileInput,
2586
+ onChange: onSessionZipChosen
2587
+ })
2313
2588
  )
2314
2589
  }
2315
2590
 
package/lib/core/index.js CHANGED
@@ -482,7 +482,10 @@ export function apply(ctx, config = {}) {
482
482
  commands: webCtx.get('commands'),
483
483
  // 删完目录要让宿主索引忘掉它,否则设置页列表和搜索留幽灵。
484
484
  sessionProjectionCache: webCtx.get('sessionProjectionCache'),
485
- sessionQuery: webCtx.get('sessionQuery')
485
+ sessionQuery: webCtx.get('sessionQuery'),
486
+ // 导入落盘后要让主界面左侧列表出现这条会话:发宿主自己的列表新增事件
487
+ // (删除能刷新,是因为 session/disposed 自动发 api-session/removed;导入没有对应动作)。
488
+ notifySessionAdded: (summary) => webCtx.emit('api-session/added', summary)
486
489
  })
487
490
  // 0.4.1:选项一落盘就同步工具,赶在下一次 systemPrompt.assemble() 之前。
488
491
  // 0.4.6:切「清单词刷新时刻」那一下,把所有已记住的会话刷新成此刻的现词。
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { canDecodeZstd } from '../core/zstd.js'
17
+ import { canWriteZstd } from './import-session.js'
17
18
 
18
19
  const fn = (v) => typeof v === 'function'
19
20
 
@@ -93,6 +94,9 @@ export function probeCapabilities(ctx, { only } = {}) {
93
94
  // 探测函数单独留着,是为了让宿主能力表仍然是一个能查询的真值。
94
95
  const zstd = canDecodeZstd()
95
96
  need('zstd.decompress', 'zlib.zstdDecompressSync() or the built-in decoder', zstd)
97
+ // 会话导入要往盘里写 zstd(0.6.1):Node 22.15+ 才有;缺了只关掉导入那一个按钮。
98
+ optional['zstd.compress'] = canWriteZstd()
99
+ table['zstd.compress'] = optional['zstd.compress']
96
100
 
97
101
  if (Array.isArray(only)) {
98
102
  // 只报「这块此刻应该就绪」的条目:apply 刚进来时别把还没起来的服务当成缺失。
@@ -0,0 +1,498 @@
1
+ /**
2
+ * 会话导入(0.6.1):把 DSH 导出的 dsh-session-<id>.zip 装进本机,
3
+ * 不重启,会话立刻可开,图片与文件都能显示。
4
+ *
5
+ * 格式来源(实测):导出包是**未压缩的 JSONL**(session.v4.jsonl,第一行是户口本),
6
+ * 落盘要转成 zstd:**首帧只装户口本一行**(DSH 有硬断言),正文一帧,两帧都在行边界结束。
7
+ * 图片在包里叫 media/sha256:<哈希>.<后缀>,要落两处:
8
+ * sessions/<格子>/<id>/media/sha256_<哈希>.<后缀> (会话自己的 media)
9
+ * attachments/v1/objects/<前2>/<哈希> (全局附件库,纯哈希)
10
+ * 文件在包里叫 files/<前2>/<哈希>/<原名>,落到 attachments/v1/files/<前2>/<哈希>/<原名>
11
+ * 与 file-objects/<前2>/<哈希>(附件库的规范对象)。
12
+ *
13
+ * 撞号两条(交接文件实测):同一 id 出现在两个格子、或户口本 cwd 与格子不符,
14
+ * 都会让会话列表整份 500。所以同 id 在别的 cwd 时一律换新 id,绝不覆盖别人的会话。
15
+ *
16
+ * 只依赖 node 内置模块与仓库里的 zip / projectKey。
17
+ */
18
+
19
+ import fs from 'node:fs'
20
+ import fsp from 'node:fs/promises'
21
+ import path from 'node:path'
22
+ import readline from 'node:readline'
23
+ import { createHash, randomUUID } from 'node:crypto'
24
+ import zlib from 'node:zlib'
25
+ import { projectKey } from '../core/project-key.js'
26
+ import { forEachZipEntry, readZipCentralFromFile } from '../core/zip.js'
27
+
28
+ export const SESSION_LOG_NAME = 'session.v4.jsonl.zstd'
29
+
30
+ /** 宿主能不能写 zstd(Node 22.15+)。导入必须能写,否则拒绝并说清楚。 */
31
+ export function canWriteZstd() {
32
+ return typeof zlib.zstdCompressSync === 'function' && typeof zlib.createZstdCompress === 'function'
33
+ }
34
+
35
+ const ROOT_LOG = /^session(?:\.v[1-9][0-9]*)?\.jsonl$/
36
+ const SUB_LOG = /^subagents\/([^/]+)\/session(?:\.v[1-9][0-9]*)?\.jsonl$/
37
+ const MEDIA_NAME = /^media\/sha256:([a-f0-9]{64})\.([A-Za-z0-9]+)$/
38
+ const FILE_NAME = /^files\/([0-9a-f]{2})\/([a-f0-9]{64})\/(.+)$/
39
+
40
+ const message = (e) => (e instanceof Error ? e.message : String(e))
41
+
42
+ function stamp() {
43
+ const d = new Date()
44
+ const p = (n) => String(n).padStart(2, '0')
45
+ return d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '-' + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds())
46
+ }
47
+
48
+ /** 一条 zip 条目的内容向量:只流一次,边写边算 sha256。 */
49
+ async function streamEntryToFile(entry, file) {
50
+ const handle = await fsp.open(file, 'w')
51
+ const digest = createHash('sha256')
52
+ let bytes = 0
53
+ try {
54
+ for await (const chunk of entry.read()) {
55
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
56
+ digest.update(buf)
57
+ await handle.write(buf)
58
+ bytes += buf.length
59
+ }
60
+ } finally {
61
+ await handle.close().catch(() => {})
62
+ }
63
+ return { bytes, sha256: digest.digest('hex') }
64
+ }
65
+
66
+ /** 读一个文件的前一行(以 \n 结尾);包里的户口本就这一行。 */
67
+ async function firstLineOf(file, limit = 4 * 1024 * 1024) {
68
+ const handle = await fsp.open(file, 'r')
69
+ try {
70
+ const chunks = []
71
+ let total = 0
72
+ while (total < limit) {
73
+ const buf = Buffer.allocUnsafe(64 * 1024)
74
+ const { bytesRead } = await handle.read(buf, 0, buf.length, total)
75
+ if (bytesRead <= 0) break
76
+ const hit = buf.subarray(0, bytesRead).indexOf(0x0a)
77
+ if (hit >= 0) { chunks.push(buf.subarray(0, hit + 1)); return Buffer.concat(chunks) }
78
+ chunks.push(buf.subarray(0, bytesRead))
79
+ total += bytesRead
80
+ }
81
+ throw new Error('the exported log has no complete header line')
82
+ } finally {
83
+ await handle.close().catch(() => {})
84
+ }
85
+ }
86
+
87
+ /**
88
+ * 把一份 JSONL 文本文件压成 DSH 认的 zstd 日志:首帧恰好一行,正文第二帧。
89
+ * 走流式:日志多大都不把整份读进内存。
90
+ */
91
+ async function packLog(srcFile, destFile) {
92
+ const head = await firstLineOf(srcFile)
93
+ if (head.length < 2 || head[head.length - 1] !== 0x0a) throw new Error('the exported log header line is malformed')
94
+ const opts = { params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 } }
95
+ const out = await fsp.open(destFile, 'w')
96
+ try {
97
+ await out.write(zlib.zstdCompressSync(head, opts))
98
+ // 正文帧:从户口本之后的位置开始流式压。空正文也给一帧(合法空帧)。
99
+ const rest = fs.createReadStream(srcFile, { start: head.length, highWaterMark: 1 << 20 })
100
+ const zs = zlib.createZstdCompress(opts)
101
+ rest.pipe(zs)
102
+ for await (const chunk of zs) await out.write(chunk)
103
+ } finally {
104
+ await out.close().catch(() => {})
105
+ }
106
+ }
107
+
108
+ /**
109
+ * 前端左侧列表的条目形状(照 dsh-api-session-controller 的 summarizeCold)。
110
+ * 导入只落盘、不建 Session 对象,拿不到 live summary,就按冷会话如实拼一份。
111
+ */
112
+ function coldSummary(header) {
113
+ return {
114
+ sessionId: header.id,
115
+ updatedAt: Math.max(Number(header.createdAt) || 0, 0),
116
+ agentAvailable: false,
117
+ formatStatus: 'current',
118
+ running: false,
119
+ blank: false,
120
+ ...(header.parentSession === void 0 ? {} : { parentSessionId: header.parentSession }),
121
+ ...(header.origin === void 0 ? {} : { origin: header.origin }),
122
+ ...(header.cwd === void 0 ? {} : { cwd: header.cwd })
123
+ }
124
+ }
125
+
126
+ /**
127
+ * 种子会话的继承切点:事件流里最后一个 session/end-seed(data.inherited === true)的 seq。
128
+ * DSH 校验要求 seeded 会话的这个值与标记位置严格相等,否则整条会话打不开。
129
+ * @returns 切点 seq;不是种子会话时返回 -1。
130
+ */
131
+ async function scanInheritedCut(file) {
132
+ const rl = readline.createInterface({ input: fs.createReadStream(file), crlfDelay: Infinity })
133
+ let last = -1
134
+ let index = -1
135
+ try {
136
+ for await (const line of rl) {
137
+ index += 1
138
+ if (index === 0) continue // 第一行是户口本
139
+ if (line.indexOf('"session/end-seed"') < 0) continue
140
+ let event
141
+ try { event = JSON.parse(line) } catch { continue }
142
+ if (event?.type === 'session/end-seed' && event.data?.inherited === true) {
143
+ last = typeof event.seq === 'number' ? event.seq : index - 1
144
+ }
145
+ }
146
+ } finally {
147
+ rl.close()
148
+ }
149
+ return last
150
+ }
151
+
152
+ function isFile(file) {
153
+ try { return fs.statSync(file).isFile() } catch { return false }
154
+ }
155
+
156
+ async function existsDir(dir) {
157
+ try { return (await fsp.stat(dir)).isDirectory() } catch { return false }
158
+ }
159
+
160
+ /** 落一个图片:先写到会话 media 下的临时名,验过哈希再搬两处。 */
161
+ async function saveMedia(entry, { hash, ext, sessionDir, attachRoot }) {
162
+ const mediaDir = path.join(sessionDir, 'media')
163
+ await fsp.mkdir(mediaDir, { recursive: true })
164
+ const tmp = path.join(mediaDir, 'import-' + hash.slice(0, 12) + '-' + process.pid + '.tmp')
165
+ const stored = await streamEntryToFile(entry, tmp)
166
+ if (stored.sha256 !== hash) {
167
+ await fsp.rm(tmp, { force: true }).catch(() => {})
168
+ throw new Error('media ' + hash + ' does not match its sha256 (the package is corrupt)')
169
+ }
170
+ const alias = path.join(mediaDir, 'sha256_' + hash + '.' + ext)
171
+ await fsp.rename(tmp, alias)
172
+ const objDir = path.join(attachRoot, 'objects', hash.slice(0, 2))
173
+ const obj = path.join(objDir, hash)
174
+ if (!isFile(obj)) {
175
+ await fsp.mkdir(objDir, { recursive: true })
176
+ await fsp.copyFile(alias, obj + '.tmp-' + process.pid)
177
+ await fsp.rename(obj + '.tmp-' + process.pid, obj)
178
+ }
179
+ return stored.bytes
180
+ }
181
+
182
+ /** 落一个文件附件:files/<前2>/<哈希>/<原名>,另存一份 file-objects 规范对象。 */
183
+ async function saveFile(entry, { hash, prefix, name, attachRoot }) {
184
+ const safeName = path.basename(name)
185
+ if (safeName === '' || safeName === '.' || safeName === '..') throw new Error('the package has an unsafe file name: ' + name)
186
+ const dir = path.join(attachRoot, 'files', prefix, hash)
187
+ await fsp.mkdir(dir, { recursive: true })
188
+ const tmp = path.join(dir, '.import-' + process.pid + '.tmp')
189
+ const stored = await streamEntryToFile(entry, tmp)
190
+ if (stored.sha256 !== hash) {
191
+ await fsp.rm(tmp, { force: true }).catch(() => {})
192
+ throw new Error('file ' + name + ' does not match its sha256 (the package is corrupt)')
193
+ }
194
+ const dst = path.join(dir, safeName)
195
+ await fsp.rename(tmp, dst)
196
+ const objDir = path.join(attachRoot, 'file-objects', prefix)
197
+ const obj = path.join(objDir, hash)
198
+ if (!isFile(obj)) {
199
+ await fsp.mkdir(objDir, { recursive: true })
200
+ await fsp.copyFile(dst, obj + '.tmp-' + process.pid)
201
+ await fsp.rename(obj + '.tmp-' + process.pid, obj)
202
+ }
203
+ return stored.bytes
204
+ }
205
+
206
+ /** 只读第一帧的户口本(dryRun 与真导入都用它)。 */
207
+ async function readHeader(file) {
208
+ let text = ''
209
+ let done = false
210
+ await forEachZipEntry(file, async (entry) => {
211
+ if (done || entry.isDir || !ROOT_LOG.test(entry.name)) return
212
+ for await (const chunk of entry.read()) {
213
+ text += chunk.toString('utf8')
214
+ if (text.indexOf('\n') >= 0) { done = true; break }
215
+ if (text.length > 4 * 1024 * 1024) throw new Error('the exported log header line is too long')
216
+ }
217
+ })
218
+ if (!done) throw new Error('this zip has no session.v4.jsonl at its root; it is not a session package')
219
+ const line = text.slice(0, text.indexOf('\n'))
220
+ let header
221
+ try { header = JSON.parse(line) } catch { throw new Error('the first line of session.v4.jsonl is not JSON') }
222
+ if (header === null || typeof header !== 'object' || header.type !== 'session') {
223
+ throw new Error('the first line of session.v4.jsonl is not a session header')
224
+ }
225
+ if (typeof header.id !== 'string' || header.id === '') throw new Error('the session header carries no id')
226
+ return header
227
+ }
228
+
229
+ /** 目标工作区:按 id 找(客户端传 id,不传路径)。 */
230
+ function findWorkspace(deps, workspaceId) {
231
+ const list = deps.workspaceRegistry?.list?.()
232
+ if (!Array.isArray(list) || list.length === 0) throw new Error('this host has no workspace registry; open the app once so a workspace exists')
233
+ const hit = list.find((w) => w.id === workspaceId) ?? (workspaceId === '' || workspaceId === undefined ? list[0] : undefined)
234
+ if (hit === undefined) throw new Error('no workspace with id ' + workspaceId)
235
+ if (typeof hit.path !== 'string' || hit.path === '') throw new Error('workspace ' + hit.id + ' has no path')
236
+ return hit
237
+ }
238
+
239
+ async function findGrid(root, id) {
240
+ let grids = []
241
+ try { grids = await fsp.readdir(root, { withFileTypes: true }) } catch { return null }
242
+ for (const g of grids) {
243
+ if (!g.isDirectory()) continue
244
+ if (await existsDir(path.join(root, g.name, id))) return g.name
245
+ }
246
+ return null
247
+ }
248
+
249
+ async function safeRealpath(p) {
250
+ try { return await fsp.realpath(p) } catch { return '' }
251
+ }
252
+
253
+ /**
254
+ * 撞号检查:同一个 id 在本机现在是什么状态。
255
+ * 命中一律换新 id:同工作区再挂成原会话的分支,别的工作区只换号。
256
+ */
257
+ async function inspectExisting(deps, dshHome, id, root) {
258
+ const grid = await findGrid(root, id)
259
+ let header = null
260
+ try {
261
+ const rows = await deps.persistence.list()
262
+ header = (rows.map((row) => row.header ?? row).find((h) => h.id === id)) ?? null
263
+ } catch { header = null }
264
+ const projcache = path.join(dshHome, 'storages', 'session_projcache', 'sessions', id + '.json')
265
+ return { grid, header, hasProjcache: isFile(projcache) }
266
+ }
267
+
268
+ /** 只改日志的第一行(户口本);正文原样。 */
269
+ function replaceFirstLine(file, line) {
270
+ const buf = fs.readFileSync(file)
271
+ const nl = buf.indexOf(0x0a)
272
+ if (nl < 0) return false
273
+ fs.writeFileSync(file, Buffer.concat([Buffer.from(line, 'utf8'), buf.subarray(nl + 1)]))
274
+ return true
275
+ }
276
+
277
+ /** 只改第一行的 cwd(子代理日志用:换 cwd 不换 id)。 */
278
+ async function rewriteHeaderCwd(file, cwd) {
279
+ const head = (await firstLineOf(file)).toString('utf8').replace(/\n$/, '')
280
+ const parsed = JSON.parse(head)
281
+ parsed.cwd = cwd
282
+ replaceFirstLine(file, JSON.stringify(parsed) + '\n')
283
+ }
284
+
285
+ /**
286
+ * 导入一个会话包。
287
+ * @param {object} opts
288
+ * @param {object} opts.deps 宿主依赖(persistence / sessions / agents / workspaceRegistry)
289
+ * @param {string} opts.dshHome
290
+ * @param {string} opts.file 已落盘的 zip
291
+ * @param {string} opts.workspaceId 目标工作区 id
292
+ * @param {boolean} [opts.dryRun]
293
+ */
294
+ export async function importSession({ deps, dshHome, file, workspaceId, dryRun = false }) {
295
+ if (!canWriteZstd()) throw new Error('this host runs a Node without zstdCompress; session import needs Node 22.15+')
296
+ const root = deps.persistence?.config?.root
297
+ if (typeof root !== 'string' || root === '') throw new Error('session persistence has no storage root')
298
+ const workspace = findWorkspace(deps, workspaceId)
299
+ let workspacePath
300
+ try { workspacePath = await fsp.realpath(workspace.path) } catch (error) { throw new Error('the target workspace path does not resolve: ' + message(error)) }
301
+ if (!(await existsDir(workspacePath))) throw new Error('the target workspace path is not a directory: ' + workspacePath)
302
+
303
+ const header = await readHeader(file)
304
+ const originalId = header.id
305
+ const existing = await inspectExisting(deps, dshHome, originalId, root)
306
+ const targetGrid = projectKey(workspacePath)
307
+ const sameCwd = existing.header !== null && typeof existing.header.cwd === 'string' &&
308
+ (existing.header.cwd === workspacePath || (await safeRealpath(existing.header.cwd)) === workspacePath)
309
+ // 户口本读不出来时以格子为准(格子名就是 cwd 算出来的):同格子才算同一个工作区。
310
+ // 判错的代价是两条同 id 会话落在两个格子 → 会话列表整份 500,所以宁可换号。
311
+ const sameGrid = existing.grid !== null && (existing.header !== null ? sameCwd : existing.grid === targetGrid)
312
+ // 撞号一律换新 id,绝不原地覆盖:覆盖不会在列表里多出条目,用户看到的是「没刷新」。
313
+ // 同工作区的撞号同时挂成原会话的分支(parentSession);别的工作区只换号,不跨区挂父子。
314
+ // seeded 会话的继承前缀另有语义,只换号不挂分支。
315
+ const willRename = existing.grid !== null
316
+ const willBranch = sameGrid
317
+
318
+ const entries = await readZipCentralFromFile(file)
319
+ const mediaCount = entries.filter((e) => !e.isDir && MEDIA_NAME.test(e.name)).length
320
+ const fileCount = entries.filter((e) => !e.isDir && FILE_NAME.test(e.name)).length
321
+ const subCount = entries.filter((e) => !e.isDir && SUB_LOG.test(e.name)).length
322
+
323
+ const plan = {
324
+ session: {
325
+ id: willRename ? null : originalId,
326
+ originalId,
327
+ willRename,
328
+ willBranch,
329
+ cwd: workspacePath
330
+ },
331
+ workspace: { id: workspace.id, path: workspacePath, title: workspace.title ?? '' },
332
+ counts: { media: mediaCount, files: fileCount, subagents: subCount },
333
+ warnings: []
334
+ }
335
+ if (dryRun) return { ok: true, dryRun: true, ...plan }
336
+
337
+ const attachRoot = path.join(dshHome, 'attachments', 'v1')
338
+ const id = willRename ? 'session-' + randomUUID() : originalId
339
+ const gridKey = targetGrid
340
+ const sessionDir = path.join(root, gridKey, id)
341
+ const storages = path.join(dshHome, 'storages')
342
+ const backupDir = path.join(workspacePath, '会话导入备份-' + stamp())
343
+
344
+ // 写盘前先备份:workspace.json + 目录册(会话目录不再被覆盖,无需备份)。
345
+ let backup = ''
346
+ try {
347
+ await fsp.mkdir(backupDir, { recursive: true })
348
+ if (isFile(path.join(storages, 'workspace.json'))) {
349
+ await fsp.copyFile(path.join(storages, 'workspace.json'), path.join(backupDir, 'workspace.json'))
350
+ }
351
+ const pcs = path.join(storages, 'session_projcache', 'sessions')
352
+ if (isFile(path.join(pcs, originalId + '.json'))) {
353
+ await fsp.mkdir(path.join(backupDir, 'projcache'), { recursive: true })
354
+ await fsp.copyFile(path.join(pcs, originalId + '.json'), path.join(backupDir, 'projcache', originalId + '.json'))
355
+ }
356
+ await fsp.writeFile(path.join(backupDir, 'import.json'), JSON.stringify({
357
+ at: new Date().toISOString(), package: path.basename(file), workspace: plan.workspace, id, originalId, willBranch
358
+ }, null, 2) + '\n')
359
+ backup = backupDir
360
+ } catch (error) {
361
+ throw new Error('cannot write the pre-import backup into the workspace: ' + message(error))
362
+ }
363
+
364
+ const tmpLog = path.join(sessionDir, '.import-' + process.pid + '.jsonl')
365
+ const written = []
366
+ let mediaSaved = 0
367
+ let subSaved = 0
368
+ try {
369
+ await fsp.mkdir(path.join(sessionDir, 'media'), { recursive: true })
370
+
371
+ let rootWritten = false
372
+ const subDirs = []
373
+ await forEachZipEntry(file, async (entry) => {
374
+ if (entry.isDir) return
375
+ const media = MEDIA_NAME.exec(entry.name)
376
+ if (media !== null) {
377
+ await saveMedia(entry, { hash: media[1].toLowerCase(), ext: media[2], sessionDir, attachRoot })
378
+ mediaSaved += 1
379
+ return
380
+ }
381
+ const fileHit = FILE_NAME.exec(entry.name)
382
+ if (fileHit !== null) {
383
+ await saveFile(entry, { hash: fileHit[2].toLowerCase(), prefix: fileHit[2].toLowerCase().slice(0, 2), name: fileHit[3], attachRoot })
384
+ return
385
+ }
386
+ const sub = SUB_LOG.exec(entry.name)
387
+ if (sub !== null) {
388
+ const subId = sub[1]
389
+ const subDir = path.join(root, gridKey, subId)
390
+ if (await existsDir(subDir)) {
391
+ plan.warnings.push('subagent session ' + subId + ' already exists; skipped')
392
+ return
393
+ }
394
+ await fsp.mkdir(subDir, { recursive: true })
395
+ written.push(subDir)
396
+ const tmp = path.join(subDir, '.import-' + process.pid + '.jsonl')
397
+ await streamEntryToFile(entry, tmp)
398
+ // 子代理的 cwd 也指向目标工作区,但 id / parentSession / delegationDepth 原样。
399
+ await rewriteHeaderCwd(tmp, workspacePath)
400
+ await packLog(tmp, path.join(subDir, SESSION_LOG_NAME))
401
+ await fsp.rm(tmp, { force: true }).catch(() => {})
402
+ subDirs.push(subId)
403
+ subSaved += 1
404
+ return
405
+ }
406
+ if (ROOT_LOG.test(entry.name) && !rootWritten) {
407
+ rootWritten = true
408
+ await streamEntryToFile(entry, tmpLog)
409
+ }
410
+ })
411
+ if (!rootWritten) throw new Error('this zip has no session.v4.jsonl at its root; it is not a session package')
412
+
413
+ // 户口本:改 cwd(换号时连 id 一起改)。其余字段一个都不动。
414
+ const headText = (await firstLineOf(tmpLog)).toString('utf8').replace(/\n$/, '')
415
+ const head = JSON.parse(headText)
416
+ // 种子会话的继承切点必须原样写进目录册;写错 DSH 就打不开("seeded header disagrees")。
417
+ // 顺带把自相矛盾的包挡在写盘之前:说是种子却没有标记,或不是种子却带标记。
418
+ const inheritedCut = await scanInheritedCut(tmpLog)
419
+ if (head.isSeeded === true && inheritedCut < 0) {
420
+ throw new Error('this package is marked isSeeded but its log has no inherited end-seed marker')
421
+ }
422
+ if (head.isSeeded !== true && inheritedCut >= 0) {
423
+ throw new Error('this package is not seeded but its log carries an inherited end-seed marker')
424
+ }
425
+ const inheritedEventCount = head.isSeeded === true ? inheritedCut : 0
426
+ head.cwd = workspacePath
427
+ if (willRename) head.id = id
428
+ // 挂分支:新会话登记为原同 id 会话的子会话(parentSession),历史仍独立。
429
+ // 包里本来就带父会话的(自己就是别人的分支)保留原值,不覆盖。
430
+ if (willBranch && head.parentSession === void 0) head.parentSession = originalId
431
+ if (!replaceFirstLine(tmpLog, JSON.stringify(head) + '\n')) throw new Error('cannot rewrite the session header')
432
+ await packLog(tmpLog, path.join(sessionDir, SESSION_LOG_NAME))
433
+ await fsp.rm(tmpLog, { force: true }).catch(() => {})
434
+ written.push(sessionDir)
435
+
436
+ // 目录册:没有就建最小结构,有就只改 identity.cwd。
437
+ const pcDir = path.join(storages, 'session_projcache', 'sessions')
438
+ await fsp.mkdir(pcDir, { recursive: true })
439
+ const pcFile = path.join(pcDir, id + '.json')
440
+ let cache = null
441
+ if (isFile(pcFile)) {
442
+ try { cache = JSON.parse(await fsp.readFile(pcFile, 'utf8')) } catch { cache = null }
443
+ }
444
+ if (cache === null) {
445
+ cache = { version: 7, record: { identity: { formatVersion: 4, createdAt: head.createdAt, cwd: workspacePath, isSeeded: head.isSeeded === true, inheritedEventCount }, rows: {} } }
446
+ } else {
447
+ cache.record = cache.record ?? { identity: {}, rows: {} }
448
+ cache.record.identity = cache.record.identity ?? {}
449
+ cache.record.identity.cwd = workspacePath
450
+ }
451
+ await fsp.writeFile(pcFile + '.tmp-import', JSON.stringify(cache, null, 2) + '\n')
452
+ await fsp.rename(pcFile + '.tmp-import', pcFile)
453
+
454
+ // 刷新:照删除那边的写法——在动作这一刻重新 list() 取实时工作区对象再调用,
455
+ // 不拿函数开头那份早已过期的快照(过期对象的 mutate 只写表、不发列表变更事件)。
456
+ // attachSession 会校验 cwd == workspace.path,并持久化、发变更事件。
457
+ let liveWorkspace = workspace
458
+ try {
459
+ const freshList = deps.workspaceRegistry?.list?.()
460
+ const fresh = Array.isArray(freshList) ? freshList.find((row) => row?.id === workspace.id) : undefined
461
+ if (fresh !== undefined) liveWorkspace = fresh
462
+ } catch (error) {
463
+ plan.warnings.push('cannot refresh the workspace handle: ' + message(error))
464
+ }
465
+ // 这一步失败就把刚写的东西撤掉,别留一条没有工作区认领的孤儿。
466
+ try {
467
+ await liveWorkspace.attachSession(id)
468
+ for (const subId of subDirs) {
469
+ try { await liveWorkspace.attachSession(subId) } catch (error) {
470
+ plan.warnings.push('subagent session ' + subId + ' was written but not attached: ' + message(error))
471
+ }
472
+ }
473
+ } catch (error) {
474
+ for (const dir of written) await fsp.rm(dir, { recursive: true, force: true }).catch(() => {})
475
+ await fsp.rm(pcFile, { force: true }).catch(() => {})
476
+ throw new Error('the session files were written but the workspace refused to attach the session: ' + message(error))
477
+ }
478
+ // 通知前端左侧列表:导入的会话没有 session/created,宿主的 api-session/added 不会自己发。
479
+ try {
480
+ deps.notifySessionAdded?.(coldSummary(head))
481
+ } catch (error) {
482
+ plan.warnings.push('the session was imported but the list notification failed: ' + message(error))
483
+ }
484
+
485
+ return {
486
+ ok: true,
487
+ dryRun: false,
488
+ session: { id, originalId, willRename, willBranch, renamed: id !== originalId, cwd: workspacePath, isSeeded: head.isSeeded === true, inheritedEventCount },
489
+ workspace: plan.workspace,
490
+ counts: { media: mediaSaved, files: fileCount, subagents: subSaved },
491
+ backup,
492
+ warnings: plan.warnings
493
+ }
494
+ } catch (error) {
495
+ await fsp.rm(tmpLog, { force: true }).catch(() => {})
496
+ throw error
497
+ }
498
+ }
@@ -3,6 +3,7 @@
3
3
  * 装配 /state 的那一套也在这里(它是这份列表唯一的读者)。
4
4
  */
5
5
 
6
+ import fsp from 'node:fs/promises'
6
7
  import { join } from 'node:path'
7
8
  import { stat } from 'node:fs/promises'
8
9
  import { memoryDir, readAssembly } from '../../core/store.js'
@@ -13,7 +14,9 @@ import { readOptionsSync, REMINDER_SYSTEM } from '../../core/settings.js'
13
14
  import { deleteSessionPermanently, sessionDirOf } from '../delete.js'
14
15
  import { readDigest } from '../summary.js'
15
16
  import { compactThenDelete } from '../compact-delete.js'
16
- import { respond, readBody } from '../http-util.js'
17
+ import { respond, readBody, readBodyToFile } from '../http-util.js'
18
+ import { runsDir } from '../../core/schema.js'
19
+ import { importSession, canWriteZstd } from '../import-session.js'
17
20
 
18
21
  const PREFIX = '/api/session-seal-scripts.'
19
22
  const digestCache = new Map()
@@ -116,8 +119,17 @@ export async function buildState(deps, dshHome, snapshot = null) {
116
119
  workspaces.push({ cwd, sessions, memories, health })
117
120
  }
118
121
  workspaces.sort((a, b) => a.cwd.localeCompare(b.cwd))
122
+ // 导入的目标工作区(0.6.1):空工作区不会出现在上面那份按 cwd 分组的列表里,
123
+ // 所以单独给一份名册,界面用 id 选、服务端只信 id。
124
+ let targets = []
125
+ try {
126
+ targets = (deps.workspaceRegistry?.list?.() ?? [])
127
+ .filter((w) => typeof w.id === 'string' && typeof w.path === 'string')
128
+ .map((w) => ({ id: w.id, path: w.path, title: typeof w.title === 'string' ? w.title : '' }))
129
+ } catch { targets = [] }
119
130
  return {
120
131
  workspaces,
132
+ targets,
121
133
  options,
122
134
  // 失败与降级只有一个入口:缺什么能力、本机能力表、宿主层面最近一次失败。
123
135
  // 拆回顾失败按工作区记在 workspaces[].health 里,这里只放宿主自己的那条。
@@ -177,6 +189,40 @@ export function routesSessions(route, { dshHome, getDeps, waitForSplit, canLifec
177
189
  respond(res, 200, describeLoad(dshHome, body.cwd, now, options, reminder))
178
190
  })
179
191
 
192
+ /**
193
+ * 会话导入(0.6.1):把 dsh-session-<id>.zip 装进指定工作区。
194
+ *
195
+ * POST 体就是 zip 原始字节(和「自创工具」的导入同一条路:先流到 _runs/,不吃内存);
196
+ * ?workspaceId=<id>&dryRun=1 走预演,只报会碰到谁、要不要换 id,不写盘。
197
+ *
198
+ * 写盘前先备份到 <工作区>/会话导入备份-<时间>/;刷新用 workspace.attachSession(id),
199
+ * 它会校验 cwd == workspace.path、持久化并发出变更事件,所以不用重启。
200
+ */
201
+ route(PREFIX + 'session-import', async (req, res) => {
202
+ if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
203
+ if (!canWriteZstd()) {
204
+ respond(res, 503, { error: { code: 'host-capability', message: 'this host runs a Node without zstdCompress; session import needs Node 22.15+' } })
205
+ return
206
+ }
207
+ let query
208
+ try { query = new URL(req.url ?? '/', 'http://placeholder').searchParams } catch { query = new URLSearchParams() }
209
+ const dryRun = query.get('dryRun') === '1'
210
+ const workspaceId = query.get('workspaceId') || ''
211
+ const dir = runsDir(dshHome)
212
+ await fsp.mkdir(dir, { recursive: true })
213
+ const tmp = join(dir, 'session-import-' + Date.now() + '-' + process.pid + '.zip')
214
+ try {
215
+ const written = await readBodyToFile(req, tmp)
216
+ if (written.bytes === 0) { respond(res, 400, { error: { code: 'empty-file', message: 'the package is empty' } }); return }
217
+ const result = await importSession({ deps: getDeps(), dshHome, file: tmp, workspaceId, dryRun })
218
+ respond(res, 200, result)
219
+ } catch (error) {
220
+ respond(res, 400, { error: { code: 'import-failed', message: error?.message ?? String(error) } })
221
+ } finally {
222
+ await fsp.rm(tmp, { force: true }).catch(() => {})
223
+ }
224
+ })
225
+
180
226
  route(PREFIX + 'compact-delete', async (req, res) => {
181
227
  if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
182
228
  const body = JSON.parse(await readBody(req) || '{}')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-seal-scripts",
3
- "version": "0.6.0",
3
+ "version": "0.6.1",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "index.js",