dsh-pinwhy 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/viewer.js ADDED
@@ -0,0 +1,270 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import http from 'node:http';
4
+ import { pipeline } from 'node:stream';
5
+ import { bound, cliEnv } from './bridge.js';
6
+ import { PinwhyError } from './config.js';
7
+ import { selectScope } from './scope.js';
8
+
9
+ const PREFIX = '/pinwhy-viewer/';
10
+
11
+ /** One opaque node identity: never a path, so a read cannot be redirected to a file. */
12
+ function nodeIdentity(value) {
13
+ if (typeof value !== 'string' || !value || value !== value.trim() || value.includes('\0')
14
+ || /\s/.test(value) || /[\\/]/.test(value) || value === '.' || value === '..') {
15
+ throw new PinwhyError('INVALID_ARGUMENT', 'Expected one node identity, not a path.');
16
+ }
17
+ return value;
18
+ }
19
+
20
+ /** Exact-key object validation shared across viewer RPC handlers. */
21
+ function sessionPayload(payload, extraKeys = [], label = 'a Session identity') {
22
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
23
+ throw new PinwhyError('INVALID_ARGUMENT', `Expected ${label}.`);
24
+ }
25
+ const expected = ['sessionId', ...extraKeys];
26
+ const keys = Object.keys(payload);
27
+ if (keys.length !== expected.length || !expected.every(key => keys.includes(key))) {
28
+ throw new PinwhyError('INVALID_ARGUMENT', `Expected exactly ${label}.`);
29
+ }
30
+ if (typeof payload.sessionId !== 'string' || !payload.sessionId.trim() || payload.sessionId.includes('\0')) {
31
+ throw new PinwhyError('INVALID_ARGUMENT', 'Expected a Session identity.');
32
+ }
33
+ return payload;
34
+ }
35
+
36
+ /** `pinwhy/node.read` payloads are exact: a Session identity plus one node identity. */
37
+ function nodeReadPayload(payload) {
38
+ const { sessionId, nodeId } = sessionPayload(payload, ['nodeId'], 'a Session and one node identity');
39
+ return { sessionId, nodeId: nodeIdentity(nodeId) };
40
+ }
41
+
42
+ /** Validate the single JSON startup line emitted by `pinwhy serve --ephemeral --json`. */
43
+ function parseViewerReadyLine(line, boardRoot, basePath) {
44
+ try {
45
+ const value = JSON.parse(line);
46
+ const url = new URL(value.url);
47
+ if (value.schema !== 'pinwhy.viewer.v1' || value.cwd !== boardRoot || value.readOnly !== true
48
+ || url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || !url.port
49
+ || url.pathname !== basePath || url.search || url.hash || url.username || url.password) {
50
+ throw new Error('unexpected viewer identity');
51
+ }
52
+ return value.url;
53
+ } catch (cause) {
54
+ throw new PinwhyError('INVALID_JSON', 'The CLI did not return a valid read-only viewer address.', { cause });
55
+ }
56
+ }
57
+
58
+ /** One owned, read-only CLI process. A ready response never changes project configuration. */
59
+ function startViewer(config, runtime, scope, basePath) {
60
+ const child = spawn(config.nodeExecutable, [runtime.real, 'serve', `--cwd=${scope.boardRoot}`,
61
+ '--read-only', '--ephemeral', '--json', '--port=0', `--base-path=${basePath}`], {
62
+ cwd: scope.boardRoot, env: cliEnv(), shell: false, stdio: ['pipe', 'pipe', 'pipe'],
63
+ });
64
+ child.stdout.setEncoding('utf8');
65
+ child.stderr.setEncoding('utf8');
66
+ let alive = true, settled = false, bytes = 0, stdout = '', stderr = '', escalation;
67
+ let resolveReady, rejectReady;
68
+ const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; });
69
+ const closed = new Promise(resolve => child.once('close', () => { alive = false; clearTimeout(escalation); resolve(); }));
70
+ const stop = () => {
71
+ if (!alive) return closed;
72
+ child.kill('SIGTERM');
73
+ escalation ??= setTimeout(() => child.kill('SIGKILL'), 500);
74
+ escalation.unref();
75
+ return closed;
76
+ };
77
+ const settle = (fn, value) => {
78
+ if (settled) return;
79
+ settled = true;
80
+ clearTimeout(deadline);
81
+ fn(value);
82
+ };
83
+ const fail = error => { settle(rejectReady, error); void stop(); };
84
+ const deadline = setTimeout(() => fail(new PinwhyError('TIMEOUT', 'The read-only viewer did not become ready.')), config.timeoutMs);
85
+ child.once('error', cause => fail(new PinwhyError('SPAWN_FAILED', 'The viewer process could not start.', { cause })));
86
+ child.once('close', (code, signal) => settle(rejectReady, new PinwhyError('CLI_FAILED', `Viewer exited ${code ?? signal}: ${stderr.trim()}`)));
87
+ const collect = chunk => {
88
+ bytes += Buffer.byteLength(chunk);
89
+ if (bytes > config.maxOutputBytes) { fail(new PinwhyError('OUTPUT_LIMIT', 'The viewer startup output exceeded its limit.')); return false; }
90
+ return true;
91
+ };
92
+ child.stderr.on('data', chunk => { if (collect(chunk)) stderr += chunk; });
93
+ child.stdout.on('data', chunk => {
94
+ if (!collect(chunk) || settled) return;
95
+ stdout += chunk;
96
+ const newline = stdout.indexOf('\n');
97
+ if (newline < 0) return;
98
+ try { settle(resolveReady, parseViewerReadyLine(stdout.slice(0, newline), scope.boardRoot, basePath)); }
99
+ catch (error) { fail(error); }
100
+ });
101
+ return { ready, stop, get alive() { return alive; } };
102
+ }
103
+
104
+ /** Host-owned viewer processes are isolated by Session and discarded with their lifecycle. */
105
+ export class ViewerSessions {
106
+ #entries = new Map();
107
+ #disposed = false;
108
+ constructor(config, bridge, session) { this.config = config; this.bridge = bridge; this.session = session; }
109
+
110
+ #assertActive(sessionId, signal, missingMessage = 'Open a live project Session before opening its board.') {
111
+ if (this.#disposed) throw new PinwhyError('DISPOSED', 'The viewer adapter has unloaded.');
112
+ signal?.throwIfAborted();
113
+ const session = this.session(sessionId);
114
+ if (!session) throw new PinwhyError('SESSION_REQUIRED', missingMessage);
115
+ return session;
116
+ }
117
+
118
+ async #binding(sessionId, signal) {
119
+ const session = this.#assertActive(sessionId, signal);
120
+ const config = this.config();
121
+ const scope = await selectScope(config, { agent: { session }, signal });
122
+ return { config, scope };
123
+ }
124
+
125
+ async open(sessionId, signal) {
126
+ const { config, scope } = await this.#binding(sessionId, signal);
127
+ const runtime = await this.bridge.runtime(config);
128
+ if (runtime.capabilities.features?.ephemeralViewer !== true
129
+ || runtime.capabilities.outputs?.serve?.schema !== 'pinwhy.viewer.v1') {
130
+ throw new PinwhyError('RUNTIME_INCOMPATIBLE', 'Upgrade Pinwhy to a runtime providing the ephemeral read-only Web viewer.');
131
+ }
132
+ this.#assertActive(sessionId, signal);
133
+ const key = JSON.stringify([scope.boardRoot, config.nodeExecutable, runtime.real, config.timeoutMs, config.maxOutputBytes]);
134
+ let entry = this.#entries.get(sessionId);
135
+ if (entry && (entry.key !== key || !entry.process.alive)) {
136
+ this.#entries.delete(sessionId);
137
+ await entry.process.stop();
138
+ entry = undefined;
139
+ }
140
+ // Recheck after stopping an obsolete process: another opener may have won the slot.
141
+ this.#assertActive(sessionId, signal, 'The Session closed while opening its board.');
142
+ entry ??= this.#entries.get(sessionId);
143
+ if (!entry) {
144
+ const viewerId = randomUUID(), basePath = `${PREFIX}${viewerId}/`;
145
+ const process = startViewer(config, runtime, scope, basePath);
146
+ entry = { key, scope, viewerId, basePath, process, sessionId };
147
+ this.#entries.set(sessionId, entry);
148
+ process.ready.catch(() => { if (this.#entries.get(sessionId) === entry) this.#entries.delete(sessionId); });
149
+ }
150
+ const url = await entry.process.ready;
151
+ signal?.throwIfAborted();
152
+ if (this.#disposed || this.#entries.get(sessionId) !== entry) throw new PinwhyError('DISPOSED', 'The viewer Session has closed.');
153
+ return { url, boardRoot: scope.boardRoot, agentId: scope.agentId, viewerId: entry.viewerId };
154
+ }
155
+
156
+ /** Re-read one canonical CLI record; no cursor, init, write or viewer process is involved. */
157
+ async readNode(sessionId, nodeId, signal) {
158
+ const { config, scope } = await this.#binding(sessionId, signal);
159
+ // `show` is the CLI's canonical node-get contract. It is board-scoped but not
160
+ // cursor-aware, so `path` binds only --cwd (the command has no --agent option).
161
+ const argv = bound(['show', '--json', '--', nodeId], scope, 'path');
162
+ const { boardRoot, agentId, data } = await this.bridge.run(scope, argv, signal, undefined, config);
163
+ const node = data?.node;
164
+ if (!node || typeof node !== 'object' || Array.isArray(node)
165
+ || typeof node.id !== 'string' || !node.id.trim() || node.id.includes('\0')
166
+ || typeof node.title !== 'string' || !node.title.trim()) {
167
+ throw new PinwhyError('CLI_FAILED', 'The CLI did not return one canonical node record.');
168
+ }
169
+ return { boardRoot, agentId, node };
170
+ }
171
+
172
+ async resolve(pathname, signal) {
173
+ const entry = [...this.#entries.values()].find(item => pathname.startsWith(item.basePath));
174
+ if (!entry || !entry.process.alive) throw new PinwhyError('VIEWER_MISSING', 'Reopen the board to start its viewer.');
175
+ const { scope } = await this.#binding(entry.sessionId, signal);
176
+ if (scope.boardRoot !== entry.scope.boardRoot) throw new PinwhyError('NOT_ENABLED', 'The Session board binding has changed. Reopen the board.');
177
+ const url = await entry.process.ready;
178
+ return new URL(url).origin;
179
+ }
180
+
181
+ async closeSession(sessionId) {
182
+ const entry = this.#entries.get(sessionId);
183
+ this.#entries.delete(sessionId);
184
+ await entry?.process.stop();
185
+ }
186
+
187
+ async dispose() {
188
+ this.#disposed = true;
189
+ const entries = [...this.#entries.values()];
190
+ this.#entries.clear();
191
+ await Promise.all(entries.map(entry => entry.process.stop()));
192
+ }
193
+ }
194
+
195
+ /** Authenticated Web transport uses the same prefix as the native loopback viewer. */
196
+ function proxyViewer(ctx, viewers, req, res) {
197
+ const admission = ctx.connection.admit(req);
198
+ if ('rejection' in admission || admission.peer.principal.kind !== 'owner') {
199
+ res.writeHead('rejection' in admission ? admission.rejection : 403); res.end(); return;
200
+ }
201
+ if (!['GET', 'HEAD'].includes(req.method)) { res.writeHead(405, { Allow: 'GET, HEAD' }); res.end(); return; }
202
+ const abort = new AbortController();
203
+ res.once('close', () => abort.abort());
204
+ const url = new URL(req.url, 'http://viewer.invalid');
205
+ viewers.resolve(url.pathname, abort.signal).then(origin => {
206
+ if (abort.signal.aborted) return;
207
+ const upstream = http.request(new URL(url.pathname + url.search, origin), {
208
+ method: req.method, signal: abort.signal, headers: { accept: req.headers.accept ?? '*/*' },
209
+ }, response => {
210
+ // Do not forward cookies or grant cross-origin access; this stays inside the authenticated Host.
211
+ const headers = {};
212
+ for (const key of ['content-type', 'cache-control']) if (response.headers[key]) headers[key] = response.headers[key];
213
+ res.writeHead(response.statusCode ?? 502, headers);
214
+ pipeline(response, res, () => { /* client/upstream close handled by stream events */ });
215
+ });
216
+ upstream.on('error', () => { if (!res.headersSent) res.writeHead(502); res.end(); });
217
+ upstream.end();
218
+ }).catch(error => {
219
+ if (abort.signal.aborted) return;
220
+ res.writeHead(error.code === 'VIEWER_MISSING' ? 410 : 403, { 'Content-Type': 'text/plain; charset=utf-8' });
221
+ res.end(error.message);
222
+ });
223
+ }
224
+
225
+ /**
226
+ * Exact Fetch RPC: one `client-request` envelope on Web and native carriers.
227
+ * A malformed envelope is a transport error; handling failures stay inside `result`.
228
+ */
229
+ function registerRpc(ctx, path, method, failureCode, handle) {
230
+ ctx.effect(() => ctx.connection.fetch.register({
231
+ path, methods: ['POST'], requestBody: 'buffered',
232
+ async fetch(request) {
233
+ let message;
234
+ try { message = await request.json(); } catch { return new Response('Invalid JSON envelope', { status: 400 }); }
235
+ if (message?.type !== 'client-request' || typeof message.rpcId !== 'string' || message.method !== method) {
236
+ return new Response('Invalid RPC envelope', { status: 400 });
237
+ }
238
+ let result;
239
+ try { result = { ok: true, value: await handle(message.payload, request) }; }
240
+ catch (error) { result = { ok: false, error: { code: error.code ?? failureCode, message: error.message, details: {} } }; }
241
+ return Response.json({ type: 'server-response', rpcId: message.rpcId, result });
242
+ },
243
+ }));
244
+ }
245
+
246
+ /** Add GUI support optionally: headless tools and Skills have no viewer dependency. */
247
+ export function mountViewer(ctx, config, bridge) {
248
+ const viewers = new ViewerSessions(config, bridge, id => ctx.sessions.get(id));
249
+ ctx.effect(() => () => viewers.dispose());
250
+ ctx.effect(() => ctx.on('session/disposed', session => { void viewers.closeSession(session.id); }));
251
+ // Exact Fetch routes use the Host's owner admission on Web and native carriers.
252
+ registerRpc(ctx, '/api/pinwhy/viewer.open', 'pinwhy/viewer.open', 'VIEWER_FAILED', async (payload, request) => {
253
+ const { sessionId } = sessionPayload(payload);
254
+ const value = await viewers.open(sessionId, request.signal);
255
+ const url = new URL(value.url);
256
+ url.searchParams.set('agent', value.agentId);
257
+ url.searchParams.set('view', 'logic');
258
+ url.searchParams.set('embed', '1');
259
+ value.url = ctx.get('webServer') ? url.pathname + url.search : url.href;
260
+ return value;
261
+ });
262
+ // The board may hand a node identity to the Host; the record itself is re-read from the CLI.
263
+ registerRpc(ctx, '/api/pinwhy/node.read', 'pinwhy/node.read', 'NODE_READ_FAILED', async (payload, request) => {
264
+ const { sessionId, nodeId } = nodeReadPayload(payload);
265
+ return viewers.readNode(sessionId, nodeId, request.signal);
266
+ });
267
+ ctx.inject(['webServer'], web => {
268
+ web.effect(() => web.webServer.register({ kind: 'prefix', path: PREFIX.slice(0, -1), handler: (req, res) => proxyViewer(ctx, viewers, req, res) }));
269
+ });
270
+ }