@4fu/dsh-arbor-ui 0.0.0-stage → 2026.1110.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 4fuu
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,250 @@
1
- # Temporary Holding Version
1
+ # dsh-arbor
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
+ Run [arbor](https://github.com/4fuu/arbor) as the agent driver inside
4
+ [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (DSH).
5
+
6
+ DSH gives a user a session, a transcript, approvals, plugins, skills and a model
7
+ picker. arbor gives an agent disposable context windows over one shared journal,
8
+ note store and workspace, instead of one long conversation. dsh-arbor connects
9
+ them: one arbor host runs inside the DSH process, each DSH session that selects
10
+ **Arbor** is served by that host, and the window's reply is written back to the
11
+ DSH session as an ordinary assistant message. A DSH session that does not select
12
+ Arbor keeps running on DSH's own embedded AgentLoop, in the same process.
13
+
14
+ > **Status.** This is a research-grade integration, not a DSH release. It is
15
+ > pinned to one DSH version and relies on DSH internals. Read
16
+ > [Versions and compatibility](docs/versions.md) before installing it on
17
+ > anything you care about. The packages are published under `@4fu` at
18
+ > `2026.1110.1`; the bundle and the font plugin install independently from npm.
19
+
20
+ ## What an arbor session changes
21
+
22
+ Choosing **Arbor** in a DSH composer creates the session under the `arbor` agent
23
+ preset. That session then runs on arbor, and the following are true for it:
24
+
25
+ - **One window per turn, one chain per session.** A DSH session is one arbor
26
+ conversation: its first turn opens a window, a window that ends hands off to a
27
+ continuation, and the next turn drives the chain. The journal and note store
28
+ live under `$DSH_HOME/arbor/` and survive a restart.
29
+ - **arbor's workspace, not DSH's sandbox.** A window works in arbor's shared
30
+ folder (`$DSH_HOME/arbor/shared`). When the `ovnfs` binary is available a
31
+ window opens a copy-on-write checkout and merges back with `apply`; otherwise
32
+ arbor uses a plain directory. **There is no DSH sandbox for an arbor session:**
33
+ arbor's file tools and commands run on the host, and arbor's own secret scrub
34
+ is the only protection on what reaches the model.
35
+ - **arbor's projects.** The shared folder's project folders are the DSH project
36
+ list for arbor composers. A directory the user adds outside the shared folder
37
+ is recorded as an external pointer for that session and used in place.
38
+ - **arbor's prompt and tools.** DSH's official prompt sections are decided one by
39
+ one; the ones arbor replaces are absent, third-party sections go into a
40
+ `<dsh>` data block, and a trusted `<harness>` section says what remains true of
41
+ DSH. DSH tools are offered to the model as arbor external tools, and arbor's
42
+ own tools replace DSH tools with the same capability.
43
+ - **The Arbor page.** A permanent **Arbor** entry in DSH's left navigation opens
44
+ the whole-host overview and one tab per arbor session: windows, chains,
45
+ handoffs, projects, the board, notes, `/env`, schedules and arbor's search.
46
+ An arbor composer hides DSH's sandbox access-mode switch, because that switch
47
+ does not apply to it.
48
+
49
+ ## What stays untouched in ordinary DSH sessions
50
+
51
+ A session that does not select Arbor is an ordinary DSH session. It keeps:
52
+
53
+ - DSH's embedded AgentLoop, session format, turn boundaries and streaming path;
54
+ - DSH's sandbox policy and its `ctx.fs` / `ctx.shell` file and command tools;
55
+ - DSH's project management, working directory and prompt assembly;
56
+ - its composer, sandbox access-mode switch, header and sidebar behavior.
57
+
58
+ It gets **no Arbor tab** and no arbor windows. The only shared surface is the
59
+ permanent Arbor entry in the left navigation, which simply does not list that
60
+ session. The routing registry replaces DSH's base `agent` row so it can send
61
+ `agentPreset: 'arbor'` sessions to arbor; every other session goes to the
62
+ official loop. Approvals still use DSH's approval path for both kinds of
63
+ session, and arbor's windows are registered so DSH's sidebar leaves them out.
64
+
65
+ ## Screenshots
66
+
67
+ | Overview, light | Overview, dark |
68
+ | --- | --- |
69
+ | ![Arbor overview in light mode](docs/screenshots/overview-light.png) | ![Arbor overview in dark mode](docs/screenshots/overview-dark.png) |
70
+ | **Session tab, light** | **Session tab, dark** |
71
+ | ![An arbor session tab in light mode](docs/screenshots/session-light.png) | ![An arbor session tab in dark mode](docs/screenshots/session-dark.png) |
72
+
73
+ These are the web profile at 1440 px wide with the optional
74
+ [font plugin](https://github.com/4fuu/dsh-arbor-fonts) installed: ChillDIN
75
+ Gothic for labels and ChillDIN for numerals, while body text and code keep
76
+ DSH's fonts. The same overview without the plugin is
77
+ [here](docs/screenshots/overview-without-fonts.png).
78
+
79
+ ## Install
80
+
81
+ Requirements: Node.js 24.9 or newer and DeepSeek Harness `dsh-v0.2.2-rc.1`.
82
+ The bundle is published with all packages it depends on; nothing has to be
83
+ built or linked.
84
+
85
+ ```bash
86
+ npm install -g @deepseek-ai/dsh@0.2.2-rc.1
87
+ dsh plugin --profile web add @4fu/dsh-arbor-bundle@2026.1110.1
88
+ dsh web
89
+ ```
90
+
91
+ `dsh plugin` adds the bundle to the profile's `dsh.profile.bundles` and installs
92
+ its packages into the profile. The packages declare DSH's runtime packages as
93
+ peer dependencies, so the profile keeps DSH's own copies rather than installing
94
+ a second set. Pick **Arbor** in a composer and send a message.
95
+ The optional [font plugin](https://github.com/4fuu/dsh-arbor-fonts) installs the
96
+ same way, but it is a Host row rather than a bundle. Add the row to the
97
+ profile's `cordis.patch.yml` after installing it:
98
+
99
+ ```bash
100
+ dsh plugin --profile web add @4fu/dsh-arbor-fonts@2026.1110.0
101
+ ```
102
+
103
+ ```yaml
104
+ - insert:
105
+ - id: arbor-fonts
106
+ name: '@4fu/dsh-arbor-fonts'
107
+ ```
108
+
109
+ Replace the default `[]` in that file with the entry, then restart the profile.
110
+
111
+ ### From a checkout
112
+
113
+ The proofs and development use the TypeScript sources directly; that checkout is
114
+ what the scripts and the pin check run against.
115
+
116
+ ```bash
117
+ git clone https://github.com/4fuu/dsh-arbor
118
+ cd dsh-arbor
119
+ pnpm install --frozen-lockfile
120
+ pnpm check # tsc --noEmit over every package and proof
121
+ pnpm proofs # 29 proofs against the scripted model
122
+ ```
123
+
124
+ The first install may ask pnpm to approve dependency build scripts. Do not
125
+ approve them by hand: the repository's `pnpm-workspace.yaml` already denies the
126
+ six scripts it pulls in, each with the reason, and `pnpm install` finishes
127
+ cleanly with that policy.
128
+
129
+ ### Hand the install to a model
130
+
131
+ [docs/install-for-agents.md](docs/install-for-agents.md) is a step-by-step guide
132
+ written for an AI agent: install from npm or a checkout, run the proofs, drive a
133
+ live turn with a restart, boot the web profile, and inspect what ran. Give a
134
+ model this prompt, editing the bracketed parts or dropping them:
135
+
136
+ ```text copy Copy Install Prompt
137
+ Install dsh-arbor (https://github.com/4fuu/dsh-arbor) in this environment [in a
138
+ scratch DSH home under /tmp] and show me that it works: follow
139
+ docs/install-for-agents.md, install @4fu/dsh-arbor-bundle@2026.1110.1 into a DSH
140
+ web profile, pick Arbor for one session, and [also run the proof suite from a
141
+ checkout with pnpm install --frozen-lockfile, pnpm check and pnpm proofs]. Report
142
+ which checks passed, what the live session answered, and anything that did not
143
+ work. Fix only what is yours to fix and tell me what you changed.
144
+ ```
145
+
146
+ ## Use it in DSH
147
+
148
+ The npm install above adds the bundle to a DSH web profile. Pick **Arbor** in a
149
+ composer and send a message: the session is created under the preset, its window
150
+ and chain appear under the **Arbor** entry, and an ordinary session started
151
+ beside it keeps DSH's own composer and sandbox behavior. A checkout can also be
152
+ wired by hand; [section 7 of the install guide](docs/install-for-agents.md#7-wiring-the-bundle-into-a-real-dsh-installation)
153
+ shows the profile layout.
154
+
155
+ The one-shot `dsh <task>` runner cannot drive an arbor-preset session: DSH's
156
+ runner refuses to adopt a session that runs under a preset. Use the web client,
157
+ the SDK path the proofs use, or a remote `agent-preset/select` on a blank.
158
+
159
+ ## Pinned DSH version
160
+
161
+ DSH is pinned to **`dsh-v0.2.2-rc.1`** (npm
162
+ `@deepseek-ai/dsh@0.2.2-rc.1`, commit `66491b05e3` of
163
+ `deepseek-ai/deepseek-harness`). Every `@deepseek-ai/dsh*` dependency is an
164
+ exact version, every package under `packages/` declares
165
+ `engines.dsh: 0.2.2-rc.1`, and `pnpm check:pin` checks both plus the prompt
166
+ bridge's `DSH_PINNED_VERSION`. DSH's runtime packages are peer dependencies, and
167
+ `pnpm check:profile` installs the packed packages into a fresh DSH web profile to
168
+ prove the profile keeps one copy and can create both kinds of session.
169
+
170
+ A different DSH version is unsupported. The bundle depends on DSH's row names,
171
+ its one-`AgentFactory` rule, its prompt-section registry, its client slot
172
+ registration and its exact Fetch registry; a move in any of them can fail the
173
+ boot, leave an official prompt section undecided, or stop the Arbor page from
174
+ registering. `proofs/12-official-sections.ts` and `proofs/18-picker-pin.ts`
175
+ are the behavioral checks. The canonical pin and the upgrade procedure are in
176
+ [Versions and compatibility](docs/versions.md).
177
+
178
+ ## Optional: the font plugin
179
+
180
+ [dsh-arbor-fonts](https://github.com/4fuu/dsh-arbor-fonts) is a separate DSH
181
+ client plugin that changes only the typography of the Arbor page. It sets
182
+ ChillDIN Gothic for display labels and ChillDIN for numerals, leaves body text
183
+ and code on DSH's fonts, and does nothing on ordinary pages. It is optional and
184
+ installs into the same DSH profile:
185
+
186
+ ```bash
187
+ dsh plugin --profile web add @4fu/dsh-arbor-fonts@2026.1110.0
188
+ ```
189
+
190
+ The fonts are licensed under the SIL Open Font License 1.1; the plugin ships the
191
+ license text, per-file hashes and attribution. The plugin is a Host row rather
192
+ than a bundle: after installing it, add the `arbor-fonts` entry described under
193
+ [Install](#install) to `cordis.patch.yml` and restart the profile.
194
+
195
+ ## Limits worth knowing
196
+
197
+ - The judge is off: a model-based judge cannot run through the DSH backend yet.
198
+ - The 12 bundle packages are published together at one version; install and
199
+ upgrade the bundle as a unit, because its packages name each other exactly.
200
+ - `ovnfs` is optional. Without it arbor uses the plain-directory workspace, and a
201
+ window no longer gets a copy-on-write checkout.
202
+ - The web page's numbers and layout are read from arbor's journal and API; it is
203
+ not a generic DSH dashboard, and it deliberately shows only arbor sessions.
204
+ - The prompt bridge, the UI and the picker filter are pinned to DSH's internals,
205
+ not to a stable public API. See [Versions and compatibility](docs/versions.md).
206
+
207
+ ## Documentation
208
+
209
+ - [Installing and inspecting dsh-arbor](docs/install-for-agents.md) — the
210
+ agent-facing install, proof, live-turn, web-profile and wiring guide.
211
+ - [Versions and compatibility](docs/versions.md) — the DSH and arbor pins, and
212
+ what breaks on another DSH version.
213
+ - [B0 findings](docs/b0-findings.md), [B3 findings](docs/b3-findings.md) and
214
+ [B3b projects and sandbox](docs/b3b-projects-and-sandbox.md) — historical
215
+ records of the integration's decisions, with the DSH source locations each
216
+ one rests on. They describe earlier stages; the install guide is the current
217
+ status.
218
+ - [Layout and proofs](#layout) below for a quick map of the packages.
219
+
220
+ ## Layout
221
+
222
+ ```text
223
+ packages/
224
+ arbor-host/ one Arbor host per process: SQLite journal and notes,
225
+ settings, window lifecycle, workspace and environment
226
+ arbor-driver/ the routing AgentRegistry, AgentFactory, session agent,
227
+ inbox and stream mirrors, and the journal relay
228
+ arbor-llm/ the arbor AgentBackend over DSH's ctx.llm and ctx.tools
229
+ arbor-prompt/ <harness>, the <dsh> data block, and the section table
230
+ arbor-tools/ DSH tools as arbor external tools, same-name replacement
231
+ arbor-workspace/ arbor's workspace over the shared folder (ovnfs or dir)
232
+ arbor-env/ /env, with DSH's skills and MCP servers mounted read-only
233
+ arbor-bundle/ the installable patch that mounts the rows and UI
234
+ arbor-facts/ the read face behind the Arbor page and its Fetch routes
235
+ arbor-ui/ the Arbor page, session tabs, copy and composer gate
236
+ arbor-ui-workspace/
237
+ the per-preset hero project picker
238
+ arbor-preset/ the agent-preset row that puts Arbor in the roster
239
+ arbor-testkit/ the boot harness, memory journal and scripted model
240
+ patches/ overlay layers a proof applies above the shipped profile
241
+ proofs/ one runnable proof per integration point
242
+ docs/ install, versions, screenshots and historical findings
243
+ scripts/ the pin and profile checks, the release build and packing
244
+ ```
245
+
246
+ ## License
247
+
248
+ MIT. See [LICENSE](LICENSE). The optional font plugin vendors fonts under the
249
+ SIL Open Font License 1.1; its repository carries the license text and
250
+ attribution.
package/channel.d.ts ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The browser half of arbor's facts channels.
3
+ *
4
+ * The host serves NDJSON streams on DSH's exact Fetch routes: one per session
5
+ * (`/api/arbor/facts?sessionId=…`) and one for the whole host
6
+ * (`/api/arbor/host`), both registered by `@4fu/dsh-arbor-facts`. This module
7
+ * owns one stream per scope for as long as a component holds it, folds the
8
+ * frames into the snapshot React reads, and reconnects with a bounded backoff
9
+ * when the page's carrier drops one.
10
+ *
11
+ * A frame is either the facts (the initial read and every rebuild) or one live
12
+ * delta from `Arbor.stream(window, …)`. The deltas are folded per window into
13
+ * a short buffer; the facts are kept as they arrived, because they are arbor's
14
+ * own values and nothing here recomputes them.
15
+ */
16
+ import type { ArborFacts, ArborHostFacts } from '@4fu/dsh-arbor-facts/types';
17
+ /** Where one channel stands right now. */
18
+ export type ArborChannelStatus = 'connecting' | 'live' | 'error';
19
+ /** What one live window has written recently. */
20
+ export interface ArborWindowStream {
21
+ /** The model's assistant text, newest at the end. */
22
+ readonly text: string;
23
+ /** The `send` call's arguments while it is being written, when parsable. */
24
+ readonly send: string;
25
+ /** A live delta arrived in the last moment. */
26
+ readonly streaming: boolean;
27
+ }
28
+ /** The immutable snapshot a component subscribes to. */
29
+ export interface FactsSnapshot<F> {
30
+ readonly status: ArborChannelStatus;
31
+ readonly facts?: F;
32
+ readonly error?: string;
33
+ /** The live buffers, keyed by arbor window ref. */
34
+ readonly streams: Readonly<Record<string, ArborWindowStream>>;
35
+ /** A live window wrote something within the activity window. */
36
+ readonly streaming: boolean;
37
+ }
38
+ /** One scope's live stream, usable by any number of components. */
39
+ export declare class FactsChannel<F extends ArborFacts | ArborHostFacts> {
40
+ private readonly url;
41
+ private readonly listeners;
42
+ private snapshot;
43
+ private controller;
44
+ private retry;
45
+ private retryDelay;
46
+ private activity;
47
+ private holds;
48
+ private stopped;
49
+ constructor(url: string);
50
+ /** The current snapshot; the same reference until something changed. */
51
+ readonly getSnapshot: () => FactsSnapshot<F>;
52
+ /** Subscribe one React store listener. */
53
+ readonly subscribe: (listener: () => void) => (() => void);
54
+ /** Take one hold on the stream; the first starts it. */
55
+ retain(): void;
56
+ /** Release one hold; the last stops the stream. */
57
+ release(): void;
58
+ /** Stop this channel for good, whoever still holds it. */
59
+ close(): void;
60
+ /** Open the stream and read it until the page's carrier drops it. */
61
+ private connect;
62
+ /** Read one response's NDJSON body, one frame at a time. */
63
+ private read;
64
+ /** Fold one frame into the snapshot. */
65
+ private handle;
66
+ /** Fold one live window delta into its own buffer. */
67
+ private stream;
68
+ /** Publish one snapshot and wake React. */
69
+ private set;
70
+ }
71
+ /** The channel for one session, created on first use. */
72
+ export declare function channelFor(sessionId: string): FactsChannel<ArborFacts>;
73
+ /** The whole-host channel, created on first use. */
74
+ export declare function hostChannel(): FactsChannel<ArborHostFacts>;
75
+ /** Stop every channel this page holds; called when the plugin unloads. */
76
+ export declare function closeChannels(): void;
package/channel.js ADDED
@@ -0,0 +1,230 @@
1
+ /// <reference lib="dom" />
2
+ /**
3
+ * The browser half of arbor's facts channels.
4
+ *
5
+ * The host serves NDJSON streams on DSH's exact Fetch routes: one per session
6
+ * (`/api/arbor/facts?sessionId=…`) and one for the whole host
7
+ * (`/api/arbor/host`), both registered by `@4fu/dsh-arbor-facts`. This module
8
+ * owns one stream per scope for as long as a component holds it, folds the
9
+ * frames into the snapshot React reads, and reconnects with a bounded backoff
10
+ * when the page's carrier drops one.
11
+ *
12
+ * A frame is either the facts (the initial read and every rebuild) or one live
13
+ * delta from `Arbor.stream(window, …)`. The deltas are folded per window into
14
+ * a short buffer; the facts are kept as they arrived, because they are arbor's
15
+ * own values and nothing here recomputes them.
16
+ */
17
+ /** How much assistant text one window's buffer keeps. */
18
+ const TEXT_LIMIT = 6_000;
19
+ /** How much of a `send` draft one window's buffer keeps. */
20
+ const SEND_LIMIT = 1_500;
21
+ /** How long a frame keeps the "streaming" mark after it arrives. */
22
+ const ACTIVITY_MS = 1_600;
23
+ /** The first reconnect delay, doubled to the cap. */
24
+ const RETRY_BASE_MS = 800;
25
+ /** The longest a reconnect waits. */
26
+ const RETRY_MAX_MS = 5_000;
27
+ /** Read the `content` a `send` call is composing out of its partial JSON. */
28
+ function sendContentOf(raw) {
29
+ // The arguments arrive as the characters the model has written so far, so
30
+ // they are not valid JSON until the call closes. The text field is quoted,
31
+ // so its opening quote is the one thing that is there early enough to read.
32
+ const match = /"content"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(raw);
33
+ if (match === null)
34
+ return undefined;
35
+ const body = match[1] ?? '';
36
+ return body
37
+ .replace(/\\n/g, '\n')
38
+ .replace(/\\t/g, '\t')
39
+ .replace(/\\"/g, '"')
40
+ .replace(/\\\\/g, '\\');
41
+ }
42
+ /** Keep the last `limit` characters of a buffer. */
43
+ function tail(text, limit) {
44
+ return text.length <= limit ? text : text.slice(text.length - limit);
45
+ }
46
+ /** One scope's live stream, usable by any number of components. */
47
+ export class FactsChannel {
48
+ url;
49
+ listeners = new Set();
50
+ snapshot = { status: 'connecting', streams: {}, streaming: false };
51
+ controller;
52
+ retry;
53
+ retryDelay = RETRY_BASE_MS;
54
+ activity;
55
+ holds = 0;
56
+ stopped = true;
57
+ constructor(url) {
58
+ this.url = url;
59
+ }
60
+ /** The current snapshot; the same reference until something changed. */
61
+ getSnapshot = () => this.snapshot;
62
+ /** Subscribe one React store listener. */
63
+ subscribe = (listener) => {
64
+ this.listeners.add(listener);
65
+ return () => { this.listeners.delete(listener); };
66
+ };
67
+ /** Take one hold on the stream; the first starts it. */
68
+ retain() {
69
+ this.holds += 1;
70
+ if (this.holds !== 1)
71
+ return;
72
+ this.stopped = false;
73
+ void this.connect();
74
+ }
75
+ /** Release one hold; the last stops the stream. */
76
+ release() {
77
+ this.holds -= 1;
78
+ if (this.holds > 0)
79
+ return;
80
+ this.close();
81
+ }
82
+ /** Stop this channel for good, whoever still holds it. */
83
+ close() {
84
+ this.stopped = true;
85
+ this.holds = 0;
86
+ this.controller?.abort();
87
+ this.controller = undefined;
88
+ if (this.retry !== undefined)
89
+ clearTimeout(this.retry);
90
+ this.retry = undefined;
91
+ if (this.activity !== undefined)
92
+ clearTimeout(this.activity);
93
+ this.activity = undefined;
94
+ }
95
+ /** Open the stream and read it until the page's carrier drops it. */
96
+ async connect() {
97
+ if (this.stopped)
98
+ return;
99
+ this.set({ ...this.snapshot, status: this.snapshot.facts === undefined ? 'connecting' : 'live' });
100
+ const controller = new AbortController();
101
+ this.controller = controller;
102
+ try {
103
+ const response = await fetch(this.url, {
104
+ signal: controller.signal,
105
+ headers: { accept: 'application/x-ndjson' },
106
+ cache: 'no-store',
107
+ });
108
+ if (!response.ok)
109
+ throw new Error(`facts stream answered ${response.status}`);
110
+ if (response.body === null)
111
+ throw new Error('facts stream has no body');
112
+ this.retryDelay = RETRY_BASE_MS;
113
+ this.set({ ...this.snapshot, status: 'live', error: undefined });
114
+ await this.read(response.body, controller.signal);
115
+ if (controller.signal.aborted)
116
+ return;
117
+ throw new Error('facts stream ended');
118
+ }
119
+ catch (error) {
120
+ if (controller.signal.aborted || this.stopped)
121
+ return;
122
+ this.set({
123
+ ...this.snapshot,
124
+ status: this.snapshot.facts === undefined ? 'error' : 'live',
125
+ error: error instanceof Error ? error.message : String(error),
126
+ });
127
+ this.retry = setTimeout(() => {
128
+ this.retry = undefined;
129
+ void this.connect();
130
+ }, this.retryDelay);
131
+ this.retryDelay = Math.min(this.retryDelay * 2, RETRY_MAX_MS);
132
+ }
133
+ }
134
+ /** Read one response's NDJSON body, one frame at a time. */
135
+ async read(body, signal) {
136
+ const reader = body.getReader();
137
+ const decoder = new TextDecoder();
138
+ let buffer = '';
139
+ for (;;) {
140
+ const { value, done } = await reader.read();
141
+ if (signal.aborted) {
142
+ await reader.cancel().catch(() => undefined);
143
+ return;
144
+ }
145
+ if (done)
146
+ return;
147
+ buffer += decoder.decode(value, { stream: true });
148
+ for (;;) {
149
+ const newline = buffer.indexOf('\n');
150
+ if (newline < 0)
151
+ break;
152
+ const line = buffer.slice(0, newline).trim();
153
+ buffer = buffer.slice(newline + 1);
154
+ if (line !== '')
155
+ this.handle(JSON.parse(line));
156
+ }
157
+ }
158
+ }
159
+ /** Fold one frame into the snapshot. */
160
+ handle(frame) {
161
+ if (frame.type === 'facts') {
162
+ this.set({ ...this.snapshot, status: 'live', facts: frame.facts, error: undefined });
163
+ return;
164
+ }
165
+ if (frame.type === 'error') {
166
+ this.set({ ...this.snapshot, error: frame.message });
167
+ return;
168
+ }
169
+ this.stream(frame.window, frame.event);
170
+ }
171
+ /** Fold one live window delta into its own buffer. */
172
+ stream(window, event) {
173
+ const before = this.snapshot.streams[window] ?? { text: '', send: '', streaming: false };
174
+ let next = before;
175
+ if (event.kind === 'text_delta') {
176
+ next = { ...before, text: tail(before.text + event.delta, TEXT_LIMIT) };
177
+ }
178
+ else {
179
+ const content = sendContentOf(event.args);
180
+ if (event.name === 'send' && content !== undefined) {
181
+ next = { ...before, send: tail(content, SEND_LIMIT) };
182
+ }
183
+ }
184
+ const streams = { ...this.snapshot.streams, [window]: { ...next, streaming: true } };
185
+ this.set({ ...this.snapshot, streams, streaming: true });
186
+ if (this.activity !== undefined)
187
+ clearTimeout(this.activity);
188
+ this.activity = setTimeout(() => {
189
+ this.activity = undefined;
190
+ const cleared = {};
191
+ for (const [ref, view] of Object.entries(this.snapshot.streams))
192
+ cleared[ref] = { ...view, streaming: false };
193
+ this.set({ ...this.snapshot, streams: cleared, streaming: false });
194
+ }, ACTIVITY_MS);
195
+ }
196
+ /** Publish one snapshot and wake React. */
197
+ set(snapshot) {
198
+ this.snapshot = snapshot;
199
+ for (const listener of this.listeners)
200
+ listener();
201
+ }
202
+ }
203
+ /** The channels one page holds, by scope, while a component holds them. */
204
+ const channels = new Map();
205
+ /** The channel for one session, created on first use. */
206
+ export function channelFor(sessionId) {
207
+ const key = `session:${sessionId}`;
208
+ let channel = channels.get(key);
209
+ if (channel === undefined) {
210
+ channel = new FactsChannel(`/api/arbor/facts?sessionId=${encodeURIComponent(sessionId)}`);
211
+ channels.set(key, channel);
212
+ }
213
+ return channel;
214
+ }
215
+ /** The whole-host channel, created on first use. */
216
+ export function hostChannel() {
217
+ const key = 'host';
218
+ let channel = channels.get(key);
219
+ if (channel === undefined) {
220
+ channel = new FactsChannel('/api/arbor/host');
221
+ channels.set(key, channel);
222
+ }
223
+ return channel;
224
+ }
225
+ /** Stop every channel this page holds; called when the plugin unloads. */
226
+ export function closeChannels() {
227
+ for (const channel of channels.values())
228
+ channel.close();
229
+ channels.clear();
230
+ }