@zmskco/dsh-notebook 0.0.0-stage → 0.1.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/lib/config.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Plugin configuration: validation and defaults.
3
+ *
4
+ * The plugin exports no `Config` schema, because the schema DSL lives in a DSH
5
+ * package this out-of-checkout bundle does not depend on. Configuration that a
6
+ * profile patch supplies therefore arrives unvalidated, and this module is the
7
+ * replacement: every field is checked once at activation and either accepted or
8
+ * replaced with a default, with a warning naming the field.
9
+ */
10
+ import { isAbsolute, join, resolve } from 'node:path';
11
+ function optionalString(value) {
12
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
13
+ }
14
+ /**
15
+ * Resolve the effective configuration.
16
+ * @param raw - the row's `config`, or `undefined` when the row declared none.
17
+ * @param fallbackRoot - default root, already derived from the sandbox boundary.
18
+ * @param warn - sink for rejected fields; the caller supplies the plugin logger.
19
+ * @param workspaceRoot - the sandbox's `workspace-write` boundary, when known.
20
+ * A **relative** `rootDir` resolves against it, so `rootDir: notes` lands
21
+ * inside the one directory the sandbox is guaranteed to permit. Without a
22
+ * boundary a relative path falls back to resolving against `process.cwd()`.
23
+ * @returns the validated configuration.
24
+ */
25
+ export function resolveConfig(raw, fallbackRoot, warn, workspaceRoot) {
26
+ const input = typeof raw === 'object' && raw !== null ? raw : {};
27
+ const configured = optionalString(input.rootDir);
28
+ let rootDir = fallbackRoot;
29
+ let rootDirOverride = false;
30
+ if (configured !== null) {
31
+ rootDirOverride = true;
32
+ if (isAbsolute(configured))
33
+ rootDir = configured;
34
+ else if (workspaceRoot !== undefined && workspaceRoot.length > 0)
35
+ rootDir = join(workspaceRoot, configured);
36
+ else
37
+ rootDir = resolve(configured);
38
+ }
39
+ else if (input.rootDir !== undefined) {
40
+ warn(`rootDir must be a non-empty string; received ${JSON.stringify(input.rootDir)}, using the workspace`);
41
+ }
42
+ return { rootDir, rootDirOverride };
43
+ }
package/lib/dsh.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ export class NotebookError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.name = 'NotebookError';
6
+ this.code = code;
7
+ }
8
+ }
9
+ /**
10
+ * Narrow an unknown rejection into a `NotebookError`.
11
+ * @param error - the caught value.
12
+ * @param fallback - message used when the value carries no usable text.
13
+ * @returns the value itself when it already is a `NotebookError`, else a wrapped one.
14
+ */
15
+ export function asNotebookError(error, fallback = 'unexpected failure') {
16
+ if (error instanceof NotebookError)
17
+ return error;
18
+ const message = error instanceof Error && error.message.length > 0 ? error.message : fallback;
19
+ return new NotebookError('internal', message);
20
+ }
@@ -0,0 +1,179 @@
1
+ import { NotebookError, asNotebookError } from '../errors.js';
2
+ import { assertPathName, assertRelativePath } from '../story/paths.js';
3
+ import { assessWriteAccess, writeAccessGuidance } from '../story/sandbox.js';
4
+ import { WORKSPACE_PROJECT } from '../story/project.js';
5
+ import { workspaceDirFor, workspaceStore } from '../story/workspace.js';
6
+ import { revealCommand, revealInFileManager } from './reveal.js';
7
+ import { workspaceReadme } from '../story/readme.js';
8
+ import { STATUS_BY_CODE } from './status.js';
9
+ /** The one path this plugin claims on the Connection Fetch registry. */
10
+ export const API_PATH = '/api/notebook';
11
+ function json(body, status = 200) {
12
+ return new Response(JSON.stringify(body), {
13
+ status,
14
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
15
+ });
16
+ }
17
+ function failure(error) {
18
+ const notebookError = asNotebookError(error);
19
+ const body = { code: notebookError.code, message: notebookError.message };
20
+ return json(body, STATUS_BY_CODE[notebookError.code]);
21
+ }
22
+ /**
23
+ * Read one JSON request body.
24
+ *
25
+ * A missing or malformed body is the caller's mistake and is reported as such,
26
+ * rather than surfacing as an opaque crash inside a handler.
27
+ * @param request - the incoming request.
28
+ * @returns the parsed object; an empty body reads as `{}`.
29
+ */
30
+ async function readBody(request) {
31
+ const text = await request.text();
32
+ if (text.trim().length === 0)
33
+ return {};
34
+ try {
35
+ const value = JSON.parse(text);
36
+ return typeof value === 'object' && value !== null ? value : {};
37
+ }
38
+ catch {
39
+ throw new NotebookError('bad-request', 'the request body is not JSON');
40
+ }
41
+ }
42
+ /**
43
+ * Register the control-plane route.
44
+ * @param deps - services and state the operations need.
45
+ * @returns the registration disposer.
46
+ */
47
+ export function registerApi(deps) {
48
+ const { connection, fs, roots, log, policy, focus } = deps;
49
+ const handle = async (request) => {
50
+ const url = new URL(request.url);
51
+ const op = url.searchParams.get('op') ?? '';
52
+ // One resolution for the whole request, so every branch below — and the
53
+ // failure path that explains a refusal — agrees on which directory is being
54
+ // talked about. The panel sends the Session it belongs to; a scripted caller
55
+ // may send none, and then the activation fallback applies.
56
+ const sessionId = url.searchParams.get('session') ?? undefined;
57
+ const { root, session } = roots(sessionId);
58
+ // The panel's directory column is rooted at the workspace itself.
59
+ const workspaceDir = workspaceDirFor(session, root.dir);
60
+ const workspace = workspaceStore({ fs, policy, log }, session, workspaceDir);
61
+ const open = async (name) => {
62
+ if (name === WORKSPACE_PROJECT)
63
+ return { store: workspace, project: await workspace.openRoot() };
64
+ throw new NotebookError('bad-request', 'this plugin serves the workspace itself; project must be ""');
65
+ };
66
+ const access = assessWriteAccess(workspaceDir, policy, session);
67
+ try {
68
+ switch (op) {
69
+ case 'state': {
70
+ return json({
71
+ rootDir: workspaceDir,
72
+ rootSource: root.source,
73
+ sandbox: {
74
+ mode: access.mode ?? null,
75
+ workspaceRoot: access.workspaceRoot ?? null,
76
+ writable: access.writable,
77
+ // Sending the text rather than a reason code keeps the one copy of
78
+ // the remedy on the half that knows the paths. `null` while the
79
+ // arrangement is the ordinary one: the workspace the operator opened.
80
+ guidance: writeAccessGuidance(workspaceDir, access),
81
+ },
82
+ });
83
+ }
84
+ case 'files': {
85
+ const { store, project } = await open(url.searchParams.get('project'));
86
+ return json({ project: project.id, files: await store.listFiles(project) });
87
+ }
88
+ case 'file': {
89
+ const { store, project } = await open(url.searchParams.get('project'));
90
+ return json(await store.readTextFile(project, url.searchParams.get('path') ?? ''));
91
+ }
92
+ case 'save-file': {
93
+ const body = await readBody(request);
94
+ const { store, project } = await open(body.project);
95
+ const path = assertRelativePath(typeof body.path === 'string' ? body.path : '');
96
+ const content = typeof body.content === 'string' ? body.content : '';
97
+ return json(await store.writeTextFile(project, path, content));
98
+ }
99
+ case 'create-dir': {
100
+ const body = await readBody(request);
101
+ const { store, project } = await open(body.project);
102
+ // One segment, not a path: the panel sends the directory it is aimed
103
+ // at separately, so a name carrying separators could only ever mean
104
+ // something other than what it looks like.
105
+ const name = assertPathName(body.name);
106
+ const dir = typeof body.dir === 'string' && body.dir.length > 0 ? assertRelativePath(body.dir) : '';
107
+ const path = dir === '' ? name : `${dir}/${name}`;
108
+ return json(await store.createDirectory(project, path), 201);
109
+ }
110
+ case 'create-file': {
111
+ const body = await readBody(request);
112
+ const { store, project } = await open(body.project);
113
+ const title = typeof body.title === 'string' && body.title.trim().length > 0 ? body.title : '未命名';
114
+ // The directory the author is browsing, sent by the panel. Without one,
115
+ // the workspace root is where the tree is.
116
+ const dir = typeof body.dir === 'string' && body.dir.length > 0 ? assertRelativePath(body.dir) : '';
117
+ // The name is kept exactly as typed: no `.md` the author did not ask
118
+ // for, and no second extension when the name has one. The heading is
119
+ // seeded only for prose names — a `.json` is not a document.
120
+ const name = assertPathName(title);
121
+ const extension = /\.[A-Za-z0-9]+$/.exec(name)?.[0].toLowerCase() ?? '';
122
+ const prose = extension === '' || extension === '.md' || extension === '.markdown';
123
+ const stem = extension === '' ? name : name.slice(0, -extension.length);
124
+ const path = await store.newNamedPath(project, dir, name);
125
+ return json(await store.writeTextFile(project, path, prose ? `# ${stem}\n\n` : ''), 201);
126
+ }
127
+ case 'focus': {
128
+ // The page's directory, made to matter to the model: the Session's
129
+ // working directory becomes the workspace the tree shows. No file is
130
+ // touched, so this is not a write op: a read-only deployment still gets
131
+ // it, and the model still reads the right directory.
132
+ const body = await readBody(request);
133
+ const { project } = await open(body.project);
134
+ const focused = await focus(sessionId, project.abs);
135
+ return json({ project: project.id, dir: project.abs, focused });
136
+ }
137
+ case 'reveal': {
138
+ // Show the workspace in the OS file manager. The directory is always the
139
+ // one this request resolved to; no path is ever taken from the client, so
140
+ // the panel cannot be talked into opening somewhere else. `dryRun` is the
141
+ // test hook: it answers what would be launched without launching it.
142
+ const body = await readBody(request);
143
+ if (body.dryRun === true) {
144
+ const launch = revealCommand(process.platform, workspaceDir);
145
+ return json({ dir: workspaceDir, command: launch.command, args: launch.args, opened: false });
146
+ }
147
+ const opened = await revealInFileManager(workspaceDir);
148
+ if (!opened)
149
+ log.warn(`cannot open a file manager for ${workspaceDir}`);
150
+ return json({ dir: workspaceDir, opened });
151
+ }
152
+ case 'ensure-readme': {
153
+ // The one file the panel adds to a workspace on first open. Never an
154
+ // overwrite: a workspace that already has a README keeps it, and the
155
+ // answer says so.
156
+ const { store, project } = await open(WORKSPACE_PROJECT);
157
+ const present = await store.readTextFile(project, 'README.md')
158
+ .then(() => true, () => false);
159
+ if (present)
160
+ return json({ path: 'README.md', created: false });
161
+ await store.writeTextFile(project, 'README.md', workspaceReadme());
162
+ return json({ path: 'README.md', created: true }, 201);
163
+ }
164
+ // Not in the write set: a reply touches nothing.
165
+ default:
166
+ return json({ code: 'bad-request', message: `unknown op ${JSON.stringify(op)}` }, 400);
167
+ }
168
+ }
169
+ catch (error) {
170
+ return failure(error);
171
+ }
172
+ };
173
+ return connection.fetch.register({
174
+ path: API_PATH,
175
+ methods: ['GET', 'POST'],
176
+ requestBody: 'buffered',
177
+ fetch: handle,
178
+ });
179
+ }
@@ -0,0 +1,187 @@
1
+ import { NotebookError, asNotebookError } from '../errors.js';
2
+ import { assertRelativePath, assertStoryName } from '../story/paths.js';
3
+ import { statusFor } from './status.js';
4
+ /** Mount point of this plugin's media route. */
5
+ export const MEDIA_PREFIX = '/notebook/media';
6
+ /** Byte ranges above this size are streamed in chunks instead of buffered. */
7
+ const STREAM_THRESHOLD = 4 * 1024 * 1024;
8
+ const CHUNK_SIZE = 1024 * 1024;
9
+ /** Hard cap for one un-ranged response; larger files must be ranged. */
10
+ const MAX_BUFFERED = 64 * 1024 * 1024;
11
+ const CONTENT_TYPES = {
12
+ '.png': 'image/png',
13
+ '.jpg': 'image/jpeg',
14
+ '.jpeg': 'image/jpeg',
15
+ '.webp': 'image/webp',
16
+ '.gif': 'image/gif',
17
+ '.mp4': 'video/mp4',
18
+ '.webm': 'video/webm',
19
+ '.json': 'application/json; charset=utf-8',
20
+ '.md': 'text/markdown; charset=utf-8',
21
+ '.txt': 'text/plain; charset=utf-8',
22
+ };
23
+ function contentTypeFor(path) {
24
+ const dot = path.lastIndexOf('.');
25
+ const extension = dot < 0 ? '' : path.slice(dot).toLowerCase();
26
+ return CONTENT_TYPES[extension] ?? 'application/octet-stream';
27
+ }
28
+ function sendJson(res, status, body) {
29
+ const text = JSON.stringify(body);
30
+ res.statusCode = status;
31
+ res.setHeader('content-type', 'application/json; charset=utf-8');
32
+ res.setHeader('content-length', Buffer.byteLength(text));
33
+ res.end(text);
34
+ }
35
+ /**
36
+ * Parse a single-range `Range` header.
37
+ * @param header - the raw header value.
38
+ * @param size - the resource size.
39
+ * @returns the range, or `null` when the header is unsatisfiable.
40
+ */
41
+ function parseRange(header, size) {
42
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
43
+ if (match === null)
44
+ return null;
45
+ const rawStart = match[1] ?? '';
46
+ const rawEnd = match[2] ?? '';
47
+ if (rawStart.length === 0 && rawEnd.length === 0)
48
+ return null;
49
+ if (rawStart.length === 0) {
50
+ // Suffix form: the last N bytes.
51
+ const length = Number(rawEnd);
52
+ if (!Number.isFinite(length) || length <= 0 || size === 0)
53
+ return null;
54
+ return { start: Math.max(0, size - length), end: size - 1 };
55
+ }
56
+ const start = Number(rawStart);
57
+ if (!Number.isFinite(start) || start >= size)
58
+ return null;
59
+ const end = rawEnd.length === 0 ? size - 1 : Math.min(Number(rawEnd), size - 1);
60
+ if (!Number.isFinite(end) || end < start)
61
+ return null;
62
+ return { start, end };
63
+ }
64
+ /** Write one buffer, waiting for drain when the socket is saturated. */
65
+ async function writeChunk(res, chunk) {
66
+ if (res.write(chunk))
67
+ return;
68
+ await new Promise((resolve, reject) => {
69
+ const cleanup = () => {
70
+ res.off('drain', onDrain);
71
+ res.off('close', onClose);
72
+ };
73
+ function onDrain() { cleanup(); resolve(); }
74
+ function onClose() { cleanup(); reject(new NotebookError('internal', 'client closed the connection')); }
75
+ res.on('drain', onDrain);
76
+ res.on('close', onClose);
77
+ });
78
+ }
79
+ /**
80
+ * Register the media route on the HTTP carrier.
81
+ * @param deps - carrier, filesystem, trust fence, store and logger.
82
+ * @returns the route disposer.
83
+ */
84
+ export function registerMediaRoute(deps) {
85
+ const { webServer, fs, connection, roots, log } = deps;
86
+ const handle = async (req, res) => {
87
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
88
+ res.setHeader('allow', 'GET, HEAD');
89
+ res.statusCode = 405;
90
+ res.end();
91
+ return;
92
+ }
93
+ const url = new URL(String(req.url), 'http://localhost');
94
+ const pathname = url.pathname;
95
+ const rest = decodeURIComponent(pathname.slice(MEDIA_PREFIX.length).replace(/^\//, ''));
96
+ const segments = rest.split('/');
97
+ const rawProject = segments[0];
98
+ const rawFile = segments.slice(1);
99
+ if (rawProject === undefined || rawFile.length === 0) {
100
+ sendJson(res, 400, { code: 'bad-request', message: `expected ${MEDIA_PREFIX}/<project>/<path>` });
101
+ return;
102
+ }
103
+ const projectId = assertStoryName(rawProject);
104
+ const rel = assertRelativePath(rawFile.join('/'));
105
+ // The image URL carries the Session whose workspace holds this project, for
106
+ // the same reason every other route does: the story root is per workspace.
107
+ const { store } = roots(url.searchParams.get('session') ?? undefined);
108
+ const project = await store.open(projectId);
109
+ const target = await store.resolveInside(project, rel);
110
+ const info = await fs.stat(target);
111
+ if (info === undefined || info.type !== 'file') {
112
+ sendJson(res, 404, { code: 'not-found', message: `${rel} does not exist in project ${projectId}` });
113
+ return;
114
+ }
115
+ const size = info.size ?? 0;
116
+ res.setHeader('content-type', contentTypeFor(rel));
117
+ res.setHeader('accept-ranges', 'bytes');
118
+ res.setHeader('cache-control', 'no-cache');
119
+ res.setHeader('etag', `"${info.version}"`);
120
+ if (req.headers['if-none-match'] === `"${info.version}"`) {
121
+ res.statusCode = 304;
122
+ res.end();
123
+ return;
124
+ }
125
+ const rangeHeader = req.headers.range;
126
+ const hasRange = typeof rangeHeader === 'string' && rangeHeader.length > 0;
127
+ const range = hasRange ? parseRange(rangeHeader, size) : null;
128
+ if (hasRange && range === null) {
129
+ res.statusCode = 416;
130
+ res.setHeader('content-range', `bytes */${String(size)}`);
131
+ res.end();
132
+ return;
133
+ }
134
+ const start = range?.start ?? 0;
135
+ const end = range?.end ?? size - 1;
136
+ const length = Math.max(0, end - start + 1);
137
+ if (range !== null) {
138
+ res.statusCode = 206;
139
+ res.setHeader('content-range', `bytes ${String(start)}-${String(end)}/${String(size)}`);
140
+ }
141
+ else if (length > MAX_BUFFERED) {
142
+ // Refuse rather than exhaust memory; a well-behaved client ranges.
143
+ sendJson(res, 413, { code: 'bad-request', message: `${rel} is ${String(size)} bytes; request a byte range` });
144
+ return;
145
+ }
146
+ else {
147
+ res.statusCode = 200;
148
+ }
149
+ res.setHeader('content-length', String(length));
150
+ if (req.method === 'HEAD' || length === 0) {
151
+ res.end();
152
+ return;
153
+ }
154
+ if (length <= STREAM_THRESHOLD) {
155
+ res.end(Buffer.from(await fs.readByteRange(target, { offset: start, length })));
156
+ return;
157
+ }
158
+ for (let offset = start; offset <= end; offset += CHUNK_SIZE) {
159
+ const take = Math.min(CHUNK_SIZE, end - offset + 1);
160
+ await writeChunk(res, await fs.readByteRange(target, { offset, length: take }));
161
+ }
162
+ res.end();
163
+ };
164
+ return webServer.register({
165
+ kind: 'prefix',
166
+ path: MEDIA_PREFIX,
167
+ handler: (req, res) => {
168
+ const rejection = connection.requestRejection({ headers: req.headers });
169
+ if (rejection !== undefined) {
170
+ res.statusCode = rejection;
171
+ res.end();
172
+ return;
173
+ }
174
+ void handle(req, res).catch((error) => {
175
+ const failure = asNotebookError(error);
176
+ log.warn('notebook: media request failed', failure);
177
+ if (res.headersSent)
178
+ res.end();
179
+ else
180
+ sendJson(res, statusFor(failure.code), {
181
+ code: failure.code,
182
+ message: failure.message,
183
+ });
184
+ });
185
+ },
186
+ });
187
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Show the workspace in the operating system's file manager.
3
+ *
4
+ * The directory column is a *view* of the workspace, and the browser cannot open
5
+ * a local folder — so "show me the real folder" is the one thing the page has to
6
+ * ask the Host for. The directory is always the workspace that request resolved
7
+ * to: nothing here takes a path from the client, so the panel can never be talked
8
+ * into opening somewhere else.
9
+ *
10
+ * On Windows the launch goes through **`cmd /c start`**, not `explorer.exe`
11
+ * directly, and the child is **not** started hidden. Both halves were measured:
12
+ * spawning `explorer.exe` starts a process that exits without ever showing a
13
+ * window, and a hidden show-state (`windowsHide`, `-WindowStyle Hidden`) is
14
+ * inherited by the window ShellExecute creates, so the folder opens invisibly.
15
+ * `cmd /c start` with the default show state uses ShellExecute, and the
16
+ * already-running Explorer opens a window the author can see.
17
+ *
18
+ * @module notebook/http/reveal
19
+ */
20
+ import { spawn } from 'node:child_process';
21
+ /**
22
+ * The command that opens one directory on a platform.
23
+ *
24
+ * Exported for the test that asserts the mapping without launching anything: a
25
+ * test suite that opens windows on the machine running it is not a test.
26
+ * @param platform - `process.platform`.
27
+ * @param dir - an absolute directory path.
28
+ * @returns what to launch.
29
+ */
30
+ export function revealCommand(platform, dir) {
31
+ if (platform === 'win32') {
32
+ // ShellExecute through `start`: the empty argument is the window title slot,
33
+ // which `start` requires before a quoted target.
34
+ return {
35
+ command: process.env.ComSpec ?? 'cmd.exe',
36
+ args: ['/c', `start "" "${dir}"`],
37
+ verbatim: true,
38
+ };
39
+ }
40
+ if (platform === 'darwin')
41
+ return { command: 'open', args: [dir], verbatim: false };
42
+ return { command: 'xdg-open', args: [dir], verbatim: false };
43
+ }
44
+ /**
45
+ * Launch the platform's file manager on a directory.
46
+ * @param dir - an absolute directory path.
47
+ * @returns whether the launcher was started; `false` means it was not.
48
+ */
49
+ export function revealInFileManager(dir) {
50
+ const launch = revealCommand(process.platform, dir);
51
+ return new Promise((resolve) => {
52
+ try {
53
+ const child = spawn(launch.command, launch.args, {
54
+ detached: true,
55
+ stdio: 'ignore',
56
+ // No `windowsHide`: it would be inherited by the Explorer window this
57
+ // launches, which then opens invisibly. The child inherits this process's
58
+ // console, so there is no console flash to hide either.
59
+ windowsVerbatimArguments: launch.verbatim,
60
+ });
61
+ child.on('error', () => { resolve(false); });
62
+ child.on('spawn', () => { child.unref(); resolve(true); });
63
+ }
64
+ catch {
65
+ resolve(false);
66
+ }
67
+ });
68
+ }
@@ -0,0 +1,15 @@
1
+ export const STATUS_BY_CODE = {
2
+ 'bad-request': 400,
3
+ forbidden: 403,
4
+ 'not-found': 404,
5
+ conflict: 409,
6
+ internal: 500,
7
+ };
8
+ /**
9
+ * The status for one error code, for a caller that already has the code.
10
+ * @param code - the failure's code.
11
+ * @returns the HTTP status to answer with.
12
+ */
13
+ export function statusFor(code) {
14
+ return STATUS_BY_CODE[code];
15
+ }
package/lib/index.js ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Host half of the 笔记本 (Notebook) bundle.
3
+ *
4
+ * Activation wires exactly one thing onto one owned effect, so unloading the
5
+ * plugin removes it: the authenticated JSON control plane. The client half is the
6
+ * panel; the files it edits are the workspace's own, and the harness's `read`/
7
+ * `write` tools already reach them.
8
+ *
9
+ * The three services this depends on are declared in `inject`, which is what
10
+ * keeps the plugin inactive — rather than broken — in a profile that has no web
11
+ * carrier.
12
+ */
13
+ import { defaultRootDir } from './story/bootstrap.js';
14
+ import { resolveConfig } from './config.js';
15
+ import { API_PATH, registerApi } from './http/api.js';
16
+ import { createRootResolver } from './story/root.js';
17
+ import { createFocus } from './story/focus.js';
18
+ import { assessWriteAccess, writeAccessGuidance } from './story/sandbox.js';
19
+ /**
20
+ * Services that must exist for this plugin to be useful.
21
+ *
22
+ * Nothing else is required, and nothing optional decides whether the panel
23
+ * works: the tree is rooted at the workspace the Session opened, so there is no
24
+ * directory to choose and no config row to write.
25
+ */
26
+ export const inject = ['fs', 'webServer', 'connection'];
27
+ /**
28
+ * Activate the plugin.
29
+ * @param ctx - the owning context; every registration below is an effect of it.
30
+ * @param rawConfig - the Loader row's `config`, unvalidated by design.
31
+ */
32
+ export function apply(ctx, rawConfig) {
33
+ const log = ctx.logger;
34
+ const policy = ctx.get('sandboxPolicy');
35
+ const config = resolveConfig(rawConfig, defaultRootDir(policy), (message) => { log.warn(`notebook: ${message}`); }, policy?.workspaceRoot);
36
+ // The root is resolved per call rather than here: it follows the workspace of
37
+ // the Session making the call, so one plugin instance serves every workspace in
38
+ // the profile instead of pinning one mutable root. See `root.ts` for the rule
39
+ // and the per-root write policy it stamps.
40
+ const roots = createRootResolver({ fs: ctx.fs, config, policy, agents: ctx.get('agents'), log });
41
+ const initialRoot = roots().root;
42
+ const access = assessWriteAccess(initialRoot.dir, policy);
43
+ // Puts the Session into the directory the panel shows, so the model's relative
44
+ // paths and the tree agree; see `story/focus.ts`.
45
+ const focus = createFocus({
46
+ agents: () => ctx.get('agents'),
47
+ workingDirectory: () => ctx.get('workingDirectory'),
48
+ log,
49
+ });
50
+ log.info(`notebook: root=${initialRoot.dir} (${initialRoot.source})`);
51
+ if (initialRoot.source === 'fallback') {
52
+ // A session-less activation. The panel and every call resolve their own root
53
+ // from the Session that made the call, so this fallback is what a scripted
54
+ // caller with no Session would see.
55
+ log.info(`notebook: no pinned root and no Session at activation; fallback root is ${initialRoot.dir}`);
56
+ }
57
+ if (policy === undefined) {
58
+ log.info('notebook: no sandbox-policy service in this profile; writes are unconfined');
59
+ }
60
+ else if (access.writable) {
61
+ // The boundary a write is checked against is the root of that call, not this
62
+ // deployment value: each write stamps `{ mode, workspaceRoot: <that root> }`
63
+ // (see `sandbox.ts`). The mode, though, is the Session's own.
64
+ log.info(`notebook: writes allowed (mode=${String(access.mode)}, boundary=each call's root)`);
65
+ if (access.reason === 'outside-workspace')
66
+ log.warn(`notebook: ${String(writeAccessGuidance(initialRoot.dir, access))}`);
67
+ }
68
+ else {
69
+ // Worth a warning rather than an error: the plugin still mounts and still
70
+ // reads, and the panel shows the same guidance with the exact YAML to paste.
71
+ log.warn(`notebook: deployment is read-only; every write will be refused\n${String(writeAccessGuidance(initialRoot.dir, access))}`);
72
+ }
73
+ ctx.effect(() => {
74
+ // Registration is synchronous; the returned disposer settles asynchronously
75
+ // because the Fetch bridge may be tearing down a live request.
76
+ const disposeApi = registerApi({
77
+ connection: ctx.connection,
78
+ fs: ctx.fs,
79
+ roots,
80
+ log,
81
+ policy,
82
+ focus,
83
+ });
84
+ return () => { void disposeApi(); };
85
+ }, 'notebook: api');
86
+ // Surfaced so the page can show the exact mount point it is talking to without
87
+ // hard-coding it a second time.
88
+ log.info(`notebook: api ${API_PATH}`);
89
+ }