dsh-session-path-export 0.0.0-stage → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/package.json +50 -4
- package/src/client.js +252 -0
- package/src/cordis.patch.yml +3 -0
- package/src/icon.svg +6 -0
- package/src/index.js +346 -0
- package/src/locale/en.json +6 -0
- package/src/locale/zh.json +6 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 monta-6969
|
|
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,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-session-path-export
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
会话导出成**一个目录**,并把目录的绝对路径放进剪贴板——接手的人或另一个 agent 拿到路径就能直接读。
|
|
4
|
+
|
|
5
|
+
替代原先「下载 zip → 解压 → 复制文件地址」三步:点一下,「…」菜单里多出来的那一行就做完了。
|
|
6
|
+
|
|
7
|
+
## 在哪能点到
|
|
8
|
+
|
|
9
|
+
同一行出现在两个「…」菜单里,共用一份状态和实现:
|
|
10
|
+
|
|
11
|
+
| 位置 | 触发目标 | `order` |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| 会话头部「…」 | `sessionHeader` | 300(官方「下载 Session 日志」100 之后、「反馈」600 之前) |
|
|
14
|
+
| 左侧会话行「…」 | `session` | 470(官方「复制 Session ID」450 之后、「在应用中打开」500 之前) |
|
|
15
|
+
|
|
16
|
+
菜单是 rc.3 的 `ctx.contextMenus` 注册表,不是 Slot;图标走 `contextMenu.icon` 的键 `session-path-export.folder`。
|
|
17
|
+
|
|
18
|
+
## 导出出来长什么样
|
|
19
|
+
|
|
20
|
+
落在 `~/.dsh/exports/<sessionId>/`:
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
session-d1b7995b-.../
|
|
24
|
+
├─ transcript.md 官方 Markdown 全文,图片标签已改写成相对链接
|
|
25
|
+
└─ media/
|
|
26
|
+
└─ sha256_abc123....png 被引用的图片原字节,按附件 id 命名、同一张只存一份
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
- 文本来自官方 `/api/session.markdown`(不自己造一份 Markdown),所以与「复制会话为 Markdown」完全一致。
|
|
30
|
+
- 图片来自 `attachments.readImage`,靠 `[Image: 名字 (宽×高, N bytes)]` 这个官方标签逐条反查替换;对不上的标签原样保留,不会破坏正文。
|
|
31
|
+
- 宿主端路由 `POST /api/session.export-file`,body 是 `{ sessionId, markdown }`,回 `{ path, transcript, media, mediaFailures, bytes, pruned, retentionDays, ms }`。
|
|
32
|
+
- **3 天后自动清理**:插件启动时扫一次,每次导出成功后顺带扫一次(不用常驻定时器)。只动自己写的目录,`retentionDays` 可配,≤0 关闭。
|
|
33
|
+
- 每次导出在 `~/.dsh/exports/.export-log.jsonl` 追加一行(耗时、图片数、失败原因、路径),出问题先看这个文件。
|
|
34
|
+
|
|
35
|
+
## 剪贴板
|
|
36
|
+
|
|
37
|
+
导出可能耗时几十秒,点击的“用户激活”窗口早就过期,`navigator.clipboard.writeText` 会抛 `NotAllowedError`。
|
|
38
|
+
所以点击瞬间先用 `ClipboardItem` 占住剪贴板槽(它接受一个 Promise),导出完再填内容;失败才回退 `execCommand('copy')`。
|
|
39
|
+
复制不到时 toast 会明说「已导出到该路径,但复制未成功」,并把路径显示出来——不会再谎报导出失败。
|
|
40
|
+
|
|
41
|
+
## 装上
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
dsh plugin install link:C:\Users\mota\Desktop\工程自动化\插件\dsh-session-path-export
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
或手工在 `C:\Users\mota\.dsh\profiles\desktop\package.json` 加:
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
"dependencies": { "dsh-session-path-export": "link:C:/Users/mota/Desktop/工程自动化/插件/dsh-session-path-export" }
|
|
51
|
+
"dsh": { "profile": { "bundles": [ "dsh-session-path-export" ] } }
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
之后重启 DeepSeek Harness(客户端 bundle 启动时加载一次,不重启看不到新菜单行)。
|
|
55
|
+
|
|
56
|
+
## 结构
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
package.json 包清单:dsh.bundle.patch 指到 src/
|
|
60
|
+
README.md 本文件
|
|
61
|
+
src/index.js 宿主半:注册 /api/session.export-file,落盘、抓图、清理
|
|
62
|
+
src/client.js 浏览器半:两处 contextMenus 注册 + 剪贴板 + toast
|
|
63
|
+
src/cordis.patch.yml insert 一行插件
|
|
64
|
+
src/icon.svg 插件图标
|
|
65
|
+
src/locale/{en,zh}.json 插件页标题与描述
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
只依赖 DSH 自带的 `connection` / `sessionQuery` / `attachments` 服务,没有第三方依赖。
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-session-path-export",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Session export folder: one row in both the conversation header “…” menu and the sidebar Session row “…” menu writes the transcript plus its images to a folder and copies the absolute path.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "monta-6969",
|
|
8
|
+
"homepage": "https://github.com/monta-6969/dsh-session-path-export",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/monta-6969/dsh-session-path-export.git"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/monta-6969/dsh-session-path-export/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"deepseek-harness",
|
|
18
|
+
"dsh",
|
|
19
|
+
"dsh-plugin",
|
|
20
|
+
"session",
|
|
21
|
+
"export",
|
|
22
|
+
"markdown"
|
|
23
|
+
],
|
|
24
|
+
"engines": {
|
|
25
|
+
"dsh": ">=0.2.2-rc.1 <0.3.0-0"
|
|
26
|
+
},
|
|
27
|
+
"exports": {
|
|
28
|
+
".": "./src/index.js",
|
|
29
|
+
"./client": "./src/client.js",
|
|
30
|
+
"./locale/*.json": "./src/locale/*.json",
|
|
31
|
+
"./icon": "./src/icon.svg",
|
|
32
|
+
"./cordis.patch.yml": "./src/cordis.patch.yml",
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"src",
|
|
37
|
+
"README.md"
|
|
38
|
+
],
|
|
39
|
+
"dsh": {
|
|
40
|
+
"bundle": {
|
|
41
|
+
"patch": "./src/cordis.patch.yml"
|
|
42
|
+
},
|
|
43
|
+
"client": {
|
|
44
|
+
"platform": "web",
|
|
45
|
+
"immediately": true,
|
|
46
|
+
"inject": [
|
|
47
|
+
"@deepseek-ai/dsh-client-ui-conversation",
|
|
48
|
+
"@deepseek-ai/dsh-client-ui-context-menu"
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: 'dsh-session-path-export',
|
|
3
|
+
factory(require) {
|
|
4
|
+
const { jsx } = require('react/jsx-runtime');
|
|
5
|
+
const ui = require('@deepseek-ai/dsh-client-ui-primitives');
|
|
6
|
+
const { createSnapshotStore } = require('@deepseek-ai/dsh-client-store');
|
|
7
|
+
|
|
8
|
+
/** Locale namespace owned by this bundle. */
|
|
9
|
+
const NS = 'session-path-export';
|
|
10
|
+
|
|
11
|
+
/** Document-relative routes this bundle reuses. */
|
|
12
|
+
const MARKDOWN_ROUTE = 'api/session.markdown';
|
|
13
|
+
/** Route registered by the Host half. */
|
|
14
|
+
const FILE_ROUTE = 'api/session.export-file';
|
|
15
|
+
|
|
16
|
+
/** Icon key this bundle registers into the shared context-menu icon slot. */
|
|
17
|
+
const ICON_KEY = 'session-path-export.folder';
|
|
18
|
+
|
|
19
|
+
/** Contribution id of this bundle's Session header row. */
|
|
20
|
+
const CONTRIBUTION_ID = 'session-path-export.export';
|
|
21
|
+
|
|
22
|
+
/** Header order: after the shipped download row (100), before feedback (600). */
|
|
23
|
+
const HEADER_ORDER = 300;
|
|
24
|
+
|
|
25
|
+
/** Sidebar row order: after the shipped “copy Session ID” row (450), before “open in app” (500). */
|
|
26
|
+
const SIDEBAR_ORDER = 470;
|
|
27
|
+
|
|
28
|
+
const zh = {
|
|
29
|
+
'menu.exportPath': '导出为目录并复制路径',
|
|
30
|
+
'toast.pathCopied': '已导出并复制目录路径',
|
|
31
|
+
'toast.pathCopiedWithMedia': '已导出(含图片)并复制目录路径',
|
|
32
|
+
'toast.pathNotCopied': '已导出到该路径,但复制未成功,请手动复制',
|
|
33
|
+
'toast.exportFailed': '导出失败,请重试',
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const en = {
|
|
37
|
+
'menu.exportPath': 'Export folder and copy path',
|
|
38
|
+
'toast.pathCopied': 'Exported, folder path copied',
|
|
39
|
+
'toast.pathCopiedWithMedia': 'Exported with images, folder path copied',
|
|
40
|
+
'toast.pathNotCopied': 'Exported to this path, but the copy failed — copy it manually',
|
|
41
|
+
'toast.exportFailed': 'Export failed. Try again.',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** Readable message from an unknown rejection. */
|
|
45
|
+
function messageOf(error) {
|
|
46
|
+
return error instanceof Error ? error.message : String(error);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Clipboard write: the shell helper first, then the selection-based fallback. */
|
|
50
|
+
async function copyText(text) {
|
|
51
|
+
if (typeof ui.writeClipboard === 'function') {
|
|
52
|
+
try {
|
|
53
|
+
if (await ui.writeClipboard(text)) return true;
|
|
54
|
+
} catch {
|
|
55
|
+
/* fall through to the selection-based path */
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
const area = document.createElement('textarea');
|
|
60
|
+
area.value = text;
|
|
61
|
+
area.setAttribute('readonly', '');
|
|
62
|
+
area.style.position = 'fixed';
|
|
63
|
+
area.style.top = '-1000px';
|
|
64
|
+
area.style.opacity = '0';
|
|
65
|
+
document.body.appendChild(area);
|
|
66
|
+
area.select();
|
|
67
|
+
const copied = typeof document.execCommand === 'function' && document.execCommand('copy');
|
|
68
|
+
area.remove();
|
|
69
|
+
return copied === true;
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Reserve the clipboard slot while the click still counts as user
|
|
77
|
+
* activation: a ClipboardItem accepts a promise, so the text can arrive
|
|
78
|
+
* seconds later when the export finishes.
|
|
79
|
+
* @returns null when this browser cannot defer the write.
|
|
80
|
+
*/
|
|
81
|
+
function beginDeferredWrite(preparation) {
|
|
82
|
+
const clipboard = navigator.clipboard;
|
|
83
|
+
if (typeof globalThis.ClipboardItem !== 'function') return null;
|
|
84
|
+
if (clipboard === undefined || typeof clipboard.write !== 'function') return null;
|
|
85
|
+
const data = preparation.then(
|
|
86
|
+
(result) => new Blob([result.path], { type: 'text/plain' }),
|
|
87
|
+
);
|
|
88
|
+
try {
|
|
89
|
+
return {
|
|
90
|
+
promise: clipboard.write([new globalThis.ClipboardItem({ 'text/plain': data })]),
|
|
91
|
+
};
|
|
92
|
+
} catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Root-overlay toast for this bundle's settled outcomes. */
|
|
98
|
+
function SessionExportToast(props) {
|
|
99
|
+
const { useNotice, dismiss } = props;
|
|
100
|
+
const notice = useNotice((state) => state.notice);
|
|
101
|
+
if (notice === null) return null;
|
|
102
|
+
const text = notice.detail === '' ? notice.text : `${notice.text} ${notice.detail}`;
|
|
103
|
+
if (notice.kind === 'success') {
|
|
104
|
+
return jsx(ui.Toast, { text, tone: 'success', onDone: dismiss, key: notice.seq });
|
|
105
|
+
}
|
|
106
|
+
return jsx(ui.Toast, {
|
|
107
|
+
text,
|
|
108
|
+
icon: jsx(ui.IconWarningOutlineRegular, {}),
|
|
109
|
+
onDone: dismiss,
|
|
110
|
+
key: notice.seq,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
inject: ['slots', 'locale', 'contextMenus'],
|
|
116
|
+
apply(ctx) {
|
|
117
|
+
const exportState = createSnapshotStore({ busy: false, notice: null });
|
|
118
|
+
let noticeSeq = 0;
|
|
119
|
+
|
|
120
|
+
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'session-path-export: dictionaries');
|
|
121
|
+
const t = ctx.locale.bind(NS);
|
|
122
|
+
|
|
123
|
+
/** Publish one settled outcome to the root toast. */
|
|
124
|
+
function notify(kind, text, detail = '') {
|
|
125
|
+
exportState.update((state) => {
|
|
126
|
+
state.notice = { kind, text, detail, seq: ++noticeSeq };
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Read the shipped transcript and let the Host write the export folder. */
|
|
131
|
+
async function runExport(sessionId) {
|
|
132
|
+
const markdown = await fetch(
|
|
133
|
+
`${MARKDOWN_ROUTE}?${new URLSearchParams({ sessionId: String(sessionId) })}`,
|
|
134
|
+
);
|
|
135
|
+
if (!markdown.ok) throw new Error(`HTTP ${markdown.status}`);
|
|
136
|
+
const body = await markdown.text();
|
|
137
|
+
const written = await fetch(FILE_ROUTE, {
|
|
138
|
+
method: 'POST',
|
|
139
|
+
headers: { 'content-type': 'application/json' },
|
|
140
|
+
body: JSON.stringify({ sessionId: String(sessionId), markdown: body }),
|
|
141
|
+
});
|
|
142
|
+
const result = await written.json().catch(() => ({}));
|
|
143
|
+
if (!written.ok || typeof result.path !== 'string') {
|
|
144
|
+
throw new Error(typeof result.error === 'string' ? result.error : `HTTP ${written.status}`);
|
|
145
|
+
}
|
|
146
|
+
return result;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Finish one export: copy the folder path and report through the toast. */
|
|
150
|
+
async function settle(preparation, deferred) {
|
|
151
|
+
try {
|
|
152
|
+
const result = await preparation;
|
|
153
|
+
let copied = false;
|
|
154
|
+
if (deferred !== null) {
|
|
155
|
+
try {
|
|
156
|
+
await deferred.promise;
|
|
157
|
+
copied = true;
|
|
158
|
+
} catch {
|
|
159
|
+
copied = await copyText(result.path);
|
|
160
|
+
}
|
|
161
|
+
} else {
|
|
162
|
+
copied = await copyText(result.path);
|
|
163
|
+
}
|
|
164
|
+
const withMedia = typeof result.media === 'number' && result.media > 0;
|
|
165
|
+
if (!copied) notify('success', t('toast.pathNotCopied'), result.path);
|
|
166
|
+
else {
|
|
167
|
+
notify('success', t(withMedia ? 'toast.pathCopiedWithMedia' : 'toast.pathCopied'), result.path);
|
|
168
|
+
}
|
|
169
|
+
} catch (error) {
|
|
170
|
+
notify('failed', t('toast.exportFailed'), messageOf(error));
|
|
171
|
+
} finally {
|
|
172
|
+
exportState.update((state) => {
|
|
173
|
+
state.busy = false;
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Export one Session to `<outDir>/<sessionId>/` and copy that path. */
|
|
179
|
+
function exportPath(sessionId) {
|
|
180
|
+
if (exportState.getSnapshot().busy) return;
|
|
181
|
+
exportState.update((state) => {
|
|
182
|
+
state.busy = true;
|
|
183
|
+
});
|
|
184
|
+
const preparation = runExport(sessionId);
|
|
185
|
+
const deferred = beginDeferredWrite(preparation);
|
|
186
|
+
void settle(preparation, deferred);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
ctx.slots.inject('contextMenu.icon', () =>
|
|
190
|
+
ctx.slots.register({ name: 'contextMenu.icon', key: ICON_KEY }, ui.IconFolderOpenRegular),
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* One contribution per Session menu target family.
|
|
195
|
+
*
|
|
196
|
+
* `sessionHeader` is the conversation header's “…” trigger; `session` is
|
|
197
|
+
* the sidebar Session row's trigger, where the row sits right after the
|
|
198
|
+
* shipped “copy Session ID” row and before “open in app”.
|
|
199
|
+
*/
|
|
200
|
+
const CONTRIBUTION_ID = 'session-path-export.export';
|
|
201
|
+
|
|
202
|
+
const MENUS = [
|
|
203
|
+
{ target: 'sessionHeader', order: HEADER_ORDER },
|
|
204
|
+
{ target: 'session', order: SIDEBAR_ORDER },
|
|
205
|
+
];
|
|
206
|
+
|
|
207
|
+
for (const menu of MENUS) {
|
|
208
|
+
ctx.effect(
|
|
209
|
+
() =>
|
|
210
|
+
ctx.contextMenus.register({
|
|
211
|
+
id: `${CONTRIBUTION_ID}.${menu.target}`,
|
|
212
|
+
target: menu.target,
|
|
213
|
+
order: menu.order,
|
|
214
|
+
observe: () => [exportState, ctx.locale],
|
|
215
|
+
resolve: ({ sessionId }) => [
|
|
216
|
+
{
|
|
217
|
+
id: 'exportPath',
|
|
218
|
+
label: t('menu.exportPath'),
|
|
219
|
+
icon: { key: ICON_KEY },
|
|
220
|
+
disabled: exportState.getSnapshot().busy,
|
|
221
|
+
run: () => {
|
|
222
|
+
exportPath(sessionId);
|
|
223
|
+
},
|
|
224
|
+
},
|
|
225
|
+
],
|
|
226
|
+
}),
|
|
227
|
+
`session-path-export: ${menu.target} row`,
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
ctx.slots.inject('shell.overlay', () =>
|
|
232
|
+
ctx.slots.register(
|
|
233
|
+
{
|
|
234
|
+
name: 'shell.overlay',
|
|
235
|
+
id: 'session-path-export.toast',
|
|
236
|
+
locale: NS,
|
|
237
|
+
inject: () => ({
|
|
238
|
+
hooks: { notice: exportState },
|
|
239
|
+
dismiss: () => {
|
|
240
|
+
exportState.update((state) => {
|
|
241
|
+
state.notice = null;
|
|
242
|
+
});
|
|
243
|
+
},
|
|
244
|
+
}),
|
|
245
|
+
},
|
|
246
|
+
SessionExportToast,
|
|
247
|
+
),
|
|
248
|
+
);
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
},
|
|
252
|
+
});
|
package/src/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Session export path">
|
|
2
|
+
<rect x="9" y="6" width="30" height="40" rx="5" fill="none" stroke="#247bbf" stroke-width="4"/>
|
|
3
|
+
<path d="M18 18h12M18 27h12" stroke="#247bbf" stroke-width="3.5" stroke-linecap="round"/>
|
|
4
|
+
<circle cx="44" cy="42" r="13" fill="#ffffff" stroke="#247bbf" stroke-width="4"/>
|
|
5
|
+
<path d="M39.5 42h9M44 37.5v9" stroke="#247bbf" stroke-width="3.5" stroke-linecap="round"/>
|
|
6
|
+
</svg>
|
package/src/index.js
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the Session "export as file path" bundle.
|
|
3
|
+
*
|
|
4
|
+
* The browser cannot write arbitrary files, so the Client half reads the
|
|
5
|
+
* existing `/api/session.markdown` transcript (the shipped Markdown export)
|
|
6
|
+
* and hands the text back here; this route materializes a self-contained
|
|
7
|
+
* directory under `~/.dsh/exports`:
|
|
8
|
+
*
|
|
9
|
+
* <session>/transcript.md the shipped Markdown transcript, with every
|
|
10
|
+
* image label rewritten to a relative link
|
|
11
|
+
* <session>/media/<id>.<ext> the referenced image bytes, read from the
|
|
12
|
+
* attachment store
|
|
13
|
+
*
|
|
14
|
+
* It answers with the absolute directory path that the Client copies to the
|
|
15
|
+
* clipboard, so another agent can open the directory and see the images.
|
|
16
|
+
*/
|
|
17
|
+
import { promises as fs } from 'node:fs'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import os from 'node:os'
|
|
20
|
+
|
|
21
|
+
/** Plugin row name. */
|
|
22
|
+
export const name = 'session-path-export'
|
|
23
|
+
|
|
24
|
+
/** The route needs Connection to register an authenticated browser route. */
|
|
25
|
+
export const inject = ['connection']
|
|
26
|
+
|
|
27
|
+
/** Absolute registration path of the write-and-reveal route. */
|
|
28
|
+
const EXPORT_FILE_PATH = '/api/session.export-file'
|
|
29
|
+
|
|
30
|
+
/** Hard ceiling for one transcript body (bytes) to keep the route bounded. */
|
|
31
|
+
const MAX_TRANSCRIPT_BYTES = 64 * 1024 * 1024
|
|
32
|
+
|
|
33
|
+
/** Default lifetime of one exported directory before it is pruned. */
|
|
34
|
+
const DEFAULT_RETENTION_DAYS = 3
|
|
35
|
+
|
|
36
|
+
/** Milliseconds in one day. */
|
|
37
|
+
const DAY_MS = 24 * 60 * 60 * 1000
|
|
38
|
+
|
|
39
|
+
/** File extension per accepted raster media type (mirrors the shipped zip export). */
|
|
40
|
+
const MEDIA_TYPE_EXTENSIONS = {
|
|
41
|
+
'image/png': 'png',
|
|
42
|
+
'image/jpeg': 'jpg',
|
|
43
|
+
'image/webp': 'webp',
|
|
44
|
+
'image/gif': 'gif',
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Filename of the transcript inside one export directory. */
|
|
48
|
+
const TRANSCRIPT_NAME = 'transcript.md'
|
|
49
|
+
|
|
50
|
+
/** Append-only request log inside the export root (never blocks an export). */
|
|
51
|
+
const EXPORT_LOG_NAME = '.export-log.jsonl'
|
|
52
|
+
|
|
53
|
+
/** Coerce whatever the attachment store hands back into writable bytes. */
|
|
54
|
+
function toBytes(value) {
|
|
55
|
+
if (value instanceof ArrayBuffer) return Buffer.from(value)
|
|
56
|
+
if (ArrayBuffer.isView(value)) return Buffer.from(value.buffer, value.byteOffset, value.byteLength)
|
|
57
|
+
return value
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Record one export attempt so a client-side failure can be diagnosed later. */
|
|
61
|
+
async function appendExportLog(outDir, entry) {
|
|
62
|
+
try {
|
|
63
|
+
await fs.mkdir(outDir, { recursive: true })
|
|
64
|
+
await fs.appendFile(path.join(outDir, EXPORT_LOG_NAME), `${JSON.stringify(entry)}\n`, 'utf8')
|
|
65
|
+
} catch {
|
|
66
|
+
/* diagnostics must never fail the export */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Session id characters kept verbatim in the filename. */
|
|
71
|
+
function safeFileStem(sessionId) {
|
|
72
|
+
return String(sessionId).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120) || 'session'
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** JSON response helper. */
|
|
76
|
+
function jsonResponse(value, status = 200) {
|
|
77
|
+
return new Response(JSON.stringify(value), {
|
|
78
|
+
status,
|
|
79
|
+
headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The label the shipped Markdown formatter prints for one image reference. */
|
|
84
|
+
function labelName(name) {
|
|
85
|
+
const normalized = name?.replace(/\s+/gu, ' ').replace(/\]/gu, '\\]').trim() ?? ''
|
|
86
|
+
return normalized === '' ? 'attachment' : normalized
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Exactly the string `formatSessionMarkdown` writes for one image block. */
|
|
90
|
+
function imageLabel(ref) {
|
|
91
|
+
return `[Image: ${labelName(ref.name)} (${String(ref.width)}×${String(ref.height)}, ${String(ref.bytes)} bytes)]`
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Collect every image attachment reference one committed event stream names,
|
|
96
|
+
* in the order the transcript renders them.
|
|
97
|
+
*
|
|
98
|
+
* A deep walk is deliberate: image blocks hide inside message content, tool
|
|
99
|
+
* results, summaries and stream chunks, and any of those carriers may appear
|
|
100
|
+
* in future log versions.
|
|
101
|
+
* @param events - the Session's logical events in seq order.
|
|
102
|
+
* @returns the image references, duplicates included (one per occurrence).
|
|
103
|
+
*/
|
|
104
|
+
function collectImageRefs(events) {
|
|
105
|
+
const refs = []
|
|
106
|
+
const visit = (node) => {
|
|
107
|
+
if (node === null || typeof node !== 'object') return
|
|
108
|
+
if (Array.isArray(node)) {
|
|
109
|
+
for (const item of node) visit(item)
|
|
110
|
+
return
|
|
111
|
+
}
|
|
112
|
+
if (node.type === 'image') {
|
|
113
|
+
const ref = node.attachment
|
|
114
|
+
if (typeof ref === 'object' && ref !== null && typeof ref.attachmentId === 'string') refs.push(ref)
|
|
115
|
+
return
|
|
116
|
+
}
|
|
117
|
+
for (const value of Object.values(node)) visit(value)
|
|
118
|
+
}
|
|
119
|
+
for (const event of events) visit(event)
|
|
120
|
+
return refs
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Rewrite each image label into a relative Markdown link.
|
|
125
|
+
*
|
|
126
|
+
* Replacement is by exact label text, one occurrence at a time, so an export
|
|
127
|
+
* never depends on the transcript's segment ordering staying stable: a label
|
|
128
|
+
* the transcript does not contain is simply left alone.
|
|
129
|
+
* @param markdown - the shipped transcript text.
|
|
130
|
+
* @param links - label text to the queue of relative media paths.
|
|
131
|
+
* @returns the rewritten transcript.
|
|
132
|
+
*/
|
|
133
|
+
function rewriteImageLabels(markdown, links) {
|
|
134
|
+
if (links.size === 0) return markdown
|
|
135
|
+
const labels = [...links.keys()]
|
|
136
|
+
let out = ''
|
|
137
|
+
let rest = markdown
|
|
138
|
+
while (rest.length > 0) {
|
|
139
|
+
let at = -1
|
|
140
|
+
let matched = ''
|
|
141
|
+
for (const label of labels) {
|
|
142
|
+
const found = rest.indexOf(label)
|
|
143
|
+
if (found >= 0 && (at < 0 || found < at)) {
|
|
144
|
+
at = found
|
|
145
|
+
matched = label
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (at < 0) {
|
|
149
|
+
out += rest
|
|
150
|
+
break
|
|
151
|
+
}
|
|
152
|
+
const queue = links.get(matched)
|
|
153
|
+
const relative = queue.length > 1 ? queue.shift() : queue[0]
|
|
154
|
+
const alt = matched.slice('[Image: '.length, matched.lastIndexOf(' (')).replace(/\\\]/gu, ']')
|
|
155
|
+
out += `${rest.slice(0, at)}`
|
|
156
|
+
rest = rest.slice(at + matched.length)
|
|
157
|
+
}
|
|
158
|
+
return out
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Delete exported sessions older than the retention window.
|
|
163
|
+
*
|
|
164
|
+
* Each export is one directory (plus any legacy single `.md` file) named after
|
|
165
|
+
* its Session, so a custom `outDir` never loses unrelated entries. `keep` is
|
|
166
|
+
* the export just written and is skipped even if a clock skew made it look
|
|
167
|
+
* stale.
|
|
168
|
+
* @param outDir - export root.
|
|
169
|
+
* @param retentionDays - days to keep; non-positive disables pruning.
|
|
170
|
+
* @param keep - absolute path of the fresh export.
|
|
171
|
+
* @returns how many entries were removed.
|
|
172
|
+
*/
|
|
173
|
+
async function pruneOldExports(outDir, retentionDays, keep = '') {
|
|
174
|
+
if (!(retentionDays > 0)) return 0
|
|
175
|
+
let entries
|
|
176
|
+
try {
|
|
177
|
+
entries = await fs.readdir(outDir, { withFileTypes: true })
|
|
178
|
+
} catch {
|
|
179
|
+
return 0
|
|
180
|
+
}
|
|
181
|
+
const cutoff = Date.now() - retentionDays * DAY_MS
|
|
182
|
+
let removed = 0
|
|
183
|
+
for (const entry of entries) {
|
|
184
|
+
if (!entry.isDirectory() && !entry.isFile()) continue
|
|
185
|
+
const target = path.join(outDir, entry.name)
|
|
186
|
+
if (target === keep) continue
|
|
187
|
+
try {
|
|
188
|
+
const stat = await fs.stat(target)
|
|
189
|
+
if (stat.mtimeMs > cutoff) continue
|
|
190
|
+
await fs.rm(target, { recursive: true, force: true })
|
|
191
|
+
removed += 1
|
|
192
|
+
} catch {
|
|
193
|
+
/* an entry that vanished mid-scan is already pruned */
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return removed
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Copy every referenced image into `<dir>/media` and report the label mapping.
|
|
201
|
+
* Best-effort: a missing service or an unreadable attachment never fails the
|
|
202
|
+
* export, it only leaves that label as text.
|
|
203
|
+
* @returns number of images written and the label-to-link map.
|
|
204
|
+
*/
|
|
205
|
+
async function materializeImages({ ctx, sessionId, dir, signal }) {
|
|
206
|
+
const links = new Map()
|
|
207
|
+
const failures = []
|
|
208
|
+
const sessionQuery = ctx.get('sessionQuery')
|
|
209
|
+
const attachments = ctx.get('attachments')
|
|
210
|
+
if (sessionQuery === undefined || attachments === undefined) {
|
|
211
|
+
failures.push('sessionQuery/attachments service unavailable')
|
|
212
|
+
return { links, written: 0, failures }
|
|
213
|
+
}
|
|
214
|
+
let refs
|
|
215
|
+
try {
|
|
216
|
+
const snapshot = await sessionQuery.readSession(sessionId)
|
|
217
|
+
refs = collectImageRefs(snapshot.events)
|
|
218
|
+
} catch (error) {
|
|
219
|
+
failures.push(`readSession: ${error instanceof Error ? error.message : String(error)}`)
|
|
220
|
+
return { links, written: 0, failures }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const copied = new Map()
|
|
224
|
+
let written = 0
|
|
225
|
+
const mediaDir = path.join(dir, 'media')
|
|
226
|
+
for (const ref of refs) {
|
|
227
|
+
const id = String(ref.attachmentId)
|
|
228
|
+
let relative = copied.get(id)
|
|
229
|
+
if (relative === undefined) {
|
|
230
|
+
const extension = MEDIA_TYPE_EXTENSIONS[ref.mediaType]
|
|
231
|
+
if (extension === undefined) {
|
|
232
|
+
if (failures.length < 5) failures.push(`${id}: unsupported mediaType ${String(ref.mediaType)}`)
|
|
233
|
+
continue
|
|
234
|
+
}
|
|
235
|
+
const file = `${safeFileStem(id)}.${extension}`
|
|
236
|
+
try {
|
|
237
|
+
const stored = await attachments.readImage(ref, signal)
|
|
238
|
+
const bytes = stored?.data
|
|
239
|
+
if (bytes === undefined) throw new Error('readImage returned no data')
|
|
240
|
+
await fs.mkdir(mediaDir, { recursive: true })
|
|
241
|
+
await fs.writeFile(path.join(mediaDir, file), toBytes(bytes))
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (failures.length < 5) failures.push(`${id}: ${error instanceof Error ? error.message : String(error)}`)
|
|
244
|
+
continue
|
|
245
|
+
}
|
|
246
|
+
relative = `media/${file}`
|
|
247
|
+
copied.set(id, relative)
|
|
248
|
+
written += 1
|
|
249
|
+
}
|
|
250
|
+
const label = imageLabel(ref)
|
|
251
|
+
const queue = links.get(label)
|
|
252
|
+
if (queue === undefined) links.set(label, [relative])
|
|
253
|
+
else queue.push(relative)
|
|
254
|
+
}
|
|
255
|
+
return { links, written, failures }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Register the export-to-directory route.
|
|
260
|
+
* @param ctx - Host context carrying Connection, Session query and Attachments.
|
|
261
|
+
* @param config - optional row configuration (`outDir`, `retentionDays`).
|
|
262
|
+
*/
|
|
263
|
+
export function apply(ctx, config = {}) {
|
|
264
|
+
const configured = typeof config?.outDir === 'string' ? config.outDir.trim() : ''
|
|
265
|
+
const outDir = configured === '' ? path.join(os.homedir(), '.dsh', 'exports') : path.resolve(configured)
|
|
266
|
+
const retentionDays =
|
|
267
|
+
typeof config?.retentionDays === 'number' && Number.isFinite(config.retentionDays)
|
|
268
|
+
? config.retentionDays
|
|
269
|
+
: DEFAULT_RETENTION_DAYS
|
|
270
|
+
|
|
271
|
+
/* Drop whatever aged out while the app was closed. */
|
|
272
|
+
void pruneOldExports(outDir, retentionDays)
|
|
273
|
+
|
|
274
|
+
/** Write one export directory and answer with its absolute path. */
|
|
275
|
+
async function exportFile(request) {
|
|
276
|
+
let body
|
|
277
|
+
try {
|
|
278
|
+
body = await request.json()
|
|
279
|
+
} catch {
|
|
280
|
+
return jsonResponse({ error: 'invalid JSON body' }, 400)
|
|
281
|
+
}
|
|
282
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : ''
|
|
283
|
+
const markdown = typeof body?.markdown === 'string' ? body.markdown : ''
|
|
284
|
+
if (sessionId === '') return jsonResponse({ error: 'missing sessionId' }, 400)
|
|
285
|
+
if (markdown === '') return jsonResponse({ error: 'missing markdown transcript' }, 400)
|
|
286
|
+
const bytes = Buffer.byteLength(markdown, 'utf8')
|
|
287
|
+
if (bytes > MAX_TRANSCRIPT_BYTES) return jsonResponse({ error: 'transcript too large' }, 413)
|
|
288
|
+
|
|
289
|
+
const dir = path.join(outDir, safeFileStem(sessionId))
|
|
290
|
+
const transcript = path.join(dir, TRANSCRIPT_NAME)
|
|
291
|
+
const started = Date.now()
|
|
292
|
+
let media = { links: new Map(), written: 0, failures: [] }
|
|
293
|
+
try {
|
|
294
|
+
await fs.mkdir(dir, { recursive: true })
|
|
295
|
+
media = await materializeImages({ ctx, sessionId, dir, signal: request.signal })
|
|
296
|
+
const text = rewriteImageLabels(markdown, media.links)
|
|
297
|
+
const temporary = `${transcript}.${process.pid}.tmp`
|
|
298
|
+
await fs.writeFile(temporary, text, 'utf8')
|
|
299
|
+
await fs.rename(temporary, transcript)
|
|
300
|
+
} catch (error) {
|
|
301
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
302
|
+
await appendExportLog(outDir, {
|
|
303
|
+
at: new Date().toISOString(),
|
|
304
|
+
sessionId,
|
|
305
|
+
markdownBytes: bytes,
|
|
306
|
+
media: media.written,
|
|
307
|
+
mediaFailures: media.failures,
|
|
308
|
+
ms: Date.now() - started,
|
|
309
|
+
error: message,
|
|
310
|
+
})
|
|
311
|
+
return jsonResponse({ error: `cannot write export: ${message}` }, 500)
|
|
312
|
+
}
|
|
313
|
+
/* Every export sweeps the folder, so stale transcripts never pile up. */
|
|
314
|
+
const pruned = await pruneOldExports(outDir, retentionDays, dir)
|
|
315
|
+
const elapsed = Date.now() - started
|
|
316
|
+
await appendExportLog(outDir, {
|
|
317
|
+
at: new Date().toISOString(),
|
|
318
|
+
sessionId,
|
|
319
|
+
markdownBytes: bytes,
|
|
320
|
+
media: media.written,
|
|
321
|
+
mediaFailures: media.failures,
|
|
322
|
+
pruned,
|
|
323
|
+
ms: elapsed,
|
|
324
|
+
path: dir,
|
|
325
|
+
})
|
|
326
|
+
return jsonResponse({
|
|
327
|
+
path: dir,
|
|
328
|
+
transcript,
|
|
329
|
+
media: media.written,
|
|
330
|
+
mediaFailures: media.failures.length,
|
|
331
|
+
bytes,
|
|
332
|
+
pruned,
|
|
333
|
+
retentionDays,
|
|
334
|
+
ms: elapsed,
|
|
335
|
+
})
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const connection = Reflect.get(ctx, 'connection')
|
|
339
|
+
if (connection === undefined) throw new Error('session-path-export requires the connection service')
|
|
340
|
+
connection.fetch.register({
|
|
341
|
+
path: EXPORT_FILE_PATH,
|
|
342
|
+
methods: ['POST'],
|
|
343
|
+
requestBody: 'buffered',
|
|
344
|
+
fetch: exportFile,
|
|
345
|
+
})
|
|
346
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
{
|
|
2
|
+
"meta": {
|
|
3
|
+
"title": "Session export folder",
|
|
4
|
+
"description": "Adds a row to both the conversation header “…” menu and the sidebar Session row “…” menu: exports the Session as a folder (transcript.md + media/) and copies its absolute path; exports older than 3 days are pruned."
|
|
5
|
+
}
|
|
6
|
+
}
|