@d0nj/dsh-narration 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 d0nj
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 BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # @d0nj/dsh-narration
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
+ Watches the agent work, inside the transcript.
4
+
5
+ The browser half replaces the rendered assistant row with a live one: the model's
6
+ reasoning streams expanded and auto-scrolling instead of collapsing into a
7
+ one-line preview, and a header carries phase, elapsed time and throughput so the
8
+ row is never a blank spinner. The answer still renders as Markdown through the
9
+ shipped renderer. Every tool call is rendered open, and shaped by what it
10
+ actually did: `edit` and `write` show a patch-viewer diff with a line-number
11
+ gutter and inline `+added −removed`, `apply_patch` shows its patch,
12
+ `bash`/`pwsh` show the command as a shell line, and command output previews as a
13
+ tail with a `… N earlier lines` control that expands in place.
14
+
15
+ The Host half adds one system-prompt section asking the model to state its intent
16
+ in a single sentence in the same message as every tool call, and to batch
17
+ independent read-only calls so they run concurrently.
18
+
19
+ ## What is live
20
+
21
+ | Surface | Source | Cadence |
22
+ |---|---|---|
23
+ | Reasoning | `AssistantChatData.blocks` of kind `reasoning` | frame-paced drip, expands while streaming |
24
+ | Tool calls | `legacy.runningCalls` — preparing and dispatched | republished by the Chat snapshot |
25
+ | Partial arguments | `PartialArguments.text(...)` read during render | grows in place |
26
+ | Answer | `blocks` of kind `text` | shipped Markdown, `streaming` flag |
27
+ | Phase, elapsed, throughput | local clock and a windowed rate meter | 10 Hz |
28
+
29
+ Tokens are never painted straight off the wire. `PacedText` holds them in a FIFO
30
+ queue and releases them inside `requestAnimationFrame`: one or two characters per
31
+ frame while the backlog is shallow, accelerating to drain a deep backlog within
32
+ about six frames, and never splitting a surrogate pair.
33
+
34
+ ## The trade this makes
35
+
36
+ A slot occupant cannot render the row's child slots, so replacing the assistant
37
+ row gives up what the shipped one contributed: the message action row (copy,
38
+ retry), inline images, quote gestures and the message context menu. The answer's
39
+ Markdown itself survives because the row renders it through the shipped
40
+ `conversation.chat.reasoning.content` factory, with body typography restored by
41
+ the injected stylesheet.
42
+
43
+ Set `liveReasoning: false` to restore the shipped row untouched. The prompt rules
44
+ are independent of that switch.
45
+
46
+ ## Limits
47
+
48
+ The harness streams no foreground command output. The `bash` tool collects both
49
+ streams and returns them when the process exits, and no tool-level progress event
50
+ reaches the browser, so the row shows the command materialising plus the time it
51
+ has been running — not its stdout. Background jobs remain readable incrementally
52
+ through `job_output`.
53
+
54
+ ## Config
55
+
56
+ | Key | Default | Meaning |
57
+ |---|---|---|
58
+ | `liveReasoning` | `true` | Replace the assistant row with the live renderer |
59
+ | `verboseTools` | `true` | Render each tool call with its arguments and full output inline |
60
+ | `intentLine` | `true` | Require one sentence of intent per tool call |
61
+ | `parallelReads` | `true` | Ask for independent read-only calls in one message |
62
+ | `intentWords` | `24` | Upper bound on that sentence |
63
+
64
+ Typography and colour come from the theme: `--dsw-font-family`, the
65
+ `--dsw-font-*` scale and the `--dsw-alias-*` colour tokens. Nothing hardcodes a
66
+ family or a pixel size, so a theme change or a different font pairing applies
67
+ here too.
68
+
69
+ ## Install
70
+
71
+ ```bash
72
+ pnpm --filter @d0nj/dsh-narration build
73
+ ```
74
+
75
+ Then install the package directory from **Plugins** > **Add plugin**, or:
76
+
77
+ ```
78
+ plugin_manager install_bundle target=D:\projects\dsh-plugins\packages\narration
79
+ ```
80
+
81
+ The client half is fetched on page load, so a reload is what picks up a rebuild.
@@ -0,0 +1,7 @@
1
+ - insert:
2
+ - id: narration
3
+ name: '@d0nj/dsh-narration'
4
+ config:
5
+ intentLine: true
6
+ parallelReads: true
7
+ intentWords: 24
package/dist/ansi.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export type TermTone = 'default' | 'error' | 'success' | 'warn';
2
+ export interface TermSpan {
3
+ readonly text: string;
4
+ readonly tone: TermTone;
5
+ readonly bold: boolean;
6
+ readonly dim: boolean;
7
+ readonly underline: boolean;
8
+ }
9
+ export declare function normalizeTerminalText(source: string, tabSize?: number): string;
10
+ export declare function compactOutput(source: string): string;
11
+ export declare function stripAnsi(source: string): string;
12
+ export declare function parseAnsi(source: string, tabSize?: number): TermSpan[];
13
+ //# sourceMappingURL=ansi.d.ts.map
package/dist/ansi.js ADDED
@@ -0,0 +1,83 @@
1
+ const INITIAL = { tone: 'default', bold: false, dim: false, underline: false };
2
+ const OSC = /\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/gu;
3
+ const CSI = /\u001b\[([0-9;?]*)([A-Za-z])/gu;
4
+ function toneOf(code) {
5
+ if (code === 31 || code === 91)
6
+ return 'error';
7
+ if (code === 32 || code === 92)
8
+ return 'success';
9
+ if (code === 33 || code === 93)
10
+ return 'warn';
11
+ if (code === 39 || code === 99)
12
+ return 'default';
13
+ return undefined;
14
+ }
15
+ function applySgr(state, parameters) {
16
+ let next = state;
17
+ for (const field of parameters.split(';')) {
18
+ const code = field.length === 0 ? 0 : Number.parseInt(field, 10);
19
+ if (!Number.isFinite(code))
20
+ continue;
21
+ if (code === 0) {
22
+ next = INITIAL;
23
+ continue;
24
+ }
25
+ if (code === 1)
26
+ next = { ...next, bold: true };
27
+ else if (code === 2)
28
+ next = { ...next, dim: true };
29
+ else if (code === 4)
30
+ next = { ...next, underline: true };
31
+ else if (code === 22)
32
+ next = { ...next, bold: false, dim: false };
33
+ else if (code === 24)
34
+ next = { ...next, underline: false };
35
+ else {
36
+ const tone = toneOf(code);
37
+ if (tone !== undefined)
38
+ next = { ...next, tone };
39
+ }
40
+ }
41
+ return next;
42
+ }
43
+ export function normalizeTerminalText(source, tabSize = 4) {
44
+ const withoutOsc = source.replace(OSC, '');
45
+ const lines = withoutOsc.split('\n');
46
+ const flattened = lines.map((line) => {
47
+ const carriage = line.lastIndexOf('\r');
48
+ return carriage >= 0 ? line.slice(carriage + 1) : line;
49
+ });
50
+ return flattened.join('\n').replaceAll('\t', ' '.repeat(tabSize));
51
+ }
52
+ export function compactOutput(source) {
53
+ return source
54
+ .replace(/[ \t]+$/gmu, '')
55
+ .replace(/\n{3,}/gu, '\n\n')
56
+ .replace(/^\n+/u, '')
57
+ .replace(/\n+$/u, '');
58
+ }
59
+ export function stripAnsi(source) {
60
+ return normalizeTerminalText(source).replace(CSI, '');
61
+ }
62
+ export function parseAnsi(source, tabSize = 4) {
63
+ const text = normalizeTerminalText(source, tabSize);
64
+ const spans = [];
65
+ let state = INITIAL;
66
+ let last = 0;
67
+ CSI.lastIndex = 0;
68
+ let match = CSI.exec(text);
69
+ while (match !== null) {
70
+ const index = match.index;
71
+ if (index > last) {
72
+ spans.push({ text: text.slice(last, index), ...state });
73
+ }
74
+ if (match[2] === 'm')
75
+ state = applySgr(state, match[1] ?? '');
76
+ last = index + match[0].length;
77
+ match = CSI.exec(text);
78
+ }
79
+ if (last < text.length)
80
+ spans.push({ text: text.slice(last), ...state });
81
+ return spans;
82
+ }
83
+ //# sourceMappingURL=ansi.js.map
@@ -0,0 +1,25 @@
1
+ import type { LiveCall } from '../live.js';
2
+ export interface ReactApi {
3
+ createElement(type: unknown, props?: Record<string, unknown> | null, ...children: unknown[]): unknown;
4
+ useState<T>(initial: T | (() => T)): [T, (next: T | ((prev: T) => T)) => void];
5
+ useEffect(effect: () => void | (() => void), deps?: readonly unknown[]): void;
6
+ useRef<T>(initial: T): {
7
+ current: T;
8
+ };
9
+ }
10
+ type Selector = (snapshot: unknown) => unknown;
11
+ export interface AssistantNodeProps {
12
+ readonly node?: unknown;
13
+ readonly groupPart?: string | undefined;
14
+ readonly renderFactorySlot?: ((id: string, input: unknown) => unknown) | undefined;
15
+ readonly useChat?: ((select: Selector) => unknown) | undefined;
16
+ }
17
+ export type AssistantStatus = 'running' | 'settled' | 'interrupted';
18
+ export declare const REASONING_FACTORY = "conversation.chat.reasoning.content";
19
+ export declare function toLiveCalls(raw: unknown): LiveCall[];
20
+ export declare function assistantStatus(node: unknown): AssistantStatus;
21
+ export declare function blocksOf(node: unknown): readonly unknown[];
22
+ export declare function textOfBlocks(blocks: readonly unknown[], kind: 'reasoning' | 'text'): string;
23
+ export declare function createAssistantNarration(React: ReactApi): (props: AssistantNodeProps) => unknown;
24
+ export {};
25
+ //# sourceMappingURL=assistant.d.ts.map
@@ -0,0 +1,208 @@
1
+ import { PacedText, RateMeter } from '../pacing.js';
2
+ import { formatElapsed, formatRate, narrateCall, phaseLabel, splitPath, summarize, } from '../live.js';
3
+ import { PHASE_COLOUR } from './style.js';
4
+ const NO_SELECT = () => undefined;
5
+ const MISSING_ARGS = { text: () => undefined };
6
+ export const REASONING_FACTORY = 'conversation.chat.reasoning.content';
7
+ function legacyOf(snapshot) {
8
+ if (snapshot === null || typeof snapshot !== 'object')
9
+ return undefined;
10
+ const legacy = snapshot.legacy;
11
+ return legacy !== null && typeof legacy === 'object' ? legacy : undefined;
12
+ }
13
+ export function toLiveCalls(raw) {
14
+ if (!Array.isArray(raw))
15
+ return [];
16
+ const calls = [];
17
+ for (const entry of raw) {
18
+ if (entry === null || typeof entry !== 'object')
19
+ continue;
20
+ const record = entry;
21
+ if (typeof record.callId !== 'string' || typeof record.name !== 'string')
22
+ continue;
23
+ const source = record.args;
24
+ const usable = source !== null && typeof source === 'object' && typeof source.text === 'function';
25
+ calls.push({
26
+ callId: record.callId,
27
+ name: record.name,
28
+ phase: record.phase === 'start' ? 'start' : 'preparing',
29
+ time: typeof record.time === 'number' ? record.time : 0,
30
+ args: usable ? source : MISSING_ARGS,
31
+ });
32
+ }
33
+ return calls;
34
+ }
35
+ export function assistantStatus(node) {
36
+ if (node === null || typeof node !== 'object')
37
+ return 'settled';
38
+ const data = node.data;
39
+ if (data === null || typeof data !== 'object')
40
+ return 'settled';
41
+ const status = data.status;
42
+ return status === 'running' || status === 'interrupted' ? status : 'settled';
43
+ }
44
+ export function blocksOf(node) {
45
+ if (node === null || typeof node !== 'object')
46
+ return [];
47
+ const data = node.data;
48
+ if (data === null || typeof data !== 'object')
49
+ return [];
50
+ const blocks = data.blocks;
51
+ return Array.isArray(blocks) ? blocks : [];
52
+ }
53
+ export function textOfBlocks(blocks, kind) {
54
+ let text = '';
55
+ for (const block of blocks) {
56
+ if (block === null || typeof block !== 'object')
57
+ continue;
58
+ const entry = block;
59
+ if (entry.kind !== kind || typeof entry.text !== 'string')
60
+ continue;
61
+ text += entry.text;
62
+ }
63
+ return text;
64
+ }
65
+ function usePacedText(React, target, animating) {
66
+ const [shown, setShown] = React.useState(target);
67
+ const stream = React.useRef({ seen: target, queue: new PacedText() });
68
+ React.useEffect(() => {
69
+ const state = stream.current;
70
+ const previouslySeen = state.seen;
71
+ state.seen = target;
72
+ if (!target.startsWith(previouslySeen)) {
73
+ state.queue.reset();
74
+ setShown(target);
75
+ return;
76
+ }
77
+ const delta = target.slice(previouslySeen.length);
78
+ if (delta.length === 0)
79
+ return;
80
+ if (!animating) {
81
+ state.queue.reset();
82
+ setShown(target);
83
+ return;
84
+ }
85
+ state.queue.push(delta);
86
+ let frame = 0;
87
+ const step = () => {
88
+ const chunk = state.queue.take();
89
+ if (chunk.length > 0)
90
+ setShown((previous) => previous + chunk);
91
+ frame = state.queue.pending > 0 ? requestAnimationFrame(step) : 0;
92
+ };
93
+ frame = requestAnimationFrame(step);
94
+ return () => {
95
+ if (frame !== 0)
96
+ cancelAnimationFrame(frame);
97
+ };
98
+ }, [target, animating]);
99
+ return shown;
100
+ }
101
+ function useClock(React, working, meter, charsOf) {
102
+ const [now, setNow] = React.useState(() => Date.now());
103
+ const [rate, setRate] = React.useState(0);
104
+ React.useEffect(() => {
105
+ if (!working) {
106
+ meter.current.reset();
107
+ setRate(0);
108
+ return;
109
+ }
110
+ const tick = setInterval(() => {
111
+ const at = Date.now();
112
+ setNow(at);
113
+ setRate(meter.current.sample(at, charsOf()));
114
+ }, 100);
115
+ return () => clearInterval(tick);
116
+ }, [working]);
117
+ return { now, rate };
118
+ }
119
+ function callRow(React, call, now) {
120
+ const narration = narrateCall(call, 220);
121
+ const parts = splitPath(narration.argument);
122
+ const spent = call.time > 0 ? formatElapsed(Math.max(0, now - call.time)) : '';
123
+ return React.createElement('div', { key: call.callId, className: 'd0nj-narr-call', 'data-preparing': String(narration.preparing) }, React.createElement('span', { className: 'd0nj-narr-verb' }, narration.verb), React.createElement('span', { className: 'd0nj-narr-arg' }, parts.directory.length > 0
124
+ ? React.createElement('span', { className: 'd0nj-narr-dir' }, parts.directory)
125
+ : null, React.createElement('span', { className: 'd0nj-narr-base' }, parts.base), React.createElement('span', { className: 'd0nj-narr-caret' })), spent.length > 0 ? React.createElement('span', { className: 'd0nj-narr-spent' }, spent) : null);
126
+ }
127
+ export function createAssistantNarration(React) {
128
+ const h = React.createElement;
129
+ return function AssistantNarration(props) {
130
+ const useChat = props.useChat ?? NO_SELECT;
131
+ const status = assistantStatus(props.node);
132
+ const streaming = status === 'running';
133
+ const blocks = blocksOf(props.node);
134
+ const reasoningTarget = textOfBlocks(blocks, 'reasoning');
135
+ const answer = textOfBlocks(blocks, 'text');
136
+ const part = typeof props.groupPart === 'string' ? props.groupPart : undefined;
137
+ const showReasoning = part !== 'response';
138
+ const showAnswer = part !== 'reasoning';
139
+ const rawCalls = useChat((snapshot) => legacyOf(snapshot)?.runningCalls);
140
+ const calls = streaming ? toLiveCalls(rawCalls) : [];
141
+ const reasoning = usePacedText(React, reasoningTarget, streaming);
142
+ const meter = React.useRef(new RateMeter());
143
+ const charsRef = React.useRef(0);
144
+ charsRef.current = reasoningTarget.length + answer.length;
145
+ const { now, rate } = useClock(React, streaming, meter, () => charsRef.current);
146
+ const start = React.useRef(0);
147
+ React.useEffect(() => {
148
+ if (streaming && start.current === 0)
149
+ start.current = Date.now();
150
+ if (!streaming)
151
+ start.current = 0;
152
+ }, [streaming]);
153
+ const [thinkingOpen, setThinkingOpen] = React.useState(true);
154
+ const toggleThinking = () => {
155
+ setThinkingOpen((previous) => !previous);
156
+ };
157
+ const pinned = React.useRef(true);
158
+ const summary = summarize({ calls, reasoning, answer, running: streaming, limit: 120 });
159
+ const elapsed = start.current === 0 ? 0 : Math.max(0, now - start.current);
160
+ const countLabel = calls.length > 1 ? String(calls.length) : '';
161
+ const hasReasoning = reasoningTarget.length > 0;
162
+ const header = streaming && showReasoning
163
+ ? h('button', {
164
+ type: 'button',
165
+ className: 'd0nj-narr-live',
166
+ 'data-working': 'true',
167
+ 'aria-expanded': hasReasoning ? thinkingOpen : undefined,
168
+ onClick: hasReasoning ? toggleThinking : undefined,
169
+ }, h('span', { className: 'd0nj-narr-dot', style: { '--d0nj-narr-phase': PHASE_COLOUR[summary.phase] ?? PHASE_COLOUR.idle } }), h('span', { className: 'd0nj-narr-phase' }, phaseLabel(summary.phase)), countLabel.length > 0 ? h('span', { className: 'd0nj-narr-count' }, countLabel + ' calls') : null, h('span', { className: 'd0nj-narr-metrics' }, h('span', null, formatElapsed(elapsed)), rate > 0 ? h('span', null, formatRate(rate)) : null))
170
+ : null;
171
+ const roster = calls.length > 0 && showReasoning
172
+ ? h('div', { className: 'd0nj-narr-calls' }, calls.map((call) => callRow(React, call, now)))
173
+ : null;
174
+ const thinkingBody = showReasoning && thinkingOpen && hasReasoning
175
+ ? h('pre', {
176
+ className: 'd0nj-narr-think-body',
177
+ ref: (element) => {
178
+ if (element !== null && pinned.current)
179
+ element.scrollTop = element.scrollHeight;
180
+ },
181
+ onScroll: (event) => {
182
+ const element = event.currentTarget;
183
+ pinned.current = element.scrollHeight - element.scrollTop - element.clientHeight < 12;
184
+ },
185
+ }, reasoning)
186
+ : null;
187
+ const thinking = hasReasoning && showReasoning
188
+ ? h('div', { className: 'd0nj-narr-think' }, streaming
189
+ ? null
190
+ : h('button', {
191
+ type: 'button',
192
+ className: 'd0nj-narr-think-head',
193
+ 'aria-expanded': thinkingOpen,
194
+ onClick: toggleThinking,
195
+ }, (thinkingOpen ? '\u25be ' : '\u25b8 ') + 'Thinking'), thinkingBody)
196
+ : null;
197
+ const factory = props.renderFactorySlot;
198
+ const answerNode = answer.length > 0 && showAnswer
199
+ ? h('div', { className: 'd0nj-narr-answer' }, typeof factory === 'function'
200
+ ? factory(REASONING_FACTORY, { text: answer, running: streaming })
201
+ : h('div', { className: 'd0nj-narr-plain' }, answer))
202
+ : null;
203
+ if (header === null && roster === null && thinking === null && answerNode === null)
204
+ return null;
205
+ return h('div', { className: 'd0nj-narr' }, header, roster, thinking, answerNode);
206
+ };
207
+ }
208
+ //# sourceMappingURL=assistant.js.map