dsh-plugin-external-session-sync 0.0.0-stage → 1.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,116 @@
1
+ # Changelog
2
+
3
+ All notable changes to `dsh-plugin-external-session-sync`.
4
+
5
+ ## 1.2.1 — 2026-11-10
6
+
7
+ ### Fixed
8
+
9
+ - **The plugin could not activate on current DSH.** `POST /external-session-sync/sync` was
10
+ registered twice, so the Host row failed with `duplicate exact route` and nothing mounted.
11
+ - **Every session read failed with 500.** `sessionController.inspect` no longer exists on
12
+ current DSH; stored sessions are now read through `sessionPersistence.open(id, 'read')`,
13
+ which returns the validated header and events and closes the handle afterwards.
14
+ - `/health` and `client-mounted` now report the real version instead of `1.0.0`.
15
+
16
+ ### Credits
17
+
18
+ - **Thanks to [@rumeng2580](https://github.com/rumeng2580)** — PR
19
+ [#1](https://github.com/s17765152890-gif/dsh-plugin-external-session-sync/pull/1) diagnosed
20
+ both root causes and proposed the `sessionPersistence.open(id, 'read')` fix that this release
21
+ ships. The duplicate-route failure in particular meant 1.2.0 was unusable on a recent build.
22
+
23
+ ## 1.2.0 — 2026-11-06
24
+
25
+ ### Added
26
+
27
+ - **Permanent deletion of archived sessions.** `POST /external-session-sync/delete-archived`
28
+ removes the archived session log under `$DSH_HOME/sessions/<project>/<session-id>` and the
29
+ plugin's plain-text archive, then records a tombstone. Dry run unless `dryRun:false`.
30
+ - Never touches pinned, currently-open, non-archived or already-deleted sessions.
31
+ - Every path is validated as `<sessions-root>/<one project slot>/<session-id>` before it is removed.
32
+ - Each run writes a journal at `$DSH_HOME/external-session-sync/deletions-<timestamp>.json`.
33
+ - `/unarchive` now refuses a tombstoned id instead of surfacing an unreadable chat.
34
+ - Sidebar footer action **删除已归档**: two confirmation dialogs, then deletes and reports the
35
+ reclaimed byte count.
36
+
37
+ ## 1.1.1 — 2026-11-02
38
+
39
+ ### Added
40
+
41
+ - `POST /external-session-sync/unarchive`: the reverse of `/archive`, so a migration or an
42
+ over-eager archive run can be undone per session without touching logs.
43
+
44
+ ### Changed
45
+
46
+ - Migration guidance: run `migrate-heads` in small batches. Importing hundreds of large
47
+ histories in one pass is memory-heavy and can restart the DSH process mid-run; a restart
48
+ aborts the in-flight batch with `cannot get required service ... in inactive context`.
49
+ Archive-then-import is idempotent, so recovering means re-running `sync` for the archived
50
+ conversations whose `newSessionId` is missing from the migration journal.
51
+
52
+ ## 1.1.0 — 2026-11-02
53
+
54
+ ### Added
55
+
56
+ - `GET /external-session-sync/legacy-imports` and `POST /external-session-sync/migrate-heads`:
57
+ detect sessions imported before the protected head, archive them, and re-import the same
58
+ source conversation under a fresh identity. Reversible: old logs are archived, never
59
+ deleted, so `workspaceRegistry.unarchiveSession` restores them. Every run writes
60
+ `$DSH_HOME/external-session-sync/migration-<timestamp>.json` as a rollback journal.
61
+ - `POST /external-session-sync/self-check`: pushes the generated event shape through DSH's
62
+ own session validator, once as written and once with the system message the runtime
63
+ appends when a conversation continues. Nothing is persisted.
64
+
65
+ ### Changed
66
+
67
+ - Native session ids carry an importer format version (`dsh-sync-native-2:`), so a migrated
68
+ import never reuses the identity of the archived log it replaces. Existing mappings keep
69
+ their recorded ids because re-syncing a known revision goes through the stored entry.
70
+
71
+ ## 1.0.2 — 2026-11-02
72
+
73
+ ### Fixed
74
+
75
+ - Imported sessions now open with a protected system head. DSH records the protected head
76
+ only when a `system/message` is the first surface event, and that event must sit inside an
77
+ open turn and step and be an identified message. Continuing an imported chat previously
78
+ made the runtime append its own system message, which `session-format` rejects with
79
+ `system/message requires a protected first surface head`, corrupting the whole log on the
80
+ first continued turn.
81
+ - The canonical turn/step structure: the first assistant reply of a turn shares the turn's
82
+ opening step, later replies open their own step.
83
+
84
+ ### Added
85
+
86
+ - `tests/native-format.test.mjs` mirrors the V4 relations keeper, reproduces the reported
87
+ failure for the previous shape, and proves the new shape survives continuation.
88
+
89
+ ## 1.0.1 — 2026-11-02
90
+
91
+ ### Fixed
92
+
93
+ - The `/sync` route had been dropped from the route table, so the panel's sync buttons hit
94
+ the server fallback and reported a non-JSON response.
95
+ - A non-user `session/title` now always cites a message sequence; with no user message to
96
+ anchor, the event is omitted instead of being written invalid.
97
+ - An unreadable stored log is detected, left untouched, and the conversation is re-imported
98
+ under a deterministic `recovered` identity instead of failing forever (reported in
99
+ `recovered[]`).
100
+ - The client separates request timeouts from body-read aborts and reports the HTTP status
101
+ plus a body excerpt instead of a generic "invalid response".
102
+
103
+ ## 1.0.0 — 2026-11-01
104
+
105
+ ### Added
106
+
107
+ - Discover Codex threads from `state_5.sqlite` and merge every `rollout-*.jsonl` segment of a
108
+ thread, including rollouts that exist on disk before Codex indexes them.
109
+ - Import Codex and Claude Code history into native DSH sessions through the Session,
110
+ Session Persistence, Session Controller and Workspace Registry APIs.
111
+ - Verify an import: body readable, original session id resumed, project registered.
112
+ Repeated syncs repair a missing registration without rewriting history.
113
+ - Web panel with source picker, search, per-session and bulk sync, and "continue in DSH".
114
+ - Bulk archival for old sessions (1 / 3 / 6 / 12 months), pinned sessions never archived,
115
+ empty projects unregistered only after a real archive in the same request.
116
+ - Three agent tools: `codex_sync_status`, `codex_sync_import`, `codex_read_conversation`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 s17765152890-gif
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,129 @@
1
- # Temporary Holding Version
1
+ ![External Session Sync — import Codex and Claude Code conversations into DSH, continue work, and archive older sessions](assets/external-session-sync-hero.png)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ # dsh-plugin-external-session-sync
4
+
5
+ A standard DSH (DeepSeek Harness) plugin bundle that imports **Codex** and **Claude Code** conversation history into **native DSH sessions**, verifies that each imported chat is registered in its project, and lets you continue the work inside DSH. It also ships **bulk archival** for old sessions.
6
+
7
+ > DSH plugin, not a standalone app. It runs inside a DSH profile: one Host row (routes + agent tools) and one browser bundle (the panel and the sidebar actions).
8
+
9
+ ## Features
10
+
11
+ - **One import list for both sources.** Codex rollouts and Claude Code JSONL are read directly, read-only.
12
+ - **Complete Codex history.** A single Codex thread is often split across many `rollout-*.jsonl` files; the reader merges every segment of the thread and sorts by timestamp, so an import contains the newest turns instead of only the first rollout.
13
+ - **Uses Codex's own thread index.** Discovery reads `state_5.sqlite` so archived and continuation threads are not silently dropped, and it also finds a rollout that exists on disk before Codex indexes it.
14
+ - **Native imports only.** Each chat is created through DSH's Session, Session Persistence, Session Controller and Workspace Registry APIs. No hand-written session log, no edited workspace index.
15
+ - **Verified project membership.** "Synced" means the body is readable, the **original session id** resumed, and the chat is registered in its project. Re-running sync repairs a missing registration without rewriting history.
16
+ - **Work handoff.** From the panel you can open the imported native session and keep working in it with DSH's own composer.
17
+ - **Idempotent snapshots.** Same source revision → skip. New source revision → a new native session, so a chat you already continued is never overwritten.
18
+ - **Bulk archival.** Archive old sessions by age (1 / 3 / 6 / 12 months), pinned sessions are never archived, and a project whose members are all archived can be unregistered so the sidebar has no empty projects. Chat bodies, session logs and directories are kept.
19
+ - **Agent tools.** `codex_sync_status`, `codex_sync_import`, `codex_read_conversation`.
20
+
21
+ ## Install
22
+
23
+ Install the directory as a DSH bundle (Plugin Manager → install bundle from a local package directory), or add the row by hand to your profile patch:
24
+
25
+ ```yaml
26
+ - insert:
27
+ - id: external-session-sync-native
28
+ name: dsh-plugin-external-session-sync
29
+ ```
30
+
31
+ Requirements: DSH with the Web client, Node.js 22.5+ (the readers use the built-in `node:sqlite`, and degrade to filesystem-only discovery when it is unavailable).
32
+
33
+ ## Use
34
+
35
+ 1. Click **Codex 同步 / External Sync** in the left sidebar, or **会话同步** in a chat header.
36
+ 2. Pick **Codex** or **Claude**, search by title or project directory.
37
+ 3. **同步所选** imports the selected conversation, **同步全部** imports every normal conversation of that source.
38
+ 4. The result line reports `新增 / 已同步 / 修复项目关联 / 失败`.
39
+ 5. **在 DSH 继续** opens the imported native session and hands the work over to DSH.
40
+
41
+ Archive buttons:
42
+
43
+ - Panel row: month selector (**1 month** by default) + **归档旧会话** — archives synced conversations of the current source.
44
+ - Sidebar footer: **旧会话归档** — archives **native DSH sessions only**, older than 1 month, with a confirmation dialog.
45
+
46
+ ## Where data lives
47
+
48
+ | Path | Purpose |
49
+ | --- | --- |
50
+ | `$DSH_HOME/storages/external-session-sync-v1.json` | external id → native session id map |
51
+ | `$DSH_HOME/external-session-sync/archives/<session-id>.json` | plain-text archive of the imported messages |
52
+ | `$DSH_HOME/external-session-sync/runtime.log` | runtime log |
53
+
54
+ Source history is never modified: `.codex/` and `.claude/` are opened read-only.
55
+
56
+ ## What is imported
57
+
58
+ Visible user and assistant text, title, and working directory. Tool calls, hidden reasoning and binary attachments are **not** replayed as actions. Only text is imported, so a chat with paths or secrets inside its transcript carries that text with it — remember that when you publish or share a synced profile.
59
+
60
+ ## Security notes
61
+
62
+ - HTTP routes are bound to the local DSH web server and reject non-loopback `Origin`s and POSTs without the `x-dsh-sync` header.
63
+ - The plugin never stores credentials. It does not read provider configuration.
64
+ - Archiving uses DSH's registry, so it is reversible with `workspaceRegistry.unarchiveSession`.
65
+ - `deleteEmptyWorkspaces` only runs after a real archive in the same request; an empty request can never unregister projects.
66
+
67
+ ## Session format compatibility
68
+
69
+ DSH records the first surface event of a session as its **protected system head** and rejects
70
+ any later `system/message` when no head was recorded
71
+ (`system/message requires a protected first surface head`). Continuing an imported chat makes
72
+ the runtime append its own system message, so an import that starts with a user message
73
+ corrupts the log on the first continued turn.
74
+
75
+ Imports therefore open with `turn/start -> step/start -> system/message` (role `system`,
76
+ source `system-prompt`, carrying an id) and only then the transcript.
77
+
78
+ `POST /external-session-sync/self-check` runs the generated shape through DSH's own session
79
+ validator, once as written and once with the appended runtime system message, so a profile
80
+ upgrade cannot silently break imports.
81
+
82
+ Sessions imported by versions before 1.0.2 lack that head and can still corrupt when continued.
83
+
84
+ ### Migrating older imports
85
+
86
+ `GET /external-session-sync/legacy-imports` lists every mapping whose log has no protected
87
+ head, split into re-importable and no-longer-recoverable ones. `POST
88
+ /external-session-sync/migrate-heads` archives the old session and re-imports the same source
89
+ conversation under a new identity, in batches:
90
+
91
+ ```bash
92
+ curl -s -XPOST -H 'x-dsh-sync: 1' -H 'content-type: application/json' \
93
+ -d '{"dryRun":true}' http://127.0.0.1:<port>/external-session-sync/migrate-heads
94
+ curl -s -XPOST -H 'x-dsh-sync: 1' -H 'content-type: application/json' \
95
+ -d '{"dryRun":false,"limit":30}' http://127.0.0.1:<port>/external-session-sync/migrate-heads
96
+ ```
97
+
98
+ Repeat until `remaining` reaches 0 or a batch reports no progress. Mappings whose source
99
+ history is gone are never touched. Archiving is reversible with
100
+ `workspaceRegistry.unarchiveSession(oldSessionId)`, and each run appends a rollback journal at
101
+ `$DSH_HOME/external-session-sync/migration-<timestamp>.json`.
102
+
103
+ ## Known limitations
104
+
105
+ - Codex `state_5.sqlite` may lag behind the newest rollout; discovery compensates by scanning rollouts, but a thread whose files are all gone cannot be imported.
106
+ - A conversation whose original working directory no longer exists is imported into the plugin checkout's parent directory and flagged with a warning.
107
+ - Imported sessions are snapshots: continuing inside DSH does not write back to Codex or Claude Code.
108
+ - Codex reasoning items and tool payloads are intentionally dropped.
109
+
110
+ ## Tests
111
+
112
+ ```bash
113
+ node --test test/
114
+ ```
115
+
116
+ The suite covers thread-index discovery, multi-rollout merging, snapshot stability, missing-project repair, idempotent re-sync, dry runs, attachment failures, and the panel/footer archive selection logic. It uses temporary fixtures only — no personal data.
117
+
118
+ ## 中文速览
119
+
120
+ 这是一个标准 DSH 插件包:把 Codex / Claude Code 的历史会话导入为 DSH 原生会话,校验项目归属后可继续对话,并支持按时间批量归档旧会话。
121
+
122
+ - 左侧「Codex 同步」打开同步页;聊天标题旁「会话同步」打开右侧上下文面板。
123
+ - 同步完成需同时满足:正文可读、原会话 id 恢复成功、已登记到对应项目。
124
+ - 同一版本重复同步会跳过;源会话更新则创建新快照,保护你已经接手过的会话。
125
+ - 右侧面板可选择 1 / 3 / 6 / 12 个月并「归档旧会话」;左下角「旧会话归档」只作用于 DSH 原生会话。
126
+ - 置顶会话永不归档;归档保留正文与文件;某项目成员全部归档后会移除该空项目注册。
127
+ - 只导入可见的用户/助手文本,不回放工具调用与隐藏推理,也不修改 `.codex` / `.claude` 原始文件。
128
+
129
+ MIT License.
package/cleanup.js ADDED
@@ -0,0 +1,99 @@
1
+ // Permanent deletion of archived session payloads.
2
+ //
3
+ // DSH exposes no session-delete API: `sessionPersistence` is create/open/flush/stat/list
4
+ // and `ctx.sessions` is the in-memory store with no removal. Deletion therefore removes
5
+ // the on-disk payload and records a tombstone in the sync state, while the id stays in the
6
+ // workspace registry's archived list. Archived ids are never rendered by the sidebar, so a
7
+ // deleted session cannot reappear as an empty chat; `unarchive` refuses tombstoned ids.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+
11
+ const SAFE_ID = /^session-[0-9a-f-]{16,}$/i;
12
+
13
+ /** A session id must look like a session id before it is ever joined into a path. */
14
+ export function isSafeSessionId(sessionId) {
15
+ return typeof sessionId === 'string' && SAFE_ID.test(sessionId);
16
+ }
17
+
18
+ /** `$DSH_HOME/sessions/<project slug>/<sessionId>` — the slug is opaque, so look it up. */
19
+ export function sessionDirFor(sessionsRoot, sessionId) {
20
+ if (!isSafeSessionId(sessionId)) return null;
21
+ let entries;
22
+ try {
23
+ entries = fs.readdirSync(sessionsRoot, { withFileTypes: true });
24
+ } catch {
25
+ return null;
26
+ }
27
+ for (const entry of entries) {
28
+ if (!entry.isDirectory()) continue;
29
+ const candidate = path.join(sessionsRoot, entry.name, sessionId);
30
+ if (fs.existsSync(candidate)) return candidate;
31
+ }
32
+ return null;
33
+ }
34
+
35
+ /** Refuse anything that is not exactly `<root>/<one slug>/<sessionId>`. */
36
+ export function assertContained(sessionsRoot, dir, sessionId) {
37
+ const root = path.resolve(sessionsRoot);
38
+ const target = path.resolve(dir);
39
+ const relative = path.relative(root, target);
40
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) {
41
+ throw new Error(`拒绝删除工作目录之外的路径: ${target}`);
42
+ }
43
+ const parts = relative.split(path.sep);
44
+ if (parts.length !== 2 || parts[1] !== sessionId) {
45
+ throw new Error(`拒绝删除非会话目录结构的路径: ${target}`);
46
+ }
47
+ return target;
48
+ }
49
+
50
+ export function directoryBytes(dir) {
51
+ let total = 0;
52
+ let entries = [];
53
+ try {
54
+ entries = fs.readdirSync(dir, { withFileTypes: true });
55
+ } catch {
56
+ return 0;
57
+ }
58
+ for (const entry of entries) {
59
+ const full = path.join(dir, entry.name);
60
+ try {
61
+ if (entry.isDirectory()) total += directoryBytes(full);
62
+ else total += fs.statSync(full).size;
63
+ } catch {
64
+ // a file that disappeared mid-walk contributes nothing
65
+ }
66
+ }
67
+ return total;
68
+ }
69
+
70
+ /** What deletion would remove for one archived session, without touching anything. */
71
+ export function planSessionDeletion({ sessionsRoot, archivesRoot, sessionId }) {
72
+ const dir = sessionDirFor(sessionsRoot, sessionId);
73
+ const archiveFile = path.join(archivesRoot, `${sessionId}.json`);
74
+ const hasArchiveFile = fs.existsSync(archiveFile);
75
+ return {
76
+ sessionId,
77
+ dir,
78
+ exists: !!dir,
79
+ archiveFile: hasArchiveFile ? archiveFile : null,
80
+ bytes: dir ? directoryBytes(dir) + (hasArchiveFile ? fs.statSync(archiveFile).size : 0) : 0,
81
+ };
82
+ }
83
+
84
+ /** Delete one session payload. Returns the bytes reclaimed. Irreversible by design. */
85
+ export function deleteSessionPayload({ sessionsRoot, archivesRoot, sessionId }) {
86
+ const plan = planSessionDeletion({ sessionsRoot, archivesRoot, sessionId });
87
+ if (plan.dir) {
88
+ assertContained(sessionsRoot, plan.dir, sessionId);
89
+ fs.rmSync(plan.dir, { recursive: true, force: true });
90
+ if (fs.existsSync(plan.dir)) throw new Error(`会话目录仍然存在: ${plan.dir}`);
91
+ }
92
+ if (plan.archiveFile) {
93
+ const root = path.resolve(archivesRoot);
94
+ const target = path.resolve(plan.archiveFile);
95
+ if (path.relative(root, target).startsWith('..')) throw new Error('拒绝删除存档目录之外的文件');
96
+ fs.rmSync(plan.archiveFile, { force: true });
97
+ }
98
+ return { sessionId, bytes: plan.bytes, removedDir: !!plan.dir, removedArchive: !!plan.archiveFile };
99
+ }