@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/LICENSE +23 -0
- package/README.md +95 -2
- package/cordis.patch.yml +7 -0
- package/icon.svg +9 -0
- package/lib/client.js +15135 -0
- package/lib/config.js +43 -0
- package/lib/dsh.js +1 -0
- package/lib/errors.js +20 -0
- package/lib/http/api.js +179 -0
- package/lib/http/media.js +187 -0
- package/lib/http/reveal.js +68 -0
- package/lib/http/status.js +15 -0
- package/lib/index.js +89 -0
- package/lib/render/backend.js +247 -0
- package/lib/render/jobs.js +267 -0
- package/lib/render/png.js +125 -0
- package/lib/story/bootstrap.js +45 -0
- package/lib/story/focus.js +43 -0
- package/lib/story/manuscript.js +49 -0
- package/lib/story/paths.js +95 -0
- package/lib/story/project.js +289 -0
- package/lib/story/readme.js +26 -0
- package/lib/story/root.js +60 -0
- package/lib/story/sandbox.js +186 -0
- package/lib/story/workspace.js +46 -0
- package/lib/tools.js +341 -0
- package/lib/types.js +7 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build the focus function over the host's services.
|
|
3
|
+
*
|
|
4
|
+
* The move itself is best-effort — a panel that opened a story must not fail
|
|
5
|
+
* because this profile has no working-directory service, because the Session is
|
|
6
|
+
* gone, or because the directory was removed between the read and the write.
|
|
7
|
+
* Every failure is reported in the log and answered with `false`.
|
|
8
|
+
*
|
|
9
|
+
* @param deps - the agent registry, working-directory service and logger.
|
|
10
|
+
* @returns a function that moves one Session into one story.
|
|
11
|
+
*/
|
|
12
|
+
export function createFocus(deps) {
|
|
13
|
+
const { agents, workingDirectory, log } = deps;
|
|
14
|
+
let warned = false;
|
|
15
|
+
return async (sessionId, book) => {
|
|
16
|
+
if (sessionId === undefined)
|
|
17
|
+
return false;
|
|
18
|
+
const service = workingDirectory();
|
|
19
|
+
if (service === undefined) {
|
|
20
|
+
// Once, not per selection: a profile without the service would otherwise log
|
|
21
|
+
// on every story the panel opens.
|
|
22
|
+
if (!warned) {
|
|
23
|
+
warned = true;
|
|
24
|
+
log.warn('notebook: no working-directory service in this profile; the Session keeps its own directory');
|
|
25
|
+
}
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
const agent = agents()?.get(sessionId);
|
|
29
|
+
// A scripted caller can name a Session that is not live; there is nothing to
|
|
30
|
+
// move and nothing worth reporting, since the next panel request retries.
|
|
31
|
+
if (agent === undefined)
|
|
32
|
+
return false;
|
|
33
|
+
try {
|
|
34
|
+
await service.set(agent, book);
|
|
35
|
+
log.info(`notebook: Session ${sessionId} works in ${book}`);
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
log.warn(`notebook: could not move Session ${sessionId} into ${book}`, error);
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the notebook's tree shows, and how a file is read back.
|
|
3
|
+
*
|
|
4
|
+
* The format layer, kept apart from the IO that serves it: everything here is
|
|
5
|
+
* pure — which names the browser may open, how a text is counted — and the store
|
|
6
|
+
* in `project.ts` owns the filesystem, the sandbox policy and the listing.
|
|
7
|
+
*
|
|
8
|
+
* @module notebook/story/manuscript
|
|
9
|
+
*/
|
|
10
|
+
import { basename } from 'node:path';
|
|
11
|
+
/** Deepest nesting the tree descends into. */
|
|
12
|
+
export const MAX_TREE_DEPTH = 8;
|
|
13
|
+
/** Ceiling on files listed for one root, so a huge tree cannot stall the page. */
|
|
14
|
+
export const MAX_TREE_ENTRIES = 2_000;
|
|
15
|
+
/** Extensions the browser opens as editable text. */
|
|
16
|
+
export const TEXT_EXTENSIONS = new Set(['.md', '.markdown', '.txt', '.json', '.jsonl', '.yml', '.yaml', '.csv']);
|
|
17
|
+
/**
|
|
18
|
+
* Whether a file is text the editor may open.
|
|
19
|
+
*
|
|
20
|
+
* An allowlist rather than a denylist: a working directory accumulates images,
|
|
21
|
+
* archives and OS droppings, and showing all of it would bury the notes. A bare
|
|
22
|
+
* name has no extension at all — the panel names files by title (`第一章`) — and
|
|
23
|
+
* a title is a text file; only an *unknown* extension is refused.
|
|
24
|
+
* @param path - project-relative path; only its basename is considered.
|
|
25
|
+
* @returns true when the file is editable text.
|
|
26
|
+
*/
|
|
27
|
+
export function isTextFile(path) {
|
|
28
|
+
const name = basename(path);
|
|
29
|
+
const dot = name.lastIndexOf('.');
|
|
30
|
+
if (dot <= 0)
|
|
31
|
+
return true;
|
|
32
|
+
return TEXT_EXTENSIONS.has(name.slice(dot).toLowerCase());
|
|
33
|
+
}
|
|
34
|
+
/** Whether an error means "the file is not there". */
|
|
35
|
+
export function isMissing(error) {
|
|
36
|
+
const code = error?.code;
|
|
37
|
+
return code === 'ENOENT' || code === 'FS_NOT_FOUND';
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Count characters the way a writer counts them: code points, front-matter aside.
|
|
41
|
+
* @param content - the full file text.
|
|
42
|
+
* @returns the code-point count of the body.
|
|
43
|
+
*/
|
|
44
|
+
export function countChars(content) {
|
|
45
|
+
const withoutFrontMatter = content.startsWith('---')
|
|
46
|
+
? content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '')
|
|
47
|
+
: content;
|
|
48
|
+
return [...withoutFrontMatter].length;
|
|
49
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Name and relative-path validation.
|
|
3
|
+
*
|
|
4
|
+
* Every path that reaches the filesystem is built here first. The defence is
|
|
5
|
+
* two-layered on purpose: this module rejects the shapes that are never
|
|
6
|
+
* legitimate (absolute paths, `..`, backslashes, drive letters), and
|
|
7
|
+
* {@link ProjectStore.resolveInside} then re-checks the canonicalized target
|
|
8
|
+
* against the root through the filesystem provider, so a symlink or a
|
|
9
|
+
* backend-specific alias cannot escape either.
|
|
10
|
+
*/
|
|
11
|
+
import { NotebookError } from '../errors.js';
|
|
12
|
+
/**
|
|
13
|
+
* Characters no mainstream filesystem accepts inside one path segment.
|
|
14
|
+
*
|
|
15
|
+
* The ASCII forms only. Their fullwidth cousins (`:`, `?`, `*`) are ordinary
|
|
16
|
+
* characters to every filesystem, so a Chinese title is free to use them.
|
|
17
|
+
*/
|
|
18
|
+
const ILLEGAL_IN_NAME = /[<>:"/\\|?*\u0000-\u001f\u007f]/;
|
|
19
|
+
/** Windows device names, reserved with or without an extension. */
|
|
20
|
+
const RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
|
|
21
|
+
/**
|
|
22
|
+
* Cap on a name, in bytes rather than characters.
|
|
23
|
+
*
|
|
24
|
+
* The limit that bites first is ext4's 255 bytes per path segment, and one CJK
|
|
25
|
+
* character costs three of them, so a character-count cap would allow a name
|
|
26
|
+
* that cannot be created.
|
|
27
|
+
*/
|
|
28
|
+
const MAX_NAME_BYTES = 120;
|
|
29
|
+
/** Windows silently drops a trailing dot or space, so a name ending in one is a lie. */
|
|
30
|
+
const TRAILING_DOTS = /[. ]+$/;
|
|
31
|
+
/**
|
|
32
|
+
* Validate one name used as a path segment — a file or a folder.
|
|
33
|
+
*
|
|
34
|
+
* Unicode is allowed — a note called 第一章 gets a file called 第一章, which is
|
|
35
|
+
* the point. What is *not* allowed is anything the filesystem would refuse,
|
|
36
|
+
* silently rewrite, or resolve somewhere unintended: separators, the
|
|
37
|
+
* Windows-illegal set, control characters, the reserved device names, a trailing
|
|
38
|
+
* dot or space, and `.` / `..`.
|
|
39
|
+
*
|
|
40
|
+
* Normalizing to NFC first matters on macOS, where the filesystem decomposes
|
|
41
|
+
* accented names: without it, the name the user typed and the name read back
|
|
42
|
+
* from disk are different strings, and every containment or equality check
|
|
43
|
+
* between them fails.
|
|
44
|
+
* @param value - the untrusted name.
|
|
45
|
+
* @returns the normalized, filesystem-safe name.
|
|
46
|
+
* @throws {NotebookError} `bad-request` when the name cannot be a path segment.
|
|
47
|
+
*/
|
|
48
|
+
export function assertPathName(value) {
|
|
49
|
+
if (typeof value !== 'string') {
|
|
50
|
+
throw new NotebookError('bad-request', `name must be a string; received ${JSON.stringify(value)}`);
|
|
51
|
+
}
|
|
52
|
+
const name = value.normalize('NFC').trim().replace(TRAILING_DOTS, '');
|
|
53
|
+
if (name.length === 0) {
|
|
54
|
+
throw new NotebookError('bad-request', 'name must contain something other than spaces and dots');
|
|
55
|
+
}
|
|
56
|
+
if (name === '.' || name === '..') {
|
|
57
|
+
throw new NotebookError('bad-request', `name must not be ${JSON.stringify(name)}`);
|
|
58
|
+
}
|
|
59
|
+
if (ILLEGAL_IN_NAME.test(name)) {
|
|
60
|
+
throw new NotebookError('bad-request', `name must not contain < > : " / \\ | ? * or control characters; received ${JSON.stringify(name)}`);
|
|
61
|
+
}
|
|
62
|
+
if (RESERVED_NAME.test(name)) {
|
|
63
|
+
throw new NotebookError('bad-request', `name must not be a reserved device name such as CON or LPT1; received ${JSON.stringify(name)}`);
|
|
64
|
+
}
|
|
65
|
+
if (Buffer.byteLength(name, 'utf8') > MAX_NAME_BYTES) {
|
|
66
|
+
throw new NotebookError('bad-request', `name must be at most ${String(MAX_NAME_BYTES)} bytes; received ${String(Buffer.byteLength(name, 'utf8'))}`);
|
|
67
|
+
}
|
|
68
|
+
return name;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Normalize a project-relative file path.
|
|
72
|
+
*
|
|
73
|
+
* Accepts forward slashes only; backslashes are rejected rather than rewritten
|
|
74
|
+
* so a Windows-style path from a confused caller fails loudly instead of
|
|
75
|
+
* silently addressing a different file.
|
|
76
|
+
* @param value - the untrusted path.
|
|
77
|
+
* @returns the normalized relative path.
|
|
78
|
+
* @throws {NotebookError} `bad-request` when the path is absolute or escapes upward.
|
|
79
|
+
*/
|
|
80
|
+
export function assertRelativePath(value) {
|
|
81
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
82
|
+
throw new NotebookError('bad-request', 'path must be a non-empty string');
|
|
83
|
+
}
|
|
84
|
+
if (value.includes('\\')) {
|
|
85
|
+
throw new NotebookError('bad-request', `path must use forward slashes; received ${JSON.stringify(value)}`);
|
|
86
|
+
}
|
|
87
|
+
if (value.startsWith('/') || /^[A-Za-z]:/.test(value)) {
|
|
88
|
+
throw new NotebookError('bad-request', `path must be relative to the workspace; received ${JSON.stringify(value)}`);
|
|
89
|
+
}
|
|
90
|
+
const segments = value.split('/');
|
|
91
|
+
if (segments.some(segment => segment.length === 0 || segment === '.' || segment === '..')) {
|
|
92
|
+
throw new NotebookError('bad-request', `path must not contain empty, "." or ".." segments; received ${JSON.stringify(value)}`);
|
|
93
|
+
}
|
|
94
|
+
return segments.join('/');
|
|
95
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The workspace store: everything that touches the notebook's files.
|
|
3
|
+
*
|
|
4
|
+
* There is one root and no project layer any more: the panel's tree is the
|
|
5
|
+
* workspace itself, so the store is built over that directory and every path it
|
|
6
|
+
* returns is relative to it.
|
|
7
|
+
*
|
|
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.
|
|
12
|
+
*/
|
|
13
|
+
import { mkdir } from 'node:fs/promises';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { NotebookError, asNotebookError } from '../errors.js';
|
|
16
|
+
import { assertPathName, assertRelativePath } from './paths.js';
|
|
17
|
+
import { countChars, isMissing, isTextFile, MAX_TREE_DEPTH, MAX_TREE_ENTRIES } from './manuscript.js';
|
|
18
|
+
/**
|
|
19
|
+
* Directories the tree never descends into.
|
|
20
|
+
*
|
|
21
|
+
* `node_modules` is not writing, and a workspace-sized tree that walked it would
|
|
22
|
+
* spend seconds per listing and push the author's own files past the entry cap.
|
|
23
|
+
*/
|
|
24
|
+
const SKIP_DIRS = new Set(['node_modules']);
|
|
25
|
+
/**
|
|
26
|
+
* The project id the panel uses for the workspace itself.
|
|
27
|
+
*
|
|
28
|
+
* The empty string is the id — it cannot collide with a directory name, whose
|
|
29
|
+
* name is non-empty by construction.
|
|
30
|
+
*/
|
|
31
|
+
export const WORKSPACE_PROJECT = '';
|
|
32
|
+
export class ProjectStore {
|
|
33
|
+
fs;
|
|
34
|
+
rootDir;
|
|
35
|
+
log;
|
|
36
|
+
writePolicy;
|
|
37
|
+
rootCache;
|
|
38
|
+
constructor(fs, rootDir, log,
|
|
39
|
+
/**
|
|
40
|
+
* The policy stamped on every content write.
|
|
41
|
+
*
|
|
42
|
+
* A write through `ctx.fs` with no explicit policy resolves against the
|
|
43
|
+
* *deployment* fallback (`defaultMode` + `workspaceRoot`), which is not
|
|
44
|
+
* necessarily the directory the notebook lives in. Stamping the root as the
|
|
45
|
+
* boundary is what lets a fresh install serve a workspace outside the
|
|
46
|
+
* deployment workspace with no profile edit at all; see
|
|
47
|
+
* {@link module:notebook/story/sandbox}. `undefined` means this profile
|
|
48
|
+
* mounted no confining filesystem, so there is nothing to stamp.
|
|
49
|
+
*/
|
|
50
|
+
writePolicy) {
|
|
51
|
+
this.fs = fs;
|
|
52
|
+
this.rootDir = rootDir;
|
|
53
|
+
this.log = log;
|
|
54
|
+
this.writePolicy = writePolicy;
|
|
55
|
+
}
|
|
56
|
+
/** Resolve (and create on first use) the root directory. */
|
|
57
|
+
async root() {
|
|
58
|
+
if (this.rootCache !== undefined)
|
|
59
|
+
return this.rootCache;
|
|
60
|
+
let target = await this.fs.resolve(this.rootDir);
|
|
61
|
+
if (await this.fs.stat(target) === undefined) {
|
|
62
|
+
await mkdir(this.fs.processPath(target), { recursive: true });
|
|
63
|
+
target = await this.fs.resolve(this.rootDir);
|
|
64
|
+
}
|
|
65
|
+
this.rootCache = target;
|
|
66
|
+
return target;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Open the store's own root as the project.
|
|
70
|
+
*
|
|
71
|
+
* The operator's folder is not a project id, so this skips the name check and
|
|
72
|
+
* hands back the root the store already owns. Paths stay relative and stay
|
|
73
|
+
* containment-checked against it.
|
|
74
|
+
* @returns the root, opened as a project whose id is {@link WORKSPACE_PROJECT}.
|
|
75
|
+
* @throws {NotebookError} `not-found` when the root is not a directory.
|
|
76
|
+
*/
|
|
77
|
+
async openRoot() {
|
|
78
|
+
const dir = await this.root();
|
|
79
|
+
const info = await this.fs.stat(dir);
|
|
80
|
+
if (info === undefined || info.type !== 'directory') {
|
|
81
|
+
throw new NotebookError('not-found', `workspace ${this.rootDir} is not a directory`);
|
|
82
|
+
}
|
|
83
|
+
return { id: WORKSPACE_PROJECT, dir, abs: this.fs.processPath(dir) };
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Resolve a project-relative path and re-check containment on the canonical target.
|
|
87
|
+
* @param project - an opened root.
|
|
88
|
+
* @param rel - a project-relative POSIX path.
|
|
89
|
+
* @returns the resolved target.
|
|
90
|
+
* @throws {NotebookError} `forbidden` when the canonical target escapes the root.
|
|
91
|
+
*/
|
|
92
|
+
async resolveInside(project, rel) {
|
|
93
|
+
const safe = assertRelativePath(rel);
|
|
94
|
+
const target = await this.fs.resolve(safe, { cwd: project.abs });
|
|
95
|
+
if (!this.fs.contains(project.dir, target)) {
|
|
96
|
+
throw new NotebookError('forbidden', `${safe} resolves outside the workspace`);
|
|
97
|
+
}
|
|
98
|
+
return target;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Create the parent directories of a project-relative path.
|
|
102
|
+
*
|
|
103
|
+
* Every segment is already validated by {@link assertRelativePath}, and the base
|
|
104
|
+
* is the provider-resolved root, so this cannot create anything outside it.
|
|
105
|
+
*/
|
|
106
|
+
async ensureParent(project, rel) {
|
|
107
|
+
const segments = assertRelativePath(rel).split('/').slice(0, -1);
|
|
108
|
+
if (segments.length === 0)
|
|
109
|
+
return;
|
|
110
|
+
try {
|
|
111
|
+
await mkdir(join(project.abs, ...segments), { recursive: true });
|
|
112
|
+
}
|
|
113
|
+
catch (error) {
|
|
114
|
+
throw asNotebookError(error, `cannot create the directory for ${rel}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The names directly inside one folder of the workspace.
|
|
119
|
+
*
|
|
120
|
+
* Used when naming a new file: the question is "is this name taken *here*", so
|
|
121
|
+
* listing the whole tree would walk every subdirectory — seconds on a workspace
|
|
122
|
+
* that holds a `node_modules` — to answer something one `listDir` answers.
|
|
123
|
+
* @param project - an opened root.
|
|
124
|
+
* @param folder - project-relative folder, `''` for the root.
|
|
125
|
+
* @returns the entry names in that folder; empty when it cannot be read.
|
|
126
|
+
*/
|
|
127
|
+
async namesIn(project, folder) {
|
|
128
|
+
const target = folder === '' ? project.dir : await this.resolveInside(project, folder);
|
|
129
|
+
const entries = await this.fs.listDir(target).catch(() => []);
|
|
130
|
+
return new Set(entries.map(entry => entry.name));
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* List every file and directory under the root.
|
|
134
|
+
*
|
|
135
|
+
* Dot entries are tooling rather than notes (`.git`), `node_modules` is not
|
|
136
|
+
* writing, and unknown extensions are hidden: a file the tree cannot open is
|
|
137
|
+
* noise in a list whose purpose is to be clicked.
|
|
138
|
+
* @param project - an opened root.
|
|
139
|
+
* @returns the entries, sorted by path.
|
|
140
|
+
*/
|
|
141
|
+
async listFiles(project) {
|
|
142
|
+
const out = [];
|
|
143
|
+
const walk = async (dir, relDir, depth) => {
|
|
144
|
+
if (depth > MAX_TREE_DEPTH || out.length >= MAX_TREE_ENTRIES)
|
|
145
|
+
return;
|
|
146
|
+
let entries;
|
|
147
|
+
try {
|
|
148
|
+
entries = await this.fs.listDir(dir);
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
// One unreadable subdirectory must not cost the user the whole tree.
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
for (const entry of entries) {
|
|
155
|
+
if (out.length >= MAX_TREE_ENTRIES)
|
|
156
|
+
return;
|
|
157
|
+
if (entry.name.startsWith('.'))
|
|
158
|
+
continue;
|
|
159
|
+
if (entry.type === 'directory' && SKIP_DIRS.has(entry.name))
|
|
160
|
+
continue;
|
|
161
|
+
// Re-checked per child rather than trusting the walk, so a symlink
|
|
162
|
+
// pointing out of the root cannot smuggle an outside file in.
|
|
163
|
+
if (!this.fs.contains(project.dir, entry.target))
|
|
164
|
+
continue;
|
|
165
|
+
const rel = relDir === '' ? entry.name : `${relDir}/${entry.name}`;
|
|
166
|
+
if (entry.type === 'directory') {
|
|
167
|
+
out.push({ path: rel, name: entry.name, bytes: 0, kind: 'directory' });
|
|
168
|
+
await walk(entry.target, rel, depth + 1);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
if (entry.type !== 'file')
|
|
172
|
+
continue;
|
|
173
|
+
if (!isTextFile(entry.name))
|
|
174
|
+
continue;
|
|
175
|
+
const size = entry.size ?? (await this.fs.stat(entry.target).catch(() => undefined))?.size ?? 0;
|
|
176
|
+
out.push({ path: rel, name: entry.name, bytes: size, kind: 'text' });
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
await walk(project.dir, '', 0);
|
|
180
|
+
// `numeric` so 第2章 sorts before 第10章 rather than after it, and Chinese
|
|
181
|
+
// collation so the folder names group the way a reader expects.
|
|
182
|
+
out.sort((left, right) => left.path.localeCompare(right.path, 'zh-Hans-CN', { numeric: true }));
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Read one text file.
|
|
187
|
+
* @param project - an opened root.
|
|
188
|
+
* @param rel - project-relative POSIX path.
|
|
189
|
+
* @returns the document.
|
|
190
|
+
* @throws {NotebookError} `bad-request` when the extension is not editable text,
|
|
191
|
+
* `not-found` when the file is absent.
|
|
192
|
+
*/
|
|
193
|
+
async readTextFile(project, rel) {
|
|
194
|
+
const safe = assertRelativePath(rel);
|
|
195
|
+
if (!isTextFile(safe))
|
|
196
|
+
throw new NotebookError('bad-request', `${safe} is not a text file this editor opens`);
|
|
197
|
+
const target = await this.resolveInside(project, safe);
|
|
198
|
+
let content;
|
|
199
|
+
try {
|
|
200
|
+
content = await this.fs.readText(target);
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
if (isMissing(error))
|
|
204
|
+
throw new NotebookError('not-found', `${safe} does not exist`);
|
|
205
|
+
throw asNotebookError(error, `cannot read ${safe}`);
|
|
206
|
+
}
|
|
207
|
+
return { path: safe, content, chars: countChars(content), bytes: Buffer.byteLength(content, 'utf8') };
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Write one text file, creating parent directories as needed.
|
|
211
|
+
* @param project - an opened root.
|
|
212
|
+
* @param rel - project-relative POSIX path.
|
|
213
|
+
* @param content - the full new contents.
|
|
214
|
+
* @returns the stored document.
|
|
215
|
+
* @throws {NotebookError} `bad-request` when the extension is not editable text.
|
|
216
|
+
*/
|
|
217
|
+
async writeTextFile(project, rel, content) {
|
|
218
|
+
const safe = assertRelativePath(rel);
|
|
219
|
+
if (!isTextFile(safe))
|
|
220
|
+
throw new NotebookError('bad-request', `${safe} is not a text file this editor writes`);
|
|
221
|
+
await this.ensureParent(project, safe);
|
|
222
|
+
const target = await this.resolveInside(project, safe);
|
|
223
|
+
try {
|
|
224
|
+
await this.fs.writeText(target, content, undefined, undefined, this.writePolicy);
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
throw asNotebookError(error, `cannot write ${safe}`);
|
|
228
|
+
}
|
|
229
|
+
return { path: safe, content, chars: countChars(content), bytes: Buffer.byteLength(content, 'utf8') };
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Create one directory inside the workspace.
|
|
233
|
+
*
|
|
234
|
+
* `ctx.fs` writes files but cannot make a directory, so this reaches `node:fs`
|
|
235
|
+
* at a path the provider resolved and proved is inside the root. The path is
|
|
236
|
+
* validated by {@link assertRelativePath} before it is resolved, so it cannot
|
|
237
|
+
* name an absolute path or climb out with `..`.
|
|
238
|
+
* @param project - an opened root.
|
|
239
|
+
* @param rel - project-relative POSIX path of the new directory.
|
|
240
|
+
* @returns the path that was created.
|
|
241
|
+
* @throws {NotebookError} `conflict` when something already holds that path.
|
|
242
|
+
*/
|
|
243
|
+
async createDirectory(project, rel) {
|
|
244
|
+
const safe = assertRelativePath(rel);
|
|
245
|
+
const target = await this.resolveInside(project, safe);
|
|
246
|
+
if (await this.fs.stat(target) !== undefined) {
|
|
247
|
+
throw new NotebookError('conflict', `${safe} already exists`);
|
|
248
|
+
}
|
|
249
|
+
try {
|
|
250
|
+
await mkdir(this.fs.processPath(target), { recursive: true });
|
|
251
|
+
}
|
|
252
|
+
catch (error) {
|
|
253
|
+
throw asNotebookError(error, `cannot create ${safe}`);
|
|
254
|
+
}
|
|
255
|
+
return { path: safe };
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* The path for a new file whose name is exactly what the author typed.
|
|
259
|
+
*
|
|
260
|
+
* A title is the file name: appending `.md` would give the same document a
|
|
261
|
+
* second name, and a title that already carries an extension would get two
|
|
262
|
+
* (`.md.md`). Uniqueness is the only thing enforced here — a number goes before
|
|
263
|
+
* the extension, so `名.md` becomes `名-2.md` rather than `名.md-2`.
|
|
264
|
+
* @param project - an opened root.
|
|
265
|
+
* @param dir - the folder to create it in, project-relative; `''` is the root.
|
|
266
|
+
* @param name - the file name, already validated as one path segment.
|
|
267
|
+
* @returns the project-relative path, free of collisions.
|
|
268
|
+
*/
|
|
269
|
+
async newNamedPath(project, dir, name) {
|
|
270
|
+
const folder = dir.length === 0 ? '' : assertRelativePath(dir);
|
|
271
|
+
const at = (file) => (folder === '' ? file : `${folder}/${file}`);
|
|
272
|
+
const used = await this.namesIn(project, folder);
|
|
273
|
+
if (!used.has(name))
|
|
274
|
+
return at(name);
|
|
275
|
+
const dot = name.lastIndexOf('.');
|
|
276
|
+
const stem = dot > 0 ? name.slice(0, dot) : name;
|
|
277
|
+
const extension = dot > 0 ? name.slice(dot) : '';
|
|
278
|
+
for (let index = 2; index < 10_000; index += 1) {
|
|
279
|
+
const candidate = `${stem}-${String(index)}${extension}`;
|
|
280
|
+
if (!used.has(candidate))
|
|
281
|
+
return at(candidate);
|
|
282
|
+
}
|
|
283
|
+
throw new NotebookError('conflict', 'no free file name remains');
|
|
284
|
+
}
|
|
285
|
+
/** Validate one user-supplied name as a single path segment. */
|
|
286
|
+
assertName(value) {
|
|
287
|
+
return assertPathName(value);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The README the panel writes into a workspace the first time it is opened.
|
|
3
|
+
*
|
|
4
|
+
* @module notebook/story/readme
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* The workspace's README, written on first open.
|
|
8
|
+
*
|
|
9
|
+
* Fixed text on purpose: it names the plugin and lists what the panel does,
|
|
10
|
+
* which is what someone opening an unknown directory wants to know. It is
|
|
11
|
+
* created only when absent — a workspace that already has a `README.md` keeps
|
|
12
|
+
* its own.
|
|
13
|
+
* @returns the markdown.
|
|
14
|
+
*/
|
|
15
|
+
export function workspaceReadme() {
|
|
16
|
+
return `# dsh-notepad
|
|
17
|
+
|
|
18
|
+
deepseek harness 简易的markdown笔记插件
|
|
19
|
+
|
|
20
|
+
- 支持目录树浏览,创建文件夹,创建文件
|
|
21
|
+
- 支持字体样式,大小,背景颜色调整
|
|
22
|
+
- 支持字数显示,自动保存
|
|
23
|
+
- 支持AI对话框功能
|
|
24
|
+
- 重命名,删除,需要在系统资源管理器完成,或提示AI操作
|
|
25
|
+
`;
|
|
26
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ProjectStore } from './project.js';
|
|
2
|
+
import { storyWritePolicy } from './sandbox.js';
|
|
3
|
+
/**
|
|
4
|
+
* The live Session behind one id, when there is one.
|
|
5
|
+
* @param agents - the agent registry, when this profile has one.
|
|
6
|
+
* @param sessionId - the calling Session, when the caller knows it.
|
|
7
|
+
* @returns the Session, or `undefined` when it cannot be known.
|
|
8
|
+
*/
|
|
9
|
+
function liveSession(agents, sessionId) {
|
|
10
|
+
if (agents === undefined || sessionId === undefined)
|
|
11
|
+
return undefined;
|
|
12
|
+
return agents.get(sessionId)?.session;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Decide which directory a call's stories live in.
|
|
16
|
+
* @param config - the validated configuration; its `rootDir` is already absolute.
|
|
17
|
+
* @param workspace - the calling Session's workspace, when known.
|
|
18
|
+
* @returns the root and the rule that chose it.
|
|
19
|
+
*/
|
|
20
|
+
export function storyRootFor(config, workspace) {
|
|
21
|
+
if (config.rootDirOverride)
|
|
22
|
+
return { dir: config.rootDir, source: 'override' };
|
|
23
|
+
if (workspace !== undefined)
|
|
24
|
+
return { dir: workspace, source: 'workspace' };
|
|
25
|
+
return { dir: config.rootDir, source: 'fallback' };
|
|
26
|
+
}
|
|
27
|
+
/** Roots kept as live stores; a session beyond this evicts the least recently added. */
|
|
28
|
+
const MAX_CACHED_ROOTS = 8;
|
|
29
|
+
/**
|
|
30
|
+
* Build the per-call root resolver.
|
|
31
|
+
*
|
|
32
|
+
* One store per (root, mode), cached because every call in a Session resolves to
|
|
33
|
+
* the same root and a store holds nothing but its own listing cache. The mode is
|
|
34
|
+
* part of the key rather than fixed at activation because a Session's mode can be
|
|
35
|
+
* switched while the plugin is serving it, and the write policy was stamped with
|
|
36
|
+
* the old one — a second store costs a directory listing, a stale mode costs a
|
|
37
|
+
* write that should have been allowed.
|
|
38
|
+
* @param deps - filesystem, configuration, sandbox policy, agent registry, logger.
|
|
39
|
+
* @returns a resolver from an optional Session id to that call's store and root.
|
|
40
|
+
*/
|
|
41
|
+
export function createRootResolver(deps) {
|
|
42
|
+
const cache = new Map();
|
|
43
|
+
return (sessionId) => {
|
|
44
|
+
const session = liveSession(deps.agents, sessionId);
|
|
45
|
+
const root = storyRootFor(deps.config, session?.header.cwd);
|
|
46
|
+
const writePolicy = storyWritePolicy(root.dir, deps.policy, session);
|
|
47
|
+
const key = `${root.dir}\u0000${writePolicy?.mode ?? ''}`;
|
|
48
|
+
let store = cache.get(key);
|
|
49
|
+
if (store === undefined) {
|
|
50
|
+
store = new ProjectStore(deps.fs, root.dir, deps.log, writePolicy);
|
|
51
|
+
cache.set(key, store);
|
|
52
|
+
if (cache.size > MAX_CACHED_ROOTS) {
|
|
53
|
+
const oldest = cache.keys().next().value;
|
|
54
|
+
if (oldest !== undefined)
|
|
55
|
+
cache.delete(oldest);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { store, root, session };
|
|
59
|
+
};
|
|
60
|
+
}
|