@mainsoft/agent-cms 0.7.0 → 0.10.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +291 -32
  3. package/TODO.md +72 -26
  4. package/UPGRADE-0.10.md +36 -0
  5. package/UPGRADE-0.8.md +118 -0
  6. package/dist/agent.cjs +39 -17
  7. package/dist/agent.d.cts +2 -2
  8. package/dist/agent.d.ts +2 -2
  9. package/dist/agent.js +9 -7
  10. package/dist/bin.js +4528 -355
  11. package/dist/{chunk-OQ55GEF3.js → chunk-3OPKTBEI.js} +1 -1
  12. package/dist/chunk-6PB4ZCHH.js +328 -0
  13. package/dist/chunk-7SCYDG2G.js +2943 -0
  14. package/dist/chunk-7WJIIJCI.js +544 -0
  15. package/dist/chunk-7Y6TU2UA.js +150 -0
  16. package/dist/{chunk-QC2M4NZY.js → chunk-BFVBHIHV.js} +72 -1
  17. package/dist/chunk-DSJETZT4.js +493 -0
  18. package/dist/{chunk-IW3D4I7Q.js → chunk-IU2SMWAM.js} +246 -4
  19. package/dist/{chunk-VICZ76TR.js → chunk-KAO3Z3CF.js} +43 -2
  20. package/dist/{chunk-CRDW6Q72.js → chunk-MA6VKJ3F.js} +87 -25
  21. package/dist/{chunk-6K5ZTGHQ.js → chunk-PEQY4N73.js} +16 -0
  22. package/dist/{chunk-DOADAH4L.js → chunk-PGV2QPIL.js} +40 -0
  23. package/dist/{chunk-Y63XQS2J.js → chunk-QMPSOLLH.js} +1 -1
  24. package/dist/{chunk-EXV6JNLY.js → chunk-ZCUJ4MPT.js} +15 -22
  25. package/dist/cli.cjs +4528 -355
  26. package/dist/cli.d.cts +19 -3
  27. package/dist/cli.d.ts +19 -3
  28. package/dist/cli.js +206 -16
  29. package/dist/client.cjs +72 -1
  30. package/dist/client.d.cts +308 -6
  31. package/dist/client.d.ts +308 -6
  32. package/dist/client.js +1 -1
  33. package/dist/cms-C_vkAxYV.d.cts +1537 -0
  34. package/dist/cms-pqJyowu1.d.ts +1537 -0
  35. package/dist/config.d.cts +7 -1
  36. package/dist/config.d.ts +7 -1
  37. package/dist/drizzle-repo-CviH3EX7.d.cts +146 -0
  38. package/dist/drizzle-repo-DWLD0rWe.d.ts +146 -0
  39. package/dist/errors.cjs +82 -1
  40. package/dist/errors.d.cts +43 -3
  41. package/dist/errors.d.ts +43 -3
  42. package/dist/errors.js +2 -2
  43. package/dist/frontmatter.d.cts +5 -4
  44. package/dist/frontmatter.d.ts +5 -4
  45. package/dist/http.cjs +640 -94
  46. package/dist/http.d.cts +51 -2
  47. package/dist/http.d.ts +51 -2
  48. package/dist/http.js +203 -13
  49. package/dist/index.cjs +3759 -575
  50. package/dist/index.d.cts +8 -8
  51. package/dist/index.d.ts +8 -8
  52. package/dist/index.js +226 -30
  53. package/dist/markdown.cjs +89 -25
  54. package/dist/markdown.d.cts +57 -3
  55. package/dist/markdown.d.ts +57 -3
  56. package/dist/markdown.js +5 -1
  57. package/dist/mcp.cjs +314 -37
  58. package/dist/mcp.d.cts +3 -2
  59. package/dist/mcp.d.ts +3 -2
  60. package/dist/mcp.js +12 -9
  61. package/dist/messages/en.cjs +40 -0
  62. package/dist/messages/en.js +1 -1
  63. package/dist/messages/ko.cjs +40 -0
  64. package/dist/messages/ko.js +40 -0
  65. package/dist/registry/cms-audit.json +1 -1
  66. package/dist/registry/cms-doc-editor.json +15 -4
  67. package/dist/registry/cms-doc-list.json +2 -1
  68. package/dist/registry/cms-files.json +29 -0
  69. package/dist/registry/cms-lib.json +3 -3
  70. package/dist/registry/cms-media-picker.json +29 -0
  71. package/dist/registry/cms-media.json +28 -0
  72. package/dist/registry/cms-preview-comments.json +24 -0
  73. package/dist/registry/cms-releases.json +28 -0
  74. package/dist/registry/cms-shell.json +2 -2
  75. package/dist/registry/cms-trash.json +24 -0
  76. package/dist/registry/cms-versions.json +2 -1
  77. package/dist/registry/registry.json +163 -3
  78. package/dist/storage-s3.cjs +168 -0
  79. package/dist/storage-s3.d.cts +53 -0
  80. package/dist/storage-s3.d.ts +53 -0
  81. package/dist/storage-s3.js +143 -0
  82. package/dist/storage.cjs +373 -0
  83. package/dist/storage.d.cts +183 -0
  84. package/dist/storage.d.ts +183 -0
  85. package/dist/storage.js +49 -0
  86. package/dist/tables.cjs +251 -3
  87. package/dist/tables.d.cts +4965 -681
  88. package/dist/tables.d.ts +4965 -681
  89. package/dist/tables.js +14 -2
  90. package/dist/tools.cjs +331 -20
  91. package/dist/tools.d.cts +54 -7
  92. package/dist/tools.d.ts +54 -7
  93. package/dist/tools.js +16 -7
  94. package/dist/types.cjs +99 -1
  95. package/dist/types.d.cts +205 -5
  96. package/dist/types.d.ts +205 -5
  97. package/dist/types.js +5 -3
  98. package/package.json +32 -22
  99. package/dist/ai.cjs +0 -555
  100. package/dist/ai.d.cts +0 -48
  101. package/dist/ai.d.ts +0 -48
  102. package/dist/ai.js +0 -73
  103. package/dist/chunk-52NUUZC7.js +0 -1446
  104. package/dist/chunk-IGL2V6US.js +0 -324
  105. package/dist/chunk-QQV6VLYJ.js +0 -204
  106. package/dist/cms-BPp01z-8.d.ts +0 -411
  107. package/dist/cms-D6D89-qZ.d.cts +0 -411
  108. package/dist/drizzle-repo-B1rt7r4j.d.ts +0 -90
  109. package/dist/drizzle-repo-Cn-kL2FK.d.cts +0 -90
  110. package/dist/repo-BWI2Pkrv.d.ts +0 -162
  111. package/dist/repo-CeDxUxO6.d.cts +0 -162
package/dist/tables.js CHANGED
@@ -1,31 +1,43 @@
1
1
  import {
2
2
  LEGACY_COLUMNS,
3
3
  cmsApiKeys,
4
+ cmsAssetRefs,
5
+ cmsAssets,
4
6
  cmsAudit,
7
+ cmsComments,
5
8
  cmsDdl,
6
9
  cmsDocuments,
7
10
  cmsHits,
8
11
  cmsMeta,
12
+ cmsPresence,
13
+ cmsReleases,
14
+ cmsSavedFilters,
9
15
  cmsTables,
10
16
  cmsVersions,
11
17
  defaultTables,
12
18
  schemaVersionSql,
13
19
  splitSql,
14
20
  upgradeSteps
15
- } from "./chunk-IW3D4I7Q.js";
21
+ } from "./chunk-IU2SMWAM.js";
16
22
  import {
17
23
  SCHEMA_VERSION
18
- } from "./chunk-OQ55GEF3.js";
24
+ } from "./chunk-3OPKTBEI.js";
19
25
  import "./chunk-2NTK7H4W.js";
20
26
  export {
21
27
  LEGACY_COLUMNS,
22
28
  SCHEMA_VERSION,
23
29
  cmsApiKeys,
30
+ cmsAssetRefs,
31
+ cmsAssets,
24
32
  cmsAudit,
33
+ cmsComments,
25
34
  cmsDdl,
26
35
  cmsDocuments,
27
36
  cmsHits,
28
37
  cmsMeta,
38
+ cmsPresence,
39
+ cmsReleases,
40
+ cmsSavedFilters,
29
41
  cmsTables,
30
42
  cmsVersions,
31
43
  defaultTables,
package/dist/tools.cjs CHANGED
@@ -22,39 +22,58 @@ var tools_exports = {};
22
22
  __export(tools_exports, {
23
23
  CMS_TOOLS: () => CMS_TOOLS,
24
24
  CMS_TOOL_NAMES: () => CMS_TOOL_NAMES,
25
+ callTool: () => callTool,
26
+ runTool: () => runTool,
27
+ toolErrorResult: () => toolErrorResult,
25
28
  toolsFor: () => toolsFor
26
29
  });
27
30
  module.exports = __toCommonJS(tools_exports);
28
31
  var import_zod = require("zod");
29
32
 
30
- // src/cms.ts
31
- var import_node_crypto = require("crypto");
32
-
33
- // src/errors.ts
34
- function isCmsError(e) {
35
- return !!e && typeof e === "object" && e.isCmsError === true;
36
- }
37
-
38
33
  // src/markdown.ts
39
34
  var APP_LINK_RE = /\[\[link:([a-z0-9][a-z0-9._-]*)\|([^\]]+)\]\]/gi;
40
35
  function anchorOf(text) {
41
36
  const base = text.trim().toLowerCase().replace(/[`*_[\]()<>!?.,:;'"“”‘’/\\|]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
42
37
  return base || "section";
43
38
  }
39
+ var ASSET_TARGET = /^asset:([a-z0-9]{12})(?:\/([^\s)]*))?$/;
40
+ var IMAGE = String.raw`!\[([^\]]*)\]\(\s*((?:[^()\s]|\([^()\s]*\))+)(?:\s+"([^"]*)")?\s*\)`;
41
+ var IMAGE_LINE = new RegExp(`^\\s*${IMAGE}\\s*$`);
42
+ var IMAGE_ANY = new RegExp(IMAGE, "g");
43
+ var safeDecode = (s) => {
44
+ try {
45
+ return decodeURIComponent(s);
46
+ } catch {
47
+ return s;
48
+ }
49
+ };
50
+ function mediaTarget(target) {
51
+ const a = ASSET_TARGET.exec(target);
52
+ if (a) return { asset: a[1], name: safeDecode(a[2] ?? ""), src: null };
53
+ if (/^https:\/\//i.test(target)) return { asset: null, name: "", src: target };
54
+ return null;
55
+ }
44
56
  function parseInline(src) {
45
57
  const out = [];
46
- const re = /(\[\[link:([a-z0-9][a-z0-9._-]*)\|([^\]]+)\]\]|\*\*([^*]+)\*\*|`([^`]+)`|\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\))/gi;
58
+ const re = new RegExp(String.raw`(\[\[link:(?<key>[a-z0-9][a-z0-9._-]*)\|(?<keyLabel>[^\]]+)\]\]|\*\*(?<strong>[^*]+)\*\*|` + "`(?<code>[^`]+)`" + String.raw`|!\[(?<alt>[^\]]*)\]\(\s*(?<img>(?:[^()\s]|\([^()\s]*\))+)(?:\s+"(?<cap>[^"]*)")?\s*\)|\[(?<label>[^\]]+)\]\((?<href>(?:[^()\s]|\([^()\s]*\))+)\))`, "gi");
47
59
  let last = 0;
48
60
  let m;
49
61
  while (m = re.exec(src)) {
62
+ const g = m.groups;
50
63
  if (m.index > last) out.push({ t: "text", v: src.slice(last, m.index) });
51
- if (m[2]) out.push({ t: "applink", key: m[2], v: m[3] });
52
- else if (m[4] !== void 0) out.push({ t: "strong", v: m[4] });
53
- else if (m[5] !== void 0) out.push({ t: "code", v: m[5] });
54
- else if (m[6] !== void 0) {
55
- const href = m[7];
56
- if (/^(https?:\/\/|mailto:|\/(?!\/)|#)/i.test(href)) out.push({ t: "link", href, v: m[6] });
57
- else out.push({ t: "text", v: m[6] });
64
+ if (g.key) out.push({ t: "applink", key: g.key, v: g.keyLabel });
65
+ else if (g.strong !== void 0) out.push({ t: "strong", v: g.strong });
66
+ else if (g.code !== void 0) out.push({ t: "code", v: g.code });
67
+ else if (g.img !== void 0) {
68
+ const target = mediaTarget(g.img);
69
+ if (target) out.push({ t: "image", ...target, alt: g.alt, v: g.alt });
70
+ else out.push({ t: "text", v: g.alt });
71
+ } else if (g.label !== void 0) {
72
+ const href = g.href;
73
+ const file = ASSET_TARGET.exec(href);
74
+ if (file) out.push({ t: "file", asset: file[1], name: safeDecode(file[2] ?? ""), v: g.label });
75
+ else if (/^(https?:\/\/|mailto:|\/(?!\/)|#)/i.test(href)) out.push({ t: "link", href, v: g.label });
76
+ else out.push({ t: "text", v: g.label });
58
77
  }
59
78
  last = m.index + m[0].length;
60
79
  }
@@ -97,10 +116,17 @@ function splitSections(body) {
97
116
  return out;
98
117
  }
99
118
 
119
+ // src/errors.ts
120
+ function isCmsError(e) {
121
+ return !!e && typeof e === "object" && e.isCmsError === true;
122
+ }
123
+
100
124
  // src/types.ts
101
125
  var DOC_STATUSES = ["draft", "published", "archived"];
126
+ var ASSET_KINDS = ["image", "video", "audio", "document", "other", "folder"];
102
127
 
103
128
  // src/cms.ts
129
+ var import_node_crypto = require("crypto");
104
130
  var PREVIEW_TTLS = { "1h": 36e5, "24h": 864e5, "7d": 7 * 864e5 };
105
131
  var BULK_ACTIONS = ["publish", "unpublish", "archive", "unarchive", "delete"];
106
132
  var coreOf = (c) => "core" in c && c.core ? c.core : c;
@@ -153,7 +179,7 @@ async function lookupForAgent(cms, actor, collections, query, o = {}) {
153
179
  for (const id of new Set(hits.map((h) => h.docId))) {
154
180
  const doc = await core.repo.findDocById(id);
155
181
  const v = doc?.publishedVersion ? await core.repo.getVersion(id, doc.publishedVersion) : null;
156
- trustOf.set(id, v && v.authorKind !== "user" ? "agent" : "human");
182
+ trustOf.set(id, v && (v.authorKind !== "user" || v.authorAgent) ? "agent" : "human");
157
183
  }
158
184
  const links = [];
159
185
  const seen = /* @__PURE__ */ new Set();
@@ -224,12 +250,17 @@ async function lookupForAgent(cms, actor, collections, query, o = {}) {
224
250
  };
225
251
  }
226
252
 
253
+ // src/client.ts
254
+ function isCmsRemoteError(e) {
255
+ return !!e && typeof e === "object" && e.isCmsRemoteError === true;
256
+ }
257
+
227
258
  // src/tools.ts
228
259
  var docInput = {
229
260
  slug: import_zod.z.string().optional().describe("URL slug, e.g. my-first-post (lowercase letters, digits, hyphens unless the collection allows more)"),
230
261
  title: import_zod.z.string().optional(),
231
262
  summary: import_zod.z.string().optional().describe("One-line summary shown in lists and search results"),
232
- body: import_zod.z.string().optional().describe("Markdown body. `## ` headings split it into sections for search and patch_document"),
263
+ body: import_zod.z.string().optional().describe('Markdown body. `## ` headings split it into sections for search and patch_document. A file from the media library: `![alt text](asset:ID/name.jpg "caption")` on its own line (image, video or download card), `[label](asset:ID/name.pdf)` for a link (ids from list_assets)'),
233
264
  category: import_zod.z.string().nullable().optional(),
234
265
  keywords: import_zod.z.array(import_zod.z.string()).optional().describe("Other words people search with, e.g. synonyms or English names"),
235
266
  fields: import_zod.z.record(import_zod.z.unknown()).optional().describe("Collection-specific fields (see list_collections). On update a JSON Merge Patch: null removes a key")
@@ -249,6 +280,28 @@ var summaryOf = (d) => ({
249
280
  updatedAt: d.updatedAt,
250
281
  updatedBy: d.updatedBy
251
282
  });
283
+ var assetId = import_zod.z.string().describe("File id (12 letters and digits, from list_assets)");
284
+ var store = import_zod.z.string().optional().describe("Store name (see list_assets). Default: the first store");
285
+ var fileKinds = ASSET_KINDS.filter((k) => k !== "folder");
286
+ var assetOut = (a) => ({
287
+ id: a.id,
288
+ name: a.name,
289
+ store: a.store,
290
+ folder: a.folder,
291
+ kind: a.kind,
292
+ mime: a.mime,
293
+ size: a.size,
294
+ width: a.width,
295
+ height: a.height,
296
+ duration: a.duration,
297
+ alt: a.alt,
298
+ tags: a.tags,
299
+ visibility: a.visibility,
300
+ url: a.publicUrl ?? a.href,
301
+ markdown: a.kind === "image" || a.kind === "video" || a.kind === "audio" ? `![${a.alt}](asset:${a.id}/${encodeURIComponent(a.name)})` : `[${a.name}](asset:${a.id}/${encodeURIComponent(a.name)})`,
302
+ createdBy: a.createdBy,
303
+ createdAt: a.createdAt
304
+ });
252
305
  var patchOp = import_zod.z.discriminatedUnion("op", [
253
306
  import_zod.z.object({ op: import_zod.z.literal("replace"), anchor: import_zod.z.string(), markdown: import_zod.z.string(), heading: import_zod.z.string().optional() }),
254
307
  import_zod.z.object({ op: import_zod.z.literal("insert_after"), anchor: import_zod.z.string(), markdown: import_zod.z.string() }),
@@ -368,7 +421,7 @@ var CMS_TOOLS = [
368
421
  {
369
422
  name: "delete_document",
370
423
  needs: "publish",
371
- description: "Delete a document and its history permanently. Prefer archive_document unless asked to delete.",
424
+ description: "Delete a document. It goes to the trash, where it can be restored (restore_from_trash) until the trash is emptied; in an app without a trash it is gone for good. Prefer archive_document unless asked to delete.",
372
425
  input: import_zod.z.object({ collection: col, slug, expectedVersion }),
373
426
  run: async (cms, actor, a) => {
374
427
  await cms.remove(actor, a.collection, a.slug, { expectedVersion: a.expectedVersion });
@@ -392,7 +445,11 @@ var CMS_TOOLS = [
392
445
  title: v.title,
393
446
  author: v.authorLabel,
394
447
  authorKind: v.authorKind,
448
+ agent: v.authorAgent ?? null,
395
449
  note: v.note,
450
+ label: v.label,
451
+ pinned: v.pinned,
452
+ approvedBy: v.approvedBy,
396
453
  published: v.published,
397
454
  changed: v.changed?.fields ?? [],
398
455
  createdAt: v.createdAt
@@ -404,17 +461,271 @@ var CMS_TOOLS = [
404
461
  description: "Make an old version the latest again (saved as a new version).",
405
462
  input: import_zod.z.object({ collection: col, slug, version: import_zod.z.number().int().positive(), publish: import_zod.z.boolean().optional(), expectedVersion }),
406
463
  run: async (cms, actor, a) => cms.restore(actor, a.collection, a.slug, a.version, { publish: a.publish, expectedVersion: a.expectedVersion })
464
+ },
465
+ {
466
+ name: "label_version",
467
+ needs: "write",
468
+ description: 'Name a version ("launch copy") and/or pin it so it is never pruned.',
469
+ input: import_zod.z.object({ collection: col, slug, version: import_zod.z.number().int().positive(), label: import_zod.z.string().nullable().optional().describe('null or "" removes the name'), pinned: import_zod.z.boolean().optional() }),
470
+ run: async (cms, actor, a) => {
471
+ const v = await cms.labelVersion(actor, a.collection, a.slug, a.version, { label: a.label, pinned: a.pinned });
472
+ return { version: v.version, label: v.label, pinned: v.pinned };
473
+ }
474
+ },
475
+ {
476
+ name: "preview_document",
477
+ needs: "write",
478
+ description: "See what a document would be without saving it: every problem (like diagnose_document), the table of contents, the unified diff against the saved body and the public address. Pass slug to preview an edit of an existing document.",
479
+ input: import_zod.z.object({ collection: col, slug: import_zod.z.string().optional().describe("The existing document this is an edit of"), doc: import_zod.z.object(docInput) }),
480
+ run: async (cms, actor, a) => {
481
+ const p = await cms.preview(actor, a.collection, a.doc, { slug: a.slug });
482
+ return { diagnostics: p.diagnostics, toc: p.toc, diff: p.diff, publicUrl: p.publicUrl, blocks: p.blocks.length };
483
+ }
484
+ },
485
+ {
486
+ name: "schedule_document",
487
+ needs: "publish",
488
+ description: "Publish and/or unpublish a document at a time (ISO 8601 with a time zone). The version that is current now is what goes public, even if the draft changes later. Runs when the app's cron calls the CMS, so it can be a few minutes late.",
489
+ input: import_zod.z.object({ collection: col, slug, publishAt: import_zod.z.string().nullable().optional(), unpublishAt: import_zod.z.string().nullable().optional(), expectedVersion }),
490
+ run: async (cms, actor, a) => {
491
+ const d = await cms.schedule(actor, a.collection, a.slug, { publishAt: a.publishAt, unpublishAt: a.unpublishAt, expectedVersion: a.expectedVersion });
492
+ return { slug: d.slug, schedule: d.schedule };
493
+ }
494
+ },
495
+ {
496
+ name: "unschedule_document",
497
+ needs: "publish",
498
+ description: "Cancel a document's schedule.",
499
+ input: import_zod.z.object({ collection: col, slug }),
500
+ run: async (cms, actor, a) => {
501
+ await cms.unschedule(actor, a.collection, a.slug);
502
+ return { unscheduled: true };
503
+ }
504
+ },
505
+ {
506
+ name: "request_review",
507
+ needs: "write",
508
+ description: "Ask a person to review the current version. Use this where publishing answers review_required; say in the note what changed and what to look at. A person approves (which publishes) or sends it back with a note.",
509
+ input: import_zod.z.object({ collection: col, slug, note: import_zod.z.string().max(2e3).optional() }),
510
+ run: async (cms, actor, a) => {
511
+ const d = await cms.requestReview(actor, a.collection, a.slug, { note: a.note });
512
+ return { slug: d.slug, review: d.review };
513
+ }
514
+ },
515
+ {
516
+ name: "list_review_requests",
517
+ needs: "write",
518
+ description: "Documents waiting for a review, and their notes. A document whose review says changes_requested was sent back: read its note (get_document draft=true), fix it and request a review again.",
519
+ input: import_zod.z.object({ collection: import_zod.z.string().optional() }),
520
+ run: async (cms, actor, a) => (await cms.reviewRequests(actor, { collection: a.collection })).map((d) => ({ collection: d.collection, slug: d.slug, title: d.title, version: d.version, review: d.review, updatedAt: d.updatedAt }))
521
+ },
522
+ {
523
+ name: "list_comments",
524
+ needs: "write",
525
+ description: "Comments people (and agents) left on a document, as threads. Each says which section (anchor) and quoted text it is about, whether that text is still there, and whether it is resolved.",
526
+ input: import_zod.z.object({ collection: col, slug, open: import_zod.z.boolean().optional().describe("true: only unresolved threads") }),
527
+ run: async (cms, actor, a) => (await cms.comments(actor, a.collection, a.slug)).filter((t) => !a.open || !t.resolvedAt).map((t) => ({ id: t.id, anchor: t.anchor, quote: t.quote, located: t.located, line: t.line, body: t.body, author: t.authorAgent ?? t.authorLabel, authorKind: t.authorKind, at: t.createdAt, resolved: !!t.resolvedAt, replies: t.replies.map((r) => ({ id: r.id, body: r.body, author: r.authorAgent ?? r.authorLabel, authorKind: r.authorKind, at: r.createdAt })) }))
528
+ },
529
+ {
530
+ name: "add_comment",
531
+ needs: "write",
532
+ description: "Comment on a document, or answer a thread (threadId). A new thread sits on a section (anchor, from get_document draft=true sections) and optionally on a quoted piece of its text.",
533
+ input: import_zod.z.object({ collection: col, slug, body: import_zod.z.string().min(1).max(4e3), anchor: import_zod.z.string().optional().describe('Section anchor; "" or omitted: the top of the document'), quote: import_zod.z.string().max(500).optional().describe("The exact text the comment is about"), threadId: import_zod.z.string().optional().describe("Answer this thread instead of starting one") }),
534
+ run: async (cms, actor, a) => {
535
+ const c = await cms.addComment(actor, a.collection, a.slug, { body: a.body, anchor: a.anchor, quote: a.quote, threadId: a.threadId });
536
+ return { id: c.id, threadId: c.threadId };
537
+ }
538
+ },
539
+ {
540
+ name: "resolve_comment",
541
+ needs: "write",
542
+ description: "Mark a comment thread resolved after you dealt with it (answer first with add_comment so people see what you did). resolved=false opens it again.",
543
+ input: import_zod.z.object({ collection: col, slug, id: import_zod.z.string(), resolved: import_zod.z.boolean().optional() }),
544
+ run: async (cms, actor, a) => {
545
+ const c = await cms.resolveComment(actor, a.collection, a.slug, a.id, { resolved: a.resolved });
546
+ return { id: c.id, resolved: !!c.resolvedAt };
547
+ }
548
+ },
549
+ {
550
+ name: "list_trash",
551
+ needs: "write",
552
+ description: "Deleted documents and files that can still be restored, with when each is deleted for good.",
553
+ input: import_zod.z.object({ kind: import_zod.z.enum(["document", "asset"]).optional() }),
554
+ run: async (cms, actor, a) => {
555
+ const t = await cms.trash.list(actor, { kind: a.kind });
556
+ return { days: t.days, items: t.items.map((i) => ({ kind: i.kind, id: i.id, title: i.title, collection: i.collection, slug: i.slug, was: i.state, deletedAt: i.deletedAt, deletedBy: i.deletedBy, purgeAt: i.purgeAt })) };
557
+ }
558
+ },
559
+ {
560
+ name: "restore_from_trash",
561
+ needs: "publish",
562
+ description: "Take documents or files out of the trash (ids from list_trash). A document that was published is public again at once.",
563
+ input: import_zod.z.object({ items: import_zod.z.array(import_zod.z.object({ kind: import_zod.z.enum(["document", "asset"]), id: import_zod.z.string() })).min(1).max(50) }),
564
+ run: async (cms, actor, a) => cms.trash.restore(actor, a.items)
565
+ },
566
+ {
567
+ name: "list_releases",
568
+ needs: "write",
569
+ description: "Releases: sets of documents that are published (or unpublished) together. Pass id for one release with each document's pinned and latest version.",
570
+ input: import_zod.z.object({ id: import_zod.z.string().optional() }),
571
+ run: async (cms, actor, a) => {
572
+ if (a.id) return cms.releases.get(actor, a.id);
573
+ return (await cms.releases.list(actor)).map((r) => ({ id: r.id, name: r.name, state: r.state, publishAt: r.publishAt, documents: r.items.length, publishedAt: r.publishedAt, lastError: r.lastError }));
574
+ }
575
+ },
576
+ {
577
+ name: "create_release",
578
+ needs: "write",
579
+ description: "Start a release. Add documents with add_to_release.",
580
+ input: import_zod.z.object({ name: import_zod.z.string().min(1).max(80) }),
581
+ run: async (cms, actor, a) => {
582
+ const r = await cms.releases.create(actor, { name: a.name });
583
+ return { id: r.id, name: r.name };
584
+ }
585
+ },
586
+ {
587
+ name: "add_to_release",
588
+ needs: "write",
589
+ description: "Put documents in a release. Each is pinned at its latest version now; add it again after more edits to move the pin. action unpublish takes the document down when the release goes out. A document can be in one open release only.",
590
+ input: import_zod.z.object({ id: import_zod.z.string().describe("Release id (list_releases)"), items: import_zod.z.array(import_zod.z.object({ collection: col, slug, action: import_zod.z.enum(["publish", "unpublish"]).optional() })).min(1).max(50) }),
591
+ run: async (cms, actor, a) => {
592
+ const r = await cms.releases.add(actor, a.id, a.items);
593
+ return { id: r.id, name: r.name, items: r.items.map((i) => ({ collection: i.collection, slug: i.slug, action: i.action, version: i.version })) };
594
+ }
595
+ },
596
+ {
597
+ name: "publish_release",
598
+ needs: "publish",
599
+ description: "Publish everything in a release at once. All or nothing: if any document is blocked (a failed check, no permission, a missing review) nothing is published and the error lists what blocked.",
600
+ input: import_zod.z.object({ id: import_zod.z.string() }),
601
+ run: async (cms, actor, a) => {
602
+ const r = await cms.releases.publish(actor, a.id);
603
+ return { id: r.id, name: r.name, state: r.state, documents: r.items.length };
604
+ }
605
+ },
606
+ {
607
+ name: "list_assets",
608
+ media: "read",
609
+ description: "List files in the media library (images, video, documents), newest first, with the stores and their folders. Each file has the markdown that puts it in a document body.",
610
+ input: import_zod.z.object({ store, folder: import_zod.z.string().optional().describe("This folder and everything under it"), kind: import_zod.z.enum(fileKinds).optional(), q: import_zod.z.string().optional().describe("Part of the file name or a tag"), tag: import_zod.z.string().optional(), cursor: import_zod.z.string().optional(), limit: import_zod.z.number().int().min(1).max(100).optional() }),
611
+ run: async (cms, actor, a) => {
612
+ const r = await cms.assets.list(actor, { store: a.store, folder: a.folder, kinds: a.kind ? [a.kind] : void 0, q: a.q, tag: a.tag, cursor: a.cursor, limit: a.limit ?? 30 });
613
+ return { assets: r.assets.map(assetOut), cursor: r.cursor, counts: r.counts, stores: (await cms.assets.folders(actor)).map((s) => ({ store: s.store, visibility: s.visibility, files: s.total, folders: s.folders.map((f) => f.path) })) };
614
+ }
615
+ },
616
+ {
617
+ name: "get_asset",
618
+ media: "read",
619
+ description: "One file of the media library: size, alt text, tags, and the documents that use it.",
620
+ input: import_zod.z.object({ id: assetId }),
621
+ run: async (cms, actor, a) => {
622
+ const r = await cms.assets.get(actor, a.id);
623
+ return { ...assetOut(r), usedBy: r.usage.map((u) => ({ collection: u.collection, slug: u.slug, title: u.title, status: u.status, inPublished: u.inPublished })), usedByHidden: r.usageHidden };
624
+ }
625
+ },
626
+ {
627
+ name: "import_asset",
628
+ media: "write",
629
+ description: "Fetch a file from a public https address and store it in the media library. Give images an alt text. Returns the markdown to put it in a document.",
630
+ input: import_zod.z.object({ url: import_zod.z.string().describe("https address of the file"), name: import_zod.z.string().optional().describe("File name with extension. Default: taken from the address"), folder: import_zod.z.string().optional().describe("e.g. blog/2026"), store, alt: import_zod.z.string().optional().describe("What the image shows, for people who cannot see it"), tags: import_zod.z.array(import_zod.z.string()).optional() }),
631
+ run: async (cms, actor, a) => assetOut(await cms.assets.import(actor, a))
632
+ },
633
+ {
634
+ name: "update_asset",
635
+ media: "write",
636
+ description: "Change a file's alt text or tags. Documents that use the file without their own alt text show the new one.",
637
+ input: import_zod.z.object({ id: assetId, alt: import_zod.z.string().optional(), tags: import_zod.z.array(import_zod.z.string()).optional() }),
638
+ run: async (cms, actor, a) => assetOut(await cms.assets.update(actor, a.id, { alt: a.alt, tags: a.tags }))
639
+ },
640
+ {
641
+ name: "move_asset",
642
+ media: "delete",
643
+ description: "Move a file to another folder and/or rename it. Documents keep working: they point at the id, not the path.",
644
+ input: import_zod.z.object({ id: assetId, folder: import_zod.z.string().optional().describe('Target folder ("" = top level)'), name: import_zod.z.string().optional().describe("New file name; the extension is kept") }),
645
+ run: async (cms, actor, a) => assetOut(await cms.assets.move(actor, a.id, { folder: a.folder, name: a.name }))
646
+ },
647
+ {
648
+ name: "delete_asset",
649
+ media: "delete",
650
+ description: "Delete a file permanently. When documents use it, this fails with asset_in_use and lists them: tell the person, and only pass confirm=true when they said to delete it anyway.",
651
+ input: import_zod.z.object({ id: assetId, confirm: import_zod.z.boolean().optional() }),
652
+ run: async (cms, actor, a) => {
653
+ await cms.assets.remove(actor, a.id, { confirm: !!a.confirm });
654
+ return { deleted: true };
655
+ }
656
+ },
657
+ {
658
+ name: "list_store_files",
659
+ media: "read",
660
+ description: "Look into a storage bucket folder by folder: also files nobody uploaded through the CMS. Each file says whether the CMS knows it (`id`). To use an unknown file in a document, call register_asset with its key first.",
661
+ input: import_zod.z.object({ store, prefix: import_zod.z.string().optional().describe('Folder to list, e.g. "contracts/2026". Default: the top'), q: import_zod.z.string().optional().describe("Only names in this folder that start with this"), cursor: import_zod.z.string().optional(), limit: import_zod.z.number().int().min(1).max(500).optional() }),
662
+ run: async (cms, actor, a) => {
663
+ const r = await cms.assets.browse(actor, { store: a.store, prefix: a.prefix, q: a.q, cursor: a.cursor, limit: a.limit ?? 100 });
664
+ return { store: r.store, prefix: r.prefix, folders: r.folders.map((f) => f.path), files: r.files.map((f) => ({ key: f.key, size: f.size, kind: f.kind, updatedAt: f.updatedAt, id: f.asset?.id ?? null })), cursor: r.cursor };
665
+ }
666
+ },
667
+ {
668
+ name: "register_asset",
669
+ media: "write",
670
+ description: "Make a file that is already in the bucket (see list_store_files) known to the CMS, so it can be described and used in documents. Returns the markdown to put it in a document.",
671
+ input: import_zod.z.object({ key: import_zod.z.string().describe("The file's key in the bucket, e.g. contracts/2026/msa.pdf"), store, alt: import_zod.z.string().optional(), tags: import_zod.z.array(import_zod.z.string()).optional() }),
672
+ run: async (cms, actor, a) => assetOut(await cms.assets.register(actor, a))
673
+ },
674
+ {
675
+ name: "create_share_link",
676
+ media: "delete",
677
+ description: "Make an address for a file that someone outside can open. For a private file it works for the chosen time and cannot be taken back; only do this when the person asked for it.",
678
+ input: import_zod.z.object({ id: assetId, ttl: import_zod.z.enum(["1h", "24h", "7d"]).optional().describe("How long a private file's link works. Default 24h") }),
679
+ run: async (cms, actor, a) => cms.assets.share(actor, a.id, { ttl: a.ttl })
407
680
  }
408
681
  ];
409
682
  var CMS_TOOL_NAMES = CMS_TOOLS.map((t) => t.name);
410
683
  function toolsFor(cms, actor, only) {
411
684
  const core = coreOf(cms);
412
685
  const cols = core.collections().map((c) => c.slug);
413
- return CMS_TOOLS.filter((t) => (!only || only.includes(t.name)) && (!t.needs || cols.some((c) => core.can(actor, c, t.needs))));
686
+ const stores = core.assets.enabled ? core.assets.stores().map((s) => s.name) : [];
687
+ return CMS_TOOLS.filter((t) => (!only || only.includes(t.name)) && (!t.needs || cols.some((c) => core.can(actor, c, t.needs))) && (!t.media || stores.some((s) => core.assets.can(actor, s, t.media))));
688
+ }
689
+ function toolErrorResult(err) {
690
+ if (isCmsError(err)) return err.toJSON();
691
+ if (isCmsRemoteError(err)) {
692
+ return {
693
+ error: err.code,
694
+ kind: err.kind ?? "internal",
695
+ message: err.message,
696
+ params: err.params ?? {},
697
+ ...err.diagnostics ? { diagnostics: err.diagnostics } : {},
698
+ ...err.current !== void 0 ? { current: err.current } : {}
699
+ };
700
+ }
701
+ return null;
702
+ }
703
+ async function runTool(cms, actor, name, args = {}, opts = {}) {
704
+ const core = coreOf(cms);
705
+ const def = toolsFor(core, actor, opts.only).find((t) => t.name === name);
706
+ if (!def) return { ok: false, error: { error: "unknown_tool", kind: "not_found", message: `Unknown tool: ${name}`, params: { name } } };
707
+ const parsed = def.input.safeParse(args ?? {});
708
+ if (!parsed.success) {
709
+ const issues = parsed.error.issues.map((i) => `${i.path.join(".")} ${i.message}`).join("; ");
710
+ return { ok: false, error: { error: "invalid_request", kind: "invalid", message: core.message({ isCmsError: true, code: "invalid_request", params: { issues } }), params: { issues } } };
711
+ }
712
+ try {
713
+ return { ok: true, value: await def.run(core, actor, parsed.data) };
714
+ } catch (err) {
715
+ if (!isCmsError(err)) throw err;
716
+ return { ok: false, error: { ...err.toJSON(), message: core.message(err) } };
717
+ }
718
+ }
719
+ async function callTool(cms, actor, name, args = {}, opts = {}) {
720
+ const r = await runTool(cms, { ...actor, via: actor.via ?? "ai" }, name, args, opts);
721
+ return r.ok ? r.value : r.error;
414
722
  }
415
723
  // Annotate the CommonJS export names for ESM import in node:
416
724
  0 && (module.exports = {
417
725
  CMS_TOOLS,
418
726
  CMS_TOOL_NAMES,
727
+ callTool,
728
+ runTool,
729
+ toolErrorResult,
419
730
  toolsFor
420
731
  });
package/dist/tools.d.cts CHANGED
@@ -1,14 +1,16 @@
1
1
  import { z } from 'zod';
2
- import { f as CmsCore, C as CmsLike } from './cms-D6D89-qZ.cjs';
2
+ import { n as CmsCore, C as CmsLike } from './cms-C_vkAxYV.cjs';
3
3
  import { Actor } from './types.cjs';
4
+ import { Diagnostic } from './errors.cjs';
5
+ import './storage.cjs';
6
+ import './markdown.cjs';
4
7
  import './diff.cjs';
5
- import './errors.cjs';
6
- import './repo-CeDxUxO6.cjs';
7
8
 
8
9
  /**
9
- * The one list of operations an agent can perform. MCP (`mcp.ts`), the AI SDK
10
- * tools (`ai.ts`) and the CLI all expose exactly this list, so an agent sees
11
- * the same tools whichever way it connects.
10
+ * The one list of operations an agent can perform. MCP (`mcp.ts`) and the CLI
11
+ * expose exactly this list, and `toolsFor` + `callTool` hand it to an agent
12
+ * running in the app, so an agent sees the same tools whichever way it
13
+ * connects. This package never calls a model itself.
12
14
  */
13
15
 
14
16
  interface CmsToolDef {
@@ -18,10 +20,55 @@ interface CmsToolDef {
18
20
  run: (cms: CmsCore, actor: Actor, args: Record<string, unknown>) => Promise<unknown>;
19
21
  /** Hidden when the actor could never call it. */
20
22
  needs?: "write" | "publish";
23
+ /** A media library tool: hidden when there is no library or the actor may not do this in any store. */
24
+ media?: "read" | "write" | "delete";
21
25
  }
22
26
  declare const CMS_TOOLS: CmsToolDef[];
23
27
  declare const CMS_TOOL_NAMES: string[];
24
28
  /** The tools this actor can use (read-only tools for readers, and so on). */
25
29
  declare function toolsFor(cms: CmsLike, actor: Actor, only?: readonly string[]): CmsToolDef[];
30
+ /** What a failed tool call returns: the same shape as a REST error body. */
31
+ interface ToolErrorResult {
32
+ error: string;
33
+ kind: string;
34
+ message: string;
35
+ params: Record<string, unknown>;
36
+ diagnostics?: Diagnostic[];
37
+ current?: unknown;
38
+ }
39
+ type ToolOutcome = {
40
+ ok: true;
41
+ value: unknown;
42
+ } | {
43
+ ok: false;
44
+ error: ToolErrorResult;
45
+ };
46
+ interface CallToolOptions {
47
+ /** Only these tools may be called (by name). Default: every tool the actor may use. */
48
+ only?: readonly string[];
49
+ }
50
+ /**
51
+ * A CMS error (thrown in this process, or by `createCmsClient().call`) as a
52
+ * tool result an agent can read. `null` for anything else: rethrow those.
53
+ */
54
+ declare function toolErrorResult(err: unknown): ToolErrorResult | null;
55
+ /**
56
+ * Run one tool by name as `actor`: looks it up in the tools the actor may
57
+ * use, checks the input, runs it. CMS errors (a conflict, a missing
58
+ * document, no permission, bad input) come back as `{ ok: false, error }`
59
+ * with the message in the CMS's language; anything else throws.
60
+ */
61
+ declare function runTool(cms: CmsLike, actor: Actor, name: string, args?: unknown, opts?: CallToolOptions): Promise<ToolOutcome>;
62
+ /**
63
+ * The way to hand the CMS to your own agent, whatever framework runs it:
64
+ * list the tools with `toolsFor(cms, actor)` (name, description, zod input)
65
+ * and run each call the model makes with `callTool`. A CMS error is returned
66
+ * as `{ error, kind, message, params, … }` rather than thrown, so the model
67
+ * can read a conflict and retry instead of failing the whole run.
68
+ *
69
+ * Calls made this way are recorded with `via: "ai"` unless the actor says
70
+ * otherwise.
71
+ */
72
+ declare function callTool(cms: CmsLike, actor: Actor, name: string, args?: unknown, opts?: CallToolOptions): Promise<unknown>;
26
73
 
27
- export { CMS_TOOLS, CMS_TOOL_NAMES, type CmsToolDef, toolsFor };
74
+ export { CMS_TOOLS, CMS_TOOL_NAMES, type CallToolOptions, type CmsToolDef, type ToolErrorResult, type ToolOutcome, callTool, runTool, toolErrorResult, toolsFor };
package/dist/tools.d.ts CHANGED
@@ -1,14 +1,16 @@
1
1
  import { z } from 'zod';
2
- import { f as CmsCore, C as CmsLike } from './cms-BPp01z-8.js';
2
+ import { n as CmsCore, C as CmsLike } from './cms-pqJyowu1.js';
3
3
  import { Actor } from './types.js';
4
+ import { Diagnostic } from './errors.js';
5
+ import './storage.js';
6
+ import './markdown.js';
4
7
  import './diff.js';
5
- import './errors.js';
6
- import './repo-BWI2Pkrv.js';
7
8
 
8
9
  /**
9
- * The one list of operations an agent can perform. MCP (`mcp.ts`), the AI SDK
10
- * tools (`ai.ts`) and the CLI all expose exactly this list, so an agent sees
11
- * the same tools whichever way it connects.
10
+ * The one list of operations an agent can perform. MCP (`mcp.ts`) and the CLI
11
+ * expose exactly this list, and `toolsFor` + `callTool` hand it to an agent
12
+ * running in the app, so an agent sees the same tools whichever way it
13
+ * connects. This package never calls a model itself.
12
14
  */
13
15
 
14
16
  interface CmsToolDef {
@@ -18,10 +20,55 @@ interface CmsToolDef {
18
20
  run: (cms: CmsCore, actor: Actor, args: Record<string, unknown>) => Promise<unknown>;
19
21
  /** Hidden when the actor could never call it. */
20
22
  needs?: "write" | "publish";
23
+ /** A media library tool: hidden when there is no library or the actor may not do this in any store. */
24
+ media?: "read" | "write" | "delete";
21
25
  }
22
26
  declare const CMS_TOOLS: CmsToolDef[];
23
27
  declare const CMS_TOOL_NAMES: string[];
24
28
  /** The tools this actor can use (read-only tools for readers, and so on). */
25
29
  declare function toolsFor(cms: CmsLike, actor: Actor, only?: readonly string[]): CmsToolDef[];
30
+ /** What a failed tool call returns: the same shape as a REST error body. */
31
+ interface ToolErrorResult {
32
+ error: string;
33
+ kind: string;
34
+ message: string;
35
+ params: Record<string, unknown>;
36
+ diagnostics?: Diagnostic[];
37
+ current?: unknown;
38
+ }
39
+ type ToolOutcome = {
40
+ ok: true;
41
+ value: unknown;
42
+ } | {
43
+ ok: false;
44
+ error: ToolErrorResult;
45
+ };
46
+ interface CallToolOptions {
47
+ /** Only these tools may be called (by name). Default: every tool the actor may use. */
48
+ only?: readonly string[];
49
+ }
50
+ /**
51
+ * A CMS error (thrown in this process, or by `createCmsClient().call`) as a
52
+ * tool result an agent can read. `null` for anything else: rethrow those.
53
+ */
54
+ declare function toolErrorResult(err: unknown): ToolErrorResult | null;
55
+ /**
56
+ * Run one tool by name as `actor`: looks it up in the tools the actor may
57
+ * use, checks the input, runs it. CMS errors (a conflict, a missing
58
+ * document, no permission, bad input) come back as `{ ok: false, error }`
59
+ * with the message in the CMS's language; anything else throws.
60
+ */
61
+ declare function runTool(cms: CmsLike, actor: Actor, name: string, args?: unknown, opts?: CallToolOptions): Promise<ToolOutcome>;
62
+ /**
63
+ * The way to hand the CMS to your own agent, whatever framework runs it:
64
+ * list the tools with `toolsFor(cms, actor)` (name, description, zod input)
65
+ * and run each call the model makes with `callTool`. A CMS error is returned
66
+ * as `{ error, kind, message, params, … }` rather than thrown, so the model
67
+ * can read a conflict and retry instead of failing the whole run.
68
+ *
69
+ * Calls made this way are recorded with `via: "ai"` unless the actor says
70
+ * otherwise.
71
+ */
72
+ declare function callTool(cms: CmsLike, actor: Actor, name: string, args?: unknown, opts?: CallToolOptions): Promise<unknown>;
26
73
 
27
- export { CMS_TOOLS, CMS_TOOL_NAMES, type CmsToolDef, toolsFor };
74
+ export { CMS_TOOLS, CMS_TOOL_NAMES, type CallToolOptions, type CmsToolDef, type ToolErrorResult, type ToolOutcome, callTool, runTool, toolErrorResult, toolsFor };