@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,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plugin's write boundary, and the two ways a workspace can disagree with
|
|
3
|
+
* it.
|
|
4
|
+
*
|
|
5
|
+
* Every write this plugin makes — from the panel and from a model tool call
|
|
6
|
+
* alike, it is the same code path — goes through `ctx.fs` with an explicit
|
|
7
|
+
* policy. That matters because `fs-sandbox` otherwise calls
|
|
8
|
+
* `ctx.sandboxPolicy.resolve()` with **no session**: a call with no policy of
|
|
9
|
+
* its own is judged against the *deployment* fallback, `defaultMode` plus
|
|
10
|
+
* `workspaceRoot` (whose own default is wherever dsh was launched), never
|
|
11
|
+
* against the story root it is actually writing to.
|
|
12
|
+
*
|
|
13
|
+
* So {@link storyWritePolicy} states the boundary per call: the story root, which
|
|
14
|
+
* is `<workspace>/novels` under the Session that made the call (`root.ts`).
|
|
15
|
+
* Nothing is widened by that — the root is inside the Session's own workspace
|
|
16
|
+
* unless a profile pinned one elsewhere — and `fs-sandbox` still re-canonicalizes
|
|
17
|
+
* the target and enforces containment against it, which is the check that
|
|
18
|
+
* actually stops a path escaping.
|
|
19
|
+
*
|
|
20
|
+
* The **mode** is not invented either: it comes from `resolve({ session })`,
|
|
21
|
+
* the same call `fs-sandbox` makes, so a Session the operator has switched to
|
|
22
|
+
* `danger-full-access` (or a deployment still under `read-only`) behaves here
|
|
23
|
+
* exactly as it does for the model's own `write`/`edit` and `pwsh`.
|
|
24
|
+
*
|
|
25
|
+
* What is left to report is therefore not "can this plugin write" — it can, into
|
|
26
|
+
* its own shelf — but the two arrangements where the *other* writer cannot:
|
|
27
|
+
* a `read-only` deployment, where nothing may write at all, and a pinned
|
|
28
|
+
* `rootDir` outside the Session's workspace, where the plugin's own writes
|
|
29
|
+
* succeed but the model's tools and scripts are refused by the very same
|
|
30
|
+
* boundary they are confined to.
|
|
31
|
+
*
|
|
32
|
+
* @module notebook/story/sandbox
|
|
33
|
+
*/
|
|
34
|
+
import { homedir } from 'node:os';
|
|
35
|
+
import { join, resolve, sep } from 'node:path';
|
|
36
|
+
/**
|
|
37
|
+
* Whether `child` is `parent` or lives under it.
|
|
38
|
+
*
|
|
39
|
+
* Advisory only — this decides what to *say*, while `fs-sandbox` does the
|
|
40
|
+
* canonical containment check that decides what happens. Windows paths are
|
|
41
|
+
* compared case-insensitively because the filesystem is.
|
|
42
|
+
*/
|
|
43
|
+
function isUnder(child, parent) {
|
|
44
|
+
const outer = resolve(parent);
|
|
45
|
+
const inner = resolve(child);
|
|
46
|
+
const fold = (value) => (process.platform === 'win32' ? value.toLowerCase() : value);
|
|
47
|
+
const outerKey = fold(outer);
|
|
48
|
+
const innerKey = fold(inner);
|
|
49
|
+
if (innerKey === outerKey)
|
|
50
|
+
return true;
|
|
51
|
+
return innerKey.startsWith(outerKey.endsWith(sep) ? outerKey : outerKey + sep);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The mode one call runs under, resolved exactly as `fs-sandbox` resolves it.
|
|
55
|
+
*
|
|
56
|
+
* A Session carries its own mode log (`sandbox/mode`), so the panel must ask
|
|
57
|
+
* about the Session rather than read `defaultMode`: the operator can switch a
|
|
58
|
+
* Session to `danger-full-access` while the deployment stays `read-only`, and a
|
|
59
|
+
* panel disagreeing with the tools about that is a lie in the UI.
|
|
60
|
+
* @param policy - the sandbox policy service.
|
|
61
|
+
* @param session - the calling Session, when the caller named one.
|
|
62
|
+
* @returns the effective mode for that call.
|
|
63
|
+
*/
|
|
64
|
+
export function callMode(policy, session) {
|
|
65
|
+
return policy.resolve(session === undefined ? {} : { session }).mode;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The policy to stamp on every write of one story root.
|
|
69
|
+
*
|
|
70
|
+
* The mode is the caller's own; the boundary becomes the directory the stories
|
|
71
|
+
* actually live in.
|
|
72
|
+
* @param rootDir - the resolved absolute story root for this call.
|
|
73
|
+
* @param policy - the sandbox policy service, when the profile has one.
|
|
74
|
+
* @param session - the calling Session, when the caller named one.
|
|
75
|
+
* @returns the per-call policy, or `undefined` when nothing confines this
|
|
76
|
+
* profile's writes and there is therefore nothing to stamp.
|
|
77
|
+
*/
|
|
78
|
+
export function storyWritePolicy(rootDir, policy, session) {
|
|
79
|
+
if (policy === undefined)
|
|
80
|
+
return undefined;
|
|
81
|
+
return { mode: callMode(policy, session), workspaceRoot: rootDir };
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Decide whether a write to `rootDir` should be expected to work, and warn when
|
|
85
|
+
* the model's own tools will not be able to follow.
|
|
86
|
+
*
|
|
87
|
+
* Advisory only: the caller reports this and uses it to explain a failure, but
|
|
88
|
+
* still attempts the write, because refusing a write that would have succeeded
|
|
89
|
+
* is worse than a warning that turns out to be unnecessary.
|
|
90
|
+
* @param rootDir - the resolved absolute story root for this call.
|
|
91
|
+
* @param policy - the sandbox policy service, when this profile has one.
|
|
92
|
+
* @param session - the calling Session, when the caller named one.
|
|
93
|
+
* @returns the assessment shown in the panel and used to explain failures.
|
|
94
|
+
*/
|
|
95
|
+
export function assessWriteAccess(rootDir, policy, session) {
|
|
96
|
+
if (policy === undefined)
|
|
97
|
+
return { writable: true };
|
|
98
|
+
const mode = callMode(policy, session);
|
|
99
|
+
if (mode === 'read-only')
|
|
100
|
+
return { writable: false, mode, workspaceRoot: rootDir, reason: 'read-only' };
|
|
101
|
+
const workspace = session?.header.cwd;
|
|
102
|
+
if (workspace !== undefined && workspace.trim().length > 0 && !isUnder(rootDir, workspace.trim())) {
|
|
103
|
+
// Not a refusal: the plugin stamps its own boundary and writes here happily.
|
|
104
|
+
// It is the model's half that cannot follow, and silence about that is how a
|
|
105
|
+
// half-working setup looks like a working one.
|
|
106
|
+
return {
|
|
107
|
+
writable: true,
|
|
108
|
+
mode,
|
|
109
|
+
workspaceRoot: rootDir,
|
|
110
|
+
reason: 'outside-workspace',
|
|
111
|
+
sessionWorkspace: workspace.trim(),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return { writable: true, mode, workspaceRoot: rootDir };
|
|
115
|
+
}
|
|
116
|
+
/** The profile patch file a user edits to change the sandbox mode. */
|
|
117
|
+
export function profilePatchPath() {
|
|
118
|
+
const home = process.env.DSH_HOME?.trim();
|
|
119
|
+
const profile = process.env.DSH_PROFILE?.trim() || 'web';
|
|
120
|
+
const base = home !== undefined && home.length > 0 ? home : join(homedir(), '.dsh');
|
|
121
|
+
return join(base, 'profiles', profile, 'cordis.patch.yml');
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Explain a read-only deployment and give the exact edit that lifts it.
|
|
125
|
+
*
|
|
126
|
+
* The mode is the only knob that can be turned from here — the story boundary
|
|
127
|
+
* follows the call, so the remedy for a *read-only* deployment is a mode change,
|
|
128
|
+
* not a directory move. A pinned `rootDir` is a different failure (see
|
|
129
|
+
* {@link outsideWorkspaceGuidance}) and is fixed by editing that pin. The YAML is
|
|
130
|
+
* spelled out rather than described because `config` in a Loader patch is
|
|
131
|
+
* replaced wholesale, never deep-merged — an entry that set only `mode` would
|
|
132
|
+
* reset `workspaceRoot` to `process.cwd()`.
|
|
133
|
+
* @param rootDir - the root the refused call resolved to.
|
|
134
|
+
* @param access - the assessment for that root.
|
|
135
|
+
* @returns a multi-line message suitable for the panel and for a tool result.
|
|
136
|
+
*/
|
|
137
|
+
function readOnlyGuidance(rootDir, access) {
|
|
138
|
+
const patch = profilePatchPath();
|
|
139
|
+
return [
|
|
140
|
+
`目录 ${rootDir} 不可写:当前部署的文件策略是 read-only,插件的每一次写入都会被拒绝。`,
|
|
141
|
+
'',
|
|
142
|
+
`在 ${patch} 里放行(config 是整体替换,所以要连 mode 一起写):`,
|
|
143
|
+
'',
|
|
144
|
+
' - id: sandbox-policy',
|
|
145
|
+
' config:',
|
|
146
|
+
" mode: !!js process.env.DSH_PERMISSION_MODE ?? 'workspace-write'",
|
|
147
|
+
` workspaceRoot: ${access.workspaceRoot ?? rootDir}`,
|
|
148
|
+
].join('\n');
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Explain a root that sits outside the open workspace.
|
|
152
|
+
*
|
|
153
|
+
* Nothing here is broken from the plugin's side — which is exactly why it has to
|
|
154
|
+
* be said out loud, in both directions: what still works, and what does not.
|
|
155
|
+
* @param rootDir - the root the call resolved to.
|
|
156
|
+
* @param access - the assessment for that root.
|
|
157
|
+
* @returns a multi-line message suitable for the panel and for a tool result.
|
|
158
|
+
*/
|
|
159
|
+
function outsideWorkspaceGuidance(rootDir, access) {
|
|
160
|
+
const workspace = access.sessionWorkspace ?? '当前工作区';
|
|
161
|
+
return [
|
|
162
|
+
`目录 ${rootDir} 不在当前工作区 ${workspace} 之内(由 profile 里的 rootDir 固定)。`,
|
|
163
|
+
'',
|
|
164
|
+
'面板照常读写:插件给每次写入盖的边界就是这个目录本身。',
|
|
165
|
+
'但模型自己的 write/edit 工具,以及 pwsh / python 脚本,边界是本会话的工作区,',
|
|
166
|
+
'在这里会被沙箱拒绝(读不受影响)。',
|
|
167
|
+
'',
|
|
168
|
+
'两种改法,任选其一:',
|
|
169
|
+
` · 去掉 profile 里的 rootDir,笔记本就落在工作区 ${workspace};`,
|
|
170
|
+
' · 或者把这个目录本身作为工作区打开。',
|
|
171
|
+
].join('\n');
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The remedy text for a root that cannot be written, or that only this plugin
|
|
175
|
+
* can write.
|
|
176
|
+
* @param rootDir - the story root the call resolved to.
|
|
177
|
+
* @param access - the assessment for that root.
|
|
178
|
+
* @returns a multi-line message, or `null` when there is nothing to say.
|
|
179
|
+
*/
|
|
180
|
+
export function writeAccessGuidance(rootDir, access) {
|
|
181
|
+
if (access.reason === 'read-only')
|
|
182
|
+
return readOnlyGuidance(rootDir, access);
|
|
183
|
+
if (access.reason === 'outside-workspace')
|
|
184
|
+
return outsideWorkspaceGuidance(rootDir, access);
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { ProjectStore } from './project.js';
|
|
2
|
+
import { storyWritePolicy } from './sandbox.js';
|
|
3
|
+
/**
|
|
4
|
+
* The directory the panel's tree shows.
|
|
5
|
+
*
|
|
6
|
+
* A live Session knows it exactly (`header.cwd`, the folder the operator opened).
|
|
7
|
+
* Without one — a scripted caller, or the moment before the page binds — the
|
|
8
|
+
* session-less fallback root *is* the workspace, so it is used as is.
|
|
9
|
+
* @param session - the calling Session, when live.
|
|
10
|
+
* @param fallbackRoot - the store root resolved for this call.
|
|
11
|
+
* @returns an absolute path to the workspace.
|
|
12
|
+
*/
|
|
13
|
+
export function workspaceDirFor(session, fallbackRoot) {
|
|
14
|
+
const cwd = session?.header.cwd;
|
|
15
|
+
return typeof cwd === 'string' && cwd.length > 0 ? cwd : fallbackRoot;
|
|
16
|
+
}
|
|
17
|
+
/** Workspaces kept as live stores; beyond this the oldest is dropped. */
|
|
18
|
+
const MAX_CACHED_WORKSPACES = 8;
|
|
19
|
+
/** One store per (workspace, sandbox mode). */
|
|
20
|
+
const cache = new Map();
|
|
21
|
+
/**
|
|
22
|
+
* Build (or reuse) the store that treats one workspace as its root.
|
|
23
|
+
*
|
|
24
|
+
* Cached per (directory, sandbox mode): the mode can be switched while the plugin
|
|
25
|
+
* serves a Session, and a store holds the policy it was stamped with, so a second
|
|
26
|
+
* entry costs one listing.
|
|
27
|
+
* @param deps - filesystem, sandbox policy, logger.
|
|
28
|
+
* @param session - the calling Session, for the write policy.
|
|
29
|
+
* @param dir - the workspace directory.
|
|
30
|
+
* @returns a store whose root is `dir` and whose only project is that directory.
|
|
31
|
+
*/
|
|
32
|
+
export function workspaceStore(deps, session, dir) {
|
|
33
|
+
const write = storyWritePolicy(dir, deps.policy, session);
|
|
34
|
+
const key = `${dir}\u0000${write?.mode ?? ''}`;
|
|
35
|
+
let store = cache.get(key);
|
|
36
|
+
if (store === undefined) {
|
|
37
|
+
store = new ProjectStore(deps.fs, dir, deps.log, write);
|
|
38
|
+
cache.set(key, store);
|
|
39
|
+
if (cache.size > MAX_CACHED_WORKSPACES) {
|
|
40
|
+
const oldest = cache.keys().next().value;
|
|
41
|
+
if (oldest !== undefined)
|
|
42
|
+
cache.delete(oldest);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return store;
|
|
46
|
+
}
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { startRender } from './render/jobs.js';
|
|
2
|
+
import { PROSE_DIR } from './story/manuscript.js';
|
|
3
|
+
import { NotebookError } from './errors.js';
|
|
4
|
+
/** Read a required string argument. */
|
|
5
|
+
function requireString(args, key) {
|
|
6
|
+
const value = args[key];
|
|
7
|
+
if (typeof value !== 'string' || value.trim().length === 0) {
|
|
8
|
+
throw new NotebookError('bad-request', `${key} must be a non-empty string`);
|
|
9
|
+
}
|
|
10
|
+
return value;
|
|
11
|
+
}
|
|
12
|
+
/** Read an optional string argument. */
|
|
13
|
+
function optionalString(args, key) {
|
|
14
|
+
const value = args[key];
|
|
15
|
+
return typeof value === 'string' && value.length > 0 ? value : undefined;
|
|
16
|
+
}
|
|
17
|
+
/** Read an optional array of strings. */
|
|
18
|
+
function stringArray(args, key) {
|
|
19
|
+
const value = args[key];
|
|
20
|
+
if (value === undefined)
|
|
21
|
+
return [];
|
|
22
|
+
if (!Array.isArray(value))
|
|
23
|
+
throw new NotebookError('bad-request', `${key} must be an array of strings`);
|
|
24
|
+
return value.filter((item) => typeof item === 'string');
|
|
25
|
+
}
|
|
26
|
+
function text(value) {
|
|
27
|
+
return [{ type: 'text', text: value }];
|
|
28
|
+
}
|
|
29
|
+
/** The generic result envelope: one schema, one renderer per tool. */
|
|
30
|
+
function envelope(properties, required) {
|
|
31
|
+
return { type: 'object', properties, required, additionalProperties: false };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Build the tool definitions.
|
|
35
|
+
* @param deps - the root resolver, job registry, backend and logger shared with the page.
|
|
36
|
+
* @returns the definitions, in registration order.
|
|
37
|
+
*/
|
|
38
|
+
export function buildTools(deps) {
|
|
39
|
+
const { roots, jobs, backend, log, focus } = deps;
|
|
40
|
+
/**
|
|
41
|
+
* Resolve one call's store, and put the Session in the story it names.
|
|
42
|
+
*
|
|
43
|
+
* Failures are swallowed on purpose: the operation that follows reports a
|
|
44
|
+
* missing or malformed story with its own error, and a profile without Session
|
|
45
|
+
* machinery still gets a usable store.
|
|
46
|
+
*/
|
|
47
|
+
const enter = async (exec, projectId) => {
|
|
48
|
+
const { store } = roots(exec.agent?.id);
|
|
49
|
+
if (projectId !== undefined && focus !== undefined) {
|
|
50
|
+
try {
|
|
51
|
+
const opened = await store.open(projectId);
|
|
52
|
+
await focus(exec.agent?.id, opened.abs);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
// Reported by the operation itself, with its own status code.
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return store;
|
|
59
|
+
};
|
|
60
|
+
return [
|
|
61
|
+
{
|
|
62
|
+
name: 'novel_projects',
|
|
63
|
+
description: 'List, inspect or create novel projects in the 笔记本 workspace. '
|
|
64
|
+
+ 'A project is a directory holding the manuscript, the design bible and the comic storyboards. '
|
|
65
|
+
+ 'Call this first to discover a project id before reading or writing anything. '
|
|
66
|
+
+ 'A story is created inside the workspace the user has open, so its name becomes '
|
|
67
|
+
+ 'both the project id and the directory name there. A new story holds one file, '
|
|
68
|
+
+ 'README.md — the usage guide: the three regions of the panel, the recommended layout '
|
|
69
|
+
+ '(世界观/人物/势力/关系/大纲/正文/追踪) and what the tools read; '
|
|
70
|
+
+ 'make the directories you need as you write.',
|
|
71
|
+
parameters: {
|
|
72
|
+
type: 'object',
|
|
73
|
+
properties: {
|
|
74
|
+
action: { type: 'string', enum: ['list', 'info', 'create'], description: 'Operation to perform.' },
|
|
75
|
+
project: { type: 'string', description: 'Project id. Required for info.' },
|
|
76
|
+
name: { type: 'string', description: 'Story name. It becomes the project id and the directory name, so it may be Chinese; it must not contain < > : " / \\ | ? * or control characters, be a reserved device name such as CON, or end in a dot or space. Required for create.' },
|
|
77
|
+
},
|
|
78
|
+
required: ['action'],
|
|
79
|
+
additionalProperties: false,
|
|
80
|
+
},
|
|
81
|
+
output: {
|
|
82
|
+
schema: envelope({ result: { type: 'string' } }, ['result']),
|
|
83
|
+
render: (_args, value) => text(String(value.result ?? '')),
|
|
84
|
+
},
|
|
85
|
+
async execute(args, exec) {
|
|
86
|
+
const store = await enter(exec);
|
|
87
|
+
const action = requireString(args, 'action');
|
|
88
|
+
if (action === 'list') {
|
|
89
|
+
const projects = await store.list();
|
|
90
|
+
if (projects.length === 0)
|
|
91
|
+
return { result: 'No projects exist yet. Create one with action "create".' };
|
|
92
|
+
return {
|
|
93
|
+
result: projects
|
|
94
|
+
.map(project => `- ${project.id} — "${project.title}" · ${String(project.chapterCount)} chapters · ${String(project.charCount)} chars · ${String(project.characterCount)} characters · ${String(project.sceneCount)} scenes · episodes: ${project.episodes.join(', ') || 'none'}`)
|
|
95
|
+
.join('\n'),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (action === 'create') {
|
|
99
|
+
// `id` is accepted as the older spelling of `name`.
|
|
100
|
+
const created = await store.create(optionalString(args, 'name') ?? requireString(args, 'id'));
|
|
101
|
+
// A story that was just created is the one about to be written.
|
|
102
|
+
await enter(exec, created.id);
|
|
103
|
+
return {
|
|
104
|
+
result: `Created story ${created.id} ("${created.title}"). It holds a README.md — a usage guide naming `
|
|
105
|
+
+ `the recommended layout (世界观/人物/势力/关系/大纲/正文/追踪) and what the tools read; `
|
|
106
|
+
+ `create a directory by writing the first file into it.`,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
// No `set-root` and no equivalent: the story root is derived from the
|
|
110
|
+
// workspace the operator opened, and nothing here can re-point it. A model
|
|
111
|
+
// able to move the write boundary could write anywhere the panel can,
|
|
112
|
+
// which is exactly what the file sandbox exists to prevent.
|
|
113
|
+
if (action === 'info') {
|
|
114
|
+
const snapshot = await store.snapshot(requireString(args, 'project'));
|
|
115
|
+
return {
|
|
116
|
+
result: [
|
|
117
|
+
`Project ${snapshot.summary.id} — "${snapshot.summary.title}"`,
|
|
118
|
+
`chapters: ${snapshot.chapters.map(chapter => chapter.path).join(', ') || 'none'}`,
|
|
119
|
+
`characters: ${snapshot.bible.characters.map(card => `${card.id} (${card.name})`).join(', ') || 'none'}`,
|
|
120
|
+
`scenes: ${snapshot.bible.scenes.map(card => `${card.id} (${card.name})`).join(', ') || 'none'}`,
|
|
121
|
+
`episodes: ${snapshot.storyboards.map(board => `${board.episode} (${String(board.shots.length)} shots)`).join(', ') || 'none'}`,
|
|
122
|
+
].join('\n'),
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
throw new NotebookError('bad-request', `unknown action ${JSON.stringify(action)}`);
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
{
|
|
129
|
+
name: 'novel_chapters',
|
|
130
|
+
description: 'Read and write the manuscript of a novel project. '
|
|
131
|
+
+ 'Chapters are markdown files under the project\'s 正文/ directory (novel/ in projects created before the story scaffold existed); the path is project-relative and always ends in .md. '
|
|
132
|
+
+ 'Use action "list" to discover paths, "read" to load one, and "write" to create or fully replace one.',
|
|
133
|
+
parameters: {
|
|
134
|
+
type: 'object',
|
|
135
|
+
properties: {
|
|
136
|
+
action: { type: 'string', enum: ['list', 'read', 'write'], description: 'Operation to perform.' },
|
|
137
|
+
project: { type: 'string', description: 'Project id.' },
|
|
138
|
+
path: { type: 'string', description: 'Project-relative chapter path such as "正文/开端.md". Required for read. For write, omit to mint the next free path.' },
|
|
139
|
+
dir: { type: 'string', description: 'Directory for a newly minted path, such as "正文" or "人物". Defaults to 正文. Ignored when path is given.' },
|
|
140
|
+
title: { type: 'string', description: 'Chapter title when writing to a newly minted path. Becomes the file name.' },
|
|
141
|
+
content: { type: 'string', description: 'Full markdown body. Required for write; replaces the file completely.' },
|
|
142
|
+
},
|
|
143
|
+
required: ['action', 'project'],
|
|
144
|
+
additionalProperties: false,
|
|
145
|
+
},
|
|
146
|
+
output: {
|
|
147
|
+
schema: envelope({ result: { type: 'string' } }, ['result']),
|
|
148
|
+
render: (_args, value) => text(String(value.result ?? '')),
|
|
149
|
+
},
|
|
150
|
+
async execute(args, exec) {
|
|
151
|
+
const action = requireString(args, 'action');
|
|
152
|
+
const projectId = requireString(args, 'project');
|
|
153
|
+
const store = await enter(exec, projectId);
|
|
154
|
+
if (action === 'list') {
|
|
155
|
+
const snapshot = await store.snapshot(projectId);
|
|
156
|
+
if (snapshot.chapters.length === 0)
|
|
157
|
+
return { result: `Project ${projectId} has no chapters yet.` };
|
|
158
|
+
return {
|
|
159
|
+
result: snapshot.chapters
|
|
160
|
+
.map(chapter => `- ${chapter.path} — "${chapter.title}" (${String(chapter.chars)} chars)`)
|
|
161
|
+
.join('\n'),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
if (action === 'read') {
|
|
165
|
+
const chapter = await store.readChapter(projectId, requireString(args, 'path'));
|
|
166
|
+
return { result: `<path>${chapter.path}</path>\n<title>${chapter.title}</title>\n<content>\n${chapter.content}\n</content>` };
|
|
167
|
+
}
|
|
168
|
+
if (action === 'write') {
|
|
169
|
+
const content = typeof args.content === 'string' ? args.content : undefined;
|
|
170
|
+
if (content === undefined)
|
|
171
|
+
throw new NotebookError('bad-request', 'content is required for action "write"');
|
|
172
|
+
let path = optionalString(args, 'path');
|
|
173
|
+
if (path === undefined) {
|
|
174
|
+
// The tool writes chapters, so an unminted path is prose. The panel
|
|
175
|
+
// sends the directory the author is browsing instead.
|
|
176
|
+
path = await store.newFilePath(await store.open(projectId), optionalString(args, 'dir') ?? PROSE_DIR, optionalString(args, 'title') ?? 'chapter');
|
|
177
|
+
}
|
|
178
|
+
const written = await store.writeChapter(projectId, path, content);
|
|
179
|
+
return { result: `Wrote ${written.path} ("${written.title}", ${String(written.chars)} chars).` };
|
|
180
|
+
}
|
|
181
|
+
throw new NotebookError('bad-request', `unknown action ${JSON.stringify(action)}`);
|
|
182
|
+
},
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
name: 'novel_bible',
|
|
186
|
+
description: 'Read or replace a project\'s design bible: the render style plus the character and scene cards used to adapt the novel into comics. '
|
|
187
|
+
+ 'A character card\'s `prompt` is a frozen appearance prefix reused verbatim by every panel that includes that character — write it once, carefully, and do not paraphrase it later. '
|
|
188
|
+
+ 'A card\'s `seed` fixes that character\'s appearance; keep it unchanged across a whole project.',
|
|
189
|
+
parameters: {
|
|
190
|
+
type: 'object',
|
|
191
|
+
properties: {
|
|
192
|
+
action: { type: 'string', enum: ['get', 'put'], description: 'Operation to perform.' },
|
|
193
|
+
project: { type: 'string', description: 'Project id.' },
|
|
194
|
+
bible: {
|
|
195
|
+
type: 'object',
|
|
196
|
+
description: 'Full bible for action "put". Replaces the stored bible completely, so read it first with "get" and send back the whole document.',
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
required: ['action', 'project'],
|
|
200
|
+
additionalProperties: false,
|
|
201
|
+
},
|
|
202
|
+
output: {
|
|
203
|
+
schema: envelope({ result: { type: 'string' } }, ['result']),
|
|
204
|
+
render: (_args, value) => text(String(value.result ?? '')),
|
|
205
|
+
},
|
|
206
|
+
async execute(args, exec) {
|
|
207
|
+
const action = requireString(args, 'action');
|
|
208
|
+
const projectId = requireString(args, 'project');
|
|
209
|
+
const store = await enter(exec, projectId);
|
|
210
|
+
const project = await store.open(projectId);
|
|
211
|
+
if (action === 'get')
|
|
212
|
+
return { result: JSON.stringify(await store.readBible(project), null, 2) };
|
|
213
|
+
if (action === 'put') {
|
|
214
|
+
const bible = args.bible;
|
|
215
|
+
if (typeof bible !== 'object' || bible === null)
|
|
216
|
+
throw new NotebookError('bad-request', 'bible must be an object');
|
|
217
|
+
const saved = await store.writeBible(project, bible);
|
|
218
|
+
return { result: `Saved bible: ${String(saved.characters.length)} characters, ${String(saved.scenes.length)} scenes.` };
|
|
219
|
+
}
|
|
220
|
+
throw new NotebookError('bad-request', `unknown action ${JSON.stringify(action)}`);
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
name: 'comic_storyboard',
|
|
225
|
+
description: 'Read or replace one episode\'s storyboard: the ordered panels that adapt the manuscript into comic pages. '
|
|
226
|
+
+ 'Each shot names the character and scene card ids it depicts; the render step assembles the image prompt from those cards plus the shot description. '
|
|
227
|
+
+ 'Use action "get" first, edit the returned JSON, and send the whole document back with "put".',
|
|
228
|
+
parameters: {
|
|
229
|
+
type: 'object',
|
|
230
|
+
properties: {
|
|
231
|
+
action: { type: 'string', enum: ['get', 'put'], description: 'Operation to perform.' },
|
|
232
|
+
project: { type: 'string', description: 'Project id.' },
|
|
233
|
+
board: {
|
|
234
|
+
type: 'object',
|
|
235
|
+
description: 'Full storyboard for action "put". Replaces the stored board completely. '
|
|
236
|
+
+ 'Shape: { episode, title?, sourceChapters?: string[], style?, '
|
|
237
|
+
+ 'shots: [{ id, description, characterIds: string[], sceneId?, dialogue?, caption?, seed, status? }] }. '
|
|
238
|
+
+ 'The fields are "characterIds" and "sceneId" — not "characters" and "scene"; a shot whose ids do not '
|
|
239
|
+
+ 'match a bible card just renders without that card. Easiest path: action "get", edit the returned JSON, '
|
|
240
|
+
+ 'send the whole document back.',
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
required: ['action', 'project'],
|
|
244
|
+
additionalProperties: false,
|
|
245
|
+
},
|
|
246
|
+
output: {
|
|
247
|
+
schema: envelope({ result: { type: 'string' } }, ['result']),
|
|
248
|
+
render: (_args, value) => text(String(value.result ?? '')),
|
|
249
|
+
},
|
|
250
|
+
async execute(args, exec) {
|
|
251
|
+
const action = requireString(args, 'action');
|
|
252
|
+
const projectId = requireString(args, 'project');
|
|
253
|
+
const store = await enter(exec, projectId);
|
|
254
|
+
const project = await store.open(projectId);
|
|
255
|
+
const readEpisode = () => {
|
|
256
|
+
if (typeof args.board === 'object' && args.board !== null) {
|
|
257
|
+
const episode = args.board.episode;
|
|
258
|
+
if (typeof episode === 'string')
|
|
259
|
+
return episode;
|
|
260
|
+
}
|
|
261
|
+
return requireString(args, 'episode');
|
|
262
|
+
};
|
|
263
|
+
if (action === 'get') {
|
|
264
|
+
const board = await store.readStoryboard(project, requireString(args, 'episode'));
|
|
265
|
+
return { result: JSON.stringify(board, null, 2) };
|
|
266
|
+
}
|
|
267
|
+
if (action === 'put') {
|
|
268
|
+
const board = args.board;
|
|
269
|
+
if (typeof board !== 'object' || board === null)
|
|
270
|
+
throw new NotebookError('bad-request', 'board must be an object');
|
|
271
|
+
const saved = await store.writeStoryboard(project, readEpisode(), board);
|
|
272
|
+
return { result: `Saved storyboard for episode ${saved.episode}: ${String(saved.shots.length)} shots.` };
|
|
273
|
+
}
|
|
274
|
+
throw new NotebookError('bad-request', `unknown action ${JSON.stringify(action)}`);
|
|
275
|
+
},
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
name: 'comic_render',
|
|
279
|
+
description: 'Render storyboard panels into images. '
|
|
280
|
+
+ 'Action "start" queues a batch and returns a job id immediately — rendering takes minutes, so poll action "status" rather than waiting. '
|
|
281
|
+
+ 'Panels are written to the project as they finish, so a failed or cancelled batch keeps everything it completed.',
|
|
282
|
+
parameters: {
|
|
283
|
+
type: 'object',
|
|
284
|
+
properties: {
|
|
285
|
+
action: { type: 'string', enum: ['start', 'status', 'cancel'], description: 'Operation to perform.' },
|
|
286
|
+
project: { type: 'string', description: 'Project id. Required for start.' },
|
|
287
|
+
episode: { type: 'string', description: 'Episode id. Required for start.' },
|
|
288
|
+
shotIds: { type: 'array', items: { type: 'string' }, description: 'Render only these panel ids. Omit to render every panel in the episode.' },
|
|
289
|
+
job: { type: 'string', description: 'Job id. Required for cancel.' },
|
|
290
|
+
},
|
|
291
|
+
required: ['action'],
|
|
292
|
+
additionalProperties: false,
|
|
293
|
+
},
|
|
294
|
+
output: {
|
|
295
|
+
schema: envelope({ result: { type: 'string' } }, ['result']),
|
|
296
|
+
render: (_args, value) => text(String(value.result ?? '')),
|
|
297
|
+
},
|
|
298
|
+
async execute(args, exec) {
|
|
299
|
+
const action = requireString(args, 'action');
|
|
300
|
+
// Only a `start` names a story; `status` and `cancel` are about jobs.
|
|
301
|
+
const named = optionalString(args, 'project');
|
|
302
|
+
const store = await enter(exec, action === 'start' ? named : undefined);
|
|
303
|
+
const describe = (job) => `job ${job.id}: ${job.status} (${String(job.completed)}/${String(job.total)})`
|
|
304
|
+
+ (job.message === undefined ? '' : ` — ${job.message}`)
|
|
305
|
+
+ (job.error === undefined ? '' : ` — error: ${job.error}`);
|
|
306
|
+
if (action === 'start') {
|
|
307
|
+
const shotIds = stringArray(args, 'shotIds');
|
|
308
|
+
const job = startRender({ store, backend, jobs, log }, {
|
|
309
|
+
project: requireString(args, 'project'),
|
|
310
|
+
episode: requireString(args, 'episode'),
|
|
311
|
+
...shotIds.length === 0 ? {} : { shotIds },
|
|
312
|
+
});
|
|
313
|
+
return { result: `Started ${describe(job)}. Poll with action "status".` };
|
|
314
|
+
}
|
|
315
|
+
if (action === 'status') {
|
|
316
|
+
const id = optionalString(args, 'job');
|
|
317
|
+
if (id !== undefined) {
|
|
318
|
+
const job = jobs.get(id);
|
|
319
|
+
if (job === undefined)
|
|
320
|
+
throw new NotebookError('not-found', `no job ${id}`);
|
|
321
|
+
return { result: describe(job) };
|
|
322
|
+
}
|
|
323
|
+
const all = jobs.list();
|
|
324
|
+
if (all.length === 0)
|
|
325
|
+
return { result: 'No render jobs have been started.' };
|
|
326
|
+
return { result: all.map(describe).join('\n') };
|
|
327
|
+
}
|
|
328
|
+
if (action === 'cancel') {
|
|
329
|
+
return { result: jobs.cancel(requireString(args, 'job')) ? 'Cancellation requested.' : 'That job is not running.' };
|
|
330
|
+
}
|
|
331
|
+
throw new NotebookError('bad-request', `unknown action ${JSON.stringify(action)}`);
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
];
|
|
335
|
+
}
|
|
336
|
+
/** Register every tool, returning one disposer for all of them. */
|
|
337
|
+
export function registerTools(registry, deps) {
|
|
338
|
+
const disposers = buildTools(deps).map(definition => registry.register(definition));
|
|
339
|
+
return () => { for (const dispose of disposers)
|
|
340
|
+
dispose(); };
|
|
341
|
+
}
|
package/lib/types.js
ADDED
package/locale/en.json
ADDED