@nera-static/mcp 1.4.0 → 1.4.1

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.
@@ -1,4 +1,4 @@
1
- // The GitHub repository side of the hosted mode (L7b, plan D2–D6): the user's
1
+ // The GitHub repository side of the hosted mode (L7b): the user's
2
2
  // repository is the working copy. This client reads files and trees, keeps the
3
3
  // draft branch `nera-draft` (every write commits there, so nothing deploys),
4
4
  // commits one file change at a time through the Git Data API, merges the
@@ -8,6 +8,7 @@
8
8
  // the page rules live in src/pages.js. Every call goes through the injected
9
9
  // `fetch`, so tests never touch the network, and no message it builds can
10
10
  // carry the token.
11
+ import { byString } from '@nera-static/plugin-utils/sort'
11
12
  import { ToolError } from '../results.js'
12
13
  import { GitHubError } from './github.js'
13
14
 
@@ -15,7 +16,7 @@ const USER_AGENT = 'nera-mcp'
15
16
  const API_VERSION = '2022-11-28'
16
17
  /** The branch a site deploys from. */
17
18
  export const BASE_BRANCH = 'main'
18
- /** The branch every write commits to until `publish` merges it (plan D2). */
19
+ /** The branch every write commits to until `publish` merges it. */
19
20
  export const DRAFT_BRANCH = 'nera-draft'
20
21
  /** GitHub's largest page size; more than this many pages of repositories is not followed. */
21
22
  const PER_PAGE = 100
@@ -68,19 +69,22 @@ export function repoPath(input, label = 'path') {
68
69
  throw new ToolError(`The ${label} is empty. Give a path relative to the repository root, e.g. pages/about.md.`)
69
70
  }
70
71
  if (input.includes('\\')) {
71
- throw new ToolError(`The ${label} "${input}" contains a backslash. Use forward slashes, e.g. pages/blog/post.md.`)
72
+ throw new ToolError(`The ${label} "${input}" contains a backslash. Use forward slashes, ` +
73
+ 'e.g. pages/blog/post.md.')
72
74
  }
73
75
  if (input.startsWith('/')) {
74
76
  throw new ToolError(`The ${label} "${input}" is absolute. Give it relative to the repository root, e.g. ${input.replace(/^\/+/, '') || 'pages/about.md'}.`)
75
77
  }
76
78
  const segments = input.split('/')
77
79
  if (segments.some((segment) => segment === '')) {
78
- throw new ToolError(`The ${label} "${input}" has an empty segment (a doubled or trailing /). Give it like pages/blog/post.md.`)
80
+ throw new ToolError(`The ${label} "${input}" has an empty segment (a doubled or trailing /). Give it ` +
81
+ 'like pages/blog/post.md.')
79
82
  }
80
83
  if (segments.some((segment) => segment === '..' || segment === '.')) {
81
- throw new ToolError(`The ${label} "${input}" contains "." or ".." segments. Give the path inside the repository directly, e.g. pages/about.md.`)
84
+ throw new ToolError(`The ${label} "${input}" contains "." or ".." segments. Give the path inside the ` +
85
+ 'repository directly, e.g. pages/about.md.')
82
86
  }
83
- if (/[\0-\x1f]/.test(input)) {
87
+ if (/\p{Cc}/u.test(input)) {
84
88
  throw new ToolError(`The ${label} "${input}" contains a control character.`)
85
89
  }
86
90
  return input
@@ -95,7 +99,8 @@ export function repoPath(input, label = 'path') {
95
99
  */
96
100
  export function repoName(site) {
97
101
  if (typeof site !== 'string' || !REPO_NAME.test(site) || site.split('/')[1].startsWith('.')) {
98
- throw new ToolError(`"${site}" is not a GitHub repository name. Give the site as owner/name, e.g. octo/my-site — list_sites lists the ones you can edit.`)
102
+ throw new ToolError(`"${site}" is not a GitHub repository name. Give the site as owner/name, e.g. ` +
103
+ 'octo/my-site — list_sites lists the ones you can edit.')
99
104
  }
100
105
  return site
101
106
  }
@@ -114,8 +119,11 @@ export function commitMessage(message) {
114
119
  return message
115
120
  }
116
121
 
117
- /** `path` with each segment percent-encoded, for an API URL. */
118
- function encodePath(path) {
122
+ /**
123
+ * `path` with each segment percent-encoded (`#` and `?` too), for a GitHub API
124
+ * URL. Not plugin-utils' `encodePath`, which keeps `#` and `?` for a site URL.
125
+ */
126
+ function apiPath(path) {
119
127
  return path.split('/').map(encodeURIComponent).join('/')
120
128
  }
121
129
 
@@ -187,19 +195,19 @@ export function createRepoClient({ token, fetch = globalThis.fetch, apiUrl = 'ht
187
195
 
188
196
  /** The commit a branch points at, null when the branch does not exist. */
189
197
  async function branchHead(repo, branch) {
190
- const { status, body } = await request('GET', `${repoUrl(repo)}/git/ref/heads/${encodePath(branch)}`, { accept: [404] })
198
+ const { status, body } = await request('GET', `${repoUrl(repo)}/git/ref/heads/${apiPath(branch)}`, { accept: [404] })
191
199
  return status === 404 ? null : body.object.sha
192
200
  }
193
201
 
194
202
  /** Points `branch` at `sha` without force; false when GitHub refuses (422: not a fast-forward). */
195
203
  async function moveBranch(repo, branch, sha) {
196
- const { status } = await request('PATCH', `${repoUrl(repo)}/git/refs/heads/${encodePath(branch)}`, { body: { sha, force: false }, accept: [422] })
204
+ const { status } = await request('PATCH', `${repoUrl(repo)}/git/refs/heads/${apiPath(branch)}`, { body: { sha, force: false }, accept: [422] })
197
205
  return status !== 422
198
206
  }
199
207
 
200
208
  /** Deletes the draft branch; nothing happens when it is already gone. */
201
209
  async function deleteDraft(repo) {
202
- await request('DELETE', `${repoUrl(repo)}/git/refs/heads/${encodePath(DRAFT_BRANCH)}`, { accept: [404, 422] })
210
+ await request('DELETE', `${repoUrl(repo)}/git/refs/heads/${apiPath(DRAFT_BRANCH)}`, { accept: [404, 422] })
203
211
  }
204
212
 
205
213
  /**
@@ -250,7 +258,7 @@ export function createRepoClient({ token, fetch = globalThis.fetch, apiUrl = 'ht
250
258
  })
251
259
  }
252
260
  }
253
- return [...repos.values()].sort((a, b) => a.site.localeCompare(b.site))
261
+ return [...repos.values()].sort((a, b) => byString(a.site, b.site))
254
262
  },
255
263
 
256
264
  branchHead,
@@ -266,7 +274,7 @@ export function createRepoClient({ token, fetch = globalThis.fetch, apiUrl = 'ht
266
274
  * @returns {Promise<{type: 'file', content: Buffer|null, size: number, sha: string} | {type: 'dir'} | {type: 'symlink'} | null>} null when nothing is at `path`
267
275
  */
268
276
  async readFile(repo, path, ref, { maxBytes = Infinity } = {}) {
269
- const { status, body } = await request('GET', `${repoUrl(repo)}/contents/${encodePath(repoPath(path))}?ref=${encodeURIComponent(ref)}`, { accept: [404] })
277
+ const { status, body } = await request('GET', `${repoUrl(repo)}/contents/${apiPath(repoPath(path))}?ref=${encodeURIComponent(ref)}`, { accept: [404] })
270
278
  if (status === 404) return null
271
279
  if (Array.isArray(body) || body.type === 'dir') return { type: 'dir' }
272
280
  // The contents API follows a symbolic link to a file and answers
@@ -296,7 +304,12 @@ export function createRepoClient({ token, fetch = globalThis.fetch, apiUrl = 'ht
296
304
  return {
297
305
  entries: body.tree
298
306
  .filter((entry) => entry.type === 'blob' || entry.type === 'tree')
299
- .map((entry) => ({ path: entry.path, type: entry.type, mode: entry.mode, ...(entry.size === undefined ? {} : { size: entry.size }) })),
307
+ .map((entry) => ({
308
+ path: entry.path,
309
+ type: entry.type,
310
+ mode: entry.mode,
311
+ ...(entry.size === undefined ? {} : { size: entry.size }),
312
+ })),
300
313
  truncated: Boolean(body.truncated),
301
314
  }
302
315
  },
@@ -325,7 +338,8 @@ export function createRepoClient({ token, fetch = globalThis.fetch, apiUrl = 'ht
325
338
  if (existing) return { sha: existing, created: false }
326
339
  const base = await branchHead(repo, BASE_BRANCH)
327
340
  if (!base) {
328
- throw new GitHubError(`The repository ${repo} has no ${BASE_BRANCH} branch to start the draft from.`, { status: 404 })
341
+ throw new GitHubError(`The repository ${repo} has no ${BASE_BRANCH} branch ` +
342
+ 'to start the draft from.', { status: 404 })
329
343
  }
330
344
  const { status } = await request('POST', `${repoUrl(repo)}/git/refs`, {
331
345
  body: { ref: `refs/heads/${DRAFT_BRANCH}`, sha: base },
@@ -28,7 +28,7 @@ const REPLAYED = Object.freeze({
28
28
  refresh: 'an already rotated refresh token',
29
29
  })
30
30
 
31
- /** Lifetimes in seconds (plan D3). */
31
+ /** Lifetimes in seconds; a refresh token rotates on every use, a code is single use. */
32
32
  export const TTL = Object.freeze({
33
33
  pending: 10 * 60,
34
34
  code: 10 * 60,
@@ -154,7 +154,13 @@ export function createStore({ file, key, now = Date.now, log = () => {} }) {
154
154
  if (!own || !sameBrowser(own, browserToken)) return null
155
155
  return { clientId: own.client_id, params: JSON.parse(own.params), approved: own.approved === 1 }
156
156
  }
157
- const codeRecord = (row) => row && { grantId: row.grant_id, clientId: row.client_id, userId: row.user_id, ...JSON.parse(row.params), expiresAt: row.expires_at }
157
+ const codeRecord = (row) => row && {
158
+ grantId: row.grant_id,
159
+ clientId: row.client_id,
160
+ userId: row.user_id,
161
+ ...JSON.parse(row.params),
162
+ expiresAt: row.expires_at,
163
+ }
158
164
  const tokenRecord = (row) => row && {
159
165
  kind: row.kind,
160
166
  clientId: row.client_id,
@@ -193,7 +199,8 @@ export function createStore({ file, key, now = Date.now, log = () => {} }) {
193
199
  if (tombstone?.kind !== kind) return
194
200
  const revoked = Number(statements.revokeGrant.run(tombstone.grant_id).changes)
195
201
  try {
196
- log(`replay detected: ${REPLAYED[kind]} was sent again; revoked grant ${tombstone.grant_id} of client ${tombstone.client_id} (${revoked} tokens)`)
202
+ log(`replay detected: ${REPLAYED[kind]} was sent again; revoked grant ${tombstone.grant_id} of ` +
203
+ `client ${tombstone.client_id} (${revoked} tokens)`)
197
204
  } catch {
198
205
  // the revoke is what protects the user; a lost log line is not worth undoing it
199
206
  }
@@ -248,7 +255,8 @@ export function createStore({ file, key, now = Date.now, log = () => {} }) {
248
255
  saveClient(client) {
249
256
  if (!client?.client_id) throw new Error('A client needs a client_id.')
250
257
  const { client_secret: secret, ...info } = client
251
- statements.saveClient.run(client.client_id, JSON.stringify(info), secret ? encrypt(secretKey, secret) : null)
258
+ const encrypted = secret ? encrypt(secretKey, secret) : null
259
+ statements.saveClient.run(client.client_id, JSON.stringify(info), encrypted)
252
260
  return { ...client }
253
261
  },
254
262
 
@@ -263,7 +271,9 @@ export function createStore({ file, key, now = Date.now, log = () => {} }) {
263
271
  savePending({ clientId, params }) {
264
272
  const state = randomToken()
265
273
  const browserToken = randomToken()
266
- statements.savePending.run(hashToken(state), clientId, JSON.stringify(params), hashToken(browserToken), seconds() + TTL.pending)
274
+ statements.savePending.run(
275
+ hashToken(state), clientId, JSON.stringify(params), hashToken(browserToken), seconds() + TTL.pending,
276
+ )
267
277
  return { state, browserToken }
268
278
  },
269
279
 
@@ -315,7 +325,9 @@ export function createStore({ file, key, now = Date.now, log = () => {} }) {
315
325
  */
316
326
  saveCode({ clientId, userId, params }) {
317
327
  const code = randomToken()
318
- statements.saveCode.run(hashToken(code), randomUUID(), clientId, String(userId), JSON.stringify(params), seconds() + TTL.code)
328
+ statements.saveCode.run(
329
+ hashToken(code), randomUUID(), clientId, String(userId), JSON.stringify(params), seconds() + TTL.code,
330
+ )
319
331
  return code
320
332
  },
321
333
 
@@ -389,7 +401,13 @@ export function createStore({ file, key, now = Date.now, log = () => {} }) {
389
401
  if (scopes && !scopes.every((scope) => record.scopes.includes(scope))) return null
390
402
  statements.deleteToken.run(hash)
391
403
  bury(hash, 'refresh', row)
392
- return issueTokens({ clientId, userId: record.userId, scopes: scopes ?? record.scopes, resource: record.resource, grantId: row.grant_id })
404
+ return issueTokens({
405
+ clientId,
406
+ userId: record.userId,
407
+ scopes: scopes ?? record.scopes,
408
+ resource: record.resource,
409
+ grantId: row.grant_id,
410
+ })
393
411
  })
394
412
  },
395
413
 
@@ -1,4 +1,4 @@
1
- // `publish` and `preview` of the hosted mode (L7b, plan D1/D2). The write
1
+ // `publish` and `preview` of the hosted mode (L7b). The write
2
2
  // tools collect their commits on the draft branch `nera-draft`; `publish`
3
3
  // merges it into `main` in one push, so the site's deploy workflow
4
4
  // (`.github/workflows/deploy.yml`, which triggers on pushes to `main` only)
@@ -6,6 +6,7 @@
6
6
  // unpublished commits, or no draft at all, pushes nothing, so no deploy is
7
7
  // started for nothing. The build itself runs in the site's own Actions run;
8
8
  // both tools only report it, with the address the site is served at.
9
+ import { setTimeout as sleepFor } from 'node:timers/promises'
9
10
  import { z } from 'zod'
10
11
  import { ok, ToolError } from '../../results.js'
11
12
  import { GitHubError } from '../github.js'
@@ -22,8 +23,6 @@ export const RUN_LOOKUPS = 5
22
23
  /** The pause between two lookups. */
23
24
  export const RUN_LOOKUP_MS = 2000
24
25
 
25
- const sleepFor = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
26
-
27
26
  /**
28
27
  * The `origin` of `config/app.yaml` when it is an http(s) address.
29
28
  *
@@ -75,7 +74,7 @@ export function registerHostedPublishTools(server, { repos, sleep = sleepFor })
75
74
  const { openSite, appConfigAt } = createSiteAccess(repos)
76
75
 
77
76
  /** The address the site is served at: GitHub Pages', else `origin` in config/app.yaml on main. */
78
- async function siteUrl(target) {
77
+ async function deployedUrl(target) {
79
78
  const pages = await lookup(() => target.client.pagesUrl(target.site))
80
79
  if (pages) return pages
81
80
  const config = await lookup(() => appConfigAt(target, BASE_BRANCH))
@@ -96,7 +95,8 @@ export function registerHostedPublishTools(server, { repos, sleep = sleepFor })
96
95
  async function draftAhead(target) {
97
96
  if (!target.draft.exists) return 0
98
97
  if (!target.mainSha) {
99
- throw new ToolError(`The repository "${target.site}" has a draft but no ${BASE_BRANCH} branch to publish it to. Create ${BASE_BRANCH} on GitHub first.`)
98
+ throw new ToolError(`The repository "${target.site}" has a draft but no ${BASE_BRANCH} branch to publish ` +
99
+ `it to. Create ${BASE_BRANCH} on GitHub first.`)
100
100
  }
101
101
  return target.client.aheadBy(target.site, target.mainSha, target.draft.sha)
102
102
  }
@@ -104,7 +104,7 @@ export function registerHostedPublishTools(server, { repos, sleep = sleepFor })
104
104
  /** The result of a publish that pushed nothing. */
105
105
  async function nothingPublished(target, reason) {
106
106
  const run = await lookup(() => target.client.latestRun(target.site, DEPLOY_WORKFLOW))
107
- const url = await siteUrl(target)
107
+ const url = await deployedUrl(target)
108
108
  return ok(
109
109
  { site: target.site, published: false, commits: 0, commit: null, run, url },
110
110
  `${reason} Nothing was pushed to ${BASE_BRANCH}, so no deploy was started. ${runText(run)}${url ? ` The site is at ${url}.` : ''}`,
@@ -113,10 +113,19 @@ export function registerHostedPublishTools(server, { repos, sleep = sleepFor })
113
113
 
114
114
  server.registerTool('publish', {
115
115
  title: 'Publish the draft',
116
- description: `Puts a Nera site's unpublished changes live. Every write_page, write_file and delete_page commits to the draft branch ${DRAFT_BRANCH} of the site's GitHub repository; publish merges that draft into ${BASE_BRANCH} in one push and deletes it. The push starts the site's deploy workflow (.github/workflows/${DEPLOY_WORKFLOW}, GitHub Actions), which builds the site and deploys it to GitHub Pages or Netlify, once for all changes since the last publish. Call validate first and fix its errors. Returns the merge commit, the deploy run (status and address; it takes a minute or two) and the address the site is served at; call preview later to see whether the run succeeded. Without unpublished changes nothing is pushed and only the latest run is reported.`,
116
+ description: 'Puts a Nera site\'s unpublished changes live. Every write_page, write_file and delete_page ' +
117
+ `commits to the draft branch ${DRAFT_BRANCH} of the site's GitHub repository; publish merges that draft ` +
118
+ `into ${BASE_BRANCH} in one push and deletes it. The push starts the site's deploy workflow ` +
119
+ `(.github/workflows/${DEPLOY_WORKFLOW}, GitHub Actions), which builds the site and deploys it to GitHub ` +
120
+ 'Pages or Netlify, once for all changes since the last publish. Call validate first and fix its errors. ' +
121
+ 'Returns the merge commit, the deploy run (status and address; it takes a minute or two) and the address ' +
122
+ 'the site is served at; call preview later to see whether the run succeeded. Without unpublished changes ' +
123
+ 'nothing is pushed and only the latest run is reported.',
117
124
  inputSchema: {
118
125
  site: hostedSiteInput,
119
- message: z.string().optional().describe(`The merge commit's message, used only when ${BASE_BRANCH} changed since the draft began (otherwise the draft's own commits go onto ${BASE_BRANCH} as they are). Defaults to "Publish the changes from ${DRAFT_BRANCH}".`),
126
+ message: z.string().optional().describe(`The merge commit's message, used only when ${BASE_BRANCH} ` +
127
+ `changed since the draft began (otherwise the draft's own commits go onto ${BASE_BRANCH} as they ` +
128
+ `are). Defaults to "Publish the changes from ${DRAFT_BRANCH}".`),
120
129
  },
121
130
  }, hostedTool(async ({ site, message }) => {
122
131
  const target = await openSite(site)
@@ -124,37 +133,54 @@ export function registerHostedPublishTools(server, { repos, sleep = sleepFor })
124
133
  const ahead = await draftAhead(target)
125
134
  if (ahead === 0) {
126
135
  await target.client.deleteDraft(target.site)
127
- return nothingPublished(target, `The draft of "${target.site}" held no unpublished commits, so it was deleted.`)
136
+ return nothingPublished(target, `The draft of "${target.site}" held no unpublished ` +
137
+ 'commits, so it was deleted.')
128
138
  }
129
- const merged = await target.client.mergeDraft(target.site, message?.trim() || `Publish the changes from ${DRAFT_BRANCH}`)
139
+ const merged = await target.client.mergeDraft(target.site, message?.trim() || 'Publish the ' +
140
+ `changes from ${DRAFT_BRANCH}`)
130
141
  // null: the draft is gone; not pushed: main already held it. Either way another call published it in the meantime.
131
142
  if (!merged || !merged.pushed) {
132
- return nothingPublished(target, `The changes of "${target.site}" are already live on ${BASE_BRANCH}, or were published by another call in the meantime.`)
143
+ return nothingPublished(target, `The changes of "${target.site}" are already live on ${BASE_BRANCH}, or ` +
144
+ 'were published by another call in the meantime.')
133
145
  }
134
146
  const run = await runFor(target, merged.sha)
135
- const url = await siteUrl(target)
147
+ const url = await deployedUrl(target)
136
148
  const runSentence = run
137
149
  ? runText(run)
138
- : `GitHub has not started the deploy run yet; call preview in a minute to see it. If none appears, the repository has no .github/workflows/${DEPLOY_WORKFLOW} — \`nera publish\` sets it up once.`
150
+ : 'GitHub has not started the deploy run yet; call preview in a minute to see it. If none appears, the ' +
151
+ `repository has no .github/workflows/${DEPLOY_WORKFLOW} — \`nera publish\` sets it up once.`
139
152
  return ok(
140
- { site: target.site, published: true, commits: ahead, commit: merged.sha, fastForward: merged.fastForward, run, url },
153
+ {
154
+ site: target.site,
155
+ published: true,
156
+ commits: ahead,
157
+ commit: merged.sha,
158
+ fastForward: merged.fastForward,
159
+ run,
160
+ url,
161
+ },
141
162
  `Published ${ahead} commit(s) of "${target.site}" to ${BASE_BRANCH} (${merged.sha.slice(0, 7)}) and deleted the draft. ${runSentence}${url ? ` Once it succeeds, the site is live at ${url}.` : ''}`,
142
163
  )
143
164
  }))
144
165
 
145
166
  server.registerTool('preview', {
146
167
  title: 'Show the live site',
147
- description: `Shows where a Nera site in a GitHub repository is live and how its last deploy went: the address it is served at (GitHub Pages, else \`origin\` in config/app.yaml), the latest run of its deploy workflow (.github/workflows/${DEPLOY_WORKFLOW}: status, conclusion, address) and how many changes wait unpublished on the draft branch ${DRAFT_BRANCH}. Call it after publish to see whether the deploy succeeded; unpublished changes are not visible at the address until publish.`,
168
+ description: 'Shows where a Nera site in a GitHub repository is live and how its last deploy went: the ' +
169
+ 'address it is served at (GitHub Pages, else `origin` in config/app.yaml), the latest run of its ' +
170
+ `deploy workflow (.github/workflows/${DEPLOY_WORKFLOW}: status, conclusion, address) and how many ` +
171
+ `changes wait unpublished on the draft branch ${DRAFT_BRANCH}. Call it after publish to see whether the ` +
172
+ 'deploy succeeded; unpublished changes are not visible at the address until publish.',
148
173
  inputSchema: { site: hostedSiteInput },
149
174
  annotations: { readOnlyHint: true },
150
175
  }, hostedTool(async ({ site }) => {
151
176
  const target = await openSite(site)
152
177
  const ahead = await draftAhead(target)
153
178
  const run = await lookup(() => target.client.latestRun(target.site, DEPLOY_WORKFLOW))
154
- const url = await siteUrl(target)
179
+ const url = await deployedUrl(target)
155
180
  const where = url
156
181
  ? `"${target.site}" is served at ${url}.`
157
- : `No address found for "${target.site}": GitHub Pages is not set up for it and config/app.yaml has no origin.`
182
+ : `No address found for "${target.site}": GitHub Pages is not set up for it and ` +
183
+ 'config/app.yaml has no origin.'
158
184
  const draft = ahead
159
185
  ? ` ${ahead} unpublished commit(s) wait on ${DRAFT_BRANCH}; call publish to put them live.`
160
186
  : ' It has no unpublished changes.'
@@ -1,4 +1,4 @@
1
- // The read tools of the hosted mode (L7b, plan D2–D4): `list_sites`,
1
+ // The read tools of the hosted mode (L7b): `list_sites`,
2
2
  // `get_site`, `read_page` and `read_file` over the signed-in user's GitHub
3
3
  // repositories. A site is a repository as `owner/name` that the GitHub App can
4
4
  // reach with the user's token and whose package.json depends on
@@ -13,6 +13,7 @@ import fs from 'node:fs'
13
13
  import os from 'node:os'
14
14
  import path from 'node:path'
15
15
  import { computeFolders, defaultSettings } from '@nera-static/core'
16
+ import { isPlainObject } from '@nera-static/plugin-utils/values'
16
17
  import yaml from 'yaml'
17
18
  import { z } from 'zod'
18
19
  import { parsePage, refuseSecrets } from '../../pages.js'
@@ -86,11 +87,12 @@ export function treeFolders(appConfig, entries) {
86
87
  function parseAppConfig(file) {
87
88
  if (file === null) return { appConfig: {}, appConfigError: null }
88
89
  if (file.content === null) {
89
- return { appConfig: {}, appConfigError: `config/app.yaml is ${file.size} bytes, more than the ${MAX_READ_BYTES} bytes these tools read.` }
90
+ return { appConfig: {}, appConfigError: `config/app.yaml is ${file.size} bytes, more than ` +
91
+ `the ${MAX_READ_BYTES} bytes these tools read.` }
90
92
  }
91
93
  try {
92
94
  const parsed = yaml.parse(file.content.toString('utf8')) || {}
93
- if (typeof parsed !== 'object' || Array.isArray(parsed)) {
95
+ if (!isPlainObject(parsed)) {
94
96
  return { appConfig: {}, appConfigError: 'config/app.yaml is not a list of `key: value` lines.' }
95
97
  }
96
98
  return { appConfig: parsed, appConfigError: null }
@@ -140,7 +142,8 @@ export function hostedTool(handler) {
140
142
  export function requirePagePath(file, folders) {
141
143
  const pagesFolder = repoFolder(folders.pages, 'pages')
142
144
  if (!file.startsWith(`${pagesFolder}/`)) {
143
- throw new ToolError(`"${file}" is not inside the site's pages folder (${pagesFolder}/). Give a path like ${pagesFolder}/about.md; for other files use read_file / write_file.`)
145
+ throw new ToolError(`"${file}" is not inside the site's pages folder (${pagesFolder}/). Give a path ` +
146
+ `like ${pagesFolder}/about.md; for other files use read_file / write_file.`)
144
147
  }
145
148
  if (path.posix.extname(file) !== '.md') {
146
149
  throw new ToolError(`"${file}" does not end in .md. Pages are Markdown files, e.g. ${pagesFolder}/about.md.`)
@@ -148,8 +151,9 @@ export function requirePagePath(file, folders) {
148
151
  }
149
152
 
150
153
  /**
151
- * The site lookup every hosted tool goes through (plan D3), bound to the
152
- * signed-in user's repository client.
154
+ * The site lookup every hosted tool goes through, so a repository outside the
155
+ * user's installations is a tool error, never a passed-through 404; bound to
156
+ * the signed-in user's repository client.
153
157
  *
154
158
  * @param {() => Promise<ReturnType<import('../repo.js').createRepoClient>>} repos
155
159
  */
@@ -166,7 +170,9 @@ export function createSiteAccess(repos) {
166
170
  const client = await repos()
167
171
  const repo = (await client.listRepos()).find((candidate) => candidate.site.toLowerCase() === wanted)
168
172
  if (!repo) {
169
- throw new ToolError(`The repository "${input}" is not one the Nera Static GitHub App can reach for you. Call list_sites for the sites you can edit; to add a repository, grant the Nera Static GitHub App access to it in your GitHub settings (Applications → Nera Static → Configure).`)
173
+ throw new ToolError(`The repository "${input}" is not one the Nera Static GitHub App can reach for you. ` +
174
+ 'Call list_sites for the sites you can edit; to add a repository, grant the Nera Static GitHub App ' +
175
+ 'access to it in your GitHub settings (Applications → Nera Static → Configure).')
170
176
  }
171
177
  const site = repo.site
172
178
  const draftSha = await client.branchHead(site, DRAFT_BRANCH)
@@ -178,7 +184,8 @@ export function createSiteAccess(repos) {
178
184
  const branch = draftSha ? DRAFT_BRANCH : BASE_BRANCH
179
185
  const pkg = parsePackage(await client.readFile(site, 'package.json', ref))
180
186
  if (!isNeraSite(pkg)) {
181
- throw new ToolError(`"${site}" is not a Nera site: its package.json on ${branch} does not depend on @nera-static/nera. Call list_sites for the sites you can edit.`)
187
+ throw new ToolError(`"${site}" is not a Nera site: its package.json on ${branch} does not depend on ` +
188
+ '@nera-static/nera. Call list_sites for the sites you can edit.')
182
189
  }
183
190
  return { client, site, branch, ref, draft: { exists: Boolean(draftSha), sha: draftSha }, mainSha, pkg }
184
191
  }
@@ -190,7 +197,8 @@ export function createSiteAccess(repos) {
190
197
  async function readAt(target, file, what, ref = target.ref) {
191
198
  const found = await target.client.readFile(target.site, file, ref, { maxBytes: MAX_READ_BYTES })
192
199
  if (found?.type === 'symlink') {
193
- throw new ToolError(`"${file}" is a symbolic link in ${target.site}; these tools do not follow links. Use the file it points to instead.`)
200
+ throw new ToolError(`"${file}" is a symbolic link in ${target.site}; these tools do not follow links. ` +
201
+ 'Use the file it points to instead.')
194
202
  }
195
203
  if (found?.type === 'dir') throw new ToolError(`"${file}" is a folder, not ${what}.`)
196
204
  return found
@@ -234,12 +242,14 @@ export function registerHostedReadTools(server, { repos }) {
234
242
  const reachable = await client.listRepos()
235
243
  const checked = await Promise.all(reachable.map(async (repo) => {
236
244
  const pkg = parsePackage(await client.readFile(repo.site, 'package.json', BASE_BRANCH))
237
- return isNeraSite(pkg) ? { site: repo.site, name: pkg.name ?? null, nera: neraRange(pkg), private: repo.private } : null
245
+ if (!isNeraSite(pkg)) return null
246
+ return { site: repo.site, name: pkg.name ?? null, nera: neraRange(pkg), private: repo.private }
238
247
  }))
239
248
  const sites = checked.filter(Boolean)
240
249
  const text = sites.length
241
250
  ? `Found ${sites.length} Nera site(s): ${sites.map((s) => s.site).join(', ')}. Call get_site for one of them.`
242
- : `None of the ${reachable.length} repositories the Nera Static GitHub App can reach is a Nera site. Grant the App access to your site's repository in your GitHub settings.`
251
+ : `None of the ${reachable.length} repositories the Nera Static GitHub App can reach is a Nera site. ` +
252
+ 'Grant the App access to your site\'s repository in your GitHub settings.'
243
253
  return ok({ sites }, text)
244
254
  }))
245
255
 
@@ -297,16 +307,19 @@ export function registerHostedReadTools(server, { repos }) {
297
307
  requirePagePath(file, folders)
298
308
  const found = await readAt(target, file, 'a page')
299
309
  if (!found) {
300
- throw new ToolError(`The page "${file}" does not exist on ${target.branch} of ${target.site}. Call get_site for the list of pages, or write_page to create it.`)
310
+ throw new ToolError(`The page "${file}" does not exist on ${target.branch} of ${target.site}. Call ` +
311
+ 'get_site for the list of pages, or write_page to create it.')
301
312
  }
302
313
  if (found.content === null) {
303
- throw new ToolError(`The page "${file}" is ${found.size} bytes, more than the ${MAX_READ_BYTES} bytes read_page returns.`)
314
+ throw new ToolError(`The page "${file}" is ${found.size} bytes, more than the ${MAX_READ_BYTES} ` +
315
+ 'bytes read_page returns.')
304
316
  }
305
317
  const { frontmatter, body, error } = parsePage(found.content.toString('utf8'))
306
318
  const structured = { site: target.site, branch: target.branch, path: file, frontmatter, body }
307
319
  if (error) structured.frontmatterError = error
308
320
  const text = error
309
- ? `Read ${file}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, passing the whole frontmatter.`
321
+ ? `Read ${file}, but its frontmatter is invalid YAML: ${error} Fix it with write_page, ` +
322
+ 'passing the whole frontmatter.'
310
323
  : `Read ${file} (layout: ${frontmatter.layout ?? 'none — the build skips this page'}).`
311
324
  return ok(structured, text)
312
325
  }))
@@ -322,10 +335,12 @@ export function registerHostedReadTools(server, { repos }) {
322
335
  const target = await openSite(site)
323
336
  const found = await readAt(target, file, 'a file')
324
337
  if (!found) {
325
- throw new ToolError(`The file "${file}" does not exist on ${target.branch} of ${target.site}. Call get_site to see the site's folders.`)
338
+ throw new ToolError(`The file "${file}" does not exist on ${target.branch} of ${target.site}. Call ` +
339
+ 'get_site to see the site\'s folders.')
326
340
  }
327
341
  if (found.content === null) {
328
- throw new ToolError(`"${file}" is ${found.size} bytes, more than the ${MAX_READ_BYTES} bytes read_file returns.`)
342
+ throw new ToolError(`"${file}" is ${found.size} bytes, more than the ${MAX_READ_BYTES} ` +
343
+ 'bytes read_file returns.')
329
344
  }
330
345
  if (found.content.includes(0)) {
331
346
  throw new ToolError(`"${file}" is a binary file (an image, a font, …); read_file only returns text.`)
@@ -1,4 +1,4 @@
1
- // The hosted `validate` (L7b, plan D1/D6): the validator of `nera validate`
1
+ // The hosted `validate` (L7b): the validator of `nera validate`
2
2
  // over a temporary checkout of the site's draft (or of `main` when there is
3
3
  // none), made by src/hosted/checkout.js and deleted afterwards. The records
4
4
  // come back exactly as `validate({ cwd })` of `@nera-static/nera` returns
@@ -25,7 +25,13 @@ export function registerHostedValidateTool(server, { repos, userId, checkouts, v
25
25
 
26
26
  server.registerTool('validate', {
27
27
  title: 'Validate a Nera site',
28
- description: `Checks a Nera site in a GitHub repository the way the build will read it, on the draft branch ${DRAFT_BRANCH} when it exists (your unpublished changes), else on main: config/app.yaml and page frontmatter parse, every page has a \`layout\` that exists, every Pug include resolves, the theme is found. Returns one record per finding (\`file\`, \`line\`, \`severity\` error|warning, \`rule\`, \`message\` with the fix). Call it after write_page, write_file or delete_page; fix every error, then call publish. It takes a few seconds: the repository is downloaded for the check, plus the theme package when config/app.yaml names one (nothing is installed or run).`,
28
+ description: 'Checks a Nera site in a GitHub repository the way the build will read it, on the draft ' +
29
+ `branch ${DRAFT_BRANCH} when it exists (your unpublished changes), else on main: config/app.yaml and ` +
30
+ 'page frontmatter parse, every page has a `layout` that exists, every Pug include resolves, the theme ' +
31
+ 'is found. Returns one record per finding (`file`, `line`, `severity` error|warning, `rule`, ' +
32
+ '`message` with the fix). Call it after write_page, write_file or delete_page; fix every error, then ' +
33
+ 'call publish. It takes a few seconds: the repository is downloaded for the check, plus the theme ' +
34
+ 'package when config/app.yaml names one (nothing is installed or run).',
29
35
  inputSchema: { site: hostedSiteInput },
30
36
  annotations: { readOnlyHint: true },
31
37
  }, hostedTool(async ({ site }, { signal }) => {
@@ -37,7 +43,8 @@ export function registerHostedValidateTool(server, { repos, userId, checkouts, v
37
43
  )
38
44
  const counts = countBySeverity(results)
39
45
  const text = results.length
40
- ? `"${target.site}" (${target.branch}) has ${counts.errors} error(s) and ${counts.warnings} warning(s); each message says how to fix it.`
46
+ ? `"${target.site}" (${target.branch}) has ${counts.errors} error(s) and ${counts.warnings} warning(s); ` +
47
+ 'each message says how to fix it.'
41
48
  : `"${target.site}" (${target.branch}) is valid.${target.draft.exists ? ' Call publish to put the draft live.' : ''}`
42
49
  return ok({ site: target.site, branch: target.branch, ok: !hasErrors(results), counts, results }, text)
43
50
  }))
@@ -1,4 +1,4 @@
1
- // The write tools of the hosted mode (L7b, plan D2–D5): `write_page`,
1
+ // The write tools of the hosted mode (L7b): `write_page`,
2
2
  // `write_file` and `delete_page` on the signed-in user's GitHub repositories.
3
3
  // Each call makes exactly one commit, with the message the model passes, on
4
4
  // the draft branch `nera-draft`; the first write creates it from `main`. The
@@ -27,7 +27,8 @@ const messageInput = z
27
27
  .describe('The commit message: one line saying what the change does, e.g. "Add the about page" or "Fix a typo on the home page". Each call makes one commit with it.')
28
28
 
29
29
  /** What every successful write tells the model to do next. */
30
- const NEXT = `Nothing is live yet: the change waits on the draft branch ${DRAFT_BRANCH}. Call validate to check the site, then publish to put the draft live.`
30
+ const NEXT = `Nothing is live yet: the change waits on the draft branch ${DRAFT_BRANCH}. Call validate to check the ` +
31
+ 'site, then publish to put the draft live.'
31
32
 
32
33
  /**
33
34
  * Refuses a path the repository's tree cannot take as a file: one below a
@@ -44,7 +45,8 @@ export function refuseBlockedPath(entries, file) {
44
45
  const ancestor = segments.slice(0, i).join('/')
45
46
  const entry = entries.find((candidate) => candidate.path === ancestor)
46
47
  if (entry?.mode === SYMLINK_MODE) {
47
- throw new ToolError(`"${file}" is below ${ancestor}, which is a symbolic link; these tools do not follow links.`)
48
+ throw new ToolError(`"${file}" is below ${ancestor}, which is a symbolic link; these ` +
49
+ 'tools do not follow links.')
48
50
  }
49
51
  if (entry?.type === 'blob') {
50
52
  throw new ToolError(`"${file}" is below ${ancestor}, which is a file, not a folder.`)
@@ -93,7 +95,14 @@ export function registerHostedWriteTools(server, { repos }) {
93
95
 
94
96
  server.registerTool('write_page', {
95
97
  title: 'Create or update a page',
96
- description: `Creates a page of a Nera site in a GitHub repository, or replaces an existing one, as one commit on the draft branch ${DRAFT_BRANCH} (created from main on the first change; nothing goes live until publish). \`frontmatter\` becomes the YAML block at the top of the file and must contain \`layout\` (the Pug layout under the theme's views folder that renders the page, e.g. \`pages/default.pug\` — read an existing page to see which layouts the site uses); \`title\` and \`description\` are usual too. Keys you leave out are removed; comments and quoting of unchanged keys are kept. \`body\` is the Markdown content; leave it out to keep the existing body. Afterwards call validate, then publish.`,
98
+ description: 'Creates a page of a Nera site in a GitHub repository, or replaces an existing one, as one ' +
99
+ `commit on the draft branch ${DRAFT_BRANCH} (created from main on the first change; nothing goes live ` +
100
+ 'until publish). `frontmatter` becomes the YAML block at the top of the file and must contain ' +
101
+ '`layout` (the Pug layout under the theme\'s views folder that renders the page, e.g. ' +
102
+ '`pages/default.pug` — read an existing page to see which layouts the site uses); `title` and ' +
103
+ '`description` are usual too. Keys you leave out are removed; comments and quoting of unchanged keys ' +
104
+ 'are kept. `body` is the Markdown content; leave it out to keep the existing body. Afterwards call ' +
105
+ 'validate, then publish.',
97
106
  inputSchema: {
98
107
  site: hostedSiteInput,
99
108
  path: pageInput,
@@ -112,7 +121,8 @@ export function registerHostedWriteTools(server, { repos }) {
112
121
  refuseBlockedPath(tree.entries, file)
113
122
  const { current, commit } = await commitToDraft(target, file, 'a page', (existing) => {
114
123
  if (existing?.content === null) {
115
- throw new ToolError(`The page "${file}" is ${existing.size} bytes, more than the ${MAX_READ_BYTES} bytes write_page edits.`)
124
+ throw new ToolError(`The page "${file}" is ${existing.size} bytes, more than the ${MAX_READ_BYTES} ` +
125
+ 'bytes write_page edits.')
116
126
  }
117
127
  return composePage(existing ? existing.content.toString('utf8') : null, frontmatter, body)
118
128
  }, message)
@@ -125,7 +135,12 @@ export function registerHostedWriteTools(server, { repos }) {
125
135
 
126
136
  server.registerTool('write_file', {
127
137
  title: 'Create or update a site file',
128
- description: `Creates or replaces a text file of a Nera site in a GitHub repository, as one commit on the draft branch ${DRAFT_BRANCH} (created from main on the first change; nothing goes live until publish): configuration (\`config/app.yaml\`, \`config/<plugin>.yaml\`), Pug templates (\`theme/views/…\`), styles and scripts (\`assets/…\`). Pages (Markdown in the pages folder) go through write_page instead; the output folder (\`public/\`) is rebuilt on every build, so nothing is written there. Afterwards call validate, then publish.`,
138
+ description: 'Creates or replaces a text file of a Nera site in a GitHub repository, as one commit on the ' +
139
+ `draft branch ${DRAFT_BRANCH} (created from main on the first change; nothing goes live until publish): ` +
140
+ 'configuration (`config/app.yaml`, `config/<plugin>.yaml`), Pug templates (`theme/views/…`), ' +
141
+ 'styles and scripts (`assets/…`). Pages (Markdown in the pages folder) go through write_page instead; ' +
142
+ 'the output folder (`public/`) is rebuilt on every build, so nothing is written there. Afterwards call ' +
143
+ 'validate, then publish.',
129
144
  inputSchema: {
130
145
  site: hostedSiteInput,
131
146
  path: fileInput,
@@ -141,7 +156,8 @@ export function registerHostedWriteTools(server, { repos }) {
141
156
  const { folders, tree } = await siteModel(target)
142
157
  const distFolder = repoFolder(folders.dist, 'dist')
143
158
  if (file === distFolder || file.startsWith(`${distFolder}/`)) {
144
- throw new ToolError(`"${file}" is in the output folder (${distFolder}/), which every build deletes and recreates. Change the page, template or asset it is built from instead.`)
159
+ throw new ToolError(`"${file}" is in the output folder (${distFolder}/), which every build deletes and ` +
160
+ 'recreates. Change the page, template or asset it is built from instead.')
145
161
  }
146
162
  const pagesFolder = repoFolder(folders.pages, 'pages')
147
163
  if (file.startsWith(`${pagesFolder}/`) && path.posix.extname(file) === '.md') {
@@ -158,7 +174,9 @@ export function registerHostedWriteTools(server, { repos }) {
158
174
 
159
175
  server.registerTool('delete_page', {
160
176
  title: 'Delete a page',
161
- description: `Deletes one page (a Markdown file in the pages folder) of a Nera site in a GitHub repository, as one commit on the draft branch ${DRAFT_BRANCH} (nothing goes live until publish). Links to it from other pages or the navigation are not changed — check them with validate afterwards, then publish.`,
177
+ description: 'Deletes one page (a Markdown file in the pages folder) of a Nera site in a GitHub repository, ' +
178
+ `as one commit on the draft branch ${DRAFT_BRANCH} (nothing goes live until publish). Links to it from ` +
179
+ 'other pages or the navigation are not changed — check them with validate afterwards, then publish.',
162
180
  inputSchema: { site: hostedSiteInput, path: pageInput, message: messageInput },
163
181
  annotations: { destructiveHint: true },
164
182
  }, hostedTool(async ({ site, path: page, message }) => {
@@ -170,7 +188,8 @@ export function registerHostedWriteTools(server, { repos }) {
170
188
  requirePagePath(file, folders)
171
189
  const { commit } = await commitToDraft(target, file, 'a page', (existing) => {
172
190
  if (existing === null) {
173
- throw new ToolError(`The page "${file}" does not exist in ${target.site}. Call get_site for the list of pages.`)
191
+ throw new ToolError(`The page "${file}" does not exist in ${target.site}. Call ` +
192
+ 'get_site for the list of pages.')
174
193
  }
175
194
  return null
176
195
  }, message)