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.
- package/ARCHITECTURE.md +467 -0
- package/LICENSE +21 -0
- package/README.md +200 -2
- package/README.uk.md +201 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +722 -0
- package/dist/config-edit.d.ts +18 -0
- package/dist/config-edit.js +201 -0
- package/dist/config.d.ts +55 -0
- package/dist/config.js +32 -0
- package/dist/edge.d.ts +22 -0
- package/dist/edge.js +56 -0
- package/dist/gates/a2a.d.ts +45 -0
- package/dist/gates/a2a.js +126 -0
- package/dist/gates/discovery.d.ts +36 -0
- package/dist/gates/discovery.js +54 -0
- package/dist/gates/events.d.ts +14 -0
- package/dist/gates/events.js +86 -0
- package/dist/gates/graphql.d.ts +41 -0
- package/dist/gates/graphql.js +226 -0
- package/dist/gates/mcp.d.ts +8 -0
- package/dist/gates/mcp.js +60 -0
- package/dist/gates/openapi.d.ts +56 -0
- package/dist/gates/openapi.js +61 -0
- package/dist/gates/rest.d.ts +21 -0
- package/dist/gates/rest.js +263 -0
- package/dist/gates/studio.d.ts +21 -0
- package/dist/gates/studio.js +107 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +19 -0
- package/dist/kernel/action.d.ts +49 -0
- package/dist/kernel/action.js +22 -0
- package/dist/kernel/briefs.d.ts +161 -0
- package/dist/kernel/briefs.js +197 -0
- package/dist/kernel/changesets.d.ts +367 -0
- package/dist/kernel/changesets.js +765 -0
- package/dist/kernel/cms.d.ts +127 -0
- package/dist/kernel/cms.js +419 -0
- package/dist/kernel/core-actions.d.ts +5 -0
- package/dist/kernel/core-actions.js +487 -0
- package/dist/kernel/errors.d.ts +14 -0
- package/dist/kernel/errors.js +25 -0
- package/dist/kernel/install.d.ts +32 -0
- package/dist/kernel/install.js +34 -0
- package/dist/kernel/model-actions.d.ts +5 -0
- package/dist/kernel/model-actions.js +126 -0
- package/dist/kernel/modules.d.ts +221 -0
- package/dist/kernel/modules.js +207 -0
- package/dist/kernel/policy.d.ts +42 -0
- package/dist/kernel/policy.js +47 -0
- package/dist/load.d.ts +10 -0
- package/dist/load.js +63 -0
- package/dist/modules/catalog.d.ts +15 -0
- package/dist/modules/catalog.js +21 -0
- package/dist/modules/commerce.d.ts +67 -0
- package/dist/modules/commerce.js +260 -0
- package/dist/modules/git-sync.d.ts +20 -0
- package/dist/modules/git-sync.js +187 -0
- package/dist/modules/i18n.d.ts +6 -0
- package/dist/modules/i18n.js +168 -0
- package/dist/modules/index.d.ts +9 -0
- package/dist/modules/index.js +10 -0
- package/dist/modules/lint.d.ts +22 -0
- package/dist/modules/lint.js +126 -0
- package/dist/modules/media.d.ts +52 -0
- package/dist/modules/media.js +319 -0
- package/dist/modules/payments.d.ts +19 -0
- package/dist/modules/payments.js +110 -0
- package/dist/modules/search.d.ts +27 -0
- package/dist/modules/search.js +81 -0
- package/dist/modules/seo.d.ts +34 -0
- package/dist/modules/seo.js +189 -0
- package/dist/modules/text.d.ts +10 -0
- package/dist/modules/text.js +42 -0
- package/dist/node.d.ts +7 -0
- package/dist/node.js +11 -0
- package/dist/registry.d.ts +57 -0
- package/dist/registry.js +110 -0
- package/dist/schema/fields.d.ts +100 -0
- package/dist/schema/fields.js +134 -0
- package/dist/schema/markdown.d.ts +7 -0
- package/dist/schema/markdown.js +168 -0
- package/dist/schema/model.d.ts +44 -0
- package/dist/schema/model.js +104 -0
- package/dist/schema/slug.d.ts +2 -0
- package/dist/schema/slug.js +40 -0
- package/dist/store/d1.d.ts +30 -0
- package/dist/store/d1.js +27 -0
- package/dist/store/postgres.d.ts +164 -0
- package/dist/store/postgres.js +552 -0
- package/dist/store/sql.d.ts +135 -0
- package/dist/store/sql.js +530 -0
- package/dist/store/sqlite.d.ts +14 -0
- package/dist/store/sqlite.js +60 -0
- package/dist/store/types.d.ts +226 -0
- package/dist/store/types.js +21 -0
- package/dist/studio/assets/geologica-cyrillic-ext-wght-normal-C8B9Chlh.woff2 +0 -0
- package/dist/studio/assets/geologica-cyrillic-wght-normal-DbeVG3Ps.woff2 +0 -0
- package/dist/studio/assets/geologica-greek-wght-normal-DPM5d9ub.woff2 +0 -0
- package/dist/studio/assets/geologica-latin-ext-wght-normal-DZyYlgcm.woff2 +0 -0
- package/dist/studio/assets/geologica-latin-wght-normal-BBL8hQxZ.woff2 +0 -0
- package/dist/studio/assets/geologica-vietnamese-wght-normal-DcI17N1q.woff2 +0 -0
- package/dist/studio/assets/index-3dJ0YHxb.js +22 -0
- package/dist/studio/assets/index-DuyGLFw4.css +1 -0
- package/dist/studio/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
- package/dist/studio/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
- package/dist/studio/assets/unbounded-cyrillic-wght-normal-C627f1f8.woff2 +0 -0
- package/dist/studio/assets/unbounded-latin-ext-wght-normal-D6H-S6MW.woff2 +0 -0
- package/dist/studio/assets/unbounded-latin-wght-normal-D5afBTBx.woff2 +0 -0
- package/dist/studio/assets/unbounded-vietnamese-wght-normal-rat7GD3o.woff2 +0 -0
- package/dist/studio/index.html +21 -0
- package/dist/typegen.d.ts +7 -0
- package/dist/typegen.js +55 -0
- package/package.json +88 -4
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { streamSSE } from "hono/streaming";
|
|
2
|
+
import { allows, modelPermissions } from "../kernel/policy.js";
|
|
3
|
+
const HEARTBEAT_MS = 25_000;
|
|
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 function viewEvent(k, actor, e) {
|
|
10
|
+
if (allows(actor.scopes, "events:read"))
|
|
11
|
+
return e;
|
|
12
|
+
if (e.event === "presence") {
|
|
13
|
+
const m = k.models.get(e.payload?.model);
|
|
14
|
+
return m && actor.kind !== "public" && modelPermissions(actor, m).read ? e : null;
|
|
15
|
+
}
|
|
16
|
+
if (e.event.startsWith("brief.")) {
|
|
17
|
+
// Briefs: people and planners see all; an agent hears about the ones for it, including briefs open to anyone.
|
|
18
|
+
const b = e.payload ?? {};
|
|
19
|
+
if (allows(actor.scopes, "briefs:write") || b.createdBy === actor.id)
|
|
20
|
+
return e;
|
|
21
|
+
if (actor.kind !== "agent")
|
|
22
|
+
return null;
|
|
23
|
+
return (b.agent ? b.agent === actor.id : !b.claimedBy || b.claimedBy === actor.id) ? e : null;
|
|
24
|
+
}
|
|
25
|
+
if (e.event === "action" || !e.event.startsWith("changeset."))
|
|
26
|
+
return null;
|
|
27
|
+
const p = e.payload ?? {};
|
|
28
|
+
if (allows(actor.scopes, "changesets:review") || p.actor === actor.id)
|
|
29
|
+
return e;
|
|
30
|
+
if (e.event !== "changeset.merged")
|
|
31
|
+
return null;
|
|
32
|
+
const entries = (p.entries ?? []).filter((x) => {
|
|
33
|
+
const m = k.models.get(x.model);
|
|
34
|
+
return m && modelPermissions(actor, m).read;
|
|
35
|
+
});
|
|
36
|
+
return entries.length ? { ...e, payload: { changeset: p.changeset, entries } } : null;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* GET /api/v1/events — Server-Sent Events. New events only, unless the client
|
|
40
|
+
* resumes with `Last-Event-ID` (or `?after=<id>`, `?after=0` for the whole buffer).
|
|
41
|
+
*/
|
|
42
|
+
export function eventStream(k, c, actor) {
|
|
43
|
+
const resume = c.req.header("last-event-id") ?? c.req.query("after");
|
|
44
|
+
const after = resume === undefined ? k.feed.lastId() : Number(resume) || 0;
|
|
45
|
+
return streamSSE(c, async (stream) => {
|
|
46
|
+
const queue = [];
|
|
47
|
+
let wake = null;
|
|
48
|
+
let closed = false;
|
|
49
|
+
const unsubscribe = k.feed.subscribe((e) => {
|
|
50
|
+
queue.push(e);
|
|
51
|
+
wake?.();
|
|
52
|
+
});
|
|
53
|
+
stream.onAbort(() => {
|
|
54
|
+
closed = true;
|
|
55
|
+
unsubscribe();
|
|
56
|
+
wake?.();
|
|
57
|
+
});
|
|
58
|
+
queue.unshift(...k.feed.since(after));
|
|
59
|
+
let last = after;
|
|
60
|
+
// `last` lets a client that reconnects before its first event resume from here.
|
|
61
|
+
await stream.writeSSE({ event: "ready", data: JSON.stringify({ you: actor.id, last: after }), retry: 3000 });
|
|
62
|
+
while (!closed) {
|
|
63
|
+
while (queue.length && !closed) {
|
|
64
|
+
const e = queue.shift();
|
|
65
|
+
if (e.id <= last)
|
|
66
|
+
continue;
|
|
67
|
+
last = e.id;
|
|
68
|
+
const shown = viewEvent(k, actor, e);
|
|
69
|
+
if (shown)
|
|
70
|
+
await stream.writeSSE({ id: String(e.id), event: e.event, data: JSON.stringify(shown) });
|
|
71
|
+
}
|
|
72
|
+
if (closed)
|
|
73
|
+
break;
|
|
74
|
+
const timedOut = await new Promise((resolve) => {
|
|
75
|
+
const timer = setTimeout(() => resolve(true), HEARTBEAT_MS);
|
|
76
|
+
wake = () => {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
resolve(false);
|
|
79
|
+
};
|
|
80
|
+
});
|
|
81
|
+
wake = null;
|
|
82
|
+
if (timedOut && !closed)
|
|
83
|
+
await stream.write(": keep-alive\n\n");
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { GraphQLSchema } from "graphql";
|
|
2
|
+
import type { Kernel } from "../kernel/cms.ts";
|
|
3
|
+
import type { Actor } from "../kernel/policy.ts";
|
|
4
|
+
/** Build the schema for the kernel's current models. */
|
|
5
|
+
export declare function buildSchema(k: Kernel): GraphQLSchema;
|
|
6
|
+
export interface GraphQLRequest {
|
|
7
|
+
query?: string;
|
|
8
|
+
variables?: Record<string, unknown> | null;
|
|
9
|
+
operationName?: string | null;
|
|
10
|
+
}
|
|
11
|
+
/** Run one GraphQL request for an actor. `readOnly` (GET) refuses mutations. */
|
|
12
|
+
export declare function runGraphQL(k: Kernel, schema: GraphQLSchema, actor: Actor, req: GraphQLRequest, readOnly?: boolean): Promise<{
|
|
13
|
+
status: number;
|
|
14
|
+
body: {
|
|
15
|
+
errors: {
|
|
16
|
+
message: string;
|
|
17
|
+
}[];
|
|
18
|
+
};
|
|
19
|
+
} | {
|
|
20
|
+
status: number;
|
|
21
|
+
body: {
|
|
22
|
+
errors: {
|
|
23
|
+
message: string;
|
|
24
|
+
locations: readonly import("graphql").SourceLocation[] | undefined;
|
|
25
|
+
}[];
|
|
26
|
+
};
|
|
27
|
+
} | {
|
|
28
|
+
status: number;
|
|
29
|
+
body: {
|
|
30
|
+
errors?: {
|
|
31
|
+
message: string;
|
|
32
|
+
path: readonly (string | number)[] | undefined;
|
|
33
|
+
locations: readonly import("graphql").SourceLocation[] | undefined;
|
|
34
|
+
extensions: {
|
|
35
|
+
details?: {} | undefined;
|
|
36
|
+
code: string;
|
|
37
|
+
};
|
|
38
|
+
}[] | undefined;
|
|
39
|
+
data?: import("graphql/jsutils/ObjMap.js").ObjMap<unknown> | null | undefined;
|
|
40
|
+
};
|
|
41
|
+
}>;
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
// GraphQL gate, generated from the models. Every resolver calls kernel.call(),
|
|
2
|
+
// so permissions, budgets and the action log are the same as for REST and MCP.
|
|
3
|
+
import { GraphQLBoolean, GraphQLError, GraphQLFloat, GraphQLID, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLScalarType, GraphQLSchema, GraphQLString, Kind, execute, getOperationAST, parse, validate, } from "graphql";
|
|
4
|
+
import { isAicmsError } from "../kernel/errors.js";
|
|
5
|
+
import { blocksToMarkdown } from "../schema/markdown.js";
|
|
6
|
+
import { uniqueFields } from "../schema/model.js";
|
|
7
|
+
const pascal = (s) => s.replace(/(^|[_-])([a-zA-Z0-9])/g, (_, __, c) => c.toUpperCase());
|
|
8
|
+
const plural = (s) => (/(s|x|z|ch|sh)$/.test(s) ? `${s}es` : /[^aeiou]y$/.test(s) ? `${s.slice(0, -1)}ies` : `${s}s`);
|
|
9
|
+
const RESERVED = new Set(["Query", "Mutation", "Media", "JSON", "SearchHit"]);
|
|
10
|
+
const MAX_DEPTH = 10;
|
|
11
|
+
function literal(ast) {
|
|
12
|
+
switch (ast.kind) {
|
|
13
|
+
case Kind.STRING:
|
|
14
|
+
case Kind.ENUM:
|
|
15
|
+
return ast.value;
|
|
16
|
+
case Kind.BOOLEAN:
|
|
17
|
+
return ast.value;
|
|
18
|
+
case Kind.INT:
|
|
19
|
+
case Kind.FLOAT:
|
|
20
|
+
return Number(ast.value);
|
|
21
|
+
case Kind.NULL:
|
|
22
|
+
return null;
|
|
23
|
+
case Kind.LIST:
|
|
24
|
+
return ast.values.map(literal);
|
|
25
|
+
case Kind.OBJECT:
|
|
26
|
+
return Object.fromEntries(ast.fields.map((f) => [f.name.value, literal(f.value)]));
|
|
27
|
+
default:
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
const JSONScalar = new GraphQLScalarType({
|
|
32
|
+
name: "JSON",
|
|
33
|
+
description: "Any JSON value: blocks, objects, filters, results.",
|
|
34
|
+
serialize: (v) => v,
|
|
35
|
+
parseValue: (v) => v,
|
|
36
|
+
parseLiteral: (ast) => literal(ast),
|
|
37
|
+
});
|
|
38
|
+
const MediaType = new GraphQLObjectType({
|
|
39
|
+
name: "Media",
|
|
40
|
+
fields: { url: { type: new GraphQLNonNull(GraphQLString) }, alt: { type: GraphQLString }, width: { type: GraphQLInt }, height: { type: GraphQLInt } },
|
|
41
|
+
});
|
|
42
|
+
const SearchHit = new GraphQLObjectType({
|
|
43
|
+
name: "SearchHit",
|
|
44
|
+
fields: {
|
|
45
|
+
model: { type: new GraphQLNonNull(GraphQLString) },
|
|
46
|
+
id: { type: new GraphQLNonNull(GraphQLID) },
|
|
47
|
+
title: { type: GraphQLString },
|
|
48
|
+
snippet: { type: GraphQLString },
|
|
49
|
+
score: { type: GraphQLFloat },
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
/** Build the schema for the kernel's current models. */
|
|
53
|
+
export function buildSchema(k) {
|
|
54
|
+
const models = [...k.models.values()];
|
|
55
|
+
const typeNames = new Map(models.map((m) => [m.name, RESERVED.has(pascal(m.name)) ? `${pascal(m.name)}Entry` : pascal(m.name)]));
|
|
56
|
+
const types = new Map();
|
|
57
|
+
const call = (ctx, name, input) => ctx.k.call(name, input, { actor: ctx.actor, gate: "graphql" });
|
|
58
|
+
const load = (ctx, model, id) => {
|
|
59
|
+
const key = `${model}:${id}`;
|
|
60
|
+
if (!ctx.cache.has(key))
|
|
61
|
+
ctx.cache.set(key, call(ctx, `${model}.get`, { id }).catch(() => null));
|
|
62
|
+
return ctx.cache.get(key);
|
|
63
|
+
};
|
|
64
|
+
function fieldType(owner, key, f) {
|
|
65
|
+
switch (f.kind) {
|
|
66
|
+
case "number":
|
|
67
|
+
return { type: f.options.integer ? GraphQLInt : GraphQLFloat };
|
|
68
|
+
case "boolean":
|
|
69
|
+
return { type: GraphQLBoolean };
|
|
70
|
+
case "list":
|
|
71
|
+
return { type: new GraphQLList(new GraphQLNonNull(GraphQLString)) };
|
|
72
|
+
case "json":
|
|
73
|
+
return { type: JSONScalar };
|
|
74
|
+
case "media":
|
|
75
|
+
return { type: MediaType };
|
|
76
|
+
case "blocks":
|
|
77
|
+
return {
|
|
78
|
+
type: JSONScalar,
|
|
79
|
+
args: { markdown: { type: GraphQLBoolean } },
|
|
80
|
+
resolve: (src, args) => (args.markdown && Array.isArray(src[key]) ? blocksToMarkdown(src[key]) : src[key]),
|
|
81
|
+
};
|
|
82
|
+
case "object": {
|
|
83
|
+
const sub = new GraphQLObjectType({
|
|
84
|
+
name: `${owner}${pascal(key)}`,
|
|
85
|
+
fields: () => Object.fromEntries(Object.entries(f.options.fields).map(([k2, f2]) => [k2, fieldType(`${owner}${pascal(key)}`, k2, f2)])),
|
|
86
|
+
});
|
|
87
|
+
return { type: sub };
|
|
88
|
+
}
|
|
89
|
+
case "ref": {
|
|
90
|
+
// Field maps are thunks, so every model type exists by the time this runs.
|
|
91
|
+
const target = f.options.model;
|
|
92
|
+
const type = types.get(target);
|
|
93
|
+
return f.options.many
|
|
94
|
+
? { type: new GraphQLList(new GraphQLNonNull(type)), resolve: async (src, _args, ctx) => (await Promise.all((src[key] ?? []).map((id) => load(ctx, target, id)))).filter(Boolean) }
|
|
95
|
+
: { type, resolve: (src, _args, ctx) => (src[key] ? load(ctx, target, src[key]) : null) };
|
|
96
|
+
}
|
|
97
|
+
default:
|
|
98
|
+
return { type: GraphQLString };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
for (const m of models) {
|
|
102
|
+
const name = typeNames.get(m.name);
|
|
103
|
+
types.set(m.name, new GraphQLObjectType({
|
|
104
|
+
name,
|
|
105
|
+
description: m.label ?? m.description,
|
|
106
|
+
fields: () => {
|
|
107
|
+
const out = {
|
|
108
|
+
id: { type: new GraphQLNonNull(GraphQLID) },
|
|
109
|
+
locale: { type: new GraphQLNonNull(GraphQLString) },
|
|
110
|
+
version: { type: new GraphQLNonNull(GraphQLInt) },
|
|
111
|
+
updatedAt: { type: GraphQLString },
|
|
112
|
+
};
|
|
113
|
+
for (const [key, f] of Object.entries(m.fields)) {
|
|
114
|
+
out[key] = { ...fieldType(name, key, f), ...(f.options.description ? { description: String(f.options.description) } : {}) };
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
},
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
const query = {
|
|
121
|
+
search: {
|
|
122
|
+
type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(SearchHit))),
|
|
123
|
+
args: { query: { type: new GraphQLNonNull(GraphQLString) }, model: { type: GraphQLString }, limit: { type: GraphQLInt } },
|
|
124
|
+
resolve: async (_src, args, ctx) => (await call(ctx, "cms.search", strip(args))).hits,
|
|
125
|
+
},
|
|
126
|
+
describe: { type: JSONScalar, args: { model: { type: GraphQLString } }, resolve: (_src, args, ctx) => call(ctx, "cms.describe", strip(args)) },
|
|
127
|
+
};
|
|
128
|
+
const mutation = {
|
|
129
|
+
submit: { type: JSONScalar, args: { note: { type: GraphQLString } }, resolve: (_s, a, ctx) => call(ctx, "cms.submit", strip(a)) },
|
|
130
|
+
merge: { type: JSONScalar, args: { id: { type: new GraphQLNonNull(GraphQLID) } }, resolve: (_s, a, ctx) => call(ctx, "cms.merge", a) },
|
|
131
|
+
reject: {
|
|
132
|
+
type: JSONScalar,
|
|
133
|
+
args: { id: { type: new GraphQLNonNull(GraphQLID) }, comment: { type: new GraphQLNonNull(GraphQLString) }, final: { type: GraphQLBoolean } },
|
|
134
|
+
resolve: (_s, a, ctx) => call(ctx, "cms.reject", strip(a)),
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
const taken = new Set(models.map((m) => m.name));
|
|
138
|
+
for (const m of models) {
|
|
139
|
+
const t = types.get(m.name);
|
|
140
|
+
const P = pascal(m.name);
|
|
141
|
+
const page = new GraphQLObjectType({
|
|
142
|
+
name: `${typeNames.get(m.name)}Page`,
|
|
143
|
+
fields: {
|
|
144
|
+
items: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(t))) },
|
|
145
|
+
total: { type: new GraphQLNonNull(GraphQLInt) },
|
|
146
|
+
limit: { type: new GraphQLNonNull(GraphQLInt) },
|
|
147
|
+
offset: { type: new GraphQLNonNull(GraphQLInt) },
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
query[m.name] = {
|
|
151
|
+
type: t,
|
|
152
|
+
description: `One ${m.name} by id${uniqueFields(m).length ? ` or ${uniqueFields(m).join(" / ")}` : ""}.`,
|
|
153
|
+
args: { id: { type: GraphQLID }, locale: { type: GraphQLString }, ...Object.fromEntries(uniqueFields(m).map((f) => [f, { type: GraphQLString }])) },
|
|
154
|
+
resolve: (_src, args, ctx) => call(ctx, `${m.name}.get`, strip(args)),
|
|
155
|
+
};
|
|
156
|
+
const many = taken.has(plural(m.name)) ? `${m.name}List` : plural(m.name);
|
|
157
|
+
query[many] = {
|
|
158
|
+
type: new GraphQLNonNull(page),
|
|
159
|
+
description: `List ${m.name} entries. where: exact-match filters on indexed fields; order: "field" or "-field".`,
|
|
160
|
+
args: { where: { type: JSONScalar }, order: { type: GraphQLString }, limit: { type: GraphQLInt }, offset: { type: GraphQLInt }, locale: { type: GraphQLString } },
|
|
161
|
+
resolve: (_src, args, ctx) => call(ctx, `${m.name}.list`, strip(args)),
|
|
162
|
+
};
|
|
163
|
+
mutation[`draft${P}`] = {
|
|
164
|
+
type: JSONScalar,
|
|
165
|
+
description: `Create (no id) or change a ${m.name} in your changeset. data: the fields to set; block fields accept Markdown.`,
|
|
166
|
+
args: { id: { type: GraphQLID }, locale: { type: GraphQLString }, data: { type: new GraphQLNonNull(JSONScalar) } },
|
|
167
|
+
resolve: (_src, args, ctx) => call(ctx, `${m.name}.draft`, { ...args.data, ...strip({ id: args.id, locale: args.locale }) }),
|
|
168
|
+
};
|
|
169
|
+
mutation[`delete${P}`] = { type: JSONScalar, args: { id: { type: new GraphQLNonNull(GraphQLID) } }, resolve: (_src, args, ctx) => call(ctx, `${m.name}.delete`, args) };
|
|
170
|
+
}
|
|
171
|
+
return new GraphQLSchema({
|
|
172
|
+
query: new GraphQLObjectType({ name: "Query", fields: query }),
|
|
173
|
+
mutation: new GraphQLObjectType({ name: "Mutation", fields: mutation }),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
/** Drop null/undefined arguments so the kernel's strict schemas don't see them. */
|
|
177
|
+
function strip(args) {
|
|
178
|
+
return Object.fromEntries(Object.entries(args).filter(([, v]) => v !== null && v !== undefined));
|
|
179
|
+
}
|
|
180
|
+
function depth(doc) {
|
|
181
|
+
let max = 0;
|
|
182
|
+
const walk = (node, d) => {
|
|
183
|
+
if (!node || typeof node !== "object")
|
|
184
|
+
return;
|
|
185
|
+
if (node.kind === Kind.SELECTION_SET) {
|
|
186
|
+
max = Math.max(max, d);
|
|
187
|
+
for (const s of node.selections)
|
|
188
|
+
walk(s, d + 1);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
for (const v of Object.values(node)) {
|
|
192
|
+
if (Array.isArray(v))
|
|
193
|
+
v.forEach((x) => walk(x, d));
|
|
194
|
+
else if (v && typeof v === "object" && "kind" in v)
|
|
195
|
+
walk(v, d);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
walk(doc, 0);
|
|
199
|
+
return max;
|
|
200
|
+
}
|
|
201
|
+
/** Run one GraphQL request for an actor. `readOnly` (GET) refuses mutations. */
|
|
202
|
+
export async function runGraphQL(k, schema, actor, req, readOnly = false) {
|
|
203
|
+
if (!req.query)
|
|
204
|
+
return { status: 400, body: { errors: [{ message: "Send { query, variables, operationName }" }] } };
|
|
205
|
+
let doc;
|
|
206
|
+
try {
|
|
207
|
+
doc = parse(req.query);
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
return { status: 400, body: { errors: [{ message: e.message }] } };
|
|
211
|
+
}
|
|
212
|
+
if (depth(doc) > MAX_DEPTH)
|
|
213
|
+
return { status: 400, body: { errors: [{ message: `Query is nested deeper than ${MAX_DEPTH} levels` }] } };
|
|
214
|
+
const invalid = validate(schema, doc);
|
|
215
|
+
if (invalid.length)
|
|
216
|
+
return { status: 400, body: { errors: invalid.map((e) => ({ message: e.message, locations: e.locations })) } };
|
|
217
|
+
const op = getOperationAST(doc, req.operationName ?? undefined);
|
|
218
|
+
if (readOnly && op?.operation === "mutation")
|
|
219
|
+
return { status: 405, body: { errors: [{ message: "Mutations need POST" }] } };
|
|
220
|
+
const result = await execute({ schema, document: doc, variableValues: req.variables ?? undefined, operationName: req.operationName ?? undefined, contextValue: { k, actor, cache: new Map() } });
|
|
221
|
+
const errors = result.errors?.map((e) => {
|
|
222
|
+
const orig = e.originalError;
|
|
223
|
+
return { message: e.message, path: e.path, locations: e.locations, extensions: { code: isAicmsError(orig) ? orig.code : "graphql", ...(isAicmsError(orig) && orig.details ? { details: orig.details } : {}) } };
|
|
224
|
+
});
|
|
225
|
+
return { status: 200, body: { ...(result.data !== undefined ? { data: result.data } : {}), ...(errors?.length ? { errors } : {}) } };
|
|
226
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
|
+
import type { Kernel } from "../kernel/cms.ts";
|
|
3
|
+
import type { Actor } from "../kernel/policy.ts";
|
|
4
|
+
/** An MCP server whose tool list is exactly what this actor may call. */
|
|
5
|
+
export declare function createMcpServer(k: Kernel, actor: Actor): Server;
|
|
6
|
+
/** Stateless Streamable HTTP: a fresh server per request, JSON responses, no sessions. */
|
|
7
|
+
export declare function handleMcpRequest(k: Kernel, actor: Actor, request: Request): Promise<Response>;
|
|
8
|
+
export declare function serveStdio(k: Kernel, actor: Actor): Promise<void>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
3
|
+
import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
|
|
4
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
import { isAicmsError } from "../kernel/errors.js";
|
|
6
|
+
import { VERSION } from "./discovery.js";
|
|
7
|
+
const INSTRUCTIONS = `This is an AICMS content site.
|
|
8
|
+
Start with cms_describe: it lists the models you can work with, their writing guides and your permissions.
|
|
9
|
+
cms_briefs lists work people gave you; report on a brief with cms_brief_update.
|
|
10
|
+
Read with <model>_list and <model>_get. Write with <model>_draft; block fields accept Markdown.
|
|
11
|
+
Your edits are drafts in a changeset. cms_check runs the site's checks; fix errors, and warnings when you can.
|
|
12
|
+
Call cms_submit when you're done (with { brief } if it answers one); nothing is public until it is merged.
|
|
13
|
+
cms_changes shows review decisions and reviewer comments.`;
|
|
14
|
+
/** An MCP server whose tool list is exactly what this actor may call. */
|
|
15
|
+
export function createMcpServer(k, actor) {
|
|
16
|
+
const server = new Server({ name: "aicms", title: k.config.name, version: VERSION }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
|
|
17
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
18
|
+
tools: k.tools(actor).map((t) => ({
|
|
19
|
+
name: t.tool,
|
|
20
|
+
title: t.name,
|
|
21
|
+
description: t.description,
|
|
22
|
+
inputSchema: t.inputSchema,
|
|
23
|
+
annotations: { readOnlyHint: !!t.readOnly, destructiveHint: !!t.destructive, openWorldHint: false },
|
|
24
|
+
})),
|
|
25
|
+
}));
|
|
26
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
27
|
+
const tool = k.tools(actor).find((t) => t.tool === req.params.name);
|
|
28
|
+
if (!tool) {
|
|
29
|
+
return { isError: true, content: [{ type: "text", text: `Unknown tool "${req.params.name}". Call cms_describe to see what you can use.` }] };
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
const out = await k.call(tool.name, req.params.arguments ?? {}, { actor, gate: "mcp" });
|
|
33
|
+
return { content: [{ type: "text", text: JSON.stringify(out, null, 2) }] };
|
|
34
|
+
}
|
|
35
|
+
catch (e) {
|
|
36
|
+
const body = isAicmsError(e) ? { error: e.toJSON() } : { error: { code: "internal", message: e instanceof Error ? e.message : String(e) } };
|
|
37
|
+
if (!isAicmsError(e))
|
|
38
|
+
console.error("[aicms] tool failed:", e);
|
|
39
|
+
return { isError: true, content: [{ type: "text", text: JSON.stringify(body, null, 2) }] };
|
|
40
|
+
}
|
|
41
|
+
});
|
|
42
|
+
return server;
|
|
43
|
+
}
|
|
44
|
+
/** Stateless Streamable HTTP: a fresh server per request, JSON responses, no sessions. */
|
|
45
|
+
export async function handleMcpRequest(k, actor, request) {
|
|
46
|
+
const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
47
|
+
const server = createMcpServer(k, actor);
|
|
48
|
+
await server.connect(transport);
|
|
49
|
+
try {
|
|
50
|
+
return await transport.handleRequest(request);
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
// The JSON response is complete at this point; release the per-request server.
|
|
54
|
+
void server.close().catch(() => { });
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function serveStdio(k, actor) {
|
|
58
|
+
const server = createMcpServer(k, actor);
|
|
59
|
+
await server.connect(new StdioServerTransport());
|
|
60
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Kernel } from "../kernel/cms.ts";
|
|
2
|
+
import type { Actor } from "../kernel/policy.ts";
|
|
3
|
+
/**
|
|
4
|
+
* One operation per Action the caller can see: POST /api/v1/actions/<name>.
|
|
5
|
+
* operationId is the MCP tool name, so function-calling setups and MCP agree.
|
|
6
|
+
*/
|
|
7
|
+
export declare function openapi(k: Kernel, actor: Actor, origin: string): {
|
|
8
|
+
openapi: string;
|
|
9
|
+
info: {
|
|
10
|
+
title: string;
|
|
11
|
+
version: string;
|
|
12
|
+
description: string;
|
|
13
|
+
};
|
|
14
|
+
servers: {
|
|
15
|
+
url: string;
|
|
16
|
+
}[];
|
|
17
|
+
security: {
|
|
18
|
+
bearer: never[];
|
|
19
|
+
}[];
|
|
20
|
+
paths: Record<string, unknown>;
|
|
21
|
+
components: {
|
|
22
|
+
securitySchemes: {
|
|
23
|
+
bearer: {
|
|
24
|
+
type: string;
|
|
25
|
+
scheme: string;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
responses: {
|
|
29
|
+
Error: {
|
|
30
|
+
description: string;
|
|
31
|
+
content: {
|
|
32
|
+
"application/json": {
|
|
33
|
+
schema: {
|
|
34
|
+
type: string;
|
|
35
|
+
properties: {
|
|
36
|
+
error: {
|
|
37
|
+
type: string;
|
|
38
|
+
properties: {
|
|
39
|
+
code: {
|
|
40
|
+
type: string;
|
|
41
|
+
};
|
|
42
|
+
message: {
|
|
43
|
+
type: string;
|
|
44
|
+
};
|
|
45
|
+
details: {};
|
|
46
|
+
};
|
|
47
|
+
required: string[];
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { VERSION } from "./discovery.js";
|
|
2
|
+
/**
|
|
3
|
+
* One operation per Action the caller can see: POST /api/v1/actions/<name>.
|
|
4
|
+
* operationId is the MCP tool name, so function-calling setups and MCP agree.
|
|
5
|
+
*/
|
|
6
|
+
export function openapi(k, actor, origin) {
|
|
7
|
+
const paths = {};
|
|
8
|
+
for (const t of k.tools(actor)) {
|
|
9
|
+
paths[`/api/v1/actions/${t.name}`] = {
|
|
10
|
+
post: {
|
|
11
|
+
operationId: t.tool,
|
|
12
|
+
summary: t.name,
|
|
13
|
+
description: t.description,
|
|
14
|
+
tags: [t.name.split(".")[0]],
|
|
15
|
+
requestBody: { required: true, content: { "application/json": { schema: t.inputSchema } } },
|
|
16
|
+
responses: {
|
|
17
|
+
"200": { description: "Result of the action", content: { "application/json": { schema: { type: "object" } } } },
|
|
18
|
+
"401": { $ref: "#/components/responses/Error" },
|
|
19
|
+
"403": { $ref: "#/components/responses/Error" },
|
|
20
|
+
"404": { $ref: "#/components/responses/Error" },
|
|
21
|
+
"409": { $ref: "#/components/responses/Error" },
|
|
22
|
+
"422": { $ref: "#/components/responses/Error" },
|
|
23
|
+
"429": { $ref: "#/components/responses/Error" },
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
openapi: "3.1.0",
|
|
30
|
+
info: {
|
|
31
|
+
title: `${k.config.name} — AICMS API`,
|
|
32
|
+
version: VERSION,
|
|
33
|
+
description: "Every operation is an AICMS Action. Writes land in your changeset; call cms.submit to send them for review.",
|
|
34
|
+
},
|
|
35
|
+
servers: [{ url: origin }],
|
|
36
|
+
security: [{ bearer: [] }],
|
|
37
|
+
paths,
|
|
38
|
+
components: {
|
|
39
|
+
securitySchemes: { bearer: { type: "http", scheme: "bearer" } },
|
|
40
|
+
responses: {
|
|
41
|
+
Error: {
|
|
42
|
+
description: "Error",
|
|
43
|
+
content: {
|
|
44
|
+
"application/json": {
|
|
45
|
+
schema: {
|
|
46
|
+
type: "object",
|
|
47
|
+
properties: {
|
|
48
|
+
error: {
|
|
49
|
+
type: "object",
|
|
50
|
+
properties: { code: { type: "string" }, message: { type: "string" }, details: {} },
|
|
51
|
+
required: ["code", "message"],
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import type { Gate } from "../kernel/action.ts";
|
|
3
|
+
import type { Kernel } from "../kernel/cms.ts";
|
|
4
|
+
import type { Actor } from "../kernel/policy.ts";
|
|
5
|
+
import { type StudioSource } from "./studio.ts";
|
|
6
|
+
type Env = {
|
|
7
|
+
Variables: {
|
|
8
|
+
actor: Actor;
|
|
9
|
+
gate: Gate;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
export interface AppOptions {
|
|
13
|
+
/** The built Studio: a directory, a source (e.g. Workers Assets), or false to leave it out. Found automatically by default. */
|
|
14
|
+
studio?: string | StudioSource | false;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* The HTTP surface: REST routes, discovery, OpenAPI and MCP.
|
|
18
|
+
* Everything is a thin wrapper over kernel.call(), so rules are identical across gates.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createApp(k: Kernel, opts?: AppOptions): Hono<Env>;
|
|
21
|
+
export {};
|