@cloudhal/mcp-server 0.4.0 → 0.6.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.
@@ -26,6 +26,14 @@ import {
26
26
  unknownBlocks,
27
27
  unknownBlocksOf,
28
28
  } from "./content-shared.js";
29
+ import {
30
+ checkEntryFields,
31
+ describeFieldPatch,
32
+ FIELDS_INPUT,
33
+ FIELDS_PATCH,
34
+ mergeFields,
35
+ } from "./entry-fields.js";
36
+ import { ENTRY_QUERY_INPUT, listEntries } from "./entry-list.js";
29
37
  import { entryTerms, reportDeltas } from "./entry-terms.js";
30
38
  import { menuHint, menuItemsHiddenBy } from "./menu-tools.js";
31
39
  import { assignmentDeltas, describeDeltas, TAGS_INPUT, TERMS_INPUT, termLookup } from "./terms.js";
@@ -34,7 +42,7 @@ const listEntriesTool = {
34
42
  name: "list_entries",
35
43
  title: "List articles",
36
44
  description:
37
- 'Content entries, newest first. `collection` defaults to posts (unless the filter names one). `filter` selects by terms (RFC-0002 grammar): clauses joined by "+" (AND), "[a,b]" = either, "-" = none of, "primary:category:x" = primary term, "category:x>*" = x or a sub-category, "collection:posts"; values are term slugs (old slugs work) or ids. Example: "category:news+tag:[ai,llm]+-tag:sponsored".',
45
+ 'Content entries, newest first. `collection` defaults to posts (unless the filter names one). `filter` selects by terms (RFC-0002 grammar): clauses joined by "+" (AND), "[a,b]" = either, "-" = none of, "primary:category:x" = primary term, "category:x>*" = x or a sub-category, "collection:posts"; values are term slugs (old slugs work) or ids. Example: "category:news+tag:[ai,llm]+-tag:sponsored". `where`/`orderBy` filter and sort by the collection\'s list fields (RFC-0042; list_collections → listFields), e.g. upcoming events: where [{"field":"startsAt","op":"gte","value":"now"}], orderBy {"field":"startsAt","direction":"asc"}; `limit` pages the answer (total, nextCursor → cursor).',
38
46
  inputSchema: obj(
39
47
  {
40
48
  siteId: id,
@@ -51,10 +59,18 @@ const listEntriesTool = {
51
59
  minItems: 1,
52
60
  uniqueItems: true,
53
61
  },
62
+ ...ENTRY_QUERY_INPUT,
54
63
  },
55
64
  ["siteId"],
56
65
  ),
57
- outputSchema: obj({ entries: { type: "array", items: ENTRY } }, ["entries"]),
66
+ outputSchema: obj(
67
+ {
68
+ entries: { type: "array", items: ENTRY },
69
+ total: { type: "integer" },
70
+ nextCursor: { type: "string" },
71
+ },
72
+ ["entries"],
73
+ ),
58
74
  annotations: {
59
75
  readOnlyHint: true,
60
76
  destructiveHint: false,
@@ -75,10 +91,7 @@ const listEntriesTool = {
75
91
  ...(a.status !== undefined ? { status: a.status } : {}),
76
92
  };
77
93
  try {
78
- const entries = (await ctx.store.listContentEntries(a.siteId , query)).sort((x, y) =>
79
- y.updatedAt.localeCompare(x.updatedAt),
80
- );
81
- return { entries };
94
+ return await listEntries(ctx, a.siteId , query, a);
82
95
  } catch (e) {
83
96
  mapError(e);
84
97
  }
@@ -110,7 +123,7 @@ const createEntryTool = {
110
123
  name: "create_entry",
111
124
  title: "Create article",
112
125
  description:
113
- "Create a draft content entry (markdown body) in an existing collection (list_collections; a new one needs create_collection first), optionally filed under existing terms (`terms`; see list_taxonomies and list_terms). Snapshots afterwards.",
126
+ "Create a draft content entry (markdown body) in an existing collection (list_collections; a new one needs create_collection first), optionally filed under existing terms (`terms`; see list_taxonomies and list_terms). Typed custom fields go in `fields`, following the collection's fieldsSchema from list_collections; invalid values are refused with their paths. Snapshots afterwards.",
114
127
  inputSchema: obj(
115
128
  {
116
129
  siteId: id,
@@ -125,7 +138,7 @@ const createEntryTool = {
125
138
  terms: TERMS_INPUT,
126
139
  tags: TAGS_INPUT,
127
140
  coverImage: COVER_INPUT,
128
- fields: { type: "object", description: "Collection-specific fields" },
141
+ fields: FIELDS_INPUT,
129
142
  },
130
143
  ["siteId", "slug", "title", "body"],
131
144
  ),
@@ -141,9 +154,24 @@ const createEntryTool = {
141
154
  },
142
155
  scopes: ["content:write"],
143
156
  own: "entry",
144
- // RFC-0040 §5: only collections of the registry (a new one goes through create_collection).
145
- precheck: (a, ctx) =>
146
- requireRegistered(ctx, a.siteId , (a.collection ) ?? "posts"),
157
+ // RFC-0040 §5: only collections of the registry (a new one goes through create_collection);
158
+ // RFC-0041 §8: field values are checked before anyone is asked.
159
+ precheck: async (a, ctx) => {
160
+ const collection = (a.collection ) ?? "posts";
161
+ await requireRegistered(ctx, a.siteId , collection);
162
+ const site = await ctx.store.getSite(a.siteId );
163
+ if (!site) return;
164
+ await checkEntryFields(ctx, {
165
+ site,
166
+ next: {
167
+ id: "",
168
+ siteId: site.id,
169
+ collection,
170
+ status: "draft",
171
+ fields: (a.fields ) ?? {},
172
+ },
173
+ });
174
+ },
147
175
  handler: async (a, ctx) => {
148
176
  const site = await requireSite(ctx, a.siteId );
149
177
  await entryLimitCheck(ctx, "create", undefined, {
@@ -189,7 +217,7 @@ const updateEntryTool = {
189
217
  name: "update_entry",
190
218
  title: "Update article",
191
219
  description:
192
- "Update title, summary, body, slug, status (draft → review → published) or terms (`terms`: add, remove or set categories and tags by id, slug or name) of an entry. Review and published articles need a primary term in every required taxonomy. Requires the current `rev`. Changing a published article's slug leaves a redirect. Snapshots afterwards.",
220
+ "Update title, summary, body, slug, status (draft → review → published), terms (`terms`: add, remove or set categories and tags by id, slug or name) or typed custom fields (`fields`, a merge patch: null removes a key; see the collection's fieldsSchema in list_collections) of an entry. Review and published articles need a primary term in every required taxonomy and every field marked needed to publish. Requires the current `rev`. Changing a published article's slug leaves a redirect. Snapshots afterwards.",
193
221
  inputSchema: obj(
194
222
  {
195
223
  siteId: id,
@@ -207,6 +235,7 @@ const updateEntryTool = {
207
235
  description: "Cover image; null removes it",
208
236
  },
209
237
  status: { type: "string", enum: ["draft", "review", "published", "archived"] },
238
+ fields: FIELDS_PATCH,
210
239
  },
211
240
  ["siteId", "entryId", "rev"],
212
241
  ),
@@ -219,15 +248,18 @@ const updateEntryTool = {
219
248
  },
220
249
  scopes: ["content:write"],
221
250
  own: "entry",
222
- // Own-limited callers (Authors, Contributors and their agents) only touch their own articles.
251
+ // Own-limited callers (Authors, Contributors and their agents) only touch their own articles;
252
+ // field values (RFC-0041 §8) are checked before anyone is asked.
223
253
  precheck: async (a, ctx) => {
224
- if (!ctx.limit) return;
225
254
  const entry = await ctx.store.getContentEntry(a.entryId );
226
255
  if (!entry || entry.siteId !== a.siteId) return;
227
- await entryLimitCheck(ctx, "update", entry, {
228
- author: entry.author,
229
- status: (a.status ) ?? entry.status,
230
- });
256
+ const status = (a.status ) ?? entry.status;
257
+ if (ctx.limit) await entryLimitCheck(ctx, "update", entry, { author: entry.author, status });
258
+ if (a.fields === undefined && status === entry.status) return;
259
+ const site = await ctx.store.getSite(entry.siteId);
260
+ if (!site) return;
261
+ const fields = mergeFields(entry.fields, (a.fields ) ?? {});
262
+ await checkEntryFields(ctx, { site, next: { ...entry, status, fields }, stored: entry });
231
263
  },
232
264
  approvalPrompt: async (a, ctx) => {
233
265
  const entry = await ctx.store.getContentEntry(a.entryId );
@@ -247,6 +279,10 @@ const updateEntryTool = {
247
279
  : "cover image"
248
280
  : "",
249
281
  ].filter(Boolean);
282
+ if (a.fields && site && Object.keys(a.fields).length)
283
+ changes.push(
284
+ `fields: ${describeFieldPatch(site, entry.collection, a.fields )}`,
285
+ );
250
286
  if (a.terms || a.tags) {
251
287
  try {
252
288
  const { terms } = await entryTerms(ctx, site , entry, a);
@@ -295,6 +331,9 @@ const updateEntryTool = {
295
331
  ...(a.title ? { title: a.title } : {}),
296
332
  ...(a.summary !== undefined ? { summary: a.summary } : {}),
297
333
  ...(a.body !== undefined ? { body: { ...entry.body, value: a.body } } : {}),
334
+ ...(a.fields !== undefined
335
+ ? { fields: mergeFields(entry.fields, a.fields ) }
336
+ : {}),
298
337
  ...(a.slug ? { slug: a.slug } : {}),
299
338
  tags,
300
339
  ...(terms ? { terms } : {}),
@@ -0,0 +1,8 @@
1
+ /**
2
+ * RFC-0041 and RFC-0042: what an agent does next after a typed-field, listing, expiry or
3
+ * structured-data refusal. Every refusal keeps its issues in
4
+ * `details.issues`, each at its slash path (`fields/startsAt/at`), so the hint only names the tool.
5
+ */
6
+ import type { InvariantCode } from "@cloudhal/core-ts";
7
+ /** The next step for a field refusal; undefined for codes that are not about fields. */
8
+ export declare function fieldHint(code: InvariantCode, details: Readonly<Record<string, unknown>>): string | undefined;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * RFC-0041 and RFC-0042: what an agent does next after a typed-field, listing, expiry or
3
+ * structured-data refusal. Every refusal keeps its issues in
4
+ * `details.issues`, each at its slash path (`fields/startsAt/at`), so the hint only names the tool.
5
+ */
6
+
7
+
8
+ const OPERATIONS = "rename_field, change_field_type, set_field_localized or remove_field";
9
+
10
+ const HINTS = {
11
+ invalid_fields:
12
+ "fix the values at the paths in details.issues; list_collections shows the collection's fieldsSchema (types, allowed values, limits)",
13
+ unknown_field:
14
+ "use one of the collection's field keys (list_collections → fieldsSchema); a new field is added with update_collection, which a person approves",
15
+ field_not_localized:
16
+ "that field is shared by every language version: set it on the original entry named in the message, and leave it out of the translation",
17
+ required_field:
18
+ "give the fields named in details.issues a value (update_entry with fields), or keep the entry a draft",
19
+ field_key_reserved:
20
+ "pick another key: built-in entry properties (title, slug, body, …) cannot be field keys",
21
+ field_key_duplicate: "every field key appears once per collection",
22
+ field_option_duplicate: "every option value appears once per select field",
23
+ field_bounds: "a number field's minimum must not be above its maximum",
24
+ too_many_fields:
25
+ "a collection has at most 30 fields, a site 200 and a select 50 options; remove some first",
26
+ field_change_needs_operation: `that change could lose or reinterpret stored values: use ${OPERATIONS} (each shows a dry run and waits for a person; try dryRun: true first)`,
27
+ operation_in_progress:
28
+ "a person can continue or revert it in Studio, or call the same operation tool again with that operationId (it needs a new approval)",
29
+ field_values_unconvertible:
30
+ 'details.report.samples shows the values; change them first (update_entry), or call again with onInvalid: "clear" to drop them (the person approving sees how many)',
31
+ field_operation_incomplete:
32
+ "call the operation tool again with its operationId to finish it (a new approval), or ask a person to continue it in Studio",
33
+ // RFC-0042 (listings, expiry, structured data)
34
+ invalid_query:
35
+ "fix the conditions at the paths in details.issues: only the collection's listFields may be queried, with the operators list_collections shows per field (listFields[].ops); dates are YYYY-MM-DD, instants RFC 3339, or now",
36
+ structured_data_invalid:
37
+ "fix the mappings at the paths in details.issues: list_collections shows a preset's paths, which are required and the sources each takes (structuredData.paths); field sources need a field of a fitting type, and required values come from the entry, never a constant",
38
+ invalid_expiry:
39
+ "expiry.field must be a date or datetime field of the collection (list_collections → fields)",
40
+ list_field_in_use:
41
+ "contentList sections on the pages in details.pages still filter or sort by that field: change their where/orderBy first (update_page), then try again",
42
+ };
43
+
44
+ const GATES_EXPIRY =
45
+ "a collection expiry needs a site Worker that enforces derived gates: ask a person to deploy the current site (cloudhal deploy), then try again; until then leave expiry out (the rest of the change can go ahead without it)";
46
+ const GATES_AVAILABILITY =
47
+ "the site's renderer has not confirmed it enforces time gates: ask a person to deploy the current site (cloudhal deploy) before setting embargoes or expiries";
48
+
49
+ /** The next step for a field refusal; undefined for codes that are not about fields. */
50
+ export function fieldHint(code , details ) {
51
+ if (code === "gates_unsupported")
52
+ return Array.isArray(details.collections) ? GATES_EXPIRY : GATES_AVAILABILITY;
53
+ if (code === "too_large" && Array.isArray(details.issues))
54
+ return "field values are at most 256 KB per entry and collection settings 256 KB per site; shorten or drop values";
55
+ return HINTS[code];
56
+ }
@@ -0,0 +1,6 @@
1
+ import { type FieldOperation, type FieldOperationReport } from "@cloudhal/core-ts";
2
+ import { type ToolDefinition } from "./common.js";
3
+ /** The approval prompt, built from the dry run (RFC-0041 §6 step 1). */
4
+ export declare function describeOperation(op: FieldOperation, report: FieldOperationReport, locale: string): string;
5
+ /** rename_field … remove_field, after the collection tools. */
6
+ export declare function fieldTools(): ToolDefinition[];
@@ -0,0 +1,360 @@
1
+ /**
2
+ * RFC-0041 §6, §8: the four field operations for agents — `rename_field`, `change_field_type`,
3
+ * `set_field_localized` and `remove_field`. Each needs `site:write` and `content:write` (it
4
+ * rewrites entries), always waits for a person who may change site settings (`person`-classed, so
5
+ * `bypass` waits too), and shows that person the dry run: entries touched, values moved, converted
6
+ * or cleared, samples before and after. `precheck` runs the same dry run, so a call that would
7
+ * clear values without `onInvalid: "clear"` never reaches anyone.
8
+ *
9
+ * An operation that hits its budget answers `done: false` with its `operationId`. A person
10
+ * continues it in Studio, or the agent calls the same tool again with that `operationId`, which
11
+ * needs a new approval (ADR-0043 open question 9: approvals stay single use).
12
+ */
13
+
14
+ import { SiteSchema } from "@cloudhal/core-contracts";
15
+ import {
16
+ continueFieldOperation,
17
+
18
+
19
+
20
+
21
+ fieldOperationStatus,
22
+ InvariantError,
23
+ runFieldOperation,
24
+ } from "@cloudhal/core-ts";
25
+ import { FIELD_TYPES, fieldLabel } from "@cloudhal/core-ts/fields";
26
+ import {
27
+ id,
28
+
29
+ obj,
30
+ quote,
31
+ requireSite,
32
+ SLUG_PATTERN,
33
+ str,
34
+
35
+
36
+ ToolError,
37
+ toToolError,
38
+ } from "./common.js";
39
+
40
+ const DEFS = SiteSchema.$defs ;
41
+ const KEY = DEFS.FieldKey ;
42
+
43
+ const COMMON = {
44
+ siteId: id,
45
+ collection: str("Collection key (list_collections)", { pattern: SLUG_PATTERN, maxLength: 64 }),
46
+ operationId: str(
47
+ "Continue the unfinished operation this tool answered with done: false (repeat the same call with it; a person approves again)",
48
+ { pattern: id.pattern },
49
+ ),
50
+ dryRun: {
51
+ type: "boolean",
52
+ description: "Only report what would change, without asking anyone or changing anything",
53
+ },
54
+ } ;
55
+
56
+ const COUNTS = obj({
57
+ touched: { type: "integer" },
58
+ moved: { type: "integer" },
59
+ converted: { type: "integer" },
60
+ cleared: { type: "integer" },
61
+ removed: { type: "integer" },
62
+ unconvertible: { type: "integer" },
63
+ unchanged: { type: "integer" },
64
+ entries: { type: "integer" },
65
+ });
66
+
67
+ const OUTPUT = obj(
68
+ {
69
+ prompt: { type: "string" },
70
+ dryRun: { type: "boolean" },
71
+ done: { type: "boolean" },
72
+ operationId: { type: "string" },
73
+ report: { ...COUNTS, additionalProperties: true },
74
+ rewritten: { type: "integer" },
75
+ skipped: { type: "array", items: { type: "object" } },
76
+ status: { type: "object" },
77
+ hint: { type: "string" },
78
+ },
79
+ ["prompt", "dryRun", "done"],
80
+ );
81
+
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+ /** What the operation does, for the prompt's first line. */
93
+ function headline(op , report , locale ) {
94
+ const def = report.definition.before;
95
+ const field = `"${quote(fieldLabel(def, locale, locale), 40)}" (${def.key}) of ${op.collection}`;
96
+ switch (op.op) {
97
+ case "rename_field":
98
+ return `Rename the field ${field} to ${op.to}?`;
99
+ case "change_field_type":
100
+ return `Change the field ${field} from ${def.type} to ${op.type}${op.multiple ? " (multiple)" : ""}?`;
101
+ case "set_field_localized":
102
+ return op.localized
103
+ ? `Make the field ${field} localized (each language version gets its own value)?`
104
+ : `Make the field ${field} shared by all language versions (translations' own copies are deleted)?`;
105
+ case "remove_field":
106
+ return `Remove the field ${field} and its values from every entry?`;
107
+ }
108
+ }
109
+
110
+ const sample = (v ) =>
111
+ v === undefined ? "nothing" : `"${quote(typeof v === "string" ? v : JSON.stringify(v), 40)}"`;
112
+
113
+ /** The approval prompt, built from the dry run (RFC-0041 §6 step 1). */
114
+ export function describeOperation(
115
+ op ,
116
+ report ,
117
+ locale ,
118
+ ) {
119
+ const counts = [
120
+ `${report.touched} of ${report.entries} entries change`,
121
+ report.moved ? `${report.moved} values moved` : "",
122
+ report.converted ? `${report.converted} converted` : "",
123
+ report.cleared ? `${report.cleared} cleared` : "",
124
+ report.removed ? `${report.removed} removed` : "",
125
+ report.unconvertible ? `${report.unconvertible} cannot be converted` : "",
126
+ report.unchanged ? `${report.unchanged} unchanged` : "",
127
+ ].filter(Boolean);
128
+ const lines = [headline(op, report, locale), ` ${counts.join(", ")}.`];
129
+ for (const s of report.samples.slice(0, 3))
130
+ lines.push(` ${s.entryId} (${s.locale}): ${sample(s.before)} → ${sample(s.after)}`);
131
+ if (op.op === "rename_field" || op.op === "change_field_type")
132
+ lines.push(
133
+ ` Theme code reading entry.fields.${report.key} directly stops working; themes using entryFields keep working.`,
134
+ );
135
+ lines.push(
136
+ " Snapshots are taken before and after, and it can be reverted. Only the draft changes: the live site keeps the old field until the next publish.",
137
+ );
138
+ return lines.join("\n");
139
+ }
140
+
141
+ async function locale(ctx , siteId ) {
142
+ return (await requireSite(ctx, siteId)).defaultLocale;
143
+ }
144
+
145
+ /** The unfinished operation `operationId` names, checked against this call. */
146
+ async function continued(ctx , siteId , op , opId ) {
147
+ let status ;
148
+ try {
149
+ status = await fieldOperationStatus(ctx.store, siteId, opId);
150
+ } catch (e) {
151
+ throw toToolError(e);
152
+ }
153
+ if (status.operation.op !== op.op || status.operation.collection !== op.collection)
154
+ throw new ToolError(
155
+ "invalid",
156
+ `${opId} is a ${status.operation.op} on ${status.operation.collection}; call that tool with it`,
157
+ );
158
+ return status;
159
+ }
160
+
161
+ async function dryRun(ctx , siteId , op ) {
162
+ try {
163
+ return (
164
+ await runFieldOperation(ctx.store, siteId, op, { actor: ctx.principal.actor, dryRun: true })
165
+ ).report;
166
+ } catch (e) {
167
+ throw toToolError(e);
168
+ }
169
+ }
170
+
171
+ /** The precheck: the dry run's refusal, or an operation id that is not this call's. */
172
+ async function precheck(spec , a , ctx ) {
173
+ const siteId = a.siteId ;
174
+ const site = await requireSite(ctx, siteId);
175
+ const op = spec.operation(a.collection , a);
176
+ if (typeof a.operationId === "string") {
177
+ await continued(ctx, siteId, op, a.operationId);
178
+ return;
179
+ }
180
+ // Another operation still rewriting the collection is the refusal that says what to do.
181
+ const running = site.collections?.[op.collection]?.fields?.find((d) => d.migration)?.migration;
182
+ if (running)
183
+ throw toToolError(
184
+ new InvariantError(
185
+ "operation_in_progress",
186
+ `field operation ${running.id} is still rewriting ${op.collection}`,
187
+ { operationId: running.id, collection: op.collection },
188
+ ),
189
+ );
190
+ const report = await dryRun(ctx, siteId, op);
191
+ if (report.refusal)
192
+ throw toToolError(new InvariantError(report.refusal.code, report.refusal.message, { report }));
193
+ }
194
+
195
+ async function prompt(spec , a , ctx ) {
196
+ const siteId = a.siteId ;
197
+ const op = spec.operation(a.collection , a);
198
+ if (typeof a.operationId === "string") {
199
+ const status = await continued(ctx, siteId, op, a.operationId);
200
+ return `Continue the field operation ${status.operationId} (${op.op} on ${op.collection}, started earlier)? ${status.pending} entries are still to rewrite.`;
201
+ }
202
+ return describeOperation(op, await dryRun(ctx, siteId, op), await locale(ctx, siteId));
203
+ }
204
+
205
+ function answer(r , promptText ) {
206
+ return {
207
+ prompt: promptText,
208
+ dryRun: r.dryRun,
209
+ done: r.done,
210
+ ...(r.operationId ? { operationId: r.operationId } : {}),
211
+ report: r.report,
212
+ rewritten: r.rewritten,
213
+ skipped: r.skipped,
214
+ ...(!r.dryRun && !r.done
215
+ ? {
216
+ hint: `The operation stopped at its budget. A person can continue it in Studio, or call ${r.report.op} again with operationId "${r.operationId}" (it needs a new approval).`,
217
+ }
218
+ : {}),
219
+ };
220
+ }
221
+
222
+ async function handle(spec , a , ctx ) {
223
+ const siteId = a.siteId ;
224
+ const op = spec.operation(a.collection , a);
225
+ const options = { actor: ctx.principal.actor, ...(ctx.now ? { now: ctx.now } : {}) };
226
+ try {
227
+ if (typeof a.operationId === "string") {
228
+ const status = await continued(ctx, siteId, op, a.operationId);
229
+ // A dry run of a continuation only says where the operation stands.
230
+ if (a.dryRun === true)
231
+ return {
232
+ prompt: await prompt(spec, a, ctx),
233
+ dryRun: true,
234
+ done: status.state !== "running",
235
+ operationId: status.operationId,
236
+ status,
237
+ };
238
+ const r = await continueFieldOperation(ctx.store, siteId, status.operationId, options);
239
+ return answer(r, describeOperation(op, r.report, await locale(ctx, siteId)));
240
+ }
241
+ const r = await runFieldOperation(ctx.store, siteId, op, {
242
+ ...options,
243
+ dryRun: a.dryRun === true,
244
+ });
245
+ return answer(r, describeOperation(op, r.report, await locale(ctx, siteId)));
246
+ } catch (e) {
247
+ throw toToolError(e);
248
+ }
249
+ }
250
+
251
+ function operationTool(spec ) {
252
+ return {
253
+ name: spec.name,
254
+ title: spec.title,
255
+ description: `${spec.description} Needs a person who may change site settings in every mode; the approval shows the dry run (entries touched, values changed, samples). dryRun: true reports without asking. Snapshots before and after; revertible; only the draft changes until the next publish. A run that stops at its budget answers done: false with an operationId: call again with it (a new approval) or let a person continue it in Studio.`,
256
+ inputSchema: obj({ ...COMMON, ...spec.input }, ["siteId", "collection", ...spec.required]),
257
+ outputSchema: OUTPUT,
258
+ annotations: {
259
+ readOnlyHint: false,
260
+ destructiveHint: spec.destructive,
261
+ idempotentHint: false,
262
+ openWorldHint: false,
263
+ },
264
+ scopes: ["site:write", "content:write"],
265
+ approverScopes: ["site:settings"],
266
+ requiresApproval: true,
267
+ classify: (a) => (a.dryRun === true ? "read" : "person"),
268
+ precheck: (a, ctx) => precheck(spec, a, ctx),
269
+ approvalPrompt: (a, ctx) => prompt(spec, a, ctx),
270
+ handler: (a, ctx) => handle(spec, a, ctx),
271
+ };
272
+ }
273
+
274
+ const SPECS = [
275
+ {
276
+ name: "rename_field",
277
+ title: "Rename field",
278
+ description:
279
+ "Rename a typed custom field's key (RFC-0041 §6): every entry's value moves from `from` to `to`; nothing is converted.",
280
+ input: {
281
+ from: { ...KEY, description: "The field's current key" },
282
+ to: { ...KEY, description: "The new key" },
283
+ },
284
+ required: ["from", "to"],
285
+ destructive: false,
286
+ operation: (collection, a) => ({
287
+ op: "rename_field",
288
+ collection,
289
+ from: a.from ,
290
+ to: a.to ,
291
+ }),
292
+ },
293
+ {
294
+ name: "change_field_type",
295
+ title: "Change field type",
296
+ description:
297
+ "Change a typed custom field's type, or a select's multiple (RFC-0041 §6), converting every value by a closed table (text↔richText, text↔number, text↔select, text↔url, date↔datetime, single↔multiple select). Values that cannot be converted refuse the call unless onInvalid is \"clear\".",
298
+ input: {
299
+ key: { ...KEY, description: "The field's key" },
300
+ type: str("The new type", { enum: [...FIELD_TYPES] }),
301
+ options: {
302
+ type: "array",
303
+ description:
304
+ "A new select's options (default: the field's own when it already is a select)",
305
+ minItems: 1,
306
+ maxItems: 50,
307
+ items: { $ref: "#/$defs/FieldOption" },
308
+ $defs: { FieldOption: DEFS.FieldOption, Slug: DEFS.Slug, Locale: DEFS.Locale },
309
+ },
310
+ multiple: { type: "boolean", description: "For a select: the value is a list of options" },
311
+ onInvalid: str("Drop values that cannot be converted (the person approving sees how many)", {
312
+ enum: ["clear"],
313
+ }),
314
+ },
315
+ required: ["key", "type"],
316
+ destructive: true,
317
+ operation: (collection, a) => ({
318
+ op: "change_field_type",
319
+ collection,
320
+ key: a.key ,
321
+ type: a.type ,
322
+ ...(a.options ? { options: a.options } : {}),
323
+ ...(typeof a.multiple === "boolean" ? { multiple: a.multiple } : {}),
324
+ ...(a.onInvalid === "clear" ? { onInvalid: "clear" } : {}),
325
+ }),
326
+ },
327
+ {
328
+ name: "set_field_localized",
329
+ title: "Set field localization",
330
+ description:
331
+ "Make a typed custom field localized (each language version has its own value; translations fall back to the original's) or shared (only the original holds it; translations' own copies are deleted) (RFC-0041 §5, §6).",
332
+ input: {
333
+ key: { ...KEY, description: "The field's key" },
334
+ localized: { type: "boolean", description: "true: per language version; false: shared" },
335
+ },
336
+ required: ["key", "localized"],
337
+ destructive: false,
338
+ operation: (collection, a) => ({
339
+ op: "set_field_localized",
340
+ collection,
341
+ key: a.key ,
342
+ localized: a.localized ,
343
+ }),
344
+ },
345
+ {
346
+ name: "remove_field",
347
+ title: "Remove field",
348
+ description:
349
+ "Remove a typed custom field (RFC-0041 §6): its value is deleted from every entry, then its definition.",
350
+ input: { key: { ...KEY, description: "The field's key" } },
351
+ required: ["key"],
352
+ destructive: true,
353
+ operation: (collection, a) => ({ op: "remove_field", collection, key: a.key }),
354
+ },
355
+ ];
356
+
357
+ /** rename_field … remove_field, after the collection tools. */
358
+ export function fieldTools() {
359
+ return SPECS.map(operationTool);
360
+ }
@@ -26,6 +26,7 @@ import {
26
26
  unknownBlocksOf,
27
27
  } from "./content-shared.js";
28
28
  import { menuHint, menuItemsHiddenBy } from "./menu-tools.js";
29
+ import { checkSectionQueries } from "./section-queries.js";
29
30
 
30
31
  const listSitesTool = {
31
32
  name: "list_sites",
@@ -141,6 +142,7 @@ const createPageTool = {
141
142
  openWorldHint: false,
142
143
  },
143
144
  scopes: ["content:write"],
145
+ precheck: (a, ctx) => checkSectionQueries(ctx, a.siteId , a.sections),
144
146
  handler: async (a, ctx) => {
145
147
  assertNoHtmlSections(a.sections);
146
148
  const site = await requireSite(ctx, a.siteId );
@@ -216,6 +218,11 @@ const updatePageTool = {
216
218
  openWorldHint: false,
217
219
  },
218
220
  scopes: ["content:write"],
221
+ precheck: async (a, ctx) => {
222
+ const page = await ctx.store.getPage(a.pageId );
223
+ if (!page || page.siteId !== a.siteId) return;
224
+ await checkSectionQueries(ctx, page.siteId, a.sections, page.sections);
225
+ },
219
226
  handler: async (a, ctx) => {
220
227
  assertNoHtmlSections(a.sections);
221
228
  const page = await ctx.store.getPage(a.pageId );
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The items of a release as the `auto`-mode low-risk check sees them (RFC-0008 §10.3): what each
3
+ * item does, the assets riding with articles, corrections (RFC-0019 §2.4) and derived gates added
4
+ * or moved earlier on live articles (RFC-0042 §3.5, classed like `schedule_unpublish`).
5
+ */
6
+ import type { ReleaseItemRisk } from "@cloudhal/agent-runtime";
7
+ import { type SiteGraphStore } from "@cloudhal/core-ts";
8
+ import type { StoredReleaseItem } from "@cloudhal/schedules";
9
+ type Items = readonly Pick<StoredReleaseItem, "item" | "deps">[];
10
+ /** The items as the low-risk check sees them (§10.3). */
11
+ export declare function releaseRisk(items: Items, corrects?: ReadonlySet<string>, expires?: ReadonlySet<string>): ReleaseItemRisk[];
12
+ /** RFC-0019 §2.4: the release's articles whose target adds a correction to the live version. */
13
+ export declare function releaseCorrections(graph: SiteGraphStore, items: readonly Pick<StoredReleaseItem, "item">[]): Promise<Set<string>>;
14
+ /**
15
+ * RFC-0042 §3.5: the release's live articles whose target adds a derived gate or moves it
16
+ * earlier, under the site's current rules (a release that changes the rules changes the site,
17
+ * which is never low risk anyway).
18
+ */
19
+ export declare function releaseExpiries(graph: SiteGraphStore, items: readonly Pick<StoredReleaseItem, "item">[]): Promise<Set<string>>;
20
+ /** Every fact the low-risk check of a release needs, read from the graph. */
21
+ export declare function releaseRiskFor(graph: SiteGraphStore, items: Items): Promise<ReleaseItemRisk[]>;
22
+ export {};