@nera-static/mcp 1.2.1 → 1.4.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/.claude-plugin/plugin.json +2 -2
- package/CHANGELOG.md +36 -0
- package/README.md +59 -2
- package/bin/nera-mcp.js +203 -61
- package/docs/llms-full.txt +1122 -153
- package/package.json +4 -2
- package/src/hosted/app.js +129 -0
- package/src/hosted/checkout.js +427 -0
- package/src/hosted/config.js +89 -0
- package/src/hosted/consent.js +141 -0
- package/src/hosted/crypto.js +90 -0
- package/src/hosted/github.js +157 -0
- package/src/hosted/mcp.js +62 -0
- package/src/hosted/provider.js +369 -0
- package/src/hosted/repo.js +475 -0
- package/src/hosted/store.js +472 -0
- package/src/hosted/tools/publish.js +166 -0
- package/src/hosted/tools/read.js +336 -0
- package/src/hosted/tools/validate.js +44 -0
- package/src/hosted/tools/write.js +182 -0
- package/src/pages.js +168 -0
- package/src/prompts.js +52 -0
- package/src/resources.js +15 -3
- package/src/runner.js +35 -10
- package/src/tools/cli.js +7 -1
- package/src/tools/files.js +5 -104
- package/src/tools/long-running.js +96 -36
- package/src/tools/sites.js +31 -7
package/src/pages.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// The page and path rules both modes share (plan D4): how a page file splits
|
|
2
|
+
// into frontmatter and body, how new frontmatter is edited into an existing
|
|
3
|
+
// block, that a page names its `layout`, and which paths no tool reads or
|
|
4
|
+
// writes. Pure functions only — the local file tools (src/tools/files.js) and
|
|
5
|
+
// the hosted repo tools apply them to a file on disk and a file on GitHub alike.
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
8
|
+
import yaml from 'yaml'
|
|
9
|
+
import { ToolError } from './results.js'
|
|
10
|
+
|
|
11
|
+
export const FENCE = '---'
|
|
12
|
+
/** Path segments no file tool reads or writes: git internals may hold credentials. */
|
|
13
|
+
export const FORBIDDEN_SEGMENTS = new Set(['.git'])
|
|
14
|
+
/** File names no file tool reads or writes: `.env` files and `.npmrc` (npm `_authToken`) hold tokens. */
|
|
15
|
+
export const SECRET_FILE = /^(\.env(\..*)?|\.npmrc)$/
|
|
16
|
+
/** Path segments write_file refuses: installed packages belong to npm. */
|
|
17
|
+
export const NO_WRITE_SEGMENTS = new Set(['node_modules'])
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Splits a page into its frontmatter YAML and its Markdown body, the way the
|
|
21
|
+
* build reads it: a `---` first line opens the block, the next `---` line
|
|
22
|
+
* closes it (no closing line: the rest is frontmatter).
|
|
23
|
+
*
|
|
24
|
+
* @param {string} raw the file's text
|
|
25
|
+
* @returns {{ yamlText: string|null, body: string }} `yamlText` null when the page has no frontmatter
|
|
26
|
+
*/
|
|
27
|
+
export function splitPage(raw) {
|
|
28
|
+
// markdown-it, which the build parses pages with, reads CRLF as LF.
|
|
29
|
+
const lines = raw.replace(/\r\n/g, '\n').split('\n')
|
|
30
|
+
if (lines[0] !== FENCE) return { yamlText: null, body: raw }
|
|
31
|
+
const close = lines.indexOf(FENCE, 1)
|
|
32
|
+
if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
|
|
33
|
+
return {
|
|
34
|
+
yamlText: lines.slice(1, close).join('\n'),
|
|
35
|
+
body: lines.slice(close + 1).join('\n'),
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Parses frontmatter YAML into a document that keeps comments and quoting.
|
|
41
|
+
*
|
|
42
|
+
* @param {string|null} yamlText
|
|
43
|
+
* @returns {{ doc: import('yaml').Document|null, error: string|null }}
|
|
44
|
+
*/
|
|
45
|
+
export function parseFrontmatter(yamlText) {
|
|
46
|
+
const doc = yaml.parseDocument(yamlText ?? '', { merge: true, uniqueKeys: false })
|
|
47
|
+
if (doc.errors.length) {
|
|
48
|
+
return { doc: null, error: doc.errors[0].message }
|
|
49
|
+
}
|
|
50
|
+
if (doc.contents !== null && !yaml.isMap(doc.contents)) {
|
|
51
|
+
return { doc: null, error: 'The frontmatter is not a list of `key: value` lines.' }
|
|
52
|
+
}
|
|
53
|
+
return { doc, error: null }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Reads a page's text the way read_page returns it: the frontmatter as JSON
|
|
58
|
+
* (null when its YAML is invalid, with `error` saying why) and the body
|
|
59
|
+
* without its leading blank lines.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} raw the file's text
|
|
62
|
+
* @returns {{ frontmatter: object|null, body: string, error: string|null }}
|
|
63
|
+
*/
|
|
64
|
+
export function parsePage(raw) {
|
|
65
|
+
const { yamlText, body } = splitPage(raw)
|
|
66
|
+
const { doc, error } = parseFrontmatter(yamlText)
|
|
67
|
+
return { frontmatter: doc ? (doc.toJS() ?? {}) : null, body: body.replace(/^\n+/, ''), error }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The frontmatter YAML for `frontmatter`, edited into the page's existing
|
|
72
|
+
* frontmatter when it has one that parses: unchanged keys keep their comments,
|
|
73
|
+
* quoting and order, a changed value keeps its quoting style, keys left out are
|
|
74
|
+
* removed, new keys are appended. Nothing changed: the block stays byte for byte.
|
|
75
|
+
*
|
|
76
|
+
* @param {string|null} existingYaml the page's current frontmatter, null for none
|
|
77
|
+
* @param {Record<string, unknown>} frontmatter
|
|
78
|
+
* @returns {string}
|
|
79
|
+
*/
|
|
80
|
+
export function frontmatterText(existingYaml, frontmatter) {
|
|
81
|
+
const { doc } = existingYaml === null ? { doc: null } : parseFrontmatter(existingYaml)
|
|
82
|
+
if (!doc || doc.contents === null) {
|
|
83
|
+
return new yaml.Document(frontmatter).toString({ flowCollectionPadding: false })
|
|
84
|
+
}
|
|
85
|
+
const current = doc.toJS() ?? {}
|
|
86
|
+
let changed = false
|
|
87
|
+
for (const key of Object.keys(current)) {
|
|
88
|
+
if (!Object.hasOwn(frontmatter, key)) {
|
|
89
|
+
doc.delete(key)
|
|
90
|
+
changed = true
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
for (const [key, value] of Object.entries(frontmatter)) {
|
|
94
|
+
if (!isDeepStrictEqual(current[key], value)) {
|
|
95
|
+
doc.set(key, value)
|
|
96
|
+
changed = true
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (!changed) return withTrailingNewline(existingYaml)
|
|
100
|
+
return doc.toString({ flowCollectionPadding: false })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* @param {string} text
|
|
105
|
+
* @returns {string} `text`, ending in exactly the newline it had or one added
|
|
106
|
+
*/
|
|
107
|
+
export function withTrailingNewline(text) {
|
|
108
|
+
return text.endsWith('\n') ? text : `${text}\n`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Refuses frontmatter without `layout`: core never renders such a page.
|
|
113
|
+
*
|
|
114
|
+
* @param {Record<string, unknown>} frontmatter
|
|
115
|
+
* @throws {ToolError}
|
|
116
|
+
*/
|
|
117
|
+
export function requireLayout(frontmatter) {
|
|
118
|
+
if (typeof frontmatter.layout !== 'string' || frontmatter.layout.trim() === '') {
|
|
119
|
+
throw new ToolError('The frontmatter has no `layout`. Nera only renders pages that name their layout — add e.g. `layout: pages/default.pug` (read an existing page with read_page to see which layout the site uses).')
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* The new text of a page written by write_page.
|
|
125
|
+
*
|
|
126
|
+
* @param {string|null} raw the page's current text, null for a new page
|
|
127
|
+
* @param {Record<string, unknown>} frontmatter
|
|
128
|
+
* @param {string} [body] the new Markdown body; undefined keeps the existing one
|
|
129
|
+
* @returns {string}
|
|
130
|
+
*/
|
|
131
|
+
export function composePage(raw, frontmatter, body) {
|
|
132
|
+
const existing = raw === null ? null : splitPage(raw)
|
|
133
|
+
const head = `${FENCE}\n${frontmatterText(existing?.yamlText ?? null, frontmatter)}${FENCE}\n`
|
|
134
|
+
return body === undefined
|
|
135
|
+
? head + (existing?.body ?? '')
|
|
136
|
+
: `${head}\n${withTrailingNewline(body.replace(/^\n+/, ''))}`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Refuses `input` when it, or the site-relative real path it resolved to (a
|
|
141
|
+
* symbolic link may point into `.git/`), has a segment from `segments`.
|
|
142
|
+
*
|
|
143
|
+
* @param {string} input the path as the model gave it
|
|
144
|
+
* @param {string} resolved the site-relative path it resolved to
|
|
145
|
+
* @param {Set<string>} segments
|
|
146
|
+
* @param {string} why completes "…, which <why>."
|
|
147
|
+
* @throws {ToolError}
|
|
148
|
+
*/
|
|
149
|
+
export function refuseSegments(input, resolved, segments, why) {
|
|
150
|
+
const hit = [input, resolved]
|
|
151
|
+
.flatMap((candidate) => candidate.split(/[\\/]/))
|
|
152
|
+
.find((segment) => segments.has(segment))
|
|
153
|
+
if (hit) throw new ToolError(`"${input}" is inside ${hit}/, which ${why}.`)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Refuses git internals and files that can hold secrets (`.env*`, `.npmrc`).
|
|
158
|
+
*
|
|
159
|
+
* @param {string} input the path as the model gave it
|
|
160
|
+
* @param {string} resolved the site-relative path it resolved to
|
|
161
|
+
* @throws {ToolError}
|
|
162
|
+
*/
|
|
163
|
+
export function refuseSecrets(input, resolved) {
|
|
164
|
+
refuseSegments(input, resolved, FORBIDDEN_SEGMENTS, 'these tools never read or change')
|
|
165
|
+
if ([input, resolved].some((candidate) => SECRET_FILE.test(path.basename(candidate)))) {
|
|
166
|
+
throw new ToolError(`"${input}" can hold secrets (tokens, passwords); these tools never read or change it.`)
|
|
167
|
+
}
|
|
168
|
+
}
|
package/src/prompts.js
CHANGED
|
@@ -95,3 +95,55 @@ Steps:
|
|
|
95
95
|
3. Call publish for the site. It returns a short code and a GitHub web address: give me both and ask me to open the address, sign in to GitHub (or create a free account) and enter the code. Never ask me for a password or token.
|
|
96
96
|
4. After I confirm, call publish again for the same site until it reports the result, and give me the address where the site is now online. Tell me that later changes go online by calling publish again.`))
|
|
97
97
|
}
|
|
98
|
+
|
|
99
|
+
/** What the hosted prompts add: the site is a GitHub repository and changes wait on a draft. */
|
|
100
|
+
const ABOUT_HOSTED = 'Here each site is a GitHub repository of the user. write_page, write_file and delete_page commit to its draft branch nera-draft, one commit each with the message you pass; nothing goes live until publish merges the draft into main, which starts the site\'s deploy workflow once for all changes.'
|
|
101
|
+
|
|
102
|
+
const VALIDATE_AND_PUBLISH = 'Call validate and fix every error it reports (each message says how). Then ask me whether to put the changes live; when I agree, call publish, give me the address it reports and tell me the deploy takes a minute or two (preview shows how it went).'
|
|
103
|
+
|
|
104
|
+
const hostedSiteArg = z.string().optional().describe('The site as `owner/name`, as list_sites returns it; leave out to choose one with list_sites.')
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Registers the task prompts of the hosted mode, worded for its tools (write
|
|
108
|
+
* → validate → publish, no build): add a page, put my site online. The
|
|
109
|
+
* `new_*` prompts need `create_site`, which the hosted mode does not have.
|
|
110
|
+
*
|
|
111
|
+
* @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
|
|
112
|
+
*/
|
|
113
|
+
export function registerHostedPrompts(server) {
|
|
114
|
+
server.registerPrompt('add_page', {
|
|
115
|
+
title: 'Add a page',
|
|
116
|
+
description: 'Add a new page (or blog post) to a Nera site in a GitHub repository, in the style of its other pages, and put it live.',
|
|
117
|
+
argsSchema: {
|
|
118
|
+
site: hostedSiteArg,
|
|
119
|
+
topic: z.string().optional().describe('What the new page is about, e.g. "our new opening hours" or "a post about my trip to Lisbon".'),
|
|
120
|
+
},
|
|
121
|
+
}, ({ site, topic }) => userMessage(`Add a new page to my Nera site.${given('Site', site)}${given('The page', topic)}
|
|
122
|
+
|
|
123
|
+
${ABOUT_NERA}
|
|
124
|
+
|
|
125
|
+
${ABOUT_HOSTED}
|
|
126
|
+
|
|
127
|
+
Steps:
|
|
128
|
+
1. ${site ? `Call get_site with site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one. Then call get_site.'} Read the site's AGENTS.md with read_file if it has one.
|
|
129
|
+
2. Call read_page on an existing page of the same kind (a post for a post, a normal page otherwise) and copy its frontmatter fields and \`layout\`.
|
|
130
|
+
3. Choose a file name that fits the site's other pages (lowercase, hyphens, \`.md\`, in the same folder as its siblings) and write the page with write_page, with a short commit message. Ask me for content you do not know.
|
|
131
|
+
4. If the site has a navigation config (e.g. config/navigation.yaml, see get_site's plugins and read_file), add the page there when it belongs in the menu, with write_file.
|
|
132
|
+
5. ${VALIDATE_AND_PUBLISH}`))
|
|
133
|
+
|
|
134
|
+
server.registerPrompt('put_site_online', {
|
|
135
|
+
title: 'Put my site online',
|
|
136
|
+
description: 'Put the unpublished changes of a Nera site in a GitHub repository live: check them, publish them in one deploy and report the live address.',
|
|
137
|
+
argsSchema: { site: hostedSiteArg },
|
|
138
|
+
}, ({ site }) => userMessage(`Put my Nera site online.${given('Site', site)}
|
|
139
|
+
|
|
140
|
+
${ABOUT_NERA}
|
|
141
|
+
|
|
142
|
+
${ABOUT_HOSTED}
|
|
143
|
+
|
|
144
|
+
Steps:
|
|
145
|
+
1. ${site ? `Use site \`${site}\`.` : 'Call list_sites; if there is more than one site, ask me which one.'} Call preview to see the live address, the last deploy and how many changes wait unpublished.
|
|
146
|
+
2. Call validate and fix every error with write_page or write_file; tell me what you changed.
|
|
147
|
+
3. Call publish for the site. It merges the draft into main in one push and returns the deploy run and the address. If it reports that the repository has no deploy workflow, tell me to run \`nera publish\` once in the site on my computer, which sets it up.
|
|
148
|
+
4. Call preview after a minute or two and tell me whether the deploy succeeded and where the site is live. Tell me that later changes go live by calling publish again.`))
|
|
149
|
+
}
|
package/src/resources.js
CHANGED
|
@@ -53,12 +53,14 @@ function decodeSite(site) {
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
/**
|
|
56
|
-
* Registers the
|
|
56
|
+
* Registers the resources that need no folder: the docs and the three
|
|
57
|
+
* catalogs. The hosted mode offers these alone; a site's `AGENTS.md` is its
|
|
58
|
+
* `read_file` there.
|
|
57
59
|
*
|
|
58
60
|
* @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
|
|
59
|
-
* @param {{
|
|
61
|
+
* @param {{ fetch: typeof fetch, docsFile?: string }} ctx
|
|
60
62
|
*/
|
|
61
|
-
export function
|
|
63
|
+
export function registerDocsResources(server, ctx) {
|
|
62
64
|
const docsFile = ctx.docsFile ?? BUNDLED_DOCS
|
|
63
65
|
|
|
64
66
|
server.registerResource('nera_docs', 'nera://docs/llms-full.txt', {
|
|
@@ -84,6 +86,16 @@ export function registerResources(server, ctx) {
|
|
|
84
86
|
return text(uri, 'application/json', JSON.stringify({ [kindName]: items }, null, 2))
|
|
85
87
|
}))
|
|
86
88
|
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Registers the docs, the three catalogs and each site's `AGENTS.md`.
|
|
93
|
+
*
|
|
94
|
+
* @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
|
|
95
|
+
* @param {{ root: string, fetch: typeof fetch, docsFile?: string }} ctx
|
|
96
|
+
*/
|
|
97
|
+
export function registerResources(server, ctx) {
|
|
98
|
+
registerDocsResources(server, ctx)
|
|
87
99
|
|
|
88
100
|
const readAgents = resource(async (uri, { site = '.' } = {}) => {
|
|
89
101
|
const resolved = await resolveSite(ctx, decodeSite(site))
|
package/src/runner.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn as nodeSpawn } from 'node:child_process'
|
|
2
|
-
import { existsSync } from 'node:fs'
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
3
3
|
import { createRequire } from 'node:module'
|
|
4
4
|
import path from 'node:path'
|
|
5
5
|
import { activeShim, npmScripts, ownNpm, withPathPrefix } from './runtime.js'
|
|
@@ -27,6 +27,23 @@ export function neraBin(cwd) {
|
|
|
27
27
|
return path.join(path.dirname(require.resolve('@nera-static/nera/package.json')), 'bin', 'nera.js')
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
/**
|
|
31
|
+
* The version of the `@nera-static/nera` whose script `neraBin(cwd)` names:
|
|
32
|
+
* the `version` of the `package.json` two folders above it. Read synchronously,
|
|
33
|
+
* so a caller can check it and start a run without yielding in between.
|
|
34
|
+
*
|
|
35
|
+
* @param {string} cwd
|
|
36
|
+
* @returns {string|null} null when the file cannot be read or carries no string `version`
|
|
37
|
+
*/
|
|
38
|
+
export function neraVersion(cwd) {
|
|
39
|
+
try {
|
|
40
|
+
const { version } = JSON.parse(readFileSync(path.join(path.dirname(neraBin(cwd)), '..', 'package.json'), 'utf8'))
|
|
41
|
+
return typeof version === 'string' ? version : null
|
|
42
|
+
} catch {
|
|
43
|
+
return null
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
30
47
|
/**
|
|
31
48
|
* How to start npm without a shell: its `npm-cli.js` from the server's own
|
|
32
49
|
* `node_modules/npm` (the Desktop extension bundles one) or next to the running
|
|
@@ -44,9 +61,11 @@ export function npmCommand(execPath = process.execPath, own = ownNpm()) {
|
|
|
44
61
|
}
|
|
45
62
|
|
|
46
63
|
/**
|
|
47
|
-
* The executable and leading arguments for `nera`, `npm` or `
|
|
64
|
+
* The executable and leading arguments for `nera`, `npm`, `node` or `tar` in
|
|
65
|
+
* `cwd`. `tar` is the system's, found on the child's PATH (the hosted
|
|
66
|
+
* `validate` unpacks a checkout with it).
|
|
48
67
|
*
|
|
49
|
-
* @param {'nera'|'npm'|'node'} command
|
|
68
|
+
* @param {'nera'|'npm'|'node'|'tar'} command
|
|
50
69
|
* @param {string} cwd
|
|
51
70
|
* @returns {{ file: string, prefix: string[] }}
|
|
52
71
|
* @throws {Error} for any other command
|
|
@@ -59,8 +78,10 @@ export function commandFor(command, cwd) {
|
|
|
59
78
|
return npmCommand()
|
|
60
79
|
case 'node':
|
|
61
80
|
return { file: process.execPath, prefix: [] }
|
|
81
|
+
case 'tar':
|
|
82
|
+
return { file: 'tar', prefix: [] }
|
|
62
83
|
default:
|
|
63
|
-
throw new Error(`Unknown command "${command}": the runner starts nera, npm or
|
|
84
|
+
throw new Error(`Unknown command "${command}": the runner starts nera, npm, node or tar only.`)
|
|
64
85
|
}
|
|
65
86
|
}
|
|
66
87
|
|
|
@@ -218,9 +239,11 @@ export function stopChild(child, { grace = KILL_GRACE_MS, platform = process.pla
|
|
|
218
239
|
}
|
|
219
240
|
|
|
220
241
|
/**
|
|
221
|
-
* Creates the function the tools run `nera`, `npm` and `
|
|
222
|
-
* commands that finish (`nera new`, `nera build`, `npm install`). Every
|
|
223
|
-
* gets its arguments as an array and the options of `spawnOptions
|
|
242
|
+
* Creates the function the tools run `nera`, `npm`, `node` and `tar` through,
|
|
243
|
+
* for commands that finish (`nera new`, `nera build`, `npm install`). Every
|
|
244
|
+
* run gets its arguments as an array and the options of `spawnOptions`; a run
|
|
245
|
+
* given `env` gets exactly that environment instead of `childEnv`'s (the
|
|
246
|
+
* hosted checkout strips it to PATH). A run is
|
|
224
247
|
* stopped (with everything it started) when it exceeds `timeout` or when `signal`
|
|
225
248
|
* aborts — the client cancelled the request, or the server closed.
|
|
226
249
|
*
|
|
@@ -229,17 +252,19 @@ export function stopChild(child, { grace = KILL_GRACE_MS, platform = process.pla
|
|
|
229
252
|
* @param {number} [options.timeout] milliseconds before a run is stopped
|
|
230
253
|
* @param {number} [options.grace] milliseconds between SIGTERM and SIGKILL
|
|
231
254
|
* @param {NodeJS.Platform} [options.platform] injected in tests
|
|
232
|
-
* @returns {(command: 'nera'|'npm'|'node', args: string[], options: { cwd: string, signal?: AbortSignal }) => Promise<{ code: number|null, stdout: string, stderr: string, timedOut: boolean, cancelled: boolean }>}
|
|
255
|
+
* @returns {(command: 'nera'|'npm'|'node'|'tar', args: string[], options: { cwd: string, signal?: AbortSignal, env?: Record<string, string> }) => Promise<{ code: number|null, stdout: string, stderr: string, timedOut: boolean, cancelled: boolean }>}
|
|
233
256
|
* `code` is null when the process was stopped or could not start; `stderr` then says why
|
|
234
257
|
*/
|
|
235
258
|
export function createRunner({ spawn = nodeSpawn, timeout = DEFAULT_TIMEOUT_MS, grace = KILL_GRACE_MS, platform = process.platform } = {}) {
|
|
236
|
-
return (command, args, { cwd, signal }) => new Promise((resolve) => {
|
|
259
|
+
return (command, args, { cwd, signal, env }) => new Promise((resolve) => {
|
|
237
260
|
const { file, prefix } = commandFor(command, cwd)
|
|
238
261
|
if (signal?.aborted) {
|
|
239
262
|
resolve({ code: null, stdout: '', stderr: 'Cancelled before it started.', timedOut: false, cancelled: true })
|
|
240
263
|
return
|
|
241
264
|
}
|
|
242
|
-
const
|
|
265
|
+
const options = spawnOptions(cwd, {}, platform)
|
|
266
|
+
if (env) options.env = env
|
|
267
|
+
const child = spawn(file, [...prefix, ...args], options)
|
|
243
268
|
let stdout = ''
|
|
244
269
|
let stderr = ''
|
|
245
270
|
let timedOut = false
|
package/src/tools/cli.js
CHANGED
|
@@ -36,7 +36,13 @@ export function failureText(run) {
|
|
|
36
36
|
return tail(run.stderr) || tail(run.stdout) || `exit code ${run.code}`
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
|
|
39
|
+
/**
|
|
40
|
+
* How many of the validator's records are errors and how many warnings.
|
|
41
|
+
*
|
|
42
|
+
* @param {Array<{severity: string}>} results
|
|
43
|
+
* @returns {{ errors: number, warnings: number }}
|
|
44
|
+
*/
|
|
45
|
+
export function countBySeverity(results) {
|
|
40
46
|
const errors = results.filter((r) => r.severity === 'error').length
|
|
41
47
|
return { errors, warnings: results.length - errors }
|
|
42
48
|
}
|
package/src/tools/files.js
CHANGED
|
@@ -1,21 +1,13 @@
|
|
|
1
1
|
import fs from 'node:fs/promises'
|
|
2
2
|
import path from 'node:path'
|
|
3
|
-
import { isDeepStrictEqual } from 'node:util'
|
|
4
|
-
import yaml from 'yaml'
|
|
5
3
|
import { z } from 'zod'
|
|
4
|
+
import { NO_WRITE_SEGMENTS, composePage, parsePage, refuseSecrets, refuseSegments, requireLayout } from '../pages.js'
|
|
6
5
|
import { isInside, resolveInRoot } from '../paths.js'
|
|
7
6
|
import { ok, tool, ToolError } from '../results.js'
|
|
8
7
|
import { relativeTo, resolveSite, siteFolders, siteInput } from './sites.js'
|
|
9
8
|
|
|
10
9
|
/** Larger files are refused by read_file: a model cannot use them whole. */
|
|
11
10
|
const MAX_READ_BYTES = 1024 * 1024
|
|
12
|
-
const FENCE = '---'
|
|
13
|
-
/** Path segments no file tool reads or writes: git internals may hold credentials. */
|
|
14
|
-
const FORBIDDEN_SEGMENTS = new Set(['.git'])
|
|
15
|
-
/** File names no file tool reads or writes: `.env` files and `.npmrc` (npm `_authToken`) hold tokens. */
|
|
16
|
-
const SECRET_FILE = /^(\.env(\..*)?|\.npmrc)$/
|
|
17
|
-
/** Path segments write_file refuses: installed packages belong to npm. */
|
|
18
|
-
const NO_WRITE_SEGMENTS = new Set(['node_modules'])
|
|
19
11
|
|
|
20
12
|
const pageInput = z
|
|
21
13
|
.string()
|
|
@@ -24,71 +16,6 @@ const fileInput = z
|
|
|
24
16
|
.string()
|
|
25
17
|
.describe('The file, relative to the site folder — e.g. `config/app.yaml`, `theme/views/layouts/default.pug`, `assets/css/main.css`.')
|
|
26
18
|
|
|
27
|
-
/**
|
|
28
|
-
* Splits a page into its frontmatter YAML and its Markdown body, the way the
|
|
29
|
-
* build reads it: a `---` first line opens the block, the next `---` line
|
|
30
|
-
* closes it (no closing line: the rest is frontmatter).
|
|
31
|
-
*
|
|
32
|
-
* @param {string} raw the file's text
|
|
33
|
-
* @returns {{ yamlText: string|null, body: string }} `yamlText` null when the page has no frontmatter
|
|
34
|
-
*/
|
|
35
|
-
function splitPage(raw) {
|
|
36
|
-
// markdown-it, which the build parses pages with, reads CRLF as LF.
|
|
37
|
-
const lines = raw.replace(/\r\n/g, '\n').split('\n')
|
|
38
|
-
if (lines[0] !== FENCE) return { yamlText: null, body: raw }
|
|
39
|
-
const close = lines.indexOf(FENCE, 1)
|
|
40
|
-
if (close === -1) return { yamlText: lines.slice(1).join('\n'), body: '' }
|
|
41
|
-
return {
|
|
42
|
-
yamlText: lines.slice(1, close).join('\n'),
|
|
43
|
-
body: lines.slice(close + 1).join('\n'),
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/** Parses frontmatter YAML into a document that keeps comments and quoting. */
|
|
48
|
-
function parseFrontmatter(yamlText) {
|
|
49
|
-
const doc = yaml.parseDocument(yamlText ?? '', { merge: true, uniqueKeys: false })
|
|
50
|
-
if (doc.errors.length) {
|
|
51
|
-
return { doc: null, error: doc.errors[0].message }
|
|
52
|
-
}
|
|
53
|
-
if (doc.contents !== null && !yaml.isMap(doc.contents)) {
|
|
54
|
-
return { doc: null, error: 'The frontmatter is not a list of `key: value` lines.' }
|
|
55
|
-
}
|
|
56
|
-
return { doc, error: null }
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* The frontmatter YAML for `frontmatter`, edited into the page's existing
|
|
61
|
-
* frontmatter when it has one that parses: unchanged keys keep their comments,
|
|
62
|
-
* quoting and order, a changed value keeps its quoting style, keys left out are
|
|
63
|
-
* removed, new keys are appended. Nothing changed: the block stays byte for byte.
|
|
64
|
-
*/
|
|
65
|
-
function frontmatterText(existingYaml, frontmatter) {
|
|
66
|
-
const { doc } = existingYaml === null ? { doc: null } : parseFrontmatter(existingYaml)
|
|
67
|
-
if (!doc || doc.contents === null) {
|
|
68
|
-
return new yaml.Document(frontmatter).toString({ flowCollectionPadding: false })
|
|
69
|
-
}
|
|
70
|
-
const current = doc.toJS() ?? {}
|
|
71
|
-
let changed = false
|
|
72
|
-
for (const key of Object.keys(current)) {
|
|
73
|
-
if (!Object.hasOwn(frontmatter, key)) {
|
|
74
|
-
doc.delete(key)
|
|
75
|
-
changed = true
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
for (const [key, value] of Object.entries(frontmatter)) {
|
|
79
|
-
if (!isDeepStrictEqual(current[key], value)) {
|
|
80
|
-
doc.set(key, value)
|
|
81
|
-
changed = true
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
if (!changed) return withTrailingNewline(existingYaml)
|
|
85
|
-
return doc.toString({ flowCollectionPadding: false })
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function withTrailingNewline(text) {
|
|
89
|
-
return text.endsWith('\n') ? text : `${text}\n`
|
|
90
|
-
}
|
|
91
|
-
|
|
92
19
|
async function statOrNull(file) {
|
|
93
20
|
try {
|
|
94
21
|
return await fs.stat(file)
|
|
@@ -108,24 +35,6 @@ async function readText(file, shown) {
|
|
|
108
35
|
}
|
|
109
36
|
}
|
|
110
37
|
|
|
111
|
-
/**
|
|
112
|
-
* Refuses `input` when it, or the site-relative real path it resolved to (a
|
|
113
|
-
* symbolic link may point into `.git/`), has a segment from `segments`.
|
|
114
|
-
*/
|
|
115
|
-
function refuseSegments(input, resolved, segments, why) {
|
|
116
|
-
const hit = [input, resolved]
|
|
117
|
-
.flatMap((candidate) => candidate.split(/[\\/]/))
|
|
118
|
-
.find((segment) => segments.has(segment))
|
|
119
|
-
if (hit) throw new ToolError(`"${input}" is inside ${hit}/, which ${why}.`)
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
function refuseSecrets(input, resolved) {
|
|
123
|
-
refuseSegments(input, resolved, FORBIDDEN_SEGMENTS, 'these tools never read or change')
|
|
124
|
-
if ([input, resolved].some((candidate) => SECRET_FILE.test(path.basename(candidate)))) {
|
|
125
|
-
throw new ToolError(`"${input}" can hold secrets (tokens, passwords); these tools never read or change it.`)
|
|
126
|
-
}
|
|
127
|
-
}
|
|
128
|
-
|
|
129
38
|
/**
|
|
130
39
|
* Resolves a page argument: inside the site, inside its pages folder, a `.md`
|
|
131
40
|
* file.
|
|
@@ -178,10 +87,8 @@ export function registerFileTools(server, ctx) {
|
|
|
178
87
|
if (raw === null) {
|
|
179
88
|
throw new ToolError(`The page "${target.path}" does not exist. Call get_site for the list of pages, or write_page to create it.`)
|
|
180
89
|
}
|
|
181
|
-
const {
|
|
182
|
-
const {
|
|
183
|
-
const frontmatter = doc ? (doc.toJS() ?? {}) : null
|
|
184
|
-
const structured = { site: target.site, path: target.path, frontmatter, body: body.replace(/^\n+/, '') }
|
|
90
|
+
const { frontmatter, body, error } = parsePage(raw)
|
|
91
|
+
const structured = { site: target.site, path: target.path, frontmatter, body }
|
|
185
92
|
if (error) structured.frontmatterError = error
|
|
186
93
|
const text = error
|
|
187
94
|
? `Read ${target.path}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, passing the whole frontmatter.`
|
|
@@ -199,16 +106,10 @@ export function registerFileTools(server, ctx) {
|
|
|
199
106
|
body: z.string().optional().describe('The page\'s Markdown content, without the frontmatter. Leave out to keep the existing body.'),
|
|
200
107
|
},
|
|
201
108
|
}, tool(async ({ site, path: page, frontmatter, body }) => {
|
|
202
|
-
|
|
203
|
-
throw new ToolError('The frontmatter has no `layout`. Nera only renders pages that name their layout — add e.g. `layout: pages/default.pug` (read an existing page with read_page to see which layout the site uses).')
|
|
204
|
-
}
|
|
109
|
+
requireLayout(frontmatter)
|
|
205
110
|
const target = await resolvePage(ctx, site, page)
|
|
206
111
|
const raw = await readText(target.file, target.path)
|
|
207
|
-
const
|
|
208
|
-
const head = `${FENCE}\n${frontmatterText(existing?.yamlText ?? null, frontmatter)}${FENCE}\n`
|
|
209
|
-
const content = body === undefined
|
|
210
|
-
? head + (existing?.body ?? '')
|
|
211
|
-
: `${head}\n${withTrailingNewline(body.replace(/^\n+/, ''))}`
|
|
112
|
+
const content = composePage(raw, frontmatter, body)
|
|
212
113
|
await fs.mkdir(path.dirname(target.file), { recursive: true })
|
|
213
114
|
await fs.writeFile(target.file, content)
|
|
214
115
|
const created = raw === null
|