dsh-plugin-marginalia 0.2.1 → 0.3.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.
Files changed (3) hide show
  1. package/client.js +191 -1181
  2. package/index.js +2 -270
  3. package/package.json +2 -1
package/index.js CHANGED
@@ -1,270 +1,2 @@
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
- }
1
+ /** Host half of Marginalia; the Client module mounts a native DSH Session inside the right sidebar. */
2
+ export function apply() {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-marginalia",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Marginalia: Ask side-channel questions about the main conversation or send prompts directly from the right sidebar.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -45,6 +45,7 @@
45
45
  "inject": [
46
46
  "@deepseek-ai/dsh-client-ui-sidebar-right",
47
47
  "@deepseek-ai/dsh-client-ui-conversation",
48
+ "@deepseek-ai/dsh-client-ui-subagent",
48
49
  "@deepseek-ai/dsh-client-locale",
49
50
  "@deepseek-ai/dsh-api-session-controller"
50
51
  ]