dsh-plugin-marginalia 0.0.0-stage → 0.2.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.
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: marginalia
3
+ name: dsh-plugin-marginalia
4
+ config: {}
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
2
+ <rect x="6" y="7" width="14" height="22" rx="3" stroke="#5B7CFA" stroke-width="2.2" />
3
+ <path d="M9.5 12.5H16.5M9.5 17H15M9.5 21.5H13.5" stroke="#5B7CFA" stroke-width="2" stroke-linecap="round" />
4
+ <path d="M21 10.5C21 9.11929 22.1193 8 23.5 8H28.5C29.8807 8 31 9.11929 31 10.5V19.5C31 20.8807 29.8807 22 28.5 22H25.2L22 24.8V22H23.5C22.1193 22 21 20.8807 21 19.5V10.5Z" fill="#3B82F6" fill-opacity="0.16" stroke="#3B82F6" stroke-width="2" stroke-linejoin="round" />
5
+ <path d="M26 12.2L26.7 13.8L28.3 14.5L26.7 15.2L26 16.8L25.3 15.2L23.7 14.5L25.3 13.8L26 12.2Z" fill="#3B82F6" />
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Host plugin for Marginalia: exposes an authenticated SSE endpoint `/api/marginalia/ask`
3
+ * that answers side-channel questions using the active session's conversation context
4
+ * and configured model without mutating the main session log.
5
+ */
6
+
7
+ export const inject = ['connection', 'sessions', 'llm', 'agentDefaultModel'];
8
+
9
+ const MAX_CONTEXT_MESSAGES = 24;
10
+ const MAX_CONTEXT_CHARS = 24000;
11
+ const MAX_HISTORY_TURNS = 12;
12
+
13
+ function extractBlockText(blocks) {
14
+ if (!Array.isArray(blocks)) return '';
15
+ const parts = [];
16
+ for (const block of blocks) {
17
+ if (!block || typeof block !== 'object') continue;
18
+ if (block.type === 'text' && typeof block.text === 'string') {
19
+ parts.push(block.text);
20
+ } else if (block.type === 'tool-call' && typeof block.name === 'string') {
21
+ parts.push(`[Tool call: ${block.name}]`);
22
+ } else if (block.type === 'image') {
23
+ parts.push('[Image]');
24
+ } else if (block.type === 'file' && block.attachment?.name) {
25
+ parts.push(`[File: ${block.attachment.name}]`);
26
+ }
27
+ }
28
+ return parts.join('\n').trim();
29
+ }
30
+
31
+ function formatMessagesTranscript(messages) {
32
+ const lines = [];
33
+ const slice = messages.slice(-MAX_CONTEXT_MESSAGES);
34
+ for (const msg of slice) {
35
+ if (!msg || typeof msg !== 'object') continue;
36
+ if (msg.role === 'user') {
37
+ const text = extractBlockText(msg.content);
38
+ if (text) lines.push(`User: ${text}`);
39
+ } else if (msg.role === 'assistant') {
40
+ const text = extractBlockText(msg.content);
41
+ if (text) lines.push(`Assistant: ${text}`);
42
+ } else if (msg.role === 'tool') {
43
+ const text = extractBlockText(msg.content);
44
+ if (text) {
45
+ const clipped = text.length > 600 ? `${text.slice(0, 600)}…` : text;
46
+ lines.push(`ToolResult: ${clipped}`);
47
+ }
48
+ }
49
+ }
50
+ let joined = lines.join('\n\n');
51
+ if (joined.length > MAX_CONTEXT_CHARS) {
52
+ joined = '…(earlier messages omitted)…\n\n' + joined.slice(-MAX_CONTEXT_CHARS);
53
+ }
54
+ return joined;
55
+ }
56
+
57
+ function formatColdRecordsTranscript(records) {
58
+ const lines = [];
59
+ for (const rec of records) {
60
+ const ev = rec?.event;
61
+ if (!ev || typeof ev !== 'object') continue;
62
+ if (ev.type === 'user/message') {
63
+ const text = extractBlockText(ev.data?.content);
64
+ if (text) lines.push(`User: ${text}`);
65
+ } else if (ev.type === 'assistant/message') {
66
+ const text = extractBlockText(ev.data?.message?.content);
67
+ if (text) lines.push(`Assistant: ${text}`);
68
+ }
69
+ }
70
+ let joined = lines.join('\n\n');
71
+ if (joined.length > MAX_CONTEXT_CHARS) {
72
+ joined = '…(earlier messages omitted)…\n\n' + joined.slice(-MAX_CONTEXT_CHARS);
73
+ }
74
+ return joined;
75
+ }
76
+
77
+ function sseLine(payload) {
78
+ return `data: ${JSON.stringify(payload)}\n\n`;
79
+ }
80
+
81
+ export function apply(ctx) {
82
+ ctx.effect(() => {
83
+ const disposeRoute = ctx.connection.fetch.register({
84
+ path: '/api/marginalia/ask',
85
+ methods: ['POST'],
86
+ requestBody: 'buffered',
87
+ async fetch(request) {
88
+ let body;
89
+ try {
90
+ body = await request.json();
91
+ } catch {
92
+ return Response.json({ error: 'Invalid JSON request body' }, { status: 400 });
93
+ }
94
+
95
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
96
+ const question = typeof body?.question === 'string' ? body.question.trim() : '';
97
+ const includeContext = body?.includeContext !== false;
98
+ const rawHistory = Array.isArray(body?.history) ? body.history : [];
99
+ const rawQuotes = Array.isArray(body?.quotes)
100
+ ? body.quotes.filter((q) => typeof q === 'string' && q.trim()).map((q) => q.trim().slice(0, 4000))
101
+ : [];
102
+
103
+ if (!question && rawQuotes.length === 0) {
104
+ return Response.json({ error: 'Question is required' }, { status: 400 });
105
+ }
106
+
107
+ let transcript = '';
108
+ let modelConfig;
109
+
110
+ if (sessionId) {
111
+ const liveSession = ctx.sessions.get(sessionId);
112
+ if (liveSession) {
113
+ modelConfig = liveSession.requestHeader()?.config;
114
+ if (includeContext) {
115
+ transcript = formatMessagesTranscript(liveSession.deriveMessages());
116
+ }
117
+ } else if (includeContext) {
118
+ const sc = ctx.get('sessionController');
119
+ if (sc && typeof sc.events === 'function') {
120
+ try {
121
+ const page = await sc.events(
122
+ { address: { kind: 'session', sessionId }, maxMessages: MAX_CONTEXT_MESSAGES },
123
+ request.signal,
124
+ );
125
+ if (Array.isArray(page?.records)) {
126
+ transcript = formatColdRecordsTranscript(page.records);
127
+ }
128
+ } catch {
129
+ // Best effort; proceed without transcript if cold read fails.
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ if (!modelConfig?.provider || !modelConfig?.model) {
136
+ modelConfig = ctx.agentDefaultModel.currentSelection();
137
+ }
138
+
139
+ if (!modelConfig?.provider || !modelConfig?.model) {
140
+ return Response.json(
141
+ { error: 'No active model configured. Select or configure a model first.' },
142
+ { status: 400 },
143
+ );
144
+ }
145
+
146
+ const systemParts = [
147
+ 'You are Marginalia, a concise side-channel Q&A assistant docked in the right sidebar of DeepSeek Harness.',
148
+ 'The user is asking a side question about their ongoing main conversation without wanting to interrupt or clutter the main thread.',
149
+ 'Answer clearly, directly, and in the same language as the user\'s question.',
150
+ ];
151
+ if (includeContext && transcript) {
152
+ systemParts.push(
153
+ 'Here is the recent transcript of the main conversation for reference:\n\n<main_conversation>\n' +
154
+ transcript +
155
+ '\n</main_conversation>',
156
+ );
157
+ } else if (includeContext) {
158
+ systemParts.push('The main conversation currently has no messages yet.');
159
+ }
160
+
161
+ const messages = [];
162
+ for (const item of rawHistory.slice(-MAX_HISTORY_TURNS)) {
163
+ if (!item || typeof item !== 'object') continue;
164
+ const role = item.role === 'assistant' ? 'assistant' : item.role === 'user' ? 'user' : null;
165
+ const text = typeof item.text === 'string' ? item.text.trim() : '';
166
+ if (!role || !text) continue;
167
+ messages.push({
168
+ role,
169
+ content: [{ type: 'text', text }],
170
+ });
171
+ }
172
+ const userText =
173
+ rawQuotes.length > 0
174
+ ? rawQuotes.map((q, i) => `> [Selected excerpt ${i + 1}]\n> ${q.replace(/\n/g, '\n> ')}`).join('\n\n') +
175
+ '\n\n' +
176
+ (question || 'Please explain the selected excerpt(s).')
177
+ : question;
178
+
179
+ messages.push({
180
+ role: 'user',
181
+ content: [{ type: 'text', text: userText }],
182
+ });
183
+
184
+ let prepared;
185
+ try {
186
+ prepared = await ctx.llm.prepareCall(
187
+ {
188
+ provider: modelConfig.provider,
189
+ model: modelConfig.model,
190
+ ...(modelConfig.reasoningEffort ? { reasoningEffort: modelConfig.reasoningEffort } : {}),
191
+ },
192
+ request.signal,
193
+ );
194
+ } catch (err) {
195
+ const message = err instanceof Error ? err.message : String(err);
196
+ return Response.json({ error: message || 'Failed to prepare model call' }, { status: 500 });
197
+ }
198
+
199
+ const encoder = new TextEncoder();
200
+ const stream = new ReadableStream({
201
+ async start(controller) {
202
+ const send = (obj) => {
203
+ try {
204
+ controller.enqueue(encoder.encode(sseLine(obj)));
205
+ } catch {
206
+ // Stream already closed.
207
+ }
208
+ };
209
+ send({
210
+ type: 'meta',
211
+ provider: prepared.config.provider,
212
+ model: prepared.config.model,
213
+ hasContext: Boolean(transcript),
214
+ });
215
+ try {
216
+ const chunks = prepared.stream({
217
+ provider: prepared.config.provider,
218
+ model: prepared.config.model,
219
+ ...(prepared.config.reasoningEffort ? { reasoningEffort: prepared.config.reasoningEffort } : {}),
220
+ system: systemParts.join('\n\n'),
221
+ messages,
222
+ signal: request.signal,
223
+ });
224
+ for await (const chunk of chunks) {
225
+ if (request.signal.aborted) break;
226
+ if (chunk.type === 'text-delta' && chunk.text) {
227
+ send({ type: 'delta', text: chunk.text });
228
+ } else if (chunk.type === 'reasoning-delta' && chunk.text) {
229
+ send({ type: 'reasoning', text: chunk.text });
230
+ } else if (chunk.type === 'finish') {
231
+ if (chunk.reason?.kind === 'error') {
232
+ send({
233
+ type: 'error',
234
+ message: chunk.reason.failure?.message || 'Model stream error',
235
+ });
236
+ }
237
+ }
238
+ }
239
+ send({ type: 'done' });
240
+ } catch (err) {
241
+ if (!request.signal.aborted) {
242
+ const message = err instanceof Error ? err.message : String(err);
243
+ send({ type: 'error', message: message || 'Stream failed' });
244
+ }
245
+ } finally {
246
+ try {
247
+ controller.close();
248
+ } catch {
249
+ // Ignore double close.
250
+ }
251
+ }
252
+ },
253
+ });
254
+
255
+ return new Response(stream, {
256
+ status: 200,
257
+ headers: {
258
+ 'Content-Type': 'text/event-stream; charset=utf-8',
259
+ 'Cache-Control': 'no-cache, no-transform',
260
+ 'X-Accel-Buffering': 'no',
261
+ },
262
+ });
263
+ },
264
+ });
265
+
266
+ return () => {
267
+ void disposeRoute();
268
+ };
269
+ }, 'dsh-plugin-marginalia: route');
270
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Marginalia",
4
+ "description": "Ask side-channel questions about the active conversation from the right sidebar without interrupting or cluttering the main thread, or send a prompt directly to the main chat. Open Marginalia from the header utility button in any session or from the right sidebar's Guide tab. Side-Ask queries use the session's current model and recent conversation context via the local Host; disabling the plugin removes the sidebar tab, header button, and local endpoint."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "旁注问 (Marginalia)",
4
+ "description": "在右侧边栏中随时向主对话提问:支持「旁注提问」(基于当前主对话上下文和模型进行独立问答,不打断也不污染主对话)以及「直发主对话」(将问题直接排队或插队发送到主会话)。可在任意会话顶部右侧工具栏点击 Marginalia 图标,或在右侧边栏导航页打开。停用插件后将移除侧边栏标签页、顶栏入口与本地问答接口。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "dsh-plugin-marginalia",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Marginalia: Ask side-channel questions about the main conversation or send prompts directly from the right sidebar.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/yangdw2024/dsh-plugin-marginalia.git"
10
+ },
11
+ "homepage": "https://github.com/yangdw2024/dsh-plugin-marginalia#readme",
12
+ "keywords": [
13
+ "deepseek-harness",
14
+ "dsh-plugin",
15
+ "dsh-bundle",
16
+ "sidebar",
17
+ "marginalia",
18
+ "qa"
19
+ ],
20
+ "engines": {
21
+ "dsh": ">=0.2.0"
22
+ },
23
+ "exports": {
24
+ ".": "./index.js",
25
+ "./client": "./client.js",
26
+ "./locale/*.json": "./locale/*.json",
27
+ "./icon": "./icon.svg"
28
+ },
29
+ "files": [
30
+ "index.js",
31
+ "client.js",
32
+ "cordis.patch.yml",
33
+ "locale/*.json",
34
+ "icon.svg",
35
+ "README.md",
36
+ "LICENSE"
37
+ ],
38
+ "dsh": {
39
+ "bundle": {
40
+ "patch": "./cordis.patch.yml"
41
+ },
42
+ "client": {
43
+ "platform": "web",
44
+ "immediately": true,
45
+ "inject": [
46
+ "@deepseek-ai/dsh-client-ui-sidebar-right",
47
+ "@deepseek-ai/dsh-client-ui-conversation",
48
+ "@deepseek-ai/dsh-client-locale",
49
+ "@deepseek-ai/dsh-api-session-controller"
50
+ ]
51
+ }
52
+ }
53
+ }