@eserstack/noskills-web 0.0.0-stage → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/LICENSE +13 -0
  2. package/README.md +247 -2
  3. package/dist/auth.d.ts +50 -0
  4. package/dist/auth.js +107 -0
  5. package/dist/mod.d.ts +13 -0
  6. package/dist/mod.js +11 -0
  7. package/dist/request-context.d.ts +35 -0
  8. package/dist/request-context.js +19 -0
  9. package/dist/routes/api.d.ts +45 -0
  10. package/dist/routes/api.js +167 -0
  11. package/dist/routes/pages.d.ts +20 -0
  12. package/dist/routes/pages.js +80 -0
  13. package/dist/routes/sse.d.ts +15 -0
  14. package/dist/routes/sse.js +61 -0
  15. package/dist/routes/static.d.ts +10 -0
  16. package/dist/routes/static.js +52 -0
  17. package/dist/server.d.ts +53 -0
  18. package/dist/server.js +228 -0
  19. package/dist/static/client.js +257 -0
  20. package/dist/static/icons/icon.svg +12 -0
  21. package/dist/static/manifest.json +17 -0
  22. package/dist/static/mux-remote.js +192 -0
  23. package/dist/static/mux-render.js +224 -0
  24. package/dist/static/style.css +391 -0
  25. package/dist/static/sw-register.js +31 -0
  26. package/dist/static/sw.js +109 -0
  27. package/dist/templates/components.d.ts +17 -0
  28. package/dist/templates/components.js +89 -0
  29. package/dist/templates/dashboard.d.ts +8 -0
  30. package/dist/templates/dashboard.js +28 -0
  31. package/dist/templates/escape.d.ts +8 -0
  32. package/dist/templates/escape.js +14 -0
  33. package/dist/templates/layout.d.ts +12 -0
  34. package/dist/templates/layout.js +83 -0
  35. package/dist/templates/spec-detail.d.ts +7 -0
  36. package/dist/templates/spec-detail.js +83 -0
  37. package/dist/terminal/mux-host.d.ts +65 -0
  38. package/dist/terminal/mux-host.js +166 -0
  39. package/dist/terminal/ws-bridge.d.ts +9 -0
  40. package/dist/terminal/ws-bridge.js +26 -0
  41. package/package.json +32 -3
package/dist/server.js ADDED
@@ -0,0 +1,228 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ // The URL and the shutdown notice printed here are `noskills web` output, not
3
+ // logs; failures go through the logger.
4
+ /* oxlint-disable no-console */
5
+ /**
6
+ * HTTP + WebSocket + SSE server for noskills web interface.
7
+ *
8
+ * @module
9
+ */
10
+ import * as pages from "./routes/pages.js";
11
+ import * as api from "./routes/api.js";
12
+ import * as sse from "./routes/sse.js";
13
+ import * as staticRoute from "./routes/static.js";
14
+ import * as wsBridge from "./terminal/ws-bridge.js";
15
+ import * as muxHost from "./terminal/mux-host.js";
16
+ import * as auth from "./auth.js";
17
+ import * as requestContext from "./request-context.js";
18
+ import * as logging from "@eserstack/logging";
19
+ import * as crossRuntime from "@eserstack/standards/cross-runtime";
20
+ const { runtime } = crossRuntime;
21
+ /**
22
+ * Where the server logs when the caller passes no logger. With no logging
23
+ * configuration, @eserstack/logging writes its records to stderr, which is the
24
+ * terminal that runs `noskills web`.
25
+ */
26
+ const defaultLogger = logging.logger.getLogger(["noskills-web"]);
27
+ // =============================================================================
28
+ // Static file serving
29
+ // =============================================================================
30
+ // import.meta.dirname is a native path on every platform (no "/C:/..." on
31
+ // Windows). It is undefined when the module is loaded from a remote URL; the
32
+ // static files are not on disk then, and serveStatic answers 404.
33
+ const STATIC_DIR = import.meta.dirname === undefined
34
+ ? null
35
+ : runtime.path.join(import.meta.dirname, "static");
36
+ const serveStatic = (path) => staticRoute.serveStatic(STATIC_DIR, path);
37
+ // =============================================================================
38
+ // Request router
39
+ // =============================================================================
40
+ /** The JSON object a request body carries; `{}` for any other body. */
41
+ const readJsonObject = async (request) => {
42
+ const body = await request.json().catch(() => null);
43
+ return body instanceof Object && !Array.isArray(body)
44
+ ? body
45
+ : {};
46
+ };
47
+ const route = async (request, root, host, guard, context) => {
48
+ const url = new URL(request.url);
49
+ const path = url.pathname;
50
+ const method = request.method;
51
+ // Anything that mutates server state, spawns a process, or opens the
52
+ // multiplexer socket must clear the trust boundary first. Reads of static
53
+ // assets and pages stay open so the dashboard can bootstrap and hand the
54
+ // browser its token.
55
+ const isMutating = method === "POST" ||
56
+ method === "DELETE" ||
57
+ method === "PUT" ||
58
+ method === "PATCH";
59
+ if (path === "/mux" || isMutating) {
60
+ if (!auth.isOriginAllowed(request, guard.port)) {
61
+ return auth.forbidden("origin not allowed");
62
+ }
63
+ }
64
+ if (isMutating && !auth.hasJsonContentType(request) && method !== "DELETE") {
65
+ // Blocks the form-postable content types, which are the ones a
66
+ // cross-origin page can send without triggering a preflight.
67
+ return auth.forbidden("expected application/json");
68
+ }
69
+ if (isMutating && !auth.hasValidHeaderToken(request, guard.token)) {
70
+ return auth.forbidden("missing or invalid token");
71
+ }
72
+ // PWA root-level files — service worker must be at / scope, not /static/
73
+ if (path === "/sw.js" && method === "GET") {
74
+ return serveStatic("sw.js");
75
+ }
76
+ if (path === "/manifest.json" && method === "GET") {
77
+ return serveStatic("manifest.json");
78
+ }
79
+ // Static files
80
+ if (path.startsWith("/static/")) {
81
+ return serveStatic(path.slice("/static/".length));
82
+ }
83
+ // SSE event stream
84
+ if (path === "/events" && method === "GET") {
85
+ return sse.handleSSE(root);
86
+ }
87
+ // WebSocket: the whole multiplexer rides one socket (scene + every pane).
88
+ //
89
+ // This socket can spawn PTYs, so it is the highest-value route on the server.
90
+ // WebSockets are exempt from the same-origin policy, which means binding to
91
+ // 127.0.0.1 keeps out nothing: any page the developer happens to visit can
92
+ // dial it. The token is what actually gates it — a browser can only learn it
93
+ // by reading the dashboard HTML, which the Origin check confines to us.
94
+ if (path === "/mux") {
95
+ if (request.headers.get("upgrade")?.toLowerCase() !== "websocket") {
96
+ return new Response("WebSocket upgrade required", { status: 426 });
97
+ }
98
+ if (!auth.hasValidQueryToken(request, guard.token)) {
99
+ return auth.forbidden("missing or invalid token");
100
+ }
101
+ return wsBridge.handleMuxWs(request, host);
102
+ }
103
+ // API routes
104
+ if (path === "/api/state" && method === "GET") {
105
+ return api.handleGetState(root);
106
+ }
107
+ if (path === "/api/tabs" && method === "GET") {
108
+ return api.handleListTabs(host);
109
+ }
110
+ if (path === "/api/tab" && method === "POST") {
111
+ return api.handleCreateTab(host, await readJsonObject(request));
112
+ }
113
+ if (path.startsWith("/api/tab/") && method === "DELETE") {
114
+ const tabId = path.slice("/api/tab/".length);
115
+ return api.handleCloseTab(host, tabId);
116
+ }
117
+ // API spec reads: GET /api/spec/:name/ledger | summary (decision ledger)
118
+ const specReadMatch = path.match(/^\/api\/spec\/([^/]+)\/(ledger|summary)$/);
119
+ if (specReadMatch !== null && method === "GET") {
120
+ return api.handleSpecRead(root, specReadMatch[1], specReadMatch[2]);
121
+ }
122
+ // API spec actions: /api/spec/:name/:action
123
+ const specActionMatch = path.match(/^\/api\/spec\/([^/]+)\/([^/]+)$/);
124
+ if (specActionMatch !== null && method === "POST") {
125
+ return api.handleAction(root, specActionMatch[1], specActionMatch[2], await readJsonObject(request), host, context);
126
+ }
127
+ // Spec detail page. The path is percent-encoded; the spec is its decoded
128
+ // name, which must name one directory under .eser/specs/.
129
+ if (path.startsWith("/spec/") && method === "GET") {
130
+ const specName = pages.specNameFromPath(path.slice("/spec/".length));
131
+ if (specName === null) {
132
+ return pages.specNotFound();
133
+ }
134
+ return pages.handleSpecDetail(root, specName, guard.token);
135
+ }
136
+ // Dashboard (home)
137
+ if (path === "/" && method === "GET") {
138
+ return pages.handleDashboard(root, host, guard.token);
139
+ }
140
+ return new Response("Not found", { status: 404 });
141
+ };
142
+ /**
143
+ * Give every request a context, and turn an error that `handler` throws into a
144
+ * logged fault: the record carries the request id, and the client gets a 500
145
+ * with the same id instead of the error.
146
+ *
147
+ * @param handler - Answers the request
148
+ * @param logger - Receives the error records
149
+ * @returns The handler to serve
150
+ */
151
+ export const withFaultBoundary = (handler, logger) => async (request) => {
152
+ const context = requestContext.createRequestContext(request, logger);
153
+ try {
154
+ return await handler(request, context);
155
+ }
156
+ catch (error) {
157
+ return await api.faultResponse(context, "Request could not be completed", 500, error);
158
+ }
159
+ };
160
+ // =============================================================================
161
+ // Server lifecycle
162
+ // =============================================================================
163
+ /**
164
+ * The command and leading arguments that open a URL in the default browser,
165
+ * per platform. `start` is a cmd built-in, not a program, so Windows runs it
166
+ * through cmd; its first quoted argument is a window title, hence the "".
167
+ */
168
+ const BROWSER_OPENERS = {
169
+ darwin: ["open"],
170
+ linux: ["xdg-open"],
171
+ windows: ["cmd", "/c", "start", ""],
172
+ };
173
+ /**
174
+ * Serve the noskills dashboard, its JSON API, the SSE event stream and the
175
+ * `/mux` WebSocket on 127.0.0.1, and resolve once the server stops.
176
+ *
177
+ * The token that guards mutating routes and `/mux` comes from
178
+ * `NOSKILLS_WEB_TOKEN` when it is set, and is minted per process otherwise.
179
+ */
180
+ export const startServer = async (opts) => {
181
+ const port = opts.port ?? 3000;
182
+ const logger = opts.logger ?? defaultLogger;
183
+ const host = new muxHost.MuxHost(opts.root);
184
+ // Minted per process unless the operator supplied one. The dashboard embeds
185
+ // it so the browser can open /mux; nothing persists it to disk.
186
+ const token = auth.tokenFromEnv() ?? auth.createToken();
187
+ // The Origin check needs the port the server bound, which is only known once
188
+ // serve resolves when `port` is 0. Until then the guard holds the requested
189
+ // port, so a request in that window fails the Origin check.
190
+ let guard = {
191
+ token,
192
+ port,
193
+ };
194
+ const handler = withFaultBoundary((request, context) => route(request, opts.root, host, guard, context), logger);
195
+ const server = await runtime.http.serve({ port, hostname: "127.0.0.1", signal: opts.signal }, handler);
196
+ guard = { token, port: server.port };
197
+ console.log(`noskills web → http://localhost:${server.port}`);
198
+ opts.onListen?.({ hostname: server.hostname, port: server.port });
199
+ if (opts.open === true) {
200
+ const [opener, ...openerArgs] = BROWSER_OPENERS[crossRuntime.getPlatform()];
201
+ try {
202
+ await runtime.exec.spawn(opener, [
203
+ ...openerArgs,
204
+ `http://localhost:${server.port}`,
205
+ ]);
206
+ }
207
+ catch {
208
+ // Opening a browser is a convenience: the URL is already printed above.
209
+ }
210
+ }
211
+ // Ctrl+C closes every tab and its agent process before the process exits.
212
+ // The listener lives as long as this server and is removed with it.
213
+ const onInterrupt = () => {
214
+ console.log("\nShutting down...");
215
+ host.killAll().then(() => runtime.process.exit(0), async (error) => {
216
+ await logger.with({ error }).error("Closing the agent tabs failed");
217
+ runtime.process.exit(1);
218
+ });
219
+ };
220
+ runtime.process.addSignalListener("SIGINT", onInterrupt);
221
+ try {
222
+ await server.finished;
223
+ }
224
+ finally {
225
+ runtime.process.removeSignalListener("SIGINT", onInterrupt);
226
+ }
227
+ await host.killAll();
228
+ };
@@ -0,0 +1,257 @@
1
+ // Copyright 2023-present Eser Ozvataf and other contributors. All rights reserved. Apache-2.0 license.
2
+ // noskills web — local mux client (vanilla, no build step).
3
+ //
4
+ // Thin WebSocket adapter over the shared transport-agnostic renderer
5
+ // (mux-render.js): one /mux socket carries the whole multiplexer (neutral scene
6
+ // + per-pane output in, actions out). noskills-web glue (SSE dashboard feed,
7
+ // REST tab create/close, spec CTAs) lives here; all rendering is in MuxRender.
8
+
9
+ (() => {
10
+ "use strict";
11
+
12
+ // Browser globals come from globalThis, where browser-scripts.test.ts puts
13
+ // its stand-ins for the DOM and MuxRender.
14
+ const { document } = globalThis;
15
+
16
+ // The per-process token the server embedded in the page head. Every mutating
17
+ // call and the /mux upgrade must carry it: binding to 127.0.0.1 is not an
18
+ // authorization boundary, and WebSockets ignore the same-origin policy.
19
+ const AUTH_TOKEN =
20
+ document.querySelector('meta[name="noskills-token"]')?.content ?? "";
21
+
22
+ // fetch wrapper that attaches the token to anything that is not a plain read.
23
+ const authedFetch = (url, init = {}) => {
24
+ const method = (init.method ?? "GET").toUpperCase();
25
+ if (method === "GET" || method === "HEAD") {
26
+ return fetch(url, init);
27
+ }
28
+ return fetch(url, {
29
+ ...init,
30
+ headers: { ...(init.headers ?? {}), "x-noskills-token": AUTH_TOKEN },
31
+ });
32
+ };
33
+
34
+ // ── SSE — dashboard event stream ──────────────────────────────────────────
35
+ const events = new EventSource("/events");
36
+ events.onmessage = (e) => {
37
+ try {
38
+ const event = JSON.parse(e.data);
39
+ if (
40
+ event.type === "phase-change" ||
41
+ event.type === "spec-created" ||
42
+ event.type === "task-completed"
43
+ ) {
44
+ refreshSpecList();
45
+ }
46
+ } catch {
47
+ // ignore malformed events
48
+ }
49
+ };
50
+ events.onerror = () => {
51
+ /* EventSource auto-reconnects */
52
+ };
53
+
54
+ async function refreshSpecList() {
55
+ try {
56
+ const res = await fetch("/api/state");
57
+ const state = await res.json();
58
+ if (
59
+ document.querySelector(".spec-list") !== null &&
60
+ Array.isArray(state.specs)
61
+ ) {
62
+ location.reload();
63
+ }
64
+ } catch {
65
+ // ignore — SSE will retry
66
+ }
67
+ }
68
+
69
+ // ── Mux renderer + WebSocket transport ────────────────────────────────────
70
+ const root = document.getElementById("terminal-container");
71
+ let ws = null;
72
+ let renderer = null;
73
+ let reconnectTimer = null;
74
+
75
+ function send(frame) {
76
+ if (ws !== null && ws.readyState === WebSocket.OPEN) {
77
+ ws.send(JSON.stringify(frame));
78
+ }
79
+ }
80
+
81
+ function connect() {
82
+ // The spec detail page has no terminal: no container, no xterm.
83
+ const { MuxRender, Terminal } = globalThis;
84
+ if (root === null || Terminal === undefined || MuxRender === undefined) {
85
+ return;
86
+ }
87
+
88
+ if (renderer === null) {
89
+ const cell = MuxRender.measureCell(
90
+ MuxRender.FONT_FAMILY,
91
+ MuxRender.FONT_SIZE_PX,
92
+ );
93
+ renderer = MuxRender.createRenderer({
94
+ root,
95
+ cell,
96
+ send,
97
+ tabBar: document.querySelector(".tab-bar"),
98
+ });
99
+ }
100
+
101
+ const proto = location.protocol === "https:" ? "wss:" : "ws:";
102
+ ws = new WebSocket(
103
+ `${proto}//${location.host}/mux?token=${encodeURIComponent(AUTH_TOKEN)}`,
104
+ );
105
+
106
+ ws.onopen = () => send({ t: "attach", viewport: renderer.viewport() });
107
+ ws.onmessage = (ev) => {
108
+ let frame;
109
+ try {
110
+ frame = JSON.parse(ev.data);
111
+ } catch {
112
+ return;
113
+ }
114
+ renderer.applyFrame(frame);
115
+ };
116
+ ws.onclose = () => {
117
+ if (reconnectTimer === null) {
118
+ reconnectTimer = setTimeout(() => {
119
+ reconnectTimer = null;
120
+ connect();
121
+ }, 1000);
122
+ }
123
+ };
124
+ ws.onerror = () => {
125
+ /* close handler retries */
126
+ };
127
+ }
128
+
129
+ // The result of a spec action. The action routes answer JSON, but the guard
130
+ // in front of them answers a refusal in plain text ("Forbidden: missing or
131
+ // invalid token"), and so may a proxy; such a body becomes the error.
132
+ async function readActionResult(res) {
133
+ const text = await res.text();
134
+ try {
135
+ const parsed = JSON.parse(text);
136
+ if (parsed !== null && typeof parsed === "object") return parsed;
137
+ } catch {
138
+ // Not JSON: a plain-text answer.
139
+ }
140
+ const reason = text.trim() !== "" ? text.trim() : res.statusText;
141
+ return { ok: false, error: `${reason} (HTTP ${res.status})` };
142
+ }
143
+
144
+ // ── Click delegation: tab switch (mux), tab add/close (REST), spec CTAs ────
145
+ document.addEventListener("click", async (e) => {
146
+ const target = e.target;
147
+
148
+ // Each tab is a select button and a close button side by side, so both
149
+ // take keyboard focus; Enter and Space on a button arrive here as a click.
150
+ const closeButton = target.closest(".tab-close");
151
+ if (closeButton !== null && closeButton.dataset.close !== undefined) {
152
+ await authedFetch(`/api/tab/${closeButton.dataset.close}`, {
153
+ method: "DELETE",
154
+ });
155
+ return;
156
+ }
157
+
158
+ const tabButton = target.closest(".tab-select");
159
+ if (tabButton !== null && tabButton.dataset.index !== undefined) {
160
+ send({
161
+ t: "action",
162
+ action: { type: "gotoTab", index: Number(tabButton.dataset.index) },
163
+ });
164
+ return;
165
+ }
166
+
167
+ if (target.closest("#add-tab") !== null) {
168
+ await authedFetch("/api/tab", {
169
+ method: "POST",
170
+ headers: { "content-type": "application/json" },
171
+ body: JSON.stringify({}),
172
+ });
173
+ return;
174
+ }
175
+
176
+ if (target.classList.contains("cta-btn")) {
177
+ const spec = target.dataset.spec;
178
+ const action = target.dataset.action;
179
+ if (
180
+ spec === undefined ||
181
+ spec === "" ||
182
+ action === undefined ||
183
+ action === ""
184
+ ) {
185
+ return;
186
+ }
187
+
188
+ let body = {};
189
+ if (action === "note" || action === "question") {
190
+ const text = prompt(
191
+ action === "note" ? "Add a note:" : "Ask a question:",
192
+ );
193
+ // null is a cancelled prompt; an empty answer is not worth sending.
194
+ if (text === null || text === "") return;
195
+ body = { text };
196
+ }
197
+ if (action === "reply") {
198
+ const text = prompt("Your reply:");
199
+ if (text === null || text === "") return;
200
+ // Dashboard mentions carry data-mention-id, spec questions
201
+ // data-question-id; both name the thread the reply belongs to.
202
+ const mentionId =
203
+ target.dataset.mentionId ?? target.dataset.questionId ?? "";
204
+ body = { text, mentionId };
205
+ }
206
+
207
+ let result;
208
+ try {
209
+ const res = await authedFetch(`/api/spec/${spec}/${action}`, {
210
+ method: "POST",
211
+ headers: { "content-type": "application/json" },
212
+ body: JSON.stringify(body),
213
+ });
214
+ result = await readActionResult(res);
215
+ } catch {
216
+ alert("Action failed: the noskills web server did not answer");
217
+ return;
218
+ }
219
+ if (result.ok === true) {
220
+ location.reload();
221
+ return;
222
+ }
223
+ // A fault carries the request id that its record in the server log has.
224
+ const reference =
225
+ typeof result.requestId === "string"
226
+ ? ` (request ${result.requestId} in the noskills web log)`
227
+ : "";
228
+ alert(`Action failed: ${result.error ?? "Unknown error"}${reference}`);
229
+ return;
230
+ }
231
+ });
232
+
233
+ // ── Resize → recompute grid and tell the server ───────────────────────────
234
+ let resizeTimer = null;
235
+ globalThis.addEventListener("resize", () => {
236
+ if (resizeTimer !== null) clearTimeout(resizeTimer);
237
+ resizeTimer = setTimeout(() => {
238
+ resizeTimer = null;
239
+ if (renderer !== null) {
240
+ send({ t: "resize", viewport: renderer.viewport() });
241
+ }
242
+ }, 150);
243
+ });
244
+
245
+ // ── Boot ──────────────────────────────────────────────────────────────────
246
+ connect();
247
+
248
+ fetch("/api/state")
249
+ .then((r) => r.json())
250
+ .then((state) => {
251
+ const el = document.getElementById("user-info");
252
+ if (el !== null && typeof state.currentUser?.name === "string") {
253
+ el.textContent = state.currentUser.name;
254
+ }
255
+ })
256
+ .catch(() => {});
257
+ })();
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
2
+ <rect width="512" height="512" rx="96" fill="#7c3aed" />
3
+ <text
4
+ x="256"
5
+ y="320"
6
+ font-family="monospace,system-ui"
7
+ font-size="220"
8
+ font-weight="bold"
9
+ text-anchor="middle"
10
+ fill="#f5f3ff"
11
+ >ns</text>
12
+ </svg>
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "noskills",
3
+ "short_name": "noskills",
4
+ "description": "noskills-server — persistent Claude Code sessions that survive reboots",
5
+ "start_url": "/",
6
+ "display": "standalone",
7
+ "background_color": "#0f172a",
8
+ "theme_color": "#7c3aed",
9
+ "icons": [
10
+ {
11
+ "src": "/static/icons/icon.svg",
12
+ "sizes": "any",
13
+ "type": "image/svg+xml",
14
+ "purpose": "any maskable"
15
+ }
16
+ ]
17
+ }