dsh-boost 0.1.4 → 0.2.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/README.en.md +60 -18
- package/README.md +53 -17
- package/dist/http/fence.js +119 -0
- package/dist/http/fence.js.map +1 -0
- package/dist/http/mount.js +71 -0
- package/dist/http/mount.js.map +1 -0
- package/dist/http/state.js +216 -0
- package/dist/http/state.js.map +1 -0
- package/dist/index.js +36 -4
- package/dist/index.js.map +1 -1
- package/dist/scope/doc.js +8 -0
- package/dist/scope/doc.js.map +1 -1
- package/dist/scope/store.js +5 -4
- package/dist/scope/store.js.map +1 -1
- package/dist/shared/api-prefix.js +9 -0
- package/dist/shared/api-prefix.js.map +1 -0
- package/dist/shared/api-types.js +10 -0
- package/dist/shared/api-types.js.map +1 -0
- package/dist/tools/boost.js +11 -3
- package/dist/tools/boost.js.map +1 -1
- package/lib/client.js +929 -0
- package/locale/en.json +96 -2
- package/locale/zh.json +96 -2
- package/package.json +21 -7
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's read-only HTTP surface for the settings page.
|
|
3
|
+
*
|
|
4
|
+
* WHY A ROUTE OF OUR OWN: the host's `webServer` serves the SPA and knows
|
|
5
|
+
* nothing about a plugin's state, and `ctx.settings` only describes plugins
|
|
6
|
+
* that declare a `Config` schema — this one deliberately does not (spec #2:
|
|
7
|
+
* a strict schema turns `resolveConfig`'s clamp-and-warn into a load-time hard
|
|
8
|
+
* failure). So the page reads through one prefix this plugin owns.
|
|
9
|
+
*
|
|
10
|
+
* NO AUTHENTICATION IS INHERITED. `webServer.register` performs none and
|
|
11
|
+
* claims no path namespace, so `isTrustedWebRequest` is the whole boundary;
|
|
12
|
+
* see `fence.ts` for what it closes and why an absent `Origin` is admitted on
|
|
13
|
+
* reads but refused on writes.
|
|
14
|
+
*
|
|
15
|
+
* EVERY FAILURE IS A STRUCTURED BODY. The page decides what to say from a
|
|
16
|
+
* stable code, never from prose, so a handler here returns codes even when the
|
|
17
|
+
* underlying read threw.
|
|
18
|
+
*/
|
|
19
|
+
import { HTTP_API_PREFIX } from '../shared/api-prefix.js';
|
|
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';
|
|
22
|
+
import { isTrustedWebRequest } from './fence.js';
|
|
23
|
+
/** The route prefix this plugin owns: absolute, no trailing slash. */
|
|
24
|
+
export { HTTP_API_PREFIX } from '../shared/api-prefix.js';
|
|
25
|
+
/** Stable codes this surface adds to the plugin's vocabulary. */
|
|
26
|
+
export const ERR_HTTP_METHOD = 'ERR_HTTP_METHOD';
|
|
27
|
+
export const ERR_HTTP_NOT_FOUND = 'ERR_HTTP_NOT_FOUND';
|
|
28
|
+
export const ERR_HTTP_FORBIDDEN = 'ERR_HTTP_FORBIDDEN';
|
|
29
|
+
export const ERR_HTTP_WORKSPACES_UNAVAILABLE = 'ERR_HTTP_WORKSPACES_UNAVAILABLE';
|
|
30
|
+
export const ERR_HTTP_INTERNAL = 'ERR_HTTP_INTERNAL';
|
|
31
|
+
export const ERR_HTTP_BODY = 'ERR_HTTP_BODY';
|
|
32
|
+
/**
|
|
33
|
+
* Reads the workspace registry into the page's listing shape.
|
|
34
|
+
*
|
|
35
|
+
* A registry that is absent and one whose `list()` throws are the same answer
|
|
36
|
+
* to the operator — "the list could not be read" — because both disable the
|
|
37
|
+
* same control and neither is an empty list.
|
|
38
|
+
*/
|
|
39
|
+
export function listWorkspaces(registry) {
|
|
40
|
+
if (registry === undefined || registry === null) {
|
|
41
|
+
return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE };
|
|
42
|
+
}
|
|
43
|
+
const list = registry.list;
|
|
44
|
+
if (typeof list !== 'function') {
|
|
45
|
+
return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE };
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
const entries = list();
|
|
49
|
+
if (!Array.isArray(entries)) {
|
|
50
|
+
return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE };
|
|
51
|
+
}
|
|
52
|
+
const out = [];
|
|
53
|
+
for (const entry of entries) {
|
|
54
|
+
const id = entry?.id;
|
|
55
|
+
const path = entry?.path;
|
|
56
|
+
if (typeof id !== 'string' || typeof path !== 'string')
|
|
57
|
+
continue;
|
|
58
|
+
out.push({ id, path });
|
|
59
|
+
}
|
|
60
|
+
return { available: true, entries: out };
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return { available: false, code: ERR_HTTP_WORKSPACES_UNAVAILABLE };
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Builds the payload; every branch is already a code, never a thrown error. */
|
|
67
|
+
export async function buildStatePayload(deps) {
|
|
68
|
+
const [status, scope] = await Promise.all([deps.status(), deps.scope()]);
|
|
69
|
+
return { status, scope, workspaces: deps.workspaces(), config: deps.config() };
|
|
70
|
+
}
|
|
71
|
+
/** Writes JSON with the headers this surface always uses. */
|
|
72
|
+
function writeJson(res, status, value) {
|
|
73
|
+
const body = JSON.stringify(value);
|
|
74
|
+
res.writeHead(status, {
|
|
75
|
+
'content-type': 'application/json; charset=utf-8',
|
|
76
|
+
// The scope document changes under the operator's feet (the `boost` tool
|
|
77
|
+
// shares it), so a cached read would show a stale revision and the next
|
|
78
|
+
// save would conflict for no visible reason.
|
|
79
|
+
'cache-control': 'no-store',
|
|
80
|
+
'content-length': Buffer.byteLength(body),
|
|
81
|
+
});
|
|
82
|
+
res.end(body);
|
|
83
|
+
}
|
|
84
|
+
/** The path below the prefix, with the query string removed. */
|
|
85
|
+
function subPath(url) {
|
|
86
|
+
const raw = typeof url === 'string' ? url : '';
|
|
87
|
+
const path = raw.split('?')[0] ?? '';
|
|
88
|
+
// The route is mounted as a prefix, so the host only ever dispatches paths
|
|
89
|
+
// that already start with it.
|
|
90
|
+
return path.slice(HTTP_API_PREFIX.length);
|
|
91
|
+
}
|
|
92
|
+
/** The largest write body accepted; a scope document is a few hundred bytes. */
|
|
93
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
94
|
+
/** Reads the request body as UTF-8 text, refusing anything oversized. */
|
|
95
|
+
async function readBody(req) {
|
|
96
|
+
const iterator = req[Symbol.asyncIterator];
|
|
97
|
+
if (typeof iterator !== 'function')
|
|
98
|
+
return { ok: false, code: ERR_HTTP_BODY };
|
|
99
|
+
const chunks = [];
|
|
100
|
+
let total = 0;
|
|
101
|
+
for await (const chunk of req) {
|
|
102
|
+
const buffer = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : Buffer.from(chunk);
|
|
103
|
+
total += buffer.byteLength;
|
|
104
|
+
if (total > MAX_BODY_BYTES)
|
|
105
|
+
return { ok: false, code: ERR_HTTP_BODY };
|
|
106
|
+
chunks.push(buffer);
|
|
107
|
+
}
|
|
108
|
+
return { ok: true, text: Buffer.concat(chunks).toString('utf8') };
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Maps a `scope-set` failure onto an HTTP status.
|
|
112
|
+
*
|
|
113
|
+
* The body always carries the plugin's own code, so the page never has to
|
|
114
|
+
* infer anything from the status: a conflict is 409 because the caller can
|
|
115
|
+
* retry after a re-read, a malformed request is 400 because retrying it
|
|
116
|
+
* unchanged cannot work, and everything else is a refusal of the current
|
|
117
|
+
* state (409) or an internal fault (500).
|
|
118
|
+
*/
|
|
119
|
+
function writeStatusFor(code) {
|
|
120
|
+
if (code === ERR_HTTP_BODY)
|
|
121
|
+
return 400;
|
|
122
|
+
if (code === ERR_BOOST_INVALID_BODY || code === ERR_BOOST_INVALID_ARGS)
|
|
123
|
+
return 400;
|
|
124
|
+
if (code === ERR_BOOST_INTERNAL)
|
|
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;
|
|
130
|
+
// Every remaining scope code means "this write cannot be applied to the
|
|
131
|
+
// document as it stands": stale revision, held lock, unreadable or
|
|
132
|
+
// unrecognised file. All of them are resolved by looking at the document.
|
|
133
|
+
return 409;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* The route handler: fence, dispatch, structured failure.
|
|
137
|
+
*
|
|
138
|
+
* Exported so the assembly seam (spec S-1) can drive it with a fabricated
|
|
139
|
+
* request instead of a socket.
|
|
140
|
+
*/
|
|
141
|
+
export function createStateHandler(deps, options = {}) {
|
|
142
|
+
const trustedHosts = () => options.trustedHosts?.() ?? [];
|
|
143
|
+
return async function handle(req, res) {
|
|
144
|
+
const method = req.method ?? 'GET';
|
|
145
|
+
const isWrite = method !== 'GET' && method !== 'HEAD';
|
|
146
|
+
// Reads admit an absent `Origin` (a same-origin GET never carries one, and
|
|
147
|
+
// neither does curl); writes demand it, because a browser always attaches
|
|
148
|
+
// it to a POST and that is what makes a cross-site write detectable.
|
|
149
|
+
if (!isTrustedWebRequest(req, { trustedHosts: trustedHosts(), requireOrigin: isWrite })) {
|
|
150
|
+
writeJson(res, 403, { error: ERR_HTTP_FORBIDDEN });
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const path = subPath(req.url);
|
|
154
|
+
if (isWrite) {
|
|
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') {
|
|
158
|
+
writeJson(res, 405, { error: ERR_HTTP_METHOD });
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (path !== '/scope') {
|
|
162
|
+
writeJson(res, 404, { error: ERR_HTTP_NOT_FOUND });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
await handleWrite(deps, req, res);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (path !== '/state') {
|
|
169
|
+
writeJson(res, 404, { error: ERR_HTTP_NOT_FOUND });
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
writeJson(res, 200, await buildStatePayload(deps));
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
// `buildStatePayload` converts its own failures; this catches a host
|
|
177
|
+
// service that throws from a getter, which must still leave a JSON body.
|
|
178
|
+
writeJson(res, 500, { error: ERR_HTTP_INTERNAL });
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/** The write half: parse, delegate to the tool's own command, map the answer. */
|
|
183
|
+
async function handleWrite(deps, req, res) {
|
|
184
|
+
const body = await readBody(req);
|
|
185
|
+
if (!body.ok) {
|
|
186
|
+
writeJson(res, 400, { error: body.code });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
let parsed;
|
|
190
|
+
try {
|
|
191
|
+
parsed = JSON.parse(body.text);
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
writeJson(res, 400, { error: ERR_HTTP_BODY });
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const envelope = parsed;
|
|
198
|
+
if (envelope === null || typeof envelope !== 'object') {
|
|
199
|
+
writeJson(res, 400, { error: ERR_HTTP_BODY });
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
let result;
|
|
203
|
+
try {
|
|
204
|
+
result = await deps.write(envelope.body, envelope.baseRevision);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
writeJson(res, 500, { error: ERR_HTTP_INTERNAL });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (!result.ok) {
|
|
211
|
+
writeJson(res, writeStatusFor(result.code), { error: result.code });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
writeJson(res, 200, { ok: true, data: result.data });
|
|
215
|
+
}
|
|
216
|
+
//# sourceMappingURL=state.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3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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';
|
|
@@ -44,7 +44,9 @@ import { PROTOCOL_NAME, PROTOCOL_TEXT } from './prompt/protocol.js';
|
|
|
44
44
|
import { ReceiptStore } from './receipts/store.js';
|
|
45
45
|
import { resolveWorkspace } from './scope/resolve.js';
|
|
46
46
|
import { ScopeStore } from './scope/store.js';
|
|
47
|
-
import { boostTool } from './tools/boost.js';
|
|
47
|
+
import { boostTool, runBoost } from './tools/boost.js';
|
|
48
|
+
import { registerHttpApi } from './http/mount.js';
|
|
49
|
+
import { listWorkspaces } from './http/state.js';
|
|
48
50
|
export const name = 'dsh-boost';
|
|
49
51
|
/**
|
|
50
52
|
* Required host services.
|
|
@@ -1476,7 +1478,7 @@ export function apply(ctx, config) {
|
|
|
1476
1478
|
// does a tool registration failure of its own — neither may be swallowed
|
|
1477
1479
|
// behind the other's diagnosis.
|
|
1478
1480
|
try {
|
|
1479
|
-
|
|
1481
|
+
const boostDeps = {
|
|
1480
1482
|
scope,
|
|
1481
1483
|
receipts,
|
|
1482
1484
|
host: hostFacts,
|
|
@@ -1498,7 +1500,37 @@ export function apply(ctx, config) {
|
|
|
1498
1500
|
protocolSuppressed: () => projectionCounters.protocolSuppressions(),
|
|
1499
1501
|
completeSectionSuppressions: () => projectionCounters.protocolMissings(),
|
|
1500
1502
|
partialMounts: () => [...missingMounts],
|
|
1501
|
-
}
|
|
1503
|
+
};
|
|
1504
|
+
registerBoostTool(ctx, boostDeps);
|
|
1505
|
+
// The settings page reads through this plugin's own route, and it reads
|
|
1506
|
+
// through `boostDeps` — the same object the tool spreads — so `boost
|
|
1507
|
+
// status` and the page can never disagree about the same workspace.
|
|
1508
|
+
//
|
|
1509
|
+
// Its own try: the catch below reports a failed *tool* registration, and
|
|
1510
|
+
// a route that could not mount is a different fault with a different
|
|
1511
|
+
// remedy (the tool is the control surface; the route is only the page).
|
|
1512
|
+
try {
|
|
1513
|
+
registerHttpApi(ctx, {
|
|
1514
|
+
status: () => runBoost({ ...boostDeps, args: { cmd: 'status' } }),
|
|
1515
|
+
scope: () => runBoost({ ...boostDeps, args: { cmd: 'scope-get' } }),
|
|
1516
|
+
workspaces: () => listWorkspaces(registryBackend()),
|
|
1517
|
+
config: () => cfg,
|
|
1518
|
+
write: (body, baseRevision) => runBoost({
|
|
1519
|
+
...boostDeps,
|
|
1520
|
+
// The wire is untrusted: a non-number is "no revision given",
|
|
1521
|
+
// which the command already rejects with its own code. Passing
|
|
1522
|
+
// it through as-is would only move the type error here.
|
|
1523
|
+
args: {
|
|
1524
|
+
cmd: 'scope-set',
|
|
1525
|
+
body,
|
|
1526
|
+
...(typeof baseRevision === 'number' ? { baseRevision } : {}),
|
|
1527
|
+
},
|
|
1528
|
+
}),
|
|
1529
|
+
}, message => ctx.logger?.warn?.(message));
|
|
1530
|
+
}
|
|
1531
|
+
catch (error) {
|
|
1532
|
+
ctx.logger?.warn?.(`dsh-boost: ${ERR_BOOST_HTTP_MOUNT_FAILED}: settings page has no data route (${messageOf(error)})`);
|
|
1533
|
+
}
|
|
1502
1534
|
}
|
|
1503
1535
|
catch (error) {
|
|
1504
1536
|
// The tool is the user's only control surface; its failure is reported
|