dsh-boost 0.2.0 → 0.2.2

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/README.en.md CHANGED
@@ -12,7 +12,7 @@ read-only substitution**.
12
12
  ## What it does
13
13
 
14
14
  DSH replays the whole history on every model request. Across the 300 longest sessions measured
15
- locally (`npm run --silent stats` — without `--silent`, npm prints its `> dsh-boost@0.1.3 stats`
15
+ locally (`npm run --silent stats` — without `--silent`, npm prints its `> dsh-boost@0.2.1 stats`
16
16
  banner to stdout, so use `--silent` or `node scripts/session-stats.mjs` for machine-readable
17
17
  output; snapshot at `2026-11-19T03:13:21Z`): 54,141 steps and 54,088 requests,
18
18
  10,575,904,022 raw tokens in total. The mean is 195,340 tokens per step and 195,531 per request
@@ -85,32 +85,52 @@ denominator statistic that a later version must add.
85
85
  directory:
86
86
 
87
87
  ```bash
88
- # install from the registry: npmjs has latest = 0.1.3 (this repository's
88
+ # install from the registry: npmjs has latest = 0.2.0 (this repository's
89
89
  # .npmrc and lockfile are pinned to npmjs too — see below)
90
- dsh plugin --profile <name> add dsh-boost@^0.1.3 --registry=https://registry.npmjs.org/
90
+ dsh plugin --profile <name> add dsh-boost@^0.2.0 --registry=https://registry.npmjs.org/
91
91
 
92
92
  # or from a local checkout (build first; dist/ is not committed)
93
93
  npm run build
94
94
  dsh plugin --profile <name> add /absolute/path/to/dsh-boost
95
95
  ```
96
96
 
97
- For the web profile: `dsh plugin --profile web add dsh-boost@^0.1.3 --registry=https://registry.npmjs.org/`.
97
+ For the web profile: `dsh plugin --profile web add dsh-boost@^0.2.0 --registry=https://registry.npmjs.org/`.
98
98
  `dsh plugin` forwards the operation to pnpm, so pnpm must be on `PATH`.
99
99
 
100
- > **Both registries now carry 0.1.3, so `^0.1.3` is a safe pin.**
101
- > `registry.npmjs.org` and `registry.npmmirror.com` each have five version records: `0.1.3` (the
102
- > current `latest` on both), `0.1.2`, `0.1.1`, `0.1.0`, and `0.0.0-stage`, the placeholder npm
100
+ > **`^0.2.0` is the current safe pin.** `registry.npmjs.org` has `latest` at `0.2.0`, with
101
+ > `0.1.4`, `0.1.3`, `0.1.2`, `0.1.1`, `0.1.0` behind it, plus `0.0.0-stage`, the placeholder npm
103
102
  > creates on a package's first publish — **do not install `0.0.0-stage`**; it is not a usable
104
- > build. 0.1.3 stops a substitution from committing on output the model cannot see (an outer
105
- > shaper rewrote the content) and reports the saving as a range (adding `avoided_total_tokens`),
106
- > plus three host-capability degradation codes and `status.hasSpill`; 0.1.2 carries the
107
- > scope-overwrite fix: corrupt JSON (including a non-object or an array) and an unrecognizable
108
- > version are no longer silently overwritten with the default document. Use `dsh-boost@^0.1.3`
109
- > (or `@latest`) — `^0.1.3` means "at least 0.1.3's fixes". This repository's `.npmrc` and
110
- > lockfile are pinned to npmjs, but **your machine's global npm config** may still point at a
111
- > mirror that has not synced 0.1.3: that is local configuration, not this repository's state.
112
- > Pass `--registry=https://registry.npmjs.org/` explicitly when the registry matters; against a
113
- > lagging mirror, `@^0.1.3` fails to resolve until the sync lands.
103
+ > build. `0.2.0` adds the settings page (`dsh.client`, the `./client` export, the
104
+ > `/dsh-boost/api` routes, and a `lib/client.js` shipped in the tarball) and Chinese/English
105
+ > localisation; `0.1.4` and earlier **have no settings page**, and `^0.1.4` does not resolve to
106
+ > `0.2.0` (`^` does not cross a major version), so upgrading from `0.1.x` means writing
107
+ > `@^0.2.0` explicitly. This repository's `.npmrc` and lockfile are pinned to npmjs, but **your
108
+ > machine's global npm config** may still point at a mirror that has not synced `0.2.0`: that is
109
+ > local configuration, not this repository's state. Pass `--registry=https://registry.npmjs.org/`
110
+ > explicitly when the registry matters; against a lagging mirror `@^0.2.0` fails to resolve until
111
+ > it catches up.
112
+
113
+ ## Settings page
114
+
115
+ Once installed and enabled in a profile, the host's settings panel gains a **"Token efficiency"**
116
+ section (「Token 效率」 in Chinese). It does three things:
117
+
118
+ - **Shows state**: every degradation code with what to do about it, the substitution saving as a
119
+ lower and upper bound, projection gross and net, retrieval count, receipt counts, the fixed
120
+ per-request overhead, and the **effective** configuration (read-only — editing it means editing
121
+ the profile's `cordis.patch.yml`).
122
+ - **Edits scope**: `mode` (all workspaces or selected ones), `workspaceIds`, `shadow`,
123
+ `projection`. It writes `<dshHome>/boost/scope.json` through the **same** CAS as the `boost`
124
+ tool's `scope-set`, so neither overwrites the other; if someone else got there first the page
125
+ reports `ERR_SCOPE_REVISION_CONFLICT` and keeps your draft, leaving the decision to you.
126
+ - **Warns about the two dangerous switches**: projection going to `on` shows the spill
127
+ precondition; turning shadow mode off shows the `content[].thinking` 400 to watch for. Both
128
+ give a rollback and both are **advisory, never gates** — whether this route is an
129
+ Anthropic-compatible thinking mode cannot be determined on this machine, and a gate would only
130
+ create the illusion of having checked.
131
+
132
+ When the page cannot reach its data (no `webServer`, a reverse proxy that drops `Host`) it shows a
133
+ stable code instead of an empty table; `curl <host>/dsh-boost/api/state` returns the same JSON.
114
134
 
115
135
  The package is ESM (`"type": "module"`) and the `.` entry of `exports` also maps `require` /
116
136
  `default`: on Node >= 24.9, `require('dsh-boost')` loads the very same code as `import`. Nothing
@@ -150,7 +170,10 @@ the clean default (`ENOENT` carries no degradation code, `src/scope/store.ts`);
150
170
  with the host capabilities in place, `degraded` is simply an empty array. On the `status` read
151
171
  path,
152
172
  `ERR_SCOPE_READ_FAILED` means the file **exists but cannot be read** (permissions, I/O, a
153
- directory in its place, …) — not a normal first run; fix it first. The first successful `scope-set` creates the file.
173
+ directory in its place, …) — not a normal first run; fix it first. A failed *write* is a different
174
+ code, `ERR_SCOPE_WRITE_FAILED` (disk full, directory permissions): the page then asks you to retry
175
+ unchanged rather than re-read, because the baseline is still valid and a re-read would throw away
176
+ your draft. The first successful `scope-set` creates the file.
154
177
 
155
178
  Then list the workspace to expose:
156
179
 
@@ -546,7 +569,7 @@ to load. `llm` is soft (only the selector uses it); when absent the selector fal
546
569
  | (spill backend present but failing) | — | Every `saveText` is rejected: the receipt records `projection-skipped:spill-failed` and `status.degraded` reports **`ERR_HOST_SPILL_FAILING`**. This is a **third** state — neither "no backend" nor "no footer renderer" — and telling an operator to restore the spill package would send them after a package that is installed and failing |
547
570
  | `@deepseek-ai/dsh-token-meter/estimate` | soft (dynamic import) | Fixed overhead cannot be measured, so `fixedOverheadTokens` is `'unknown'`; `status.degraded` reports `ERR_HOST_NO_ESTIMATOR` |
548
571
  | `win32` platform | runtime `isPosixOnly()` check | Substitution is refused, projection still works; `status.degraded` reports `ERR_HOST_PLATFORM_UNSUPPORTED` |
549
- | `locale` | soft (`ctx.get('locale')`) | The settings page **does not follow the host language** and stays Chinese, with one `console.warn` saying so; projection, substitution and the `boost` tool are unaffected |
572
+ | `locale` | soft (`ctx.get('locale')`) | The settings page **follows the host language** (Chinese and English, the nav label included); without this service it falls back to Chinese with one `console.warn`, and the page still works; projection, substitution and the `boost` tool are unaffected |
550
573
  | `webServer` | soft (dynamic `ctx.inject(['webServer'], …)`) | **The settings page has no data**: the route is not mounted and the page shows `ERR_CLIENT_NETWORK` with a pointer to the host log. Projection, substitution and the `boost` tool are **unaffected** — this is the only dependency whose absence costs only the page. Once mounted, the trusted `Host` list comes from `webStartup.trustedHosts` (loopback-only when unreadable), so a reverse proxy that drops `Host` is stopped by `ERR_HTTP_FORBIDDEN` |
551
574
  | Host version line | startup check of the `@deepseek-ai/dsh-app-boot` version | A version **outside the `engines.dsh` range** (`>=0.2.2-rc.4 <0.2.3-0`) logs `ERR_HOST_VERSION_MISMATCH` and loads anyway — advisory only, not a `status.degraded` code. A version inside the range but not the verified `0.2.2-rc.4` (such as `rc.5` / `0.2.2`) logs an info line, no code; an undeterminable version or an unparseable range also logs info only |
552
575
  | Receipt shard readability | `boost status` full scan (not a dependency) | When at least one receipt shard cannot be read (EACCES, a directory named `x.jsonl`, …), `status.degraded` carries `ERR_RECEIPTS_UNREADABLE`; `status` stays a **total over the healthy shards** — they are still counted — so the figures may be incomplete. Check permissions and stray entries in `<dshHome>/boost/receipts/`, fix, and re-run `status`, comparing counts |
@@ -554,6 +577,9 @@ to load. `llm` is soft (only the selector uses it); when absent the selector fal
554
577
  | Prompt assembly waterfall | outgoing-request probe (not a dependency) | When the host's `complete: true` prompt section replaces the assembled system prompt after the waterfall and the protocol section never reaches the request, `status.degraded` carries `ERR_HOST_COMPLETE_SECTION`; substitution and projection fail closed for the affected requests (the plugin stays inert although the workspace is visible). Find the complete section overriding the waterfall (usually another plugin's) and remove it, or accept the inaction on those requests |
555
578
 
556
579
  `ERR_HOST_NO_STEP_WHEN` no longer exists: step-level `when` has been part of
580
+ `ToolRegistrationOptions` since the oldest host line this package declares, so the plugin no
581
+ longer probes it and registers unconditionally.
582
+
557
583
  The settings page's data route has codes of its own, and they are **not** members of
558
584
  `status.degraded` — every failure returns one in a JSON body, and the page decides what to say from it:
559
585
 
@@ -571,9 +597,6 @@ The settings page's data route has codes of its own, and they are **not** member
571
597
  `ERR_BOOST_HTTP_MOUNT_FAILED` goes to the log only: mounting the route threw (`ctx.inject` missing or
572
598
  refused), so the page has no data source. It is not `ERR_BOOST_PARTIAL_MOUNT` — that one is about hooks.
573
599
 
574
- `ToolRegistrationOptions` since the oldest host line this package declares, so the plugin no
575
- longer probes it and registers unconditionally.
576
-
577
600
  Registration codes come in two kinds. A non-duplicate throw while registering the protocol
578
601
  section logs `ERR_BOOST_SECTION_REGISTER_FAILED` (log only). The three event hooks
579
602
  (`tools/post-execute`, `llm/stream`, `tools/execute`) are then mounted **independently**: a
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  ## 它解决什么
10
10
 
11
11
  DSH 每次模型请求都会回放全部历史。本机 300 个最长会话的实测聚合(`npm run --silent stats`——不带
12
- `--silent` 时 npm 会把 `> dsh-boost@0.1.3 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
12
+ `--silent` 时 npm 会把 `> dsh-boost@0.2.1 stats` 横幅打进 stdout,机器解析请用 `--silent` 或直接
13
13
  `node scripts/session-stats.mjs`;快照时刻 `2026-11-19T03:13:21Z`):54,141 步、54,088 个请求,合计 10,575,904,022 raw token。按步均值
14
14
  195,340 token,按请求均值 195,531、中位 187,681;97.01% 的输入是缓存读。工具回执是体积主体
15
15
  (bash 61.75%、read 22.13%、ssh 10.01%),而下一步真正会用到的部分通常远小于回执本身。
@@ -64,29 +64,44 @@ v1 的**事前估算**区间是 **3.5%(下界)– 10.0%(理想上界)**
64
64
  `dsh plugin` 要求指定 profile,剩下的参数原样转发给该 profile 目录里的 pnpm:
65
65
 
66
66
  ```bash
67
- # 从 registry 安装:npmjs 上的 latest 是 0.1.3(本仓库 .npmrc 与 lockfile
67
+ # 从 registry 安装:npmjs 上的 latest 是 0.2.1(本仓库 .npmrc 与 lockfile
68
68
  # 也已钉在 npmjs,见下)
69
- dsh plugin --profile <name> add dsh-boost@^0.1.3 --registry=https://registry.npmjs.org/
69
+ dsh plugin --profile <name> add dsh-boost@^0.2.1 --registry=https://registry.npmjs.org/
70
70
 
71
71
  # 或从本地 checkout 安装(先构建;dist/ 不入库)
72
72
  npm run build
73
73
  dsh plugin --profile <name> add /absolute/path/to/dsh-boost
74
74
  ```
75
75
 
76
- 例如 web profile:`dsh plugin --profile web add dsh-boost@^0.1.3 --registry=https://registry.npmjs.org/`。
76
+ 例如 web profile:`dsh plugin --profile web add dsh-boost@^0.2.1 --registry=https://registry.npmjs.org/`。
77
77
  `dsh plugin` 把操作转发给 pnpm,所以 pnpm 必须在 PATH 上。
78
78
 
79
- > **两个 registry 现在都到 0.1.3,`^0.1.3` 是安全的钉法。** `registry.npmjs.org` 与
80
- > `registry.npmmirror.com` 各有五条版本记录:`0.1.3`(两边都是当前 `latest`)、`0.1.2`、
81
- > `0.1.1`、`0.1.0`,以及首次发布时 npm 自动创建的占位版本 `0.0.0-stage`——**不要安装
82
- > `0.0.0-stage`**,它不是可用构建。0.1.3 修掉了「模型看到的正文被外层改写后仍按原始回执
83
- > 提交替换」的问题,并把节省改报为上下界区间(新增 `avoided_total_tokens`),另加三个宿主
84
- > 能力降级码与 `status.hasSpill`;0.1.2 修掉了 scope 文件被静默覆盖的问题:坏 JSON(含非对象
85
- > 或数组)与无法识别的版本不再被默认文档覆盖。请用 `dsh-boost@^0.1.3`(或 `@latest`)——
86
- > `^0.1.3` 表达的是「至少含 0.1.3 的修复」。本仓库已把 `.npmrc`
87
- > 与 lockfile 钉在 npmjs,但**你机器上的全局 npm 配置**可能仍指向一个尚未同步 0.1.3 的镜像:
88
- > 那是本机配置,不是本仓库的状态。在意 registry 时显式传
89
- > `--registry=https://registry.npmjs.org/`;镜像滞后时,`@^0.1.3` 会在同步前解析失败。
79
+ > **`^0.2.1` 是当前的安全钉法。** `registry.npmjs.org` 上 `latest` 是 `0.2.1`,历史版本依次是
80
+ > `0.1.4`、`0.1.3`、`0.1.2`、`0.1.1`、`0.1.0`,以及首次发布时 npm 自动创建的占位版本
81
+ > `0.0.0-stage`——**不要安装 `0.0.0-stage`**,它不是可用构建。`0.2.0` 新增了设置页(`dsh.client` 与 `./client` 出口、`/dsh-boost/api` 路由、随包发布的
82
+ > `lib/client.js`)与中英双语,`0.2.1` 修了页面上三处会读到错误数值或错误提示的缺陷;`0.1.4` 及更早**没有设置页**,`^0.1.4` 也不会解析到 `0.2.x`(`^` 不跨大版本),所以从
83
+ > `0.1.x` 升上来要显式写 `@^0.2.1`。本仓库已把 `.npmrc` 与 lockfile 钉在 npmjs,但**你机器上
84
+ > 的全局 npm 配置**可能仍指向一个尚未同步 `0.2.1` 的镜像:那是本机配置,不是本仓库的状态。
85
+ > 在意 registry 时显式传 `--registry=https://registry.npmjs.org/`;镜像滞后时 `@^0.2.1` 会在
86
+ > 同步前解析失败。
87
+
88
+ ## 设置页
89
+
90
+ 装好并在 profile 里启用之后,宿主设置面板里会多出一节 **「Token 效率」**(英文界面是
91
+ “Token efficiency”)。它做三件事:
92
+
93
+ - **看状态**:降级码及每个码该怎么办、替换节省的上下界、投影毛额与净额、取回次数、各类收据
94
+ 计数、常驻开销,以及当前**生效**配置(只读——改配置要编辑 profile 的 `cordis.patch.yml`)。
95
+ - **改作用域**:`mode`(全部工作区 / 仅选中的工作区)、`workspaceIds`、`shadow`、`projection`
96
+ 四个字段。写的是 `<dshHome>/boost/scope.json`,与 `boost` 工具的 `scope-set` 走**同一个**
97
+ CAS,所以两边改都不会互相覆盖;别人先改了,页面会给出 `ERR_SCOPE_REVISION_CONFLICT` 并保留
98
+ 你的草稿,由你决定要不要按磁盘上的文档重来。
99
+ - **提示危险开关**:投影切到 `on` 时提示 spill 前置条件;关掉影子模式时提示盯一次含
100
+ `content[].thinking` 的 400。两处都给回滚办法,都**只提示不做硬门**——当前路由是不是
101
+ Anthropic 兼容的 thinking 模式在这台机器上查不出来,硬门只会给出“已检查过”的错觉。
102
+
103
+ 页面读不到数据(宿主没有 `webServer`、反向代理没透传 `Host`)时会显示稳定码而不是空白表格;
104
+ `curl <host>/dsh-boost/api/state` 能看到同一份 JSON。
90
105
 
91
106
  包是 ESM(`"type": "module"`),`exports` 的 `.` 条目同时映射 `require` / `default`:Node ≥ 24.9
92
107
  下 `require('dsh-boost')` 与 `import` 加载同一份代码,装好的包里**不做任何构建**(`files` 只带
@@ -120,7 +135,8 @@ bundle,patch 的 `insert` 行落在 profile root 上。**装完必须重启 DS
120
135
  缺失而出现 `ERR_SCOPE_READ_FAILED`:缺失是干净的默认值(`ENOENT` 不带降级码,
121
136
  `src/scope/store.ts`);全新根目录且宿主能力齐全时,`degraded` 就是空数组。在 `status` 的
122
137
  读取路径上,`ERR_SCOPE_READ_FAILED` 只表示文件**存在但读不出来**(权限、I/O、路径是目录
123
- 等)——那不是正常的首次状态,要先修掉。
138
+ 等)——那不是正常的首次状态,要先修掉。写不进去是另一个码 `ERR_SCOPE_WRITE_FAILED`(磁盘满、
139
+ 目录权限),页面拿到它会让你原样重试而不是重读——基线还在,重读会丢掉草稿。
124
140
  第一次成功的 `scope-set` 会创建这个文件。
125
141
 
126
142
  然后列出要暴露的工作区:
@@ -456,7 +472,7 @@ horizon 重放,并计入 `projection_horizon_reestimated`;`projection_horizo
456
472
  | `@deepseek-ai/dsh-spill-policy/notice` | 软(动态 import) | spill 后端在,但页脚渲染器 `formatSpillNotice` 加载不到/不存在:apply 模式无法拼页脚,逐条跳过(收据 `projection-skipped:no-footer`;页脚渲染时抛错则记 `projection-skipped:footer-failed`),`status.degraded` 带 `ERR_HOST_NO_SPILL_NOTICE`。这与「没有 spill 后端」的 `ERR_HOST_NO_SPILL` 是两件事 |
457
473
  | (spill 后端存在但写失败) | — | 每次 `saveText` 被拒:收据 `projection-skipped:spill-failed`,`status.degraded` 带 **`ERR_HOST_SPILL_FAILING`**。这是**第三种**状态,既不是「没有后端」也不是「没有页脚渲染器」——让操作者去「恢复 spill 包」会把一个已装好却报错的包当成没装 |
458
474
  | `@deepseek-ai/dsh-token-meter/estimate` | 软(动态 import) | 固定开销无法测量,`fixedOverheadTokens` 为 `'unknown'`;`status.degraded` 带 `ERR_HOST_NO_ESTIMATOR` |
459
- | `locale` | 软(`ctx.get('locale')`) | 设置页**不跟随宿主语言**,固定用中文,`console.warn` 说明一次;投影、替换与 `boost` 工具不受影响 |
475
+ | `locale` | 软(`ctx.get('locale')`) | 设置页**跟随宿主语言**(中英双语,导航项标签一起换);缺这个服务时回落中文并 `console.warn` 说明一次,页面照常可用;投影、替换与 `boost` 工具不受影响 |
460
476
  | `webServer` | 软(动态注入 `ctx.inject(['webServer'], …)`) | **设置页读不到数据**:路由没挂上,页面显示 `ERR_CLIENT_NETWORK` 并提示去看宿主日志。投影、替换与 `boost` 工具**完全不受影响**——这是唯一一个缺失只影响页面的依赖。挂上之后 `Host` 的受信名单来自 `webStartup.trustedHosts`(读不到就只信 loopback),所以反向代理没透传 `Host` 时页面会被 `ERR_HTTP_FORBIDDEN` 挡住 |
461
477
  | `win32` 平台 | 运行时检查 `isPosixOnly()` | 拒绝替换,投影照常;`status.degraded` 带 `ERR_HOST_PLATFORM_UNSUPPORTED` |
462
478
  | 宿主版本线 | 启动时读 `@deepseek-ai/dsh-app-boot` 的版本 | 版本**落在 `engines.dsh` 区间外**(`>=0.2.2-rc.4 <0.2.3-0`)时日志警告 `ERR_HOST_VERSION_MISMATCH`,插件照常加载(advisory,不是 `status.degraded` 码);区间内但不是验证过的 `0.2.2-rc.4`(如 `rc.5` / `0.2.2`)只记 info、不发码;版本读不到或区间无法解析时也只记 info |
@@ -15,6 +15,7 @@
15
15
  * name outside the injection list.
16
16
  */
17
17
  import { HTTP_API_PREFIX } from '../shared/api-prefix.js';
18
+ import { ERR_BOOST_HTTP_MOUNT_FAILED } from '../tools/boost.js';
18
19
  import { createStateHandler } from './state.js';
19
20
  /** Where the deployment declared its trusted hosts, across host generations. */
20
21
  function resolveTrustedHosts(ctx) {
@@ -40,7 +41,8 @@ function resolveTrustedHosts(ctx) {
40
41
  */
41
42
  export function registerHttpApi(ctx, deps, warn) {
42
43
  if (typeof ctx.inject !== 'function') {
43
- warn('[boost] webServer unavailable (no dynamic injection); settings page has no data route');
44
+ warn(`${ERR_BOOST_HTTP_MOUNT_FAILED}: no dynamic injection (\`ctx.inject\` is missing); ` +
45
+ 'settings page has no data route');
44
46
  return () => { };
45
47
  }
46
48
  let dispose;
@@ -48,7 +50,7 @@ export function registerHttpApi(ctx, deps, warn) {
48
50
  ctx.inject(['webServer'], (context) => {
49
51
  const webServer = context.webServer;
50
52
  if (webServer === undefined) {
51
- warn('[boost] webServer unavailable; settings page has no data route');
53
+ warn(`${ERR_BOOST_HTTP_MOUNT_FAILED}: webServer resolved to undefined; settings page has no data route`);
52
54
  return;
53
55
  }
54
56
  const handler = createStateHandler(deps, { trustedHosts: () => resolveTrustedHosts(ctx) });
@@ -59,7 +61,7 @@ export function registerHttpApi(ctx, deps, warn) {
59
61
  // The mount must never cost the plugin: a composition without a web server
60
62
  // is the normal headless case, not a fault.
61
63
  const message = error instanceof Error ? error.message : String(error);
62
- warn(`[boost] settings page has no data route: ${message}`);
64
+ warn(`${ERR_BOOST_HTTP_MOUNT_FAILED}: ${message}`);
63
65
  }
64
66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AAC;YACD,MAAM,OAAO,GAAG,kBAAkB,CAAC,IAAI,EAAE,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,CAAC,CAAA;YAC1F,OAAO,GAAG,SAAS,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC,CAAA;QAClF,CAAC,CAAC,CAAA;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,2EAA2E;QAC3E,4CAA4C;QAC5C,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QACtE,IAAI,CAAC,4CAA4C,OAAO,EAAE,CAAC,CAAA;IAC7D,CAAC;IACD,OAAO,GAAG,EAAE;QACV,OAAO,EAAE,EAAE,CAAA;QACX,OAAO,GAAG,SAAS,CAAA;IACrB,CAAC,CAAA;AACH,CAAC","sourcesContent":["/**\n * Mounts the plugin's HTTP surface onto the host's web server.\n *\n * The mount is a CHILD FIBER, not a load-time probe: `webServer` is provided by\n * the web composition and may become active after this plugin does, so\n * `ctx.inject(['webServer'], …)` runs the callback when (and if) the service\n * exists and unloads the routes when it goes away. A load-time `ctx.get` would\n * see `undefined` in a headless deployment and never mount, which is correct,\n * but it would also never mount in a web deployment whose siblings start in a\n * different order — the silent-disable trap this repo has hit before.\n *\n * `ctx.inject` is an AND gate over its list, so `webServer` is the only key:\n * every other service this surface reads (`webStartup` for the trusted hosts)\n * goes through the un-gated `ctx.get`, because a strict proxy throws on any\n * name outside the injection list.\n */\nimport { HTTP_API_PREFIX } from '../shared/api-prefix.js'\nimport { createStateHandler, type StateDeps } from './state.js'\n\n/** The one service this plugin needs from the host's web composition. */\ninterface WebServerLike {\n register(route: { kind: 'exact' | 'prefix'; path: string; handler: unknown }): () => void\n}\n\n/** The slice of the plugin context this module uses. */\nexport interface HttpContextLike {\n inject?: (names: string[], callback: (context: { webServer?: WebServerLike }) => void) => unknown\n get?: (name: string) => unknown\n}\n\n/** Where the deployment declared its trusted hosts, across host generations. */\nfunction resolveTrustedHosts(ctx: HttpContextLike): readonly string[] {\n for (const service of ['webStartup', 'webRuntime']) {\n try {\n const value = (ctx.get?.(service) as { trustedHosts?: unknown } | undefined)?.trustedHosts\n if (Array.isArray(value)) return value.filter((entry): entry is string => typeof entry === 'string')\n } catch {\n // A service that throws on read is not a reason to skip the fence: an\n // empty list falls back to loopback-only, which is stricter, not looser.\n }\n }\n return []\n}\n\n/**\n * Registers the route and returns its disposer.\n *\n * A host without dynamic injection gets a warning and no surface — the plugin's\n * other behaviour is untouched, which is the whole point of the mount being\n * optional.\n */\nexport function registerHttpApi(\n ctx: HttpContextLike,\n deps: StateDeps,\n warn: (message: string) => void,\n): () => void {\n if (typeof ctx.inject !== 'function') {\n warn('[boost] webServer unavailable (no dynamic injection); settings page has no data route')\n return () => {}\n }\n let dispose: (() => void) | undefined\n try {\n ctx.inject(['webServer'], (context) => {\n const webServer = context.webServer\n if (webServer === undefined) {\n warn('[boost] webServer unavailable; settings page has no data route')\n return\n }\n const handler = createStateHandler(deps, { trustedHosts: () => resolveTrustedHosts(ctx) })\n dispose = webServer.register({ kind: 'prefix', path: HTTP_API_PREFIX, handler })\n })\n } catch (error) {\n // The mount must never cost the plugin: a composition without a web server\n // is the normal headless case, not a fault.\n const message = error instanceof Error ? error.message : String(error)\n warn(`[boost] settings page has no data route: ${message}`)\n }\n return () => {\n dispose?.()\n dispose = undefined\n }\n}\n"]}
1
+ {"version":3,"file":"mount.js","sourceRoot":"","sources":["../../src/http/mount.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAA;AAC/D,OAAO,EAAE,kBAAkB,E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Q,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,eAAe,EAAE,OAAO,EAAE,CAAC,CAAA;QAClF,CAAC,CAAC,CAAA;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,2EAA2E;QAC3E,4CAA4C;QAC5C,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;QACtE,IAAI,CAAC,GAAG,2BAA2B,KAAK,OAAO,EAAE,CAAC,CAAA;IACpD,CAAC;IACD,OAAO,GAAG,EAAE;QACV,OAAO,EAAE,EAAE,CAAA;QACX,OAAO,GAAG,SAAS,CAAA;IACrB,CAAC,CAAA;AACH,CAAC","sourcesContent":["/**\n * Mounts the plugin's HTTP surface onto the host's web server.\n *\n * The mount is a CHILD FIBER, not a load-time probe: `webServer` is provided by\n * the web composition and may become active after this plugin does, so\n * `ctx.inject(['webServer'], …)` runs the callback when (and if) the service\n * exists and unloads the routes when it goes away. A load-time `ctx.get` would\n * see `undefined` in a headless deployment and never mount, which is correct,\n * but it would also never mount in a web deployment whose siblings start in a\n * different order — the silent-disable trap this repo has hit before.\n *\n * `ctx.inject` is an AND gate over its list, so `webServer` is the only key:\n * every other service this surface reads (`webStartup` for the trusted hosts)\n * goes through the un-gated `ctx.get`, because a strict proxy throws on any\n * name outside the injection list.\n */\nimport { HTTP_API_PREFIX } from '../shared/api-prefix.js'\nimport { ERR_BOOST_HTTP_MOUNT_FAILED } from '../tools/boost.js'\nimport { createStateHandler, type StateDeps } from './state.js'\n\n/** The one service this plugin needs from the host's web composition. */\ninterface WebServerLike {\n register(route: { kind: 'exact' | 'prefix'; path: string; handler: unknown }): () => void\n}\n\n/** The slice of the plugin context this module uses. */\nexport interface HttpContextLike {\n inject?: (names: string[], callback: (context: { webServer?: WebServerLike }) => void) => unknown\n get?: (name: string) => unknown\n}\n\n/** Where the deployment declared its trusted hosts, across host generations. */\nfunction resolveTrustedHosts(ctx: HttpContextLike): readonly string[] {\n for (const service of ['webStartup', 'webRuntime']) {\n try {\n const value = (ctx.get?.(service) as { trustedHosts?: unknown } | undefined)?.trustedHosts\n if (Array.isArray(value)) return value.filter((entry): entry is string => typeof entry === 'string')\n } catch {\n // A service that throws on read is not a reason to skip the fence: an\n // empty list falls back to loopback-only, which is stricter, not looser.\n }\n }\n return []\n}\n\n/**\n * Registers the route and returns its disposer.\n *\n * A host without dynamic injection gets a warning and no surface — the plugin's\n * other behaviour is untouched, which is the whole point of the mount being\n * optional.\n */\nexport function registerHttpApi(\n ctx: HttpContextLike,\n deps: StateDeps,\n warn: (message: string) => void,\n): () => void {\n if (typeof ctx.inject !== 'function') {\n warn(\n `${ERR_BOOST_HTTP_MOUNT_FAILED}: no dynamic injection (\\`ctx.inject\\` is missing); ` +\n 'settings page has no data route',\n )\n return () => {}\n }\n let dispose: (() => void) | undefined\n try {\n ctx.inject(['webServer'], (context) => {\n const webServer = context.webServer\n if (webServer === undefined) {\n warn(`${ERR_BOOST_HTTP_MOUNT_FAILED}: webServer resolved to undefined; settings page has no data route`)\n return\n }\n const handler = createStateHandler(deps, { trustedHosts: () => resolveTrustedHosts(ctx) })\n dispose = webServer.register({ kind: 'prefix', path: HTTP_API_PREFIX, handler })\n })\n } catch (error) {\n // The mount must never cost the plugin: a composition without a web server\n // is the normal headless case, not a fault.\n const message = error instanceof Error ? error.message : String(error)\n warn(`${ERR_BOOST_HTTP_MOUNT_FAILED}: ${message}`)\n }\n return () => {\n dispose?.()\n dispose = undefined\n }\n}\n"]}
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import { HTTP_API_PREFIX } from '../shared/api-prefix.js';
20
20
  import { ERR_BOOST_INTERNAL, ERR_BOOST_INVALID_ARGS, ERR_BOOST_INVALID_BODY } from '../tools/boost.js';
21
+ import { ERR_SCOPE_WRITE_FAILED } from '../scope/doc.js';
21
22
  import { isTrustedWebRequest } from './fence.js';
22
23
  /** The route prefix this plugin owns: absolute, no trailing slash. */
23
24
  export { HTTP_API_PREFIX } from '../shared/api-prefix.js';
@@ -122,6 +123,10 @@ function writeStatusFor(code) {
122
123
  return 400;
123
124
  if (code === ERR_BOOST_INTERNAL)
124
125
  return 500;
126
+ // A failed write is a storage fault, not a disagreement with the document:
127
+ // re-reading cannot help, and the draft is still good.
128
+ if (code === ERR_SCOPE_WRITE_FAILED)
129
+ return 500;
125
130
  // Every remaining scope code means "this write cannot be applied to the
126
131
  // document as it stands": stale revision, held lock, unreadable or
127
132
  // unrecognised file. All of them are resolved by looking at the document.
@@ -147,7 +152,9 @@ export function createStateHandler(deps, options = {}) {
147
152
  }
148
153
  const path = subPath(req.url);
149
154
  if (isWrite) {
150
- if (method !== 'POST') {
155
+ // A write aimed at a read-only path is a method error, not a missing
156
+ // route: the path exists, the verb does not belong there.
157
+ if (path === '/state' || method !== 'POST') {
151
158
  writeJson(res, 405, { error: ERR_HTTP_METHOD });
152
159
  return;
153
160
  }
@@ -1 +1 @@
1
- {"version":3,"file":"state.js","sourceRoot":"","sources":["../../src/http/state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAA;AACtG,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAIhD,sEAAsE;AACtE,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAEzD,iEAAiE;AACjE,MAAM,CAAC,MAAM,eAAe,GAAG,iBAAiB,CAAA;AAChD,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAA;AACtD,MAAM,CAAC,MAAM,kBAAkB,GAAG,oBAAoB,CAAA;AACtD,MAAM,CAAC,MAAM,+BAA+B,GAAG,iCAAiC,CAAA;AAChF,MAAM,CAAC,MAA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AAC;QACP,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC,CAAA;QACjD,OAAM;IACR,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QACf,SAAS,CAAC,GAAG,EAAE,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;QACnE,OAAM;IACR,CAAC;IACD,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;AACtD,CAAC","sourcesContent":["/**\n * The plugin's read-only HTTP surface for the settings page.\n *\n * WHY A ROUTE OF OUR OWN: the host's `webServer` serves the SPA and knows\n * nothing about a plugin's state, and `ctx.settings` only describes plugins\n * that declare a `Config` schema — this one deliberately does not (spec #2:\n * a strict schema turns `resolveConfig`'s clamp-and-warn into a load-time hard\n * failure). So the page reads through one prefix this plugin owns.\n *\n * NO AUTHENTICATION IS INHERITED. `webServer.register` performs none and\n * claims no path namespace, so `isTrustedWebRequest` is the whole boundary;\n * see `fence.ts` for what it closes and why an absent `Origin` is admitted on\n * reads but refused on writes.\n *\n * EVERY FAILURE IS A STRUCTURED BODY. The page decides what to say from a\n * stable code, never from prose, so a handler here returns codes even when the\n * underlying read threw.\n */\nimport { HTTP_API_PREFIX } from '../shared/api-prefix.js'\nimport type { StatePayload, WorkspaceEntry, WorkspaceListing } from '../shared/api-types.js'\nimport { ERR_BOOST_INTERNAL, ERR_BOOST_INVALID_ARGS, ERR_BOOST_INVALID_BODY } from '../tools/boost.js'\nimport { isTrustedWebRequest } from './fence.js'\n\nexport type { StatePayload, WorkspaceEntry, WorkspaceListing } from '../shared/api-types.js'\n\n/** The route prefix this plugin owns: absolute, no trailing slash. */\nexport { HTTP_API_PREFIX } from '../shared/api-prefix.js'\n\n/** Stable codes this surface adds to the plugin's vocabulary. */\nexport const ERR_HTTP_METHOD = 'ERR_HTTP_METHOD'\nexport const ERR_HTTP_NOT_FOUND = 'ERR_HTTP_NOT_FOUND'\nexport const ERR_HTTP_FORBIDDEN = 'ERR_HTTP_FORBIDDEN'\nexport const ERR_HTTP_WORKSPACES_UNAVAILABLE = 'ERR_HTTP_WORKSPACES_UNAVAILABLE'\nexport const ERR_HTTP_INTERNAL = 'ERR_HTTP_INTERNAL'\nexport const ERR_HTTP_BODY = 'ERR_HTTP_BODY'\n\n/** What the state handler reads. Everything is a thunk: state moves. */\nexport interface StateDeps {\n /** `runBoost` with `{ cmd: 'status' }` — the same computation as the tool. */\n status(): Promise<{ ok: true; data: unknown } | { ok: false; code: string }>\n /** `runBoost` with `{ cmd: 'scope-get' }`. */\n scope(): Promise<{ ok: true; data: unknown } | { ok: false; code: string }>\n /** The host's workspace registry, resolved lazily. */\n workspaces(): WorkspaceListing\n /** The effective configuration `resolveConfig` produced at load. */\n config(): unknown\n /**\n * `runBoost` with `{ cmd: 'scope-set' }` — the same CAS the tool performs.\n *\n * A write goes through the tool's own command rather than a second\n * implementation of the patch rules: two copies of \"which fields may change,\n * and what a revision means\" is exactly how a page and a tool end up\n * disagreeing about whether a save succeeded.\n */\n write(body: unknown, baseRevision: unknown): Promise<{ ok: true; data: unknown } | { ok: false; code: string }>\n}\n\n/**\n * Reads the workspace registry into the page's listing shape.\n *\n * A registry that is absent and one whose `list()` throws are the same answer\n * to the operator — \"the list could not be read\" — because both disable the\n * same control and neither is an empty list.\n */\nexport function listWorkspaces(registry: unknown): WorkspaceListing {\n if (registry === undefined || registry === null) {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n const list = (registry as { list?: unknown }).list\n if (typeof list !== 'function') {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n try {\n const entries = (list as () => unknown)()\n if (!Array.isArray(entries)) {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n const out: WorkspaceEntry[] = []\n for (const entry of entries) {\n const id = (entry as { id?: unknown } | null | undefined)?.id\n const path = (entry as { path?: unknown } | null | undefined)?.path\n if (typeof id !== 'string' || typeof path !== 'string') continue\n out.push({ id, path })\n }\n return { available: true, entries: out }\n } catch {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n}\n\n/** Builds the payload; every branch is already a code, never a thrown error. */\nexport async function buildStatePayload(deps: StateDeps): Promise<StatePayload> {\n const [status, scope] = await Promise.all([deps.status(), deps.scope()])\n return { status, scope, workspaces: deps.workspaces(), config: deps.config() }\n}\n\n/** The two request/response shapes the handler touches, narrowed to what it uses. */\nexport interface HttpRequestLike {\n method?: string\n url?: string\n headers: Record<string, string | string[] | undefined>\n /** Present on writes: the request stream, as node hands it over. */\n [Symbol.asyncIterator]?: () => AsyncIterator<unknown>\n}\n\nexport interface HttpResponseLike {\n writeHead(status: number, headers?: Record<string, string | number>): unknown\n end(body?: string): unknown\n}\n\n/** Writes JSON with the headers this surface always uses. */\nfunction writeJson(res: HttpResponseLike, status: number, value: unknown): void {\n const body = JSON.stringify(value)\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n // The scope document changes under the operator's feet (the `boost` tool\n // shares it), so a cached read would show a stale revision and the next\n // save would conflict for no visible reason.\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n })\n res.end(body)\n}\n\n/** The path below the prefix, with the query string removed. */\nfunction subPath(url: string | undefined): string {\n const raw = typeof url === 'string' ? url : ''\n const path = raw.split('?')[0] ?? ''\n // The route is mounted as a prefix, so the host only ever dispatches paths\n // that already start with it.\n return path.slice(HTTP_API_PREFIX.length)\n}\n\n/** What the handler needs beyond its deps. */\nexport interface HandlerOptions {\n /**\n * The deployment's trusted hosts, read per request.\n *\n * A thunk rather than a snapshot: `webStartup` can become active after\n * `webServer` does, and a snapshot taken at mount would pin the fence to an\n * empty list — every LAN-hosted request 403 for the life of the process.\n */\n trustedHosts?: () => readonly string[]\n}\n\n/** The largest write body accepted; a scope document is a few hundred bytes. */\nconst MAX_BODY_BYTES = 64 * 1024\n\n/** Reads the request body as UTF-8 text, refusing anything oversized. */\nasync function readBody(req: HttpRequestLike): Promise<{ ok: true; text: string } | { ok: false; code: string }> {\n const iterator = req[Symbol.asyncIterator]\n if (typeof iterator !== 'function') return { ok: false, code: ERR_HTTP_BODY }\n const chunks: Buffer[] = []\n let total = 0\n for await (const chunk of req as AsyncIterable<unknown>) {\n const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk as Uint8Array)\n total += buffer.byteLength\n if (total > MAX_BODY_BYTES) return { ok: false, code: ERR_HTTP_BODY }\n chunks.push(buffer)\n }\n return { ok: true, text: Buffer.concat(chunks).toString('utf8') }\n}\n\n/**\n * Maps a `scope-set` failure onto an HTTP status.\n *\n * The body always carries the plugin's own code, so the page never has to\n * infer anything from the status: a conflict is 409 because the caller can\n * retry after a re-read, a malformed request is 400 because retrying it\n * unchanged cannot work, and everything else is a refusal of the current\n * state (409) or an internal fault (500).\n */\nfunction writeStatusFor(code: string): number {\n if (code === ERR_HTTP_BODY) return 400\n if (code === ERR_BOOST_INVALID_BODY || code === ERR_BOOST_INVALID_ARGS) return 400\n if (code === ERR_BOOST_INTERNAL) return 500\n // Every remaining scope code means \"this write cannot be applied to the\n // document as it stands\": stale revision, held lock, unreadable or\n // unrecognised file. All of them are resolved by looking at the document.\n return 409\n}\n\n/**\n * The route handler: fence, dispatch, structured failure.\n *\n * Exported so the assembly seam (spec S-1) can drive it with a fabricated\n * request instead of a socket.\n */\nexport function createStateHandler(deps: StateDeps, options: HandlerOptions = {}) {\n const trustedHosts = (): readonly string[] => options.trustedHosts?.() ?? []\n\n return async function handle(req: HttpRequestLike, res: HttpResponseLike): Promise<void> {\n const method = req.method ?? 'GET'\n const isWrite = method !== 'GET' && method !== 'HEAD'\n // Reads admit an absent `Origin` (a same-origin GET never carries one, and\n // neither does curl); writes demand it, because a browser always attaches\n // it to a POST and that is what makes a cross-site write detectable.\n if (!isTrustedWebRequest(req, { trustedHosts: trustedHosts(), requireOrigin: isWrite })) {\n writeJson(res, 403, { error: ERR_HTTP_FORBIDDEN })\n return\n }\n const path = subPath(req.url)\n\n if (isWrite) {\n if (method !== 'POST') {\n writeJson(res, 405, { error: ERR_HTTP_METHOD })\n return\n }\n if (path !== '/scope') {\n writeJson(res, 404, { error: ERR_HTTP_NOT_FOUND })\n return\n }\n await handleWrite(deps, req, res)\n return\n }\n\n if (path !== '/state') {\n writeJson(res, 404, { error: ERR_HTTP_NOT_FOUND })\n return\n }\n try {\n writeJson(res, 200, await buildStatePayload(deps))\n } catch {\n // `buildStatePayload` converts its own failures; this catches a host\n // service that throws from a getter, which must still leave a JSON body.\n writeJson(res, 500, { error: ERR_HTTP_INTERNAL })\n }\n }\n}\n\n/** The write half: parse, delegate to the tool's own command, map the answer. */\nasync function handleWrite(deps: StateDeps, req: HttpRequestLike, res: HttpResponseLike): Promise<void> {\n const body = await readBody(req)\n if (!body.ok) {\n writeJson(res, 400, { error: body.code })\n return\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(body.text)\n } catch {\n writeJson(res, 400, { error: ERR_HTTP_BODY })\n return\n }\n const envelope = parsed as { body?: unknown; baseRevision?: unknown } | null\n if (envelope === null || typeof envelope !== 'object') {\n writeJson(res, 400, { error: ERR_HTTP_BODY })\n return\n }\n let result: { ok: true; data: unknown } | { ok: false; code: string }\n try {\n result = await deps.write(envelope.body, envelope.baseRevision)\n } catch {\n writeJson(res, 500, { error: ERR_HTTP_INTERNAL })\n return\n }\n if (!result.ok) {\n writeJson(res, writeStatusFor(result.code), { error: result.code })\n return\n }\n writeJson(res, 200, { ok: true, data: result.data })\n}\n"]}
1
+ {"version":3,"file":"state.js","sourceRoot":"","sources":["../../src/http/state.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,eAAe,EAAE,MAAM,yBA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;IACR,CAAC;IACD,IAAI,MAAe,CAAA;IACnB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAChC,CAAC;IAAC,MAAM,CAAC;QACP,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,aAAa,EAAE,CAAC,CAAA;QAC7C,OAAM;IACR,CAAC;IACD,MAAM,QAAQ,GAAG,MAA2D,CAAA;IAC5E,IAAI,QAAQ,KAAK,IAAI,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACtD,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,aAAa,EAAE,CAAC,CAAA;QAC7C,OAAM;IACR,CAAC;IACD,IAAI,MAAiE,CAAA;IACrE,IAAI,CAAC;QACH,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAA;IACjE,CAAC;IAAC,MAAM,CAAC;QACP,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC,CAAA;QACjD,OAAM;IACR,CAAC;IACD,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;QACf,SAAS,CAAC,GAAG,EAAE,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;QACnE,OAAM;IACR,CAAC;IACD,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;AACtD,CAAC","sourcesContent":["/**\n * The plugin's read-only HTTP surface for the settings page.\n *\n * WHY A ROUTE OF OUR OWN: the host's `webServer` serves the SPA and knows\n * nothing about a plugin's state, and `ctx.settings` only describes plugins\n * that declare a `Config` schema — this one deliberately does not (spec #2:\n * a strict schema turns `resolveConfig`'s clamp-and-warn into a load-time hard\n * failure). So the page reads through one prefix this plugin owns.\n *\n * NO AUTHENTICATION IS INHERITED. `webServer.register` performs none and\n * claims no path namespace, so `isTrustedWebRequest` is the whole boundary;\n * see `fence.ts` for what it closes and why an absent `Origin` is admitted on\n * reads but refused on writes.\n *\n * EVERY FAILURE IS A STRUCTURED BODY. The page decides what to say from a\n * stable code, never from prose, so a handler here returns codes even when the\n * underlying read threw.\n */\nimport { HTTP_API_PREFIX } from '../shared/api-prefix.js'\nimport type { StatePayload, WorkspaceEntry, WorkspaceListing } from '../shared/api-types.js'\nimport { ERR_BOOST_INTERNAL, ERR_BOOST_INVALID_ARGS, ERR_BOOST_INVALID_BODY } from '../tools/boost.js'\nimport { ERR_SCOPE_WRITE_FAILED } from '../scope/doc.js'\nimport { isTrustedWebRequest } from './fence.js'\n\nexport type { StatePayload, WorkspaceEntry, WorkspaceListing } from '../shared/api-types.js'\n\n/** The route prefix this plugin owns: absolute, no trailing slash. */\nexport { HTTP_API_PREFIX } from '../shared/api-prefix.js'\n\n/** Stable codes this surface adds to the plugin's vocabulary. */\nexport const ERR_HTTP_METHOD = 'ERR_HTTP_METHOD'\nexport const ERR_HTTP_NOT_FOUND = 'ERR_HTTP_NOT_FOUND'\nexport const ERR_HTTP_FORBIDDEN = 'ERR_HTTP_FORBIDDEN'\nexport const ERR_HTTP_WORKSPACES_UNAVAILABLE = 'ERR_HTTP_WORKSPACES_UNAVAILABLE'\nexport const ERR_HTTP_INTERNAL = 'ERR_HTTP_INTERNAL'\nexport const ERR_HTTP_BODY = 'ERR_HTTP_BODY'\n\n/** What the state handler reads. Everything is a thunk: state moves. */\nexport interface StateDeps {\n /** `runBoost` with `{ cmd: 'status' }` — the same computation as the tool. */\n status(): Promise<{ ok: true; data: unknown } | { ok: false; code: string }>\n /** `runBoost` with `{ cmd: 'scope-get' }`. */\n scope(): Promise<{ ok: true; data: unknown } | { ok: false; code: string }>\n /** The host's workspace registry, resolved lazily. */\n workspaces(): WorkspaceListing\n /** The effective configuration `resolveConfig` produced at load. */\n config(): unknown\n /**\n * `runBoost` with `{ cmd: 'scope-set' }` — the same CAS the tool performs.\n *\n * A write goes through the tool's own command rather than a second\n * implementation of the patch rules: two copies of \"which fields may change,\n * and what a revision means\" is exactly how a page and a tool end up\n * disagreeing about whether a save succeeded.\n */\n write(body: unknown, baseRevision: unknown): Promise<{ ok: true; data: unknown } | { ok: false; code: string }>\n}\n\n/**\n * Reads the workspace registry into the page's listing shape.\n *\n * A registry that is absent and one whose `list()` throws are the same answer\n * to the operator — \"the list could not be read\" — because both disable the\n * same control and neither is an empty list.\n */\nexport function listWorkspaces(registry: unknown): WorkspaceListing {\n if (registry === undefined || registry === null) {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n const list = (registry as { list?: unknown }).list\n if (typeof list !== 'function') {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n try {\n const entries = (list as () => unknown)()\n if (!Array.isArray(entries)) {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n const out: WorkspaceEntry[] = []\n for (const entry of entries) {\n const id = (entry as { id?: unknown } | null | undefined)?.id\n const path = (entry as { path?: unknown } | null | undefined)?.path\n if (typeof id !== 'string' || typeof path !== 'string') continue\n out.push({ id, path })\n }\n return { available: true, entries: out }\n } catch {\n return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE }\n }\n}\n\n/** Builds the payload; every branch is already a code, never a thrown error. */\nexport async function buildStatePayload(deps: StateDeps): Promise<StatePayload> {\n const [status, scope] = await Promise.all([deps.status(), deps.scope()])\n return { status, scope, workspaces: deps.workspaces(), config: deps.config() }\n}\n\n/** The two request/response shapes the handler touches, narrowed to what it uses. */\nexport interface HttpRequestLike {\n method?: string\n url?: string\n headers: Record<string, string | string[] | undefined>\n /** Present on writes: the request stream, as node hands it over. */\n [Symbol.asyncIterator]?: () => AsyncIterator<unknown>\n}\n\nexport interface HttpResponseLike {\n writeHead(status: number, headers?: Record<string, string | number>): unknown\n end(body?: string): unknown\n}\n\n/** Writes JSON with the headers this surface always uses. */\nfunction writeJson(res: HttpResponseLike, status: number, value: unknown): void {\n const body = JSON.stringify(value)\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n // The scope document changes under the operator's feet (the `boost` tool\n // shares it), so a cached read would show a stale revision and the next\n // save would conflict for no visible reason.\n 'cache-control': 'no-store',\n 'content-length': Buffer.byteLength(body),\n })\n res.end(body)\n}\n\n/** The path below the prefix, with the query string removed. */\nfunction subPath(url: string | undefined): string {\n const raw = typeof url === 'string' ? url : ''\n const path = raw.split('?')[0] ?? ''\n // The route is mounted as a prefix, so the host only ever dispatches paths\n // that already start with it.\n return path.slice(HTTP_API_PREFIX.length)\n}\n\n/** What the handler needs beyond its deps. */\nexport interface HandlerOptions {\n /**\n * The deployment's trusted hosts, read per request.\n *\n * A thunk rather than a snapshot: `webStartup` can become active after\n * `webServer` does, and a snapshot taken at mount would pin the fence to an\n * empty list — every LAN-hosted request 403 for the life of the process.\n */\n trustedHosts?: () => readonly string[]\n}\n\n/** The largest write body accepted; a scope document is a few hundred bytes. */\nconst MAX_BODY_BYTES = 64 * 1024\n\n/** Reads the request body as UTF-8 text, refusing anything oversized. */\nasync function readBody(req: HttpRequestLike): Promise<{ ok: true; text: string } | { ok: false; code: string }> {\n const iterator = req[Symbol.asyncIterator]\n if (typeof iterator !== 'function') return { ok: false, code: ERR_HTTP_BODY }\n const chunks: Buffer[] = []\n let total = 0\n for await (const chunk of req as AsyncIterable<unknown>) {\n const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk as Uint8Array)\n total += buffer.byteLength\n if (total > MAX_BODY_BYTES) return { ok: false, code: ERR_HTTP_BODY }\n chunks.push(buffer)\n }\n return { ok: true, text: Buffer.concat(chunks).toString('utf8') }\n}\n\n/**\n * Maps a `scope-set` failure onto an HTTP status.\n *\n * The body always carries the plugin's own code, so the page never has to\n * infer anything from the status: a conflict is 409 because the caller can\n * retry after a re-read, a malformed request is 400 because retrying it\n * unchanged cannot work, and everything else is a refusal of the current\n * state (409) or an internal fault (500).\n */\nfunction writeStatusFor(code: string): number {\n if (code === ERR_HTTP_BODY) return 400\n if (code === ERR_BOOST_INVALID_BODY || code === ERR_BOOST_INVALID_ARGS) return 400\n if (code === ERR_BOOST_INTERNAL) return 500\n // A failed write is a storage fault, not a disagreement with the document:\n // re-reading cannot help, and the draft is still good.\n if (code === ERR_SCOPE_WRITE_FAILED) return 500\n // Every remaining scope code means \"this write cannot be applied to the\n // document as it stands\": stale revision, held lock, unreadable or\n // unrecognised file. All of them are resolved by looking at the document.\n return 409\n}\n\n/**\n * The route handler: fence, dispatch, structured failure.\n *\n * Exported so the assembly seam (spec S-1) can drive it with a fabricated\n * request instead of a socket.\n */\nexport function createStateHandler(deps: StateDeps, options: HandlerOptions = {}) {\n const trustedHosts = (): readonly string[] => options.trustedHosts?.() ?? []\n\n return async function handle(req: HttpRequestLike, res: HttpResponseLike): Promise<void> {\n const method = req.method ?? 'GET'\n const isWrite = method !== 'GET' && method !== 'HEAD'\n // Reads admit an absent `Origin` (a same-origin GET never carries one, and\n // neither does curl); writes demand it, because a browser always attaches\n // it to a POST and that is what makes a cross-site write detectable.\n if (!isTrustedWebRequest(req, { trustedHosts: trustedHosts(), requireOrigin: isWrite })) {\n writeJson(res, 403, { error: ERR_HTTP_FORBIDDEN })\n return\n }\n const path = subPath(req.url)\n\n if (isWrite) {\n // A write aimed at a read-only path is a method error, not a missing\n // route: the path exists, the verb does not belong there.\n if (path === '/state' || method !== 'POST') {\n writeJson(res, 405, { error: ERR_HTTP_METHOD })\n return\n }\n if (path !== '/scope') {\n writeJson(res, 404, { error: ERR_HTTP_NOT_FOUND })\n return\n }\n await handleWrite(deps, req, res)\n return\n }\n\n if (path !== '/state') {\n writeJson(res, 404, { error: ERR_HTTP_NOT_FOUND })\n return\n }\n try {\n writeJson(res, 200, await buildStatePayload(deps))\n } catch {\n // `buildStatePayload` converts its own failures; this catches a host\n // service that throws from a getter, which must still leave a JSON body.\n writeJson(res, 500, { error: ERR_HTTP_INTERNAL })\n }\n }\n}\n\n/** The write half: parse, delegate to the tool's own command, map the answer. */\nasync function handleWrite(deps: StateDeps, req: HttpRequestLike, res: HttpResponseLike): Promise<void> {\n const body = await readBody(req)\n if (!body.ok) {\n writeJson(res, 400, { error: body.code })\n return\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(body.text)\n } catch {\n writeJson(res, 400, { error: ERR_HTTP_BODY })\n return\n }\n const envelope = parsed as { body?: unknown; baseRevision?: unknown } | null\n if (envelope === null || typeof envelope !== 'object') {\n writeJson(res, 400, { error: ERR_HTTP_BODY })\n return\n }\n let result: { ok: true; data: unknown } | { ok: false; code: string }\n try {\n result = await deps.write(envelope.body, envelope.baseRevision)\n } catch {\n writeJson(res, 500, { error: ERR_HTTP_INTERNAL })\n return\n }\n if (!result.ok) {\n writeJson(res, writeStatusFor(result.code), { error: result.code })\n return\n }\n writeJson(res, 200, { ok: true, data: result.data })\n}\n"]}
package/dist/index.js CHANGED
@@ -28,7 +28,7 @@
28
28
  */
29
29
  import { readFileSync } from 'node:fs';
30
30
  import { createRequire } from 'node:module';
31
- import { measureBoostFixedOverhead } from './tools/boost.js';
31
+ import { ERR_BOOST_HTTP_MOUNT_FAILED, measureBoostFixedOverhead } from './tools/boost.js';
32
32
  import { RuntimeStepHorizon, StepBudget } from './admission/ledger.js';
33
33
  import { RetrievalLedger } from './admission/retrieval.js';
34
34
  import { UsageLedger } from './admission/usage.js';
@@ -1529,7 +1529,7 @@ export function apply(ctx, config) {
1529
1529
  }, message => ctx.logger?.warn?.(message));
1530
1530
  }
1531
1531
  catch (error) {
1532
- ctx.logger?.warn?.(`dsh-boost: ERR_BOOST_HTTP_MOUNT_FAILED: settings page has no data route (${messageOf(error)})`);
1532
+ ctx.logger?.warn?.(`dsh-boost: ${ERR_BOOST_HTTP_MOUNT_FAILED}: settings page has no data route (${messageOf(error)})`);
1533
1533
  }
1534
1534
  }
1535
1535
  catch (error) {