aicms 0.0.0-stage → 0.5.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.
Files changed (117) hide show
  1. package/ARCHITECTURE.md +467 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -2
  4. package/README.uk.md +201 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +722 -0
  7. package/dist/config-edit.d.ts +18 -0
  8. package/dist/config-edit.js +201 -0
  9. package/dist/config.d.ts +55 -0
  10. package/dist/config.js +32 -0
  11. package/dist/edge.d.ts +22 -0
  12. package/dist/edge.js +56 -0
  13. package/dist/gates/a2a.d.ts +45 -0
  14. package/dist/gates/a2a.js +126 -0
  15. package/dist/gates/discovery.d.ts +36 -0
  16. package/dist/gates/discovery.js +54 -0
  17. package/dist/gates/events.d.ts +14 -0
  18. package/dist/gates/events.js +86 -0
  19. package/dist/gates/graphql.d.ts +41 -0
  20. package/dist/gates/graphql.js +226 -0
  21. package/dist/gates/mcp.d.ts +8 -0
  22. package/dist/gates/mcp.js +60 -0
  23. package/dist/gates/openapi.d.ts +56 -0
  24. package/dist/gates/openapi.js +61 -0
  25. package/dist/gates/rest.d.ts +21 -0
  26. package/dist/gates/rest.js +263 -0
  27. package/dist/gates/studio.d.ts +21 -0
  28. package/dist/gates/studio.js +107 -0
  29. package/dist/index.d.ts +18 -0
  30. package/dist/index.js +19 -0
  31. package/dist/kernel/action.d.ts +49 -0
  32. package/dist/kernel/action.js +22 -0
  33. package/dist/kernel/briefs.d.ts +161 -0
  34. package/dist/kernel/briefs.js +197 -0
  35. package/dist/kernel/changesets.d.ts +367 -0
  36. package/dist/kernel/changesets.js +765 -0
  37. package/dist/kernel/cms.d.ts +127 -0
  38. package/dist/kernel/cms.js +419 -0
  39. package/dist/kernel/core-actions.d.ts +5 -0
  40. package/dist/kernel/core-actions.js +487 -0
  41. package/dist/kernel/errors.d.ts +14 -0
  42. package/dist/kernel/errors.js +25 -0
  43. package/dist/kernel/install.d.ts +32 -0
  44. package/dist/kernel/install.js +34 -0
  45. package/dist/kernel/model-actions.d.ts +5 -0
  46. package/dist/kernel/model-actions.js +126 -0
  47. package/dist/kernel/modules.d.ts +221 -0
  48. package/dist/kernel/modules.js +207 -0
  49. package/dist/kernel/policy.d.ts +42 -0
  50. package/dist/kernel/policy.js +47 -0
  51. package/dist/load.d.ts +10 -0
  52. package/dist/load.js +63 -0
  53. package/dist/modules/catalog.d.ts +15 -0
  54. package/dist/modules/catalog.js +21 -0
  55. package/dist/modules/commerce.d.ts +67 -0
  56. package/dist/modules/commerce.js +260 -0
  57. package/dist/modules/git-sync.d.ts +20 -0
  58. package/dist/modules/git-sync.js +187 -0
  59. package/dist/modules/i18n.d.ts +6 -0
  60. package/dist/modules/i18n.js +168 -0
  61. package/dist/modules/index.d.ts +9 -0
  62. package/dist/modules/index.js +10 -0
  63. package/dist/modules/lint.d.ts +22 -0
  64. package/dist/modules/lint.js +126 -0
  65. package/dist/modules/media.d.ts +52 -0
  66. package/dist/modules/media.js +319 -0
  67. package/dist/modules/payments.d.ts +19 -0
  68. package/dist/modules/payments.js +110 -0
  69. package/dist/modules/search.d.ts +27 -0
  70. package/dist/modules/search.js +81 -0
  71. package/dist/modules/seo.d.ts +34 -0
  72. package/dist/modules/seo.js +189 -0
  73. package/dist/modules/text.d.ts +10 -0
  74. package/dist/modules/text.js +42 -0
  75. package/dist/node.d.ts +7 -0
  76. package/dist/node.js +11 -0
  77. package/dist/registry.d.ts +57 -0
  78. package/dist/registry.js +110 -0
  79. package/dist/schema/fields.d.ts +100 -0
  80. package/dist/schema/fields.js +134 -0
  81. package/dist/schema/markdown.d.ts +7 -0
  82. package/dist/schema/markdown.js +168 -0
  83. package/dist/schema/model.d.ts +44 -0
  84. package/dist/schema/model.js +104 -0
  85. package/dist/schema/slug.d.ts +2 -0
  86. package/dist/schema/slug.js +40 -0
  87. package/dist/store/d1.d.ts +30 -0
  88. package/dist/store/d1.js +27 -0
  89. package/dist/store/postgres.d.ts +164 -0
  90. package/dist/store/postgres.js +552 -0
  91. package/dist/store/sql.d.ts +135 -0
  92. package/dist/store/sql.js +530 -0
  93. package/dist/store/sqlite.d.ts +14 -0
  94. package/dist/store/sqlite.js +60 -0
  95. package/dist/store/types.d.ts +226 -0
  96. package/dist/store/types.js +21 -0
  97. package/dist/studio/assets/geologica-cyrillic-ext-wght-normal-C8B9Chlh.woff2 +0 -0
  98. package/dist/studio/assets/geologica-cyrillic-wght-normal-DbeVG3Ps.woff2 +0 -0
  99. package/dist/studio/assets/geologica-greek-wght-normal-DPM5d9ub.woff2 +0 -0
  100. package/dist/studio/assets/geologica-latin-ext-wght-normal-DZyYlgcm.woff2 +0 -0
  101. package/dist/studio/assets/geologica-latin-wght-normal-BBL8hQxZ.woff2 +0 -0
  102. package/dist/studio/assets/geologica-vietnamese-wght-normal-DcI17N1q.woff2 +0 -0
  103. package/dist/studio/assets/index-3dJ0YHxb.js +22 -0
  104. package/dist/studio/assets/index-DuyGLFw4.css +1 -0
  105. package/dist/studio/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  106. package/dist/studio/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  107. package/dist/studio/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  108. package/dist/studio/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  109. package/dist/studio/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  110. package/dist/studio/assets/unbounded-cyrillic-wght-normal-C627f1f8.woff2 +0 -0
  111. package/dist/studio/assets/unbounded-latin-ext-wght-normal-D6H-S6MW.woff2 +0 -0
  112. package/dist/studio/assets/unbounded-latin-wght-normal-D5afBTBx.woff2 +0 -0
  113. package/dist/studio/assets/unbounded-vietnamese-wght-normal-rat7GD3o.woff2 +0 -0
  114. package/dist/studio/index.html +21 -0
  115. package/dist/typegen.d.ts +7 -0
  116. package/dist/typegen.js +55 -0
  117. package/package.json +88 -4
@@ -0,0 +1,18 @@
1
+ /** Entries of the modules array as source text, e.g. ["seo()", "editorial"]. */
2
+ export declare function listModuleCalls(src: string): string[];
3
+ export interface ModuleRef {
4
+ /** Identifier used in the config, e.g. "seo". */
5
+ name: string;
6
+ /** Import source, e.g. "aicms/modules" or "./modules/blog/module.ts". */
7
+ from: string;
8
+ /** Default import (local and npm modules) or named (official modules). */
9
+ isDefault: boolean;
10
+ /** What goes into the array, e.g. "seo()" or "blog". */
11
+ call: string;
12
+ }
13
+ /** Add a module to aicms.config: the import and an entry in `modules`. Returns the new source. */
14
+ export declare function addModuleSource(src: string, ref: ModuleRef): string;
15
+ /** Remove a module (by identifier) from `modules` and drop its import if nothing else uses it. */
16
+ export declare function removeModuleSource(src: string, name: string): string;
17
+ export declare function addModuleToFile(file: string, ref: ModuleRef): void;
18
+ export declare function removeModuleFromFile(file: string, name: string): void;
@@ -0,0 +1,201 @@
1
+ // Small, careful edits to aicms.config.ts: add or remove a module and its import.
2
+ // A tokenizer skips strings, template literals and comments, so brackets inside
3
+ // them never confuse the edit. If the file doesn't look like defineConfig({ ... }),
4
+ // we refuse instead of guessing.
5
+ import { readFileSync, writeFileSync } from "node:fs";
6
+ /** Index of the bracket that closes the one at `open`, or -1. */
7
+ function closing(src, open) {
8
+ const pairs = { "(": ")", "[": "]", "{": "}" };
9
+ const stack = [];
10
+ for (let i = open; i < src.length; i++) {
11
+ const c = src[i];
12
+ if (c === "/" && src[i + 1] === "/") {
13
+ i = src.indexOf("\n", i);
14
+ if (i < 0)
15
+ return -1;
16
+ continue;
17
+ }
18
+ if (c === "/" && src[i + 1] === "*") {
19
+ i = src.indexOf("*/", i + 2) + 1;
20
+ if (i <= 0)
21
+ return -1;
22
+ continue;
23
+ }
24
+ if (c === '"' || c === "'" || c === "`") {
25
+ for (i++; i < src.length && src[i] !== c; i++)
26
+ if (src[i] === "\\")
27
+ i++;
28
+ continue;
29
+ }
30
+ if (pairs[c])
31
+ stack.push(pairs[c]);
32
+ else if (c === ")" || c === "]" || c === "}") {
33
+ if (stack.pop() !== c)
34
+ return -1;
35
+ if (!stack.length)
36
+ return i;
37
+ }
38
+ }
39
+ return -1;
40
+ }
41
+ /** Top-level `key:` positions inside the object literal spanning [open, close]. */
42
+ function topLevelKey(src, open, close, key) {
43
+ let depth = 0;
44
+ for (let i = open + 1; i < close; i++) {
45
+ const c = src[i];
46
+ if (c === "/" && src[i + 1] === "/") {
47
+ i = src.indexOf("\n", i);
48
+ continue;
49
+ }
50
+ if (c === "/" && src[i + 1] === "*") {
51
+ i = src.indexOf("*/", i + 2) + 1;
52
+ continue;
53
+ }
54
+ if (c === '"' || c === "'" || c === "`") {
55
+ for (i++; i < close && src[i] !== c; i++)
56
+ if (src[i] === "\\")
57
+ i++;
58
+ continue;
59
+ }
60
+ if ("([{".includes(c))
61
+ depth++;
62
+ else if (")]}".includes(c))
63
+ depth--;
64
+ else if (depth === 0 && src.startsWith(key, i) && /[\s,{]/.test(src[i - 1]) && /^\s*:/.test(src.slice(i + key.length)))
65
+ return i;
66
+ }
67
+ return -1;
68
+ }
69
+ function configObject(src) {
70
+ const call = src.search(/defineConfig\s*\(/);
71
+ if (call < 0)
72
+ throw new Error("aicms.config doesn't call defineConfig({ ... }); add the module by hand");
73
+ const open = src.indexOf("{", call);
74
+ const close = open < 0 ? -1 : closing(src, open);
75
+ if (close < 0)
76
+ throw new Error("Couldn't read the defineConfig({ ... }) object; add the module by hand");
77
+ return { open, close };
78
+ }
79
+ function modulesArray(src) {
80
+ const obj = configObject(src);
81
+ const key = topLevelKey(src, obj.open, obj.close, "modules");
82
+ if (key < 0)
83
+ return null;
84
+ const open = src.indexOf("[", key);
85
+ const close = open < 0 ? -1 : closing(src, open);
86
+ if (close < 0 || open > obj.close)
87
+ throw new Error("`modules` isn't an array literal; add the module by hand");
88
+ return { open, close };
89
+ }
90
+ /** Entries of the modules array as source text, e.g. ["seo()", "editorial"]. */
91
+ export function listModuleCalls(src) {
92
+ const arr = modulesArray(src);
93
+ if (!arr)
94
+ return [];
95
+ const out = [];
96
+ let start = arr.open + 1;
97
+ for (let i = arr.open + 1; i < arr.close; i++) {
98
+ const c = src[i];
99
+ if ("([{".includes(c)) {
100
+ i = closing(src, i);
101
+ continue;
102
+ }
103
+ if (c === '"' || c === "'" || c === "`") {
104
+ for (i++; src[i] !== c; i++)
105
+ if (src[i] === "\\")
106
+ i++;
107
+ continue;
108
+ }
109
+ if (c === ",") {
110
+ out.push(src.slice(start, i).trim());
111
+ start = i + 1;
112
+ }
113
+ }
114
+ out.push(src.slice(start, arr.close).trim());
115
+ return out.filter(Boolean);
116
+ }
117
+ function addImport(src, name, from, isDefault) {
118
+ const escaped = from.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
119
+ const named = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*["']${escaped}["']`);
120
+ const m = named.exec(src);
121
+ if (!isDefault && m) {
122
+ const names = m[1].split(",").map((s) => s.trim()).filter(Boolean);
123
+ if (names.includes(name))
124
+ return src;
125
+ return src.replace(named, `import { ${[...names, name].join(", ")} } from "${from}"`);
126
+ }
127
+ const line = isDefault ? `import ${name} from "${from}"` : `import { ${name} } from "${from}"`;
128
+ const imports = [...src.matchAll(/^import\b[\s\S]*?from\s*["'][^"']+["'];?[ \t]*$/gm)];
129
+ if (!imports.length)
130
+ return `${line}\n${src}`;
131
+ const last = imports[imports.length - 1];
132
+ const at = last.index + last[0].length;
133
+ return src.slice(0, at) + "\n" + line + src.slice(at);
134
+ }
135
+ /** Add a module to aicms.config: the import and an entry in `modules`. Returns the new source. */
136
+ export function addModuleSource(src, ref) {
137
+ if (listModuleCalls(src).some((c) => c === ref.call || c.startsWith(`${ref.name}(`) || c === ref.name))
138
+ throw new Error(`"${ref.name}" is already in modules`);
139
+ let out = addImport(src, ref.name, ref.from, ref.isDefault);
140
+ const arr = modulesArray(out);
141
+ if (arr) {
142
+ const inner = out.slice(arr.open + 1, arr.close);
143
+ const trimmed = inner.replace(/\s+$/, "");
144
+ const multiline = inner.includes("\n");
145
+ if (!trimmed.trim())
146
+ out = out.slice(0, arr.open + 1) + ref.call + out.slice(arr.close);
147
+ else {
148
+ const trailing = trimmed.endsWith(",");
149
+ const indent = multiline ? (/\n([ \t]*)\S[^\n]*\s*$/.exec(trimmed)?.[1] ?? " ") : "";
150
+ const insertAt = arr.open + 1 + trimmed.length;
151
+ const piece = multiline ? `${trailing ? "" : ","}\n${indent}${ref.call}${trailing ? "," : ""}` : `${trailing ? "" : ","} ${ref.call}`;
152
+ out = out.slice(0, insertAt) + piece + out.slice(insertAt);
153
+ }
154
+ }
155
+ else {
156
+ const obj = configObject(out);
157
+ const indent = /\n([ \t]+)\S/.exec(out.slice(obj.open, obj.close))?.[1] ?? " ";
158
+ out = out.slice(0, obj.open + 1) + `\n${indent}modules: [${ref.call}],` + out.slice(obj.open + 1);
159
+ }
160
+ return out;
161
+ }
162
+ /** Remove a module (by identifier) from `modules` and drop its import if nothing else uses it. */
163
+ export function removeModuleSource(src, name) {
164
+ const arr = modulesArray(src);
165
+ const calls = listModuleCalls(src);
166
+ const target = calls.find((c) => c === name || c.startsWith(`${name}(`));
167
+ if (!arr || !target)
168
+ throw new Error(`"${name}" isn't in modules`);
169
+ const rest = calls.filter((c) => c !== target);
170
+ const inner = src.slice(arr.open + 1, arr.close);
171
+ const multiline = inner.includes("\n");
172
+ const indent = /\n([ \t]*)\S/.exec(inner)?.[1] ?? " ";
173
+ const closeIndent = /\n([ \t]*)$/.exec(inner)?.[1] ?? " ";
174
+ const body = !rest.length ? "" : multiline ? `\n${rest.map((c) => indent + c).join(",\n")},\n${closeIndent}` : rest.join(", ");
175
+ let out = src.slice(0, arr.open + 1) + body + src.slice(arr.close);
176
+ // Drop the import if the identifier is no longer referenced as code (strings, comments,
177
+ // object keys like `seo: { ... }` and the import itself don't count).
178
+ const code = out
179
+ .replace(/\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, "")
180
+ .replace(/(["'`])(?:\\.|(?!\1)[^\\])*\1/g, '""')
181
+ .replace(/^import\b[^\n]*$/gm, "")
182
+ .replace(new RegExp(`\\b${name}\\s*:`, "g"), "");
183
+ if (!new RegExp(`\\b${name}\\b`).test(code)) {
184
+ out = out.replace(new RegExp(`^import\\s+${name}\\s+from\\s*["'][^"']+["'];?[ \\t]*\\n?`, "m"), "");
185
+ out = out.replace(/import\s*\{([^}]*)\}\s*from\s*(["'][^"']+["']);?/g, (whole, names, from) => {
186
+ const list = names.split(",").map((s) => s.trim()).filter(Boolean);
187
+ if (!list.includes(name))
188
+ return whole;
189
+ const left = list.filter((n) => n !== name);
190
+ return left.length ? `import { ${left.join(", ")} } from ${from}` : "";
191
+ });
192
+ out = out.replace(/^\n(?=import)|\n{3,}/gm, "\n\n");
193
+ }
194
+ return out;
195
+ }
196
+ export function addModuleToFile(file, ref) {
197
+ writeFileSync(file, addModuleSource(readFileSync(file, "utf8"), ref));
198
+ }
199
+ export function removeModuleFromFile(file, name) {
200
+ writeFileSync(file, removeModuleSource(readFileSync(file, "utf8"), name));
201
+ }
@@ -0,0 +1,55 @@
1
+ import type { Model } from "./schema/model.ts";
2
+ import type { ModuleDef } from "./kernel/modules.ts";
3
+ import type { Budget, ReviewMode } from "./kernel/policy.ts";
4
+ import type { SqliteOptions } from "./store/sqlite.ts";
5
+ import type { PostgresOptions } from "./store/postgres.ts";
6
+ import type { D1Options } from "./store/d1.ts";
7
+ export interface AgentConfig {
8
+ /** e.g. ["post:draft", "tag:read", "post:update.seo"] */
9
+ scopes: string[];
10
+ /**
11
+ * "human" (default): a person approves. "auto": merged when checks pass and no model requires a person.
12
+ * `{ auto: ["post:update.seo"] }`: merged without a person only for changes these scopes cover.
13
+ * Check warnings always send changes to a person.
14
+ */
15
+ review?: ReviewMode;
16
+ budget?: Budget;
17
+ description?: string;
18
+ }
19
+ export interface WebhookConfig {
20
+ url: string;
21
+ /** Event names, e.g. ["changeset.merged"]. Default: all. */
22
+ events?: string[];
23
+ /** Signs the body: header `x-aicms-signature: sha256=<hmac>`. */
24
+ secret?: string;
25
+ }
26
+ export interface Config {
27
+ /** Shown to agents in cms_describe and llms.txt. */
28
+ name?: string;
29
+ /** sqlite(".aicms/data.db") (default) or postgres({ url }). */
30
+ db?: SqliteOptions | PostgresOptions | D1Options;
31
+ /** The first locale is the default. */
32
+ locales?: string[];
33
+ /** Defaults to every model in ./models when loaded through the CLI. */
34
+ models?: Model[];
35
+ modules?: ModuleDef[];
36
+ agents?: Record<string, AgentConfig>;
37
+ /** Scopes for requests without a token, e.g. ["post:read"]. */
38
+ public?: string[];
39
+ webhooks?: WebhookConfig[];
40
+ /** The module registry used by `aicms search` / `aicms add`: a URL or file, or false. Default: the AICMS registry. */
41
+ registry?: string | false;
42
+ }
43
+ export interface ResolvedConfig {
44
+ name: string;
45
+ db: SqliteOptions | PostgresOptions | D1Options;
46
+ locales: string[];
47
+ models: Model[];
48
+ modules: ModuleDef[];
49
+ agents: Record<string, AgentConfig>;
50
+ public: string[];
51
+ webhooks: WebhookConfig[];
52
+ registry: string | false;
53
+ }
54
+ export declare function defineConfig(config: Config): Config;
55
+ export declare function resolveConfig(c: Config): ResolvedConfig;
package/dist/config.js ADDED
@@ -0,0 +1,32 @@
1
+ import { DEFAULT_REGISTRY } from "./registry.js";
2
+ export function defineConfig(config) {
3
+ return config;
4
+ }
5
+ const AGENT_NAME = /^[a-z][a-z0-9_-]*$/;
6
+ export function resolveConfig(c) {
7
+ const agents = c.agents ?? {};
8
+ for (const [name, a] of Object.entries(agents)) {
9
+ if (!AGENT_NAME.test(name))
10
+ throw new Error(`Agent name "${name}" must be lowercase letters, digits, - or _`);
11
+ if (name === "owner" || name === "public")
12
+ throw new Error(`Agent name "${name}" is reserved`);
13
+ if (!Array.isArray(a.scopes))
14
+ throw new Error(`Agent "${name}" needs a scopes array`);
15
+ const r = a.review;
16
+ const rule = typeof r === "object" && r !== null && Array.isArray(r.auto) && r.auto.every((x) => typeof x === "string");
17
+ if (r !== undefined && r !== "human" && r !== "auto" && !rule)
18
+ throw new Error(`Agent "${name}": review must be "human", "auto" or { auto: ["<scope>", …] }`);
19
+ }
20
+ const locales = c.locales?.length ? c.locales : ["en"];
21
+ return {
22
+ name: c.name ?? "AICMS site",
23
+ db: c.db ?? { kind: "sqlite", path: ".aicms/data.db" },
24
+ locales,
25
+ models: c.models ?? [],
26
+ modules: c.modules ?? [],
27
+ agents,
28
+ public: c.public ?? [],
29
+ webhooks: c.webhooks ?? [],
30
+ registry: c.registry ?? DEFAULT_REGISTRY,
31
+ };
32
+ }
package/dist/edge.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { Config } from "./config.ts";
2
+ export { d1 } from "./store/d1.ts";
3
+ interface ExecutionContextLike {
4
+ waitUntil(promise: Promise<unknown>): void;
5
+ }
6
+ export interface WorkerOptions {
7
+ /** Assets binding with dist/studio as its directory; false to serve no Studio. Default "ASSETS". */
8
+ assets?: string | false;
9
+ /** Env var holding the owner token (24+ characters). Default "AICMS_OWNER_TOKEN". */
10
+ ownerToken?: string;
11
+ }
12
+ /**
13
+ * A Worker that serves every AICMS gate: Studio, REST, GraphQL, MCP, A2A, events.
14
+ * The kernel is created once per isolate; live events and presence are per isolate too.
15
+ * Scheduled publishing runs from a cron trigger (`"triggers": { "crons": ["* * * * *"] }`)
16
+ * and, as a fallback, on requests at most once a minute.
17
+ */
18
+ export declare function createWorker(config: Config, opts?: WorkerOptions): {
19
+ fetch(request: Request, env: Record<string, unknown>, ctx: ExecutionContextLike): Promise<Response>;
20
+ /** Cron trigger: publish what's due. */
21
+ scheduled(_controller: unknown, env: Record<string, unknown>, ctx: ExecutionContextLike): Promise<void>;
22
+ };
package/dist/edge.js ADDED
@@ -0,0 +1,56 @@
1
+ // AICMS on Cloudflare Workers: D1 for data, R2 for media, Workers Assets for Studio.
2
+ //
3
+ // // worker.ts
4
+ // import { createWorker } from "aicms/edge"
5
+ // import config from "./aicms.config"
6
+ // export default createWorker(config)
7
+ import { createCMS } from "./kernel/cms.js";
8
+ import { createApp } from "./gates/rest.js";
9
+ import { assetsSource } from "./gates/studio.js";
10
+ export { d1 } from "./store/d1.js";
11
+ /** Requests check for due scheduled changesets at most this often; a cron trigger makes it exact. */
12
+ const LAZY_PUBLISH_MS = 60_000;
13
+ /**
14
+ * A Worker that serves every AICMS gate: Studio, REST, GraphQL, MCP, A2A, events.
15
+ * The kernel is created once per isolate; live events and presence are per isolate too.
16
+ * Scheduled publishing runs from a cron trigger (`"triggers": { "crons": ["* * * * *"] }`)
17
+ * and, as a fallback, on requests at most once a minute.
18
+ */
19
+ export function createWorker(config, opts = {}) {
20
+ let ready;
21
+ let current;
22
+ let lastPublish = 0;
23
+ const boot = (env) => (ready ??= (async () => {
24
+ const token = env[opts.ownerToken ?? "AICMS_OWNER_TOKEN"];
25
+ const kernel = await createCMS(config, {
26
+ bindings: env,
27
+ cwd: "/",
28
+ ownerToken: typeof token === "string" && token ? token : undefined,
29
+ waitUntil: (p) => current?.waitUntil(p),
30
+ });
31
+ const binding = opts.assets === false ? undefined : env[opts.assets ?? "ASSETS"];
32
+ return { kernel, app: createApp(kernel, { studio: binding ? assetsSource(binding) : false }) };
33
+ })().catch((e) => {
34
+ ready = undefined; // try again on the next request
35
+ throw e;
36
+ }));
37
+ const publish = (kernel) => {
38
+ lastPublish = Date.now();
39
+ return kernel.publishDue().then((r) => r.failed.forEach((f) => console.warn(`[aicms] scheduled ${f.changeset} went back to its author: ${f.error}`)), (e) => console.error("[aicms] scheduled publishing failed:", e));
40
+ };
41
+ return {
42
+ async fetch(request, env, ctx) {
43
+ current = ctx;
44
+ const { kernel, app } = await boot(env);
45
+ if (Date.now() - lastPublish > LAZY_PUBLISH_MS)
46
+ ctx.waitUntil(publish(kernel));
47
+ return app.fetch(request, env, ctx);
48
+ },
49
+ /** Cron trigger: publish what's due. */
50
+ async scheduled(_controller, env, ctx) {
51
+ current = ctx;
52
+ const { kernel } = await boot(env);
53
+ await publish(kernel);
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,45 @@
1
+ import type { Kernel } from "../kernel/cms.ts";
2
+ import type { Actor } from "../kernel/policy.ts";
3
+ export declare const A2A_PROTOCOL = "0.3.0";
4
+ /** The Agent Card: who this agent is and what it can do: one skill per Action the caller may use. */
5
+ export declare function agentCard(k: Kernel, origin: string, actor: Actor): {
6
+ protocolVersion: string;
7
+ name: string;
8
+ description: string;
9
+ url: string;
10
+ preferredTransport: string;
11
+ version: string;
12
+ provider: {
13
+ organization: string;
14
+ url: string;
15
+ };
16
+ documentationUrl: string;
17
+ capabilities: {
18
+ streaming: boolean;
19
+ pushNotifications: boolean;
20
+ stateTransitionHistory: boolean;
21
+ };
22
+ defaultInputModes: string[];
23
+ defaultOutputModes: string[];
24
+ securitySchemes: {
25
+ bearer: {
26
+ type: string;
27
+ scheme: string;
28
+ description: string;
29
+ };
30
+ };
31
+ security: {
32
+ bearer: never[];
33
+ }[];
34
+ skills: {
35
+ id: string;
36
+ name: string;
37
+ description: string;
38
+ tags: string[];
39
+ inputModes: string[];
40
+ outputModes: string[];
41
+ examples: string[];
42
+ }[];
43
+ };
44
+ /** JSON-RPC handler for one request. Tasks live in memory, visible only to the actor that created them. */
45
+ export declare function createA2A(k: Kernel): (actor: Actor, body: unknown) => Promise<unknown>;
@@ -0,0 +1,126 @@
1
+ // A2A (Agent2Agent) gate: an Agent Card and a JSON-RPC endpoint, so other
2
+ // agents can discover this site and call its Actions as skills. A message
3
+ // carries a data part `{ action, input }`; the reply is a completed task with
4
+ // the result as a data artifact. Same pipeline, permissions and log as MCP/REST.
5
+ import { randomUUID } from "node:crypto";
6
+ import { isAicmsError } from "../kernel/errors.js";
7
+ import { toolName } from "../kernel/action.js";
8
+ import { VERSION } from "./discovery.js";
9
+ export const A2A_PROTOCOL = "0.3.0";
10
+ const ERR = {
11
+ parse: -32700,
12
+ invalidRequest: -32600,
13
+ methodNotFound: -32601,
14
+ invalidParams: -32602,
15
+ taskNotFound: -32001,
16
+ taskNotCancelable: -32002,
17
+ unsupported: -32004,
18
+ };
19
+ /** The Agent Card: who this agent is and what it can do: one skill per Action the caller may use. */
20
+ export function agentCard(k, origin, actor) {
21
+ return {
22
+ protocolVersion: A2A_PROTOCOL,
23
+ name: k.config.name,
24
+ description: `A content site running AICMS. Agents read content and propose changes; people review them before anything is published. Send a data part { "action": "<skill id>", "input": { … } }.`,
25
+ url: `${origin}/a2a`,
26
+ preferredTransport: "JSONRPC",
27
+ version: VERSION,
28
+ provider: { organization: k.config.name, url: origin },
29
+ documentationUrl: `${origin}/llms.txt`,
30
+ capabilities: { streaming: false, pushNotifications: false, stateTransitionHistory: false },
31
+ defaultInputModes: ["application/json"],
32
+ defaultOutputModes: ["application/json"],
33
+ securitySchemes: { bearer: { type: "http", scheme: "bearer", description: "An agent token issued by the site owner (aicms agent create <name>)" } },
34
+ security: [{ bearer: [] }],
35
+ skills: [...k.actions.values()].filter((a) => a.visible(actor)).map((a) => ({
36
+ id: a.name,
37
+ name: toolName(a.name),
38
+ description: a.description,
39
+ tags: [a.module ? `module:${a.module}` : a.name.split(".")[0], a.readOnly ? "read" : "write"],
40
+ inputModes: ["application/json"],
41
+ outputModes: ["application/json"],
42
+ examples: [JSON.stringify({ action: a.name, input: {} })],
43
+ })),
44
+ };
45
+ }
46
+ const now = () => new Date().toISOString();
47
+ const text = (t) => ({ kind: "message", role: "agent", messageId: randomUUID(), parts: [{ kind: "text", text: t }] });
48
+ /** JSON-RPC handler for one request. Tasks live in memory, visible only to the actor that created them. */
49
+ export function createA2A(k) {
50
+ const tasks = new Map();
51
+ const remember = (owner, task) => {
52
+ tasks.set(task.id, { owner, task });
53
+ if (tasks.size > 1000)
54
+ tasks.delete(tasks.keys().next().value);
55
+ return task;
56
+ };
57
+ async function send(actor, message) {
58
+ const contextId = message.contextId ?? randomUUID();
59
+ const base = { kind: "task", id: randomUUID(), contextId, history: [message] };
60
+ const data = message.parts.find((p) => p.kind === "data")?.data;
61
+ const action = typeof data?.action === "string" ? data.action : typeof data?.skill === "string" ? data.skill : undefined;
62
+ if (!action) {
63
+ const skills = k.tools(actor).map((t) => t.name);
64
+ return remember(actor.id, {
65
+ ...base,
66
+ status: {
67
+ state: "input-required",
68
+ timestamp: now(),
69
+ message: text(`This agent runs structured skills and has no language model. Send a data part { "action": "<skill>", "input": { … } }. Skills you can use: ${skills.join(", ") || "none — you need a token"}. Start with cms.describe.`),
70
+ },
71
+ });
72
+ }
73
+ const name = k.actions.has(action) ? action : [...k.actions.keys()].find((n) => toolName(n) === action) ?? action;
74
+ try {
75
+ const result = await k.call(name, data.input ?? {}, { actor, gate: "a2a" });
76
+ return remember(actor.id, {
77
+ ...base,
78
+ status: { state: "completed", timestamp: now() },
79
+ artifacts: [{ artifactId: randomUUID(), name: `${name} result`, parts: [{ kind: "data", data: (result && typeof result === "object" && !Array.isArray(result) ? result : { result }) }] }],
80
+ });
81
+ }
82
+ catch (e) {
83
+ const error = isAicmsError(e) ? e.toJSON() : { code: "internal", message: e instanceof Error ? e.message : String(e) };
84
+ const state = error.code === "unauthorized" || error.code === "forbidden" ? "rejected" : "failed";
85
+ return remember(actor.id, {
86
+ ...base,
87
+ status: { state, timestamp: now(), message: { ...text(error.message), parts: [{ kind: "text", text: error.message }, { kind: "data", data: { error } }] } },
88
+ });
89
+ }
90
+ }
91
+ return async function handle(actor, body) {
92
+ const req = body;
93
+ const id = req && typeof req === "object" ? (req.id ?? null) : null;
94
+ const fail = (code, message, data) => ({ jsonrpc: "2.0", id, error: { code, message, ...(data ? { data } : {}) } });
95
+ if (!req || typeof req !== "object" || req.jsonrpc !== "2.0" || typeof req.method !== "string")
96
+ return fail(ERR.invalidRequest, "Expected a JSON-RPC 2.0 request");
97
+ const ok = (result) => ({ jsonrpc: "2.0", id, result });
98
+ switch (req.method) {
99
+ case "message/send": {
100
+ const m = req.params?.message;
101
+ if (!m || !Array.isArray(m.parts) || !m.parts.length)
102
+ return fail(ERR.invalidParams, "params.message with parts is required");
103
+ return ok(await send(actor, { ...m, kind: "message", messageId: m.messageId ?? randomUUID() }));
104
+ }
105
+ case "tasks/get": {
106
+ const t = tasks.get(String(req.params?.id ?? ""));
107
+ if (!t || t.owner !== actor.id)
108
+ return fail(ERR.taskNotFound, "Task not found");
109
+ return ok(t.task);
110
+ }
111
+ case "tasks/cancel": {
112
+ const t = tasks.get(String(req.params?.id ?? ""));
113
+ if (!t || t.owner !== actor.id)
114
+ return fail(ERR.taskNotFound, "Task not found");
115
+ return fail(ERR.taskNotCancelable, `Task is already ${t.task.status.state}`);
116
+ }
117
+ case "message/stream":
118
+ case "tasks/resubscribe":
119
+ case "tasks/pushNotificationConfig/set":
120
+ case "tasks/pushNotificationConfig/get":
121
+ return fail(ERR.unsupported, `${req.method} is not supported; use message/send`);
122
+ default:
123
+ return fail(ERR.methodNotFound, `Unknown method ${req.method}`);
124
+ }
125
+ };
126
+ }
@@ -0,0 +1,36 @@
1
+ import type { Kernel } from "../kernel/cms.ts";
2
+ import { type Actor } from "../kernel/policy.ts";
3
+ export declare const VERSION = "0.5.0";
4
+ /** /llms.txt: a plain description of the site for any agent, no token needed. */
5
+ export declare function llmsTxt(k: Kernel, actor: Actor, origin: string): string;
6
+ /** /.well-known/aicms.json: machine-readable entry points. */
7
+ export declare function manifest(k: Kernel, origin: string): {
8
+ name: string;
9
+ software: {
10
+ name: string;
11
+ version: string;
12
+ };
13
+ endpoints: {
14
+ mcp: string;
15
+ rest: string;
16
+ openapi: string;
17
+ llms: string;
18
+ events: string;
19
+ graphql: string;
20
+ a2a: string;
21
+ studio: string;
22
+ };
23
+ auth: {
24
+ type: string;
25
+ issuedBy: string;
26
+ };
27
+ locales: string[];
28
+ models: {
29
+ name: string;
30
+ label: string | undefined;
31
+ }[];
32
+ modules: {
33
+ name: string;
34
+ provides: string[];
35
+ }[];
36
+ };
@@ -0,0 +1,54 @@
1
+ import { typeLabel } from "../schema/fields.js";
2
+ import { modelPermissions } from "../kernel/policy.js";
3
+ export const VERSION = "0.5.0";
4
+ /** /llms.txt: a plain description of the site for any agent, no token needed. */
5
+ export function llmsTxt(k, actor, origin) {
6
+ const lines = [
7
+ `# ${k.config.name}`,
8
+ "",
9
+ `> A content site running AICMS ${VERSION}. Agents read and propose changes through MCP or REST; people review before anything is published.`,
10
+ "",
11
+ "## Connect",
12
+ `- MCP (Streamable HTTP): ${origin}/mcp, header \`Authorization: Bearer <token>\``,
13
+ `- REST: ${origin}/api/v1 · OpenAPI: ${origin}/openapi.json`,
14
+ `- Live events (SSE): ${origin}/api/v1/events · GraphQL: ${origin}/graphql`,
15
+ `- A2A: Agent Card ${origin}/.well-known/agent-card.json, JSON-RPC ${origin}/a2a`,
16
+ "- Tokens are issued by the site owner: `aicms agent create <name>`",
17
+ "- Start with the `cms_describe` tool; it lists models, guides and your permissions.",
18
+ "",
19
+ "## Models",
20
+ ];
21
+ const models = [...k.models.values()];
22
+ for (const m of models) {
23
+ const p = modelPermissions(actor, m);
24
+ lines.push("", `### ${m.name}${m.label ? ` — ${m.label}` : ""}${p.read ? "" : " (needs a token)"}`);
25
+ if (m.description)
26
+ lines.push(m.description);
27
+ if (m.agent?.guide)
28
+ lines.push(`Guide: ${m.agent.guide}`);
29
+ lines.push(...Object.entries(m.fields).map(([key, f]) => `- ${key}${f.options.required ? "*" : ""}: ${typeLabel(f)}${f.options.description ? ` — ${f.options.description}` : ""}`));
30
+ }
31
+ lines.push("", "## Publishing", "Agents write drafts into a changeset (`<model>_draft`) and send it with `cms_submit`. Checks run on submit (`cms_check` runs them earlier): errors must be fixed, warnings go to the reviewer. A person or the agent's review policy decides whether it is merged, now or at a scheduled time. `cms_changes` shows decisions and comments.", "People hand agents work as briefs: `cms_briefs` lists yours, `cms_brief_update` reports progress or asks a question, and `cms_submit({ brief })` answers one.", "");
32
+ return lines.join("\n");
33
+ }
34
+ /** /.well-known/aicms.json: machine-readable entry points. */
35
+ export function manifest(k, origin) {
36
+ return {
37
+ name: k.config.name,
38
+ software: { name: "aicms", version: VERSION },
39
+ endpoints: {
40
+ mcp: `${origin}/mcp`,
41
+ rest: `${origin}/api/v1`,
42
+ openapi: `${origin}/openapi.json`,
43
+ llms: `${origin}/llms.txt`,
44
+ events: `${origin}/api/v1/events`,
45
+ graphql: `${origin}/graphql`,
46
+ a2a: `${origin}/.well-known/agent-card.json`,
47
+ studio: `${origin}/studio/`,
48
+ },
49
+ auth: { type: "bearer", issuedBy: "site owner via `aicms agent create <name>`" },
50
+ locales: k.config.locales,
51
+ models: [...k.models.values()].map((m) => ({ name: m.name, label: m.label })),
52
+ modules: k.modules.map((m) => ({ name: m.name, provides: m.provides ?? [] })),
53
+ };
54
+ }
@@ -0,0 +1,14 @@
1
+ import type { Context } from "hono";
2
+ import type { FeedEvent, Kernel } from "../kernel/cms.ts";
3
+ import { type Actor } from "../kernel/policy.ts";
4
+ /**
5
+ * What this actor may see of a feed event, or null.
6
+ * Admins (`events:read`) see everything, including the action log. Reviewers see every
7
+ * changeset event. Authors see their own. Anyone who can read a model hears when it is published.
8
+ */
9
+ export declare function viewEvent(k: Kernel, actor: Actor, e: FeedEvent): FeedEvent | null;
10
+ /**
11
+ * GET /api/v1/events — Server-Sent Events. New events only, unless the client
12
+ * resumes with `Last-Event-ID` (or `?after=<id>`, `?after=0` for the whole buffer).
13
+ */
14
+ export declare function eventStream(k: Kernel, c: Context, actor: Actor): Response;