@zmskco/dsh-notebook 0.1.0 → 0.2.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/http/api.js CHANGED
@@ -2,7 +2,7 @@ import { NotebookError, asNotebookError } from '../errors.js';
2
2
  import { assertPathName, assertRelativePath } from '../story/paths.js';
3
3
  import { assessWriteAccess, writeAccessGuidance } from '../story/sandbox.js';
4
4
  import { WORKSPACE_PROJECT } from '../story/project.js';
5
- import { workspaceDirFor, workspaceStore } from '../story/workspace.js';
5
+ import { workspaceStore } from '../story/workspace.js';
6
6
  import { revealCommand, revealInFileManager } from './reveal.js';
7
7
  import { workspaceReadme } from '../story/readme.js';
8
8
  import { STATUS_BY_CODE } from './status.js';
@@ -19,6 +19,22 @@ function failure(error) {
19
19
  const body = { code: notebookError.code, message: notebookError.message };
20
20
  return json(body, STATUS_BY_CODE[notebookError.code]);
21
21
  }
22
+ /**
23
+ * Refuse a mutation on a deployment that cannot write.
24
+ *
25
+ * `ctx.fs` refuses a file write on its own (the policy is stamped on it), but a
26
+ * directory is changed through `node:fs`, which no policy guards. Without this
27
+ * check a read-only deployment would silently allow "new folder", rename and
28
+ * delete — three operations whose refusal every other write in the panel already
29
+ * explains with the same guidance.
30
+ * @param access - this request's write assessment.
31
+ * @param workspaceDir - the directory it was assessed against, for the message.
32
+ */
33
+ function refuseReadOnly(access, workspaceDir) {
34
+ if (access.writable)
35
+ return;
36
+ throw new NotebookError('forbidden', writeAccessGuidance(workspaceDir, access) ?? 'this workspace is read-only');
37
+ }
22
38
  /**
23
39
  * Read one JSON request body.
24
40
  *
@@ -55,8 +71,9 @@ export function registerApi(deps) {
55
71
  // may send none, and then the activation fallback applies.
56
72
  const sessionId = url.searchParams.get('session') ?? undefined;
57
73
  const { root, session } = roots(sessionId);
58
- // The panel's directory column is rooted at the workspace itself.
59
- const workspaceDir = workspaceDirFor(session, root.dir);
74
+ // The panel's directory column is rooted at the workspace itself, and that
75
+ // workspace *is* the root: one directory, resolved once for this request.
76
+ const workspaceDir = root.dir;
60
77
  const workspace = workspaceStore({ fs, policy, log }, session, workspaceDir);
61
78
  const open = async (name) => {
62
79
  if (name === WORKSPACE_PROJECT)
@@ -69,7 +86,6 @@ export function registerApi(deps) {
69
86
  case 'state': {
70
87
  return json({
71
88
  rootDir: workspaceDir,
72
- rootSource: root.source,
73
89
  sandbox: {
74
90
  mode: access.mode ?? null,
75
91
  workspaceRoot: access.workspaceRoot ?? null,
@@ -135,19 +151,54 @@ export function registerApi(deps) {
135
151
  return json({ project: project.id, dir: project.abs, focused });
136
152
  }
137
153
  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.
154
+ // Show the workspace in the OS file manager. The path is optional and, when
155
+ // given, is resolved and re-checked against the workspace before anything is
156
+ // opened — so the panel can reveal a folder (or the folder holding a file)
157
+ // without the browser ever naming a directory the Host did not prove is
158
+ // inside the tree it shows. `dryRun` is the test hook: it answers what
159
+ // would be launched without launching it.
142
160
  const body = await readBody(request);
161
+ const wanted = typeof body.path === 'string' && body.path.length > 0
162
+ ? assertRelativePath(body.path)
163
+ : '';
164
+ const { project } = await open(WORKSPACE_PROJECT);
165
+ const target = await workspace.revealDirectoryFor(project, wanted);
143
166
  if (body.dryRun === true) {
144
- const launch = revealCommand(process.platform, workspaceDir);
145
- return json({ dir: workspaceDir, command: launch.command, args: launch.args, opened: false });
167
+ const launch = revealCommand(process.platform, target);
168
+ return json({ dir: target, command: launch.command, args: launch.args, opened: false });
146
169
  }
147
- const opened = await revealInFileManager(workspaceDir);
170
+ const opened = await revealInFileManager(target);
148
171
  if (!opened)
149
- log.warn(`cannot open a file manager for ${workspaceDir}`);
150
- return json({ dir: workspaceDir, opened });
172
+ log.warn(`cannot open a file manager for ${target}`);
173
+ return json({ dir: target, opened });
174
+ }
175
+ case 'rename': {
176
+ // One entry, in place: the new name is a single segment, so this cannot
177
+ // move a chapter folder somewhere else in the tree.
178
+ const body = await readBody(request);
179
+ const { store, project } = await open(body.project);
180
+ const path = assertRelativePath(typeof body.path === 'string' ? body.path : '');
181
+ const name = assertPathName(body.name);
182
+ refuseReadOnly(access, workspaceDir);
183
+ const renamed = await store.renameEntry(project, path, name);
184
+ return json({ ...renamed, from: path });
185
+ }
186
+ case 'delete': {
187
+ // Irreversible, so the answer says what went: the panel asks first and
188
+ // needs to tell the author what the confirmation actually removed.
189
+ const body = await readBody(request);
190
+ const { store, project } = await open(body.project);
191
+ const path = assertRelativePath(typeof body.path === 'string' ? body.path : '');
192
+ refuseReadOnly(access, workspaceDir);
193
+ const removed = await store.deleteEntry(project, path);
194
+ return json(removed);
195
+ }
196
+ case 'count': {
197
+ // How much a delete would take, for the confirmation. Read-only, so it is
198
+ // answered even on a deployment that refuses the delete itself.
199
+ const { store, project } = await open(url.searchParams.get('project'));
200
+ const path = assertRelativePath(url.searchParams.get('path') ?? '');
201
+ return json({ path, files: await store.countFilesUnder(project, path) });
151
202
  }
152
203
  case 'ensure-readme': {
153
204
  // The one file the panel adds to a workspace on first open. Never an
package/lib/index.js CHANGED
@@ -10,8 +10,7 @@
10
10
  * keeps the plugin inactive — rather than broken — in a profile that has no web
11
11
  * carrier.
12
12
  */
13
- import { defaultRootDir } from './story/bootstrap.js';
14
- import { resolveConfig } from './config.js';
13
+ import { fallbackRootDir } from './story/bootstrap.js';
15
14
  import { API_PATH, registerApi } from './http/api.js';
16
15
  import { createRootResolver } from './story/root.js';
17
16
  import { createFocus } from './story/focus.js';
@@ -27,17 +26,31 @@ export const inject = ['fs', 'webServer', 'connection'];
27
26
  /**
28
27
  * Activate the plugin.
29
28
  * @param ctx - the owning context; every registration below is an effect of it.
30
- * @param rawConfig - the Loader row's `config`, unvalidated by design.
29
+ * @param rawConfig - the Loader row's `config`, which this plugin no longer has.
30
+ * It is read only to warn about a row still carrying the retired `rootDir`:
31
+ * silently ignoring it would leave a profile that looks pinned to a directory
32
+ * the panel is not showing.
31
33
  */
32
34
  export function apply(ctx, rawConfig) {
33
35
  const log = ctx.logger;
34
36
  const policy = ctx.get('sandboxPolicy');
35
- const config = resolveConfig(rawConfig, defaultRootDir(policy), (message) => { log.warn(`notebook: ${message}`); }, policy?.workspaceRoot);
37
+ const configured = typeof rawConfig === 'object' && rawConfig !== null
38
+ ? rawConfig
39
+ : {};
40
+ if (configured.rootDir !== undefined) {
41
+ log.warn('notebook: rootDir is no longer a configuration field; the tree follows the workspace. '
42
+ + 'To keep a notebook somewhere else, open that directory as the workspace.');
43
+ }
44
+ for (const field of Object.keys(configured)) {
45
+ if (field !== 'rootDir')
46
+ log.warn(`notebook: unknown configuration field ${field}; this plugin takes none`);
47
+ }
48
+ const fallbackRoot = fallbackRootDir(policy);
36
49
  // The root is resolved per call rather than here: it follows the workspace of
37
50
  // the Session making the call, so one plugin instance serves every workspace in
38
51
  // the profile instead of pinning one mutable root. See `root.ts` for the rule
39
52
  // and the per-root write policy it stamps.
40
- const roots = createRootResolver({ fs: ctx.fs, config, policy, agents: ctx.get('agents'), log });
53
+ const roots = createRootResolver({ fs: ctx.fs, fallbackRoot, policy, agents: ctx.get('agents'), log });
41
54
  const initialRoot = roots().root;
42
55
  const access = assessWriteAccess(initialRoot.dir, policy);
43
56
  // Puts the Session into the directory the panel shows, so the model's relative
@@ -52,7 +65,7 @@ export function apply(ctx, rawConfig) {
52
65
  // A session-less activation. The panel and every call resolve their own root
53
66
  // from the Session that made the call, so this fallback is what a scripted
54
67
  // caller with no Session would see.
55
- log.info(`notebook: no pinned root and no Session at activation; fallback root is ${initialRoot.dir}`);
68
+ log.info(`notebook: no Session at activation; fallback root is ${initialRoot.dir}`);
56
69
  }
57
70
  if (policy === undefined) {
58
71
  log.info('notebook: no sandbox-policy service in this profile; writes are unconfined');
@@ -62,8 +75,6 @@ export function apply(ctx, rawConfig) {
62
75
  // deployment value: each write stamps `{ mode, workspaceRoot: <that root> }`
63
76
  // (see `sandbox.ts`). The mode, though, is the Session's own.
64
77
  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
78
  }
68
79
  else {
69
80
  // Worth a warning rather than an error: the plugin still mounts and still
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The directory a session-less caller falls back to.
3
3
  *
4
- * Stories live **in the workspace the operator opened** (see `root.ts`), so this
4
+ * Notes live **in the workspace the operator opened** (see `root.ts`), so this
5
5
  * module covers only what is left over: the directory a caller with no Session at
6
6
  * all falls back to.
7
7
  *
@@ -11,19 +11,14 @@
11
11
  * here either; the workspace's `README.md` is written on first open by
12
12
  * `op=ensure-readme`, which is the one file the panel adds rather than a scaffold
13
13
  * of empty folders.
14
- *
15
- * A `rootDir` in the profile row is still honoured, and is the one way to pin a
16
- * library that several workspaces share. It is a configuration edit — the plugin
17
- * no longer writes its own row, so no Loader reconciliation happens mid-request
18
- * and no service has to exist for the panel to work.
19
14
  */
20
15
  import { homedir } from 'node:os';
21
16
  import { join } from 'node:path';
22
17
  /**
23
- * Where stories live when nothing resolves a root.
18
+ * Where notes live when no Session resolves a root.
24
19
  *
25
20
  * Used only for a session-less caller: the panel and every tool call carry a
26
- * Session, and that Session's workspace is the story root. Chosen inside the
21
+ * Session, and that Session's workspace is the root. Chosen inside the
27
22
  * deployment's write boundary so that even this last resort is writable.
28
23
  *
29
24
  * `workingDirectory.defaultDirectory` is deliberately not consulted. Its own
@@ -33,7 +28,7 @@ import { join } from 'node:path';
33
28
  * @param policy - the sandbox policy service, when this profile has one.
34
29
  * @returns an absolute directory path; it need not exist yet.
35
30
  */
36
- export function defaultRootDir(policy) {
31
+ export function fallbackRootDir(policy) {
37
32
  const boundary = policy?.workspaceRoot;
38
33
  if (boundary !== undefined && boundary.trim().length > 0)
39
34
  return boundary.trim();
@@ -6,12 +6,19 @@
6
6
  * returns is relative to it.
7
7
  *
8
8
  * Text goes through `ctx.fs`, so reads and writes inherit the Harness filesystem
9
- * provider, its sandbox policy, and its canonicalization. Creating a directory is
10
- * the one exception: `ctx.fs` cannot make one, so `mkdir` is reached at a path the
11
- * provider already proved is inside the root.
9
+ * provider, its sandbox policy, and its canonicalization. Two operations have no
10
+ * provider equivalent and reach `node:fs` instead — creating a directory, and
11
+ * moving or removing one — always at a path the provider already resolved and
12
+ * proved is inside the root, exactly as {@link ProjectStore.createDirectory} does.
13
+ *
14
+ * Files are different, and deliberately so: deleting and renaming one goes through
15
+ * `ctx.fs.deleteFile` / `moveFile`, which stamp the same sandbox policy a write
16
+ * does. A workspace pinned outside the deployment boundary is therefore writable
17
+ * here and still stamped correctly, and a read-only deployment refuses it at the
18
+ * seam rather than trusting this file to remember the rule.
12
19
  */
13
- import { mkdir } from 'node:fs/promises';
14
- import { join } from 'node:path';
20
+ import { mkdir, rename, rm } from 'node:fs/promises';
21
+ import { dirname, join } from 'node:path';
15
22
  import { NotebookError, asNotebookError } from '../errors.js';
16
23
  import { assertPathName, assertRelativePath } from './paths.js';
17
24
  import { countChars, isMissing, isTextFile, MAX_TREE_DEPTH, MAX_TREE_ENTRIES } from './manuscript.js';
@@ -286,4 +293,167 @@ export class ProjectStore {
286
293
  assertName(value) {
287
294
  return assertPathName(value);
288
295
  }
296
+ /**
297
+ * Whether a project-relative path names a directory.
298
+ *
299
+ * Asked before a rename or a delete decides *how* to do it: a file goes through
300
+ * the filesystem provider (which stamps the sandbox policy), a directory through
301
+ * `node:fs` (which has no provider equivalent). Guessing from a trailing slash
302
+ * would be guessing about the caller's intent rather than about the disk.
303
+ * @param project - an opened root.
304
+ * @param rel - a project-relative POSIX path.
305
+ * @returns true for a directory; false for a file or anything absent.
306
+ */
307
+ async isDirectory(project, rel) {
308
+ const target = await this.resolveInside(project, rel);
309
+ const info = await this.fs.stat(target).catch(() => undefined);
310
+ return info?.type === 'directory';
311
+ }
312
+ /**
313
+ * Rename one file or directory, in place in its own folder.
314
+ *
315
+ * The new name is one path segment, validated exactly as a create name is, so a
316
+ * rename can never turn into a move: the folder stays where it was and only the
317
+ * last segment changes. That restriction is deliberate — "rename" in a file tree
318
+ * means the thing stays put, and a control that could silently relocate a chapter
319
+ * folder is not the gesture the author made.
320
+ *
321
+ * A file keeps its content byte for byte: `moveFile` publishes the source text at
322
+ * the destination and removes the source, both guarded by the write policy. A
323
+ * directory is moved with `rename(2)`, which is atomic and cheap even for a
324
+ * thousand chapters.
325
+ * @param project - an opened root.
326
+ * @param rel - the existing project-relative path.
327
+ * @param name - the new name for it, one segment.
328
+ * @returns the new project-relative path.
329
+ * @throws {NotebookError} `not-found` when the source is absent, `conflict` when
330
+ * the destination is taken.
331
+ */
332
+ async renameEntry(project, rel, name) {
333
+ const safe = assertRelativePath(rel);
334
+ const newName = assertPathName(name);
335
+ const parent = safe.includes('/') ? safe.slice(0, safe.lastIndexOf('/')) : '';
336
+ const next = parent === '' ? newName : `${parent}/${newName}`;
337
+ // A rename to the name it already has is a no-op, not a conflict: the user may
338
+ // simply have confirmed an unchanged field, and both branches below would
339
+ // otherwise refuse a state that is already what was asked for.
340
+ if (next === safe)
341
+ return { path: safe };
342
+ const source = await this.resolveInside(project, safe);
343
+ if (await this.fs.stat(source) === undefined) {
344
+ throw new NotebookError('not-found', `${safe} does not exist`);
345
+ }
346
+ const destination = await this.resolveInside(project, next);
347
+ if (await this.fs.stat(destination) !== undefined) {
348
+ throw new NotebookError('conflict', `${next} already exists`);
349
+ }
350
+ if (await this.isDirectory(project, safe)) {
351
+ try {
352
+ await rename(this.fs.processPath(source), this.fs.processPath(destination));
353
+ }
354
+ catch (error) {
355
+ throw asNotebookError(error, `cannot rename ${safe}`);
356
+ }
357
+ return { path: next };
358
+ }
359
+ try {
360
+ await this.fs.moveFile(source, destination, {}, undefined, this.writePolicy);
361
+ }
362
+ catch (error) {
363
+ throw asNotebookError(error, `cannot rename ${safe}`);
364
+ }
365
+ return { path: next };
366
+ }
367
+ /**
368
+ * Delete one file or directory.
369
+ *
370
+ * A directory goes with everything under it, which is what a file manager does
371
+ * and what "delete this folder" means. The panel asks first and says how much is
372
+ * inside (see `api.delete`), because this is the one operation in the plugin that
373
+ * cannot be undone by typing.
374
+ *
375
+ * Containment is checked before anything is removed, so a symlink pointing out of
376
+ * the workspace is refused rather than followed.
377
+ * @param project - an opened root.
378
+ * @param rel - the project-relative path to remove.
379
+ * @returns the path that was removed, and whether it was a directory.
380
+ * @throws {NotebookError} `not-found` when the path is absent.
381
+ */
382
+ async deleteEntry(project, rel) {
383
+ const safe = assertRelativePath(rel);
384
+ const target = await this.resolveInside(project, safe);
385
+ if (await this.fs.stat(target) === undefined) {
386
+ throw new NotebookError('not-found', `${safe} does not exist`);
387
+ }
388
+ if (await this.isDirectory(project, safe)) {
389
+ try {
390
+ await rm(this.fs.processPath(target), { recursive: true, force: false });
391
+ }
392
+ catch (error) {
393
+ throw asNotebookError(error, `cannot delete ${safe}`);
394
+ }
395
+ return { path: safe, directory: true };
396
+ }
397
+ try {
398
+ await this.fs.deleteFile(target, undefined, undefined, this.writePolicy);
399
+ }
400
+ catch (error) {
401
+ throw asNotebookError(error, `cannot delete ${safe}`);
402
+ }
403
+ return { path: safe, directory: false };
404
+ }
405
+ /**
406
+ * The absolute directory a path should be revealed in.
407
+ *
408
+ * "Show this in the file manager" means: the folder itself for a folder, and the
409
+ * folder containing it for a file — the file manager's own selection gesture is
410
+ * platform-specific and unreliable (`explorer /select,` starts a second shell that
411
+ * does not always surface), while opening a directory is the one launch this
412
+ * plugin has already measured on every platform.
413
+ * @param project - an opened root.
414
+ * @param rel - a project-relative path, or `''` for the workspace itself.
415
+ * @returns an absolute directory path, proven to be inside the root.
416
+ */
417
+ async revealDirectoryFor(project, rel) {
418
+ if (rel === '')
419
+ return project.abs;
420
+ const target = await this.resolveInside(project, rel);
421
+ if (await this.isDirectory(project, rel))
422
+ return this.fs.processPath(target);
423
+ return dirname(this.fs.processPath(target));
424
+ }
425
+ /**
426
+ * How many files a directory holds, for a delete confirmation.
427
+ *
428
+ * Read through the same provider and the same skips as the tree, so the number
429
+ * the dialog shows is the number the author can see. A directory that cannot be
430
+ * read counts as unknown (`null`) rather than as empty.
431
+ * @param project - an opened root.
432
+ * @param rel - a project-relative directory path.
433
+ * @returns the recursive file count, or null when it could not be read.
434
+ */
435
+ async countFilesUnder(project, rel) {
436
+ try {
437
+ let total = 0;
438
+ const walk = async (dir, depth) => {
439
+ if (depth > MAX_TREE_DEPTH || total >= MAX_TREE_ENTRIES)
440
+ return;
441
+ for (const entry of await this.fs.listDir(dir)) {
442
+ if (entry.type === 'directory') {
443
+ if (SKIP_DIRS.has(entry.name))
444
+ continue;
445
+ await walk(entry.target, depth + 1);
446
+ }
447
+ else if (entry.type === 'file') {
448
+ total += 1;
449
+ }
450
+ }
451
+ };
452
+ await walk(await this.resolveInside(project, rel), 0);
453
+ return total;
454
+ }
455
+ catch {
456
+ return null;
457
+ }
458
+ }
289
459
  }
@@ -13,14 +13,14 @@
13
13
  * @returns the markdown.
14
14
  */
15
15
  export function workspaceReadme() {
16
- return `# dsh-notepad
17
-
18
- deepseek harness 简易的markdown笔记插件
19
-
20
- - 支持目录树浏览,创建文件夹,创建文件
21
- - 支持字体样式,大小,背景颜色调整
22
- - 支持字数显示,自动保存
23
- - 支持AI对话框功能
24
- - 重命名,删除,需要在系统资源管理器完成,或提示AI操作
16
+ return `# dsh-notepad
17
+
18
+ deepseek harness 简易的markdown笔记插件
19
+
20
+ - 支持目录树浏览,创建文件夹,创建文件
21
+ - 支持字体样式,大小,背景颜色调整
22
+ - 支持字数显示,自动保存
23
+ - 支持AI对话框功能
24
+ - 重命名,删除,需要在系统资源管理器完成,或提示AI操作
25
25
  `;
26
26
  }
package/lib/story/root.js CHANGED
@@ -12,17 +12,20 @@ function liveSession(agents, sessionId) {
12
12
  return agents.get(sessionId)?.session;
13
13
  }
14
14
  /**
15
- * Decide which directory a call's stories live in.
16
- * @param config - the validated configuration; its `rootDir` is already absolute.
15
+ * Decide which directory a call's notes live in.
16
+ *
17
+ * There is nothing to choose between: a live Session *is* the root.
18
+ * @param fallbackRoot - the activation default, for a caller with no Session.
17
19
  * @param workspace - the calling Session's workspace, when known.
18
20
  * @returns the root and the rule that chose it.
19
21
  */
20
- export function storyRootFor(config, workspace) {
21
- if (config.rootDirOverride)
22
- return { dir: config.rootDir, source: 'override' };
23
- if (workspace !== undefined)
22
+ export function storyRootFor(fallbackRoot, workspace) {
23
+ // The path is used verbatim: a trailing space is legal input, and trimming the
24
+ // value would resolve a directory the operator did not open. Only the
25
+ // emptiness test looks at the trimmed form.
26
+ if (workspace !== undefined && workspace.trim().length > 0)
24
27
  return { dir: workspace, source: 'workspace' };
25
- return { dir: config.rootDir, source: 'fallback' };
28
+ return { dir: fallbackRoot, source: 'fallback' };
26
29
  }
27
30
  /** Roots kept as live stores; a session beyond this evicts the least recently added. */
28
31
  const MAX_CACHED_ROOTS = 8;
@@ -35,14 +38,14 @@ const MAX_CACHED_ROOTS = 8;
35
38
  * switched while the plugin is serving it, and the write policy was stamped with
36
39
  * the old one — a second store costs a directory listing, a stale mode costs a
37
40
  * write that should have been allowed.
38
- * @param deps - filesystem, configuration, sandbox policy, agent registry, logger.
41
+ * @param deps - filesystem, the session-less fallback root, sandbox policy, agent registry, logger.
39
42
  * @returns a resolver from an optional Session id to that call's store and root.
40
43
  */
41
44
  export function createRootResolver(deps) {
42
45
  const cache = new Map();
43
46
  return (sessionId) => {
44
47
  const session = liveSession(deps.agents, sessionId);
45
- const root = storyRootFor(deps.config, session?.header.cwd);
48
+ const root = storyRootFor(deps.fallbackRoot, session?.header.cwd);
46
49
  const writePolicy = storyWritePolicy(root.dir, deps.policy, session);
47
50
  const key = `${root.dir}\u0000${writePolicy?.mode ?? ''}`;
48
51
  let store = cache.get(key);