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,127 @@
|
|
|
1
|
+
import { type Config, type ResolvedConfig } from "../config.ts";
|
|
2
|
+
import { type Model } from "../schema/model.ts";
|
|
3
|
+
import type { Store } from "../store/types.ts";
|
|
4
|
+
import { type Gate, type RegisteredAction } from "./action.ts";
|
|
5
|
+
import { type ModuleDef, type ModuleRoute } from "./modules.ts";
|
|
6
|
+
import { type Actor } from "./policy.ts";
|
|
7
|
+
export interface ToolInfo {
|
|
8
|
+
/** Action name, e.g. "post.draft" (REST, code). */
|
|
9
|
+
name: string;
|
|
10
|
+
/** MCP tool name, e.g. "post_draft". */
|
|
11
|
+
tool: string;
|
|
12
|
+
description: string;
|
|
13
|
+
inputSchema: Record<string, unknown>;
|
|
14
|
+
readOnly?: boolean;
|
|
15
|
+
destructive?: boolean;
|
|
16
|
+
}
|
|
17
|
+
type Handler = (event: string, payload: unknown) => void | Promise<void>;
|
|
18
|
+
/** One item of the live feed behind `/api/v1/events`. `action` items mirror the action log. */
|
|
19
|
+
export interface FeedEvent {
|
|
20
|
+
id: number;
|
|
21
|
+
event: string;
|
|
22
|
+
payload: any;
|
|
23
|
+
at: string;
|
|
24
|
+
}
|
|
25
|
+
export interface Feed {
|
|
26
|
+
/** Buffered events after `id` (the last few hundred, for reconnecting clients). */
|
|
27
|
+
since(id?: number): FeedEvent[];
|
|
28
|
+
/** Id of the newest event so far (0 before any). */
|
|
29
|
+
lastId(): number;
|
|
30
|
+
subscribe(fn: (e: FeedEvent) => void): () => void;
|
|
31
|
+
}
|
|
32
|
+
export type PresenceState = "viewing" | "editing";
|
|
33
|
+
export interface PresenceEntry {
|
|
34
|
+
actor: string;
|
|
35
|
+
kind: Actor["kind"];
|
|
36
|
+
state: PresenceState;
|
|
37
|
+
since: string;
|
|
38
|
+
seen: number;
|
|
39
|
+
}
|
|
40
|
+
/** Who is looking at or working on an entry right now (in this server process). */
|
|
41
|
+
export interface Presence {
|
|
42
|
+
touch(actor: Actor, entry: string, model: string, state: PresenceState): void;
|
|
43
|
+
leave(actor: Actor, entry: string): void;
|
|
44
|
+
list(entry: string): Omit<PresenceEntry, "seen">[];
|
|
45
|
+
}
|
|
46
|
+
export interface Kernel {
|
|
47
|
+
readonly config: ResolvedConfig;
|
|
48
|
+
readonly store: Store;
|
|
49
|
+
readonly models: Map<string, Model>;
|
|
50
|
+
readonly actions: Map<string, RegisteredAction>;
|
|
51
|
+
/** Installed modules, in load order. */
|
|
52
|
+
readonly modules: ModuleDef[];
|
|
53
|
+
readonly defaultLocale: string;
|
|
54
|
+
/** The project's aicms.config file, when the kernel was started from one (lets installs persist). */
|
|
55
|
+
readonly configFile?: string;
|
|
56
|
+
/** The project folder: where aicms.config.ts lives, or the working directory. */
|
|
57
|
+
readonly projectDir: string;
|
|
58
|
+
/** A folder a module may keep files in (created on first use). */
|
|
59
|
+
moduleDir(name: string): string;
|
|
60
|
+
/** A platform binding (Cloudflare env), e.g. an R2 bucket. */
|
|
61
|
+
binding<T = unknown>(name: string): T;
|
|
62
|
+
/** The implementation of a capability, if an installed module provides it. */
|
|
63
|
+
service<T = unknown>(capability: string): T | undefined;
|
|
64
|
+
/** The module route matching a request, if any. */
|
|
65
|
+
matchRoute(method: string, path: string): {
|
|
66
|
+
route: ModuleRoute;
|
|
67
|
+
params: Record<string, string>;
|
|
68
|
+
} | null;
|
|
69
|
+
/** Load a module into the running kernel: models, Actions, hooks, routes, services, then its setup. */
|
|
70
|
+
installModule(mod: ModuleDef): Promise<void>;
|
|
71
|
+
/** Run an Action through the full pipeline: visibility, budget, validation, run, event log. */
|
|
72
|
+
call<T = any>(name: string, input: unknown, opts: {
|
|
73
|
+
actor: Actor;
|
|
74
|
+
gate: Gate;
|
|
75
|
+
}): Promise<T>;
|
|
76
|
+
/** Actions this actor can see, as tool descriptions. */
|
|
77
|
+
tools(actor: Actor): ToolInfo[];
|
|
78
|
+
actor(name: string): Actor;
|
|
79
|
+
/** No token → public actor. Unknown or revoked token → `unauthorized`. */
|
|
80
|
+
resolveToken(token: string | null | undefined): Promise<Actor>;
|
|
81
|
+
createToken(agent: string): Promise<string>;
|
|
82
|
+
revokeAgent(agent: string): Promise<{
|
|
83
|
+
tokens: number;
|
|
84
|
+
changesets: number;
|
|
85
|
+
}>;
|
|
86
|
+
/** A one-time code for a Studio sign-in link, valid for 15 minutes. */
|
|
87
|
+
createLoginCode(): Promise<string>;
|
|
88
|
+
/** Trade a login code for a 30-day owner session token. */
|
|
89
|
+
startSession(code: string): Promise<{
|
|
90
|
+
token: string;
|
|
91
|
+
expiresAt: string;
|
|
92
|
+
}>;
|
|
93
|
+
endSession(token: string): Promise<void>;
|
|
94
|
+
on(event: string, handler: Handler): () => void;
|
|
95
|
+
emit(event: string, payload: unknown): Promise<void>;
|
|
96
|
+
readonly feed: Feed;
|
|
97
|
+
readonly presence: Presence;
|
|
98
|
+
/** Merge the scheduled changesets whose time has come. */
|
|
99
|
+
publishDue(): Promise<{
|
|
100
|
+
merged: string[];
|
|
101
|
+
failed: {
|
|
102
|
+
changeset: string;
|
|
103
|
+
error: string;
|
|
104
|
+
}[];
|
|
105
|
+
}>;
|
|
106
|
+
/** Run publishDue every `everyMs` (default 30 s) until stopped or closed. */
|
|
107
|
+
startScheduler(everyMs?: number): () => void;
|
|
108
|
+
close(): Promise<void>;
|
|
109
|
+
}
|
|
110
|
+
export interface CreateOptions {
|
|
111
|
+
/** Base directory for relative paths such as the SQLite file. */
|
|
112
|
+
cwd?: string;
|
|
113
|
+
/** Bring your own store (tests, other databases). */
|
|
114
|
+
store?: Store;
|
|
115
|
+
/** Where modules keep files (media uploads, exports). Defaults to the database's folder. */
|
|
116
|
+
dataDir?: string;
|
|
117
|
+
/** The config file the kernel came from, so module installs can be written back. */
|
|
118
|
+
configFile?: string;
|
|
119
|
+
/** A token that acts as the owner (e.g. from AICMS_OWNER_TOKEN). Useful where there is no CLI, such as the edge. */
|
|
120
|
+
ownerToken?: string;
|
|
121
|
+
/** Platform bindings (Cloudflare env): D1 databases, R2 buckets. */
|
|
122
|
+
bindings?: Record<string, unknown>;
|
|
123
|
+
/** Keep background work (webhooks) alive after the response, e.g. a Worker's ctx.waitUntil. */
|
|
124
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
125
|
+
}
|
|
126
|
+
export declare function createCMS(input: Config, opts?: CreateOptions): Promise<Kernel>;
|
|
127
|
+
export {};
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes } from "node:crypto";
|
|
2
|
+
import { builtin } from "../node.js";
|
|
3
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { resolveConfig } from "../config.js";
|
|
5
|
+
import { indexedFields, isModel, toJsonSchema } from "../schema/model.js";
|
|
6
|
+
import { openPostgres } from "../store/postgres.js";
|
|
7
|
+
import { SqlStore } from "../store/sql.js";
|
|
8
|
+
import { d1Driver } from "../store/d1.js";
|
|
9
|
+
import { toolName } from "./action.js";
|
|
10
|
+
import { newId, publishDue, rejectChangeset } from "./changesets.js";
|
|
11
|
+
import { watchBriefs } from "./briefs.js";
|
|
12
|
+
import { coreActions } from "./core-actions.js";
|
|
13
|
+
import { AicmsError } from "./errors.js";
|
|
14
|
+
import { modelActions } from "./model-actions.js";
|
|
15
|
+
import { checkModules, compileRoute, moduleActions, moduleContext } from "./modules.js";
|
|
16
|
+
import { OWNER } from "./policy.js";
|
|
17
|
+
const FEED_SIZE = 500;
|
|
18
|
+
const PRESENCE_TTL_MS = 45_000;
|
|
19
|
+
const LOGIN_TTL_MS = 15 * 60_000;
|
|
20
|
+
const SESSION_TTL_MS = 30 * 24 * 3_600_000;
|
|
21
|
+
const hashToken = (token) => createHash("sha256").update(token).digest("hex");
|
|
22
|
+
/** Constant-time comparison of two tokens. */
|
|
23
|
+
function sameToken(a, b) {
|
|
24
|
+
const x = hashToken(a);
|
|
25
|
+
const y = hashToken(b);
|
|
26
|
+
let diff = 0;
|
|
27
|
+
for (let i = 0; i < x.length; i++)
|
|
28
|
+
diff |= x.charCodeAt(i) ^ y.charCodeAt(i);
|
|
29
|
+
return diff === 0;
|
|
30
|
+
}
|
|
31
|
+
export async function createCMS(input, opts = {}) {
|
|
32
|
+
const config = resolveConfig(input);
|
|
33
|
+
const cwd = opts.cwd ?? (typeof process !== "undefined" && process.cwd ? process.cwd() : "/");
|
|
34
|
+
const db = config.db;
|
|
35
|
+
const dbPath = db.kind === "sqlite" ? (db.path === ":memory:" || isAbsolute(db.path) ? db.path : resolve(cwd, db.path)) : null;
|
|
36
|
+
const binding = (name) => {
|
|
37
|
+
const b = opts.bindings?.[name];
|
|
38
|
+
if (!b)
|
|
39
|
+
throw new Error(`No binding "${name}". Add it to wrangler config and pass env as bindings.`);
|
|
40
|
+
return b;
|
|
41
|
+
};
|
|
42
|
+
const store = opts.store ??
|
|
43
|
+
(db.kind === "postgres"
|
|
44
|
+
? await openPostgres(db)
|
|
45
|
+
: db.kind === "d1"
|
|
46
|
+
? new SqlStore(d1Driver(binding(db.binding)))
|
|
47
|
+
: new (await import("../store/sqlite.js")).SqliteStore(dbPath));
|
|
48
|
+
const dataDir = opts.dataDir ?? (dbPath && dbPath !== ":memory:" ? dirname(dbPath) : db.kind === "sqlite" ? join(builtin("node:os")?.tmpdir() ?? "/tmp", `aicms-${process.pid}`) : resolve(cwd, ".aicms"));
|
|
49
|
+
const modules = [];
|
|
50
|
+
const services = new Map();
|
|
51
|
+
const routes = [];
|
|
52
|
+
const models = new Map();
|
|
53
|
+
const actions = new Map();
|
|
54
|
+
const handlers = new Map();
|
|
55
|
+
const buffer = [];
|
|
56
|
+
const subscribers = new Set();
|
|
57
|
+
let seq = 0;
|
|
58
|
+
const publish = (event, payload) => {
|
|
59
|
+
const item = { id: ++seq, event, payload, at: new Date().toISOString() };
|
|
60
|
+
buffer.push(item);
|
|
61
|
+
if (buffer.length > FEED_SIZE)
|
|
62
|
+
buffer.shift();
|
|
63
|
+
for (const fn of subscribers) {
|
|
64
|
+
try {
|
|
65
|
+
fn(item);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
/* a broken subscriber must not break the caller */
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
// ---- presence: entry → actor → state; expires without a heartbeat ----
|
|
73
|
+
const here = new Map();
|
|
74
|
+
const announce = (entry, model) => publish("presence", { entry, model, here: [...(here.get(entry)?.values() ?? [])].map(({ seen: _s, model: _m, ...p }) => p) });
|
|
75
|
+
const sweep = () => {
|
|
76
|
+
const cutoff = Date.now() - PRESENCE_TTL_MS;
|
|
77
|
+
for (const [entry, actors] of here) {
|
|
78
|
+
let model = "";
|
|
79
|
+
let changed = false;
|
|
80
|
+
for (const [id, p] of actors)
|
|
81
|
+
if (p.seen < cutoff) {
|
|
82
|
+
model = p.model;
|
|
83
|
+
actors.delete(id);
|
|
84
|
+
changed = true;
|
|
85
|
+
}
|
|
86
|
+
if (!actors.size)
|
|
87
|
+
here.delete(entry);
|
|
88
|
+
if (changed)
|
|
89
|
+
announce(entry, model);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
const sweeper = setInterval(sweep, 15_000);
|
|
93
|
+
sweeper.unref?.();
|
|
94
|
+
const presence = {
|
|
95
|
+
touch(actor, entry, model, state) {
|
|
96
|
+
if (actor.kind === "public")
|
|
97
|
+
return;
|
|
98
|
+
const actors = here.get(entry) ?? new Map();
|
|
99
|
+
const prev = actors.get(actor.id);
|
|
100
|
+
actors.set(actor.id, { actor: actor.id, kind: actor.kind, state, since: prev?.state === state ? prev.since : new Date().toISOString(), seen: Date.now(), model });
|
|
101
|
+
here.set(entry, actors);
|
|
102
|
+
if (!prev || prev.state !== state)
|
|
103
|
+
announce(entry, model);
|
|
104
|
+
},
|
|
105
|
+
leave(actor, entry) {
|
|
106
|
+
const actors = here.get(entry);
|
|
107
|
+
const prev = actors?.get(actor.id);
|
|
108
|
+
if (!actors || !prev)
|
|
109
|
+
return;
|
|
110
|
+
actors.delete(actor.id);
|
|
111
|
+
if (!actors.size)
|
|
112
|
+
here.delete(entry);
|
|
113
|
+
announce(entry, prev.model);
|
|
114
|
+
},
|
|
115
|
+
list(entry) {
|
|
116
|
+
sweep();
|
|
117
|
+
return [...(here.get(entry)?.values() ?? [])].map(({ seen: _s, model: _m, ...p }) => p);
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
const feed = {
|
|
121
|
+
since: (id = 0) => buffer.filter((e) => e.id > id),
|
|
122
|
+
lastId: () => seq,
|
|
123
|
+
subscribe(fn) {
|
|
124
|
+
subscribers.add(fn);
|
|
125
|
+
return () => subscribers.delete(fn);
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
const addModel = (m, source) => {
|
|
129
|
+
if (!isModel(m))
|
|
130
|
+
throw new Error(`${source} contains something that wasn't made with defineModel()`);
|
|
131
|
+
if (models.has(m.name))
|
|
132
|
+
throw new Error(`Model "${m.name}" is defined twice`);
|
|
133
|
+
models.set(m.name, m);
|
|
134
|
+
};
|
|
135
|
+
const addAction = (a) => {
|
|
136
|
+
if (actions.has(a.name))
|
|
137
|
+
throw new Error(`Action "${a.name}" is defined twice`);
|
|
138
|
+
const clash = [...actions.values()].find((x) => toolName(x.name) === toolName(a.name));
|
|
139
|
+
if (clash)
|
|
140
|
+
throw new Error(`Actions "${clash.name}" and "${a.name}" would share the tool name ${toolName(a.name)}`);
|
|
141
|
+
actions.set(a.name, a);
|
|
142
|
+
};
|
|
143
|
+
const kernel = {
|
|
144
|
+
config,
|
|
145
|
+
store,
|
|
146
|
+
models,
|
|
147
|
+
actions,
|
|
148
|
+
modules,
|
|
149
|
+
defaultLocale: config.locales[0],
|
|
150
|
+
configFile: opts.configFile,
|
|
151
|
+
projectDir: cwd,
|
|
152
|
+
moduleDir(name) {
|
|
153
|
+
const dir = join(dataDir, "modules", name);
|
|
154
|
+
const fs = builtin("node:fs");
|
|
155
|
+
if (!fs)
|
|
156
|
+
throw new Error(`Module "${name}" needs a file system, which this platform doesn't have`);
|
|
157
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
158
|
+
return dir;
|
|
159
|
+
},
|
|
160
|
+
service: (capability) => services.get(capability),
|
|
161
|
+
binding: (name) => binding(name),
|
|
162
|
+
matchRoute(method, path) {
|
|
163
|
+
for (const route of routes) {
|
|
164
|
+
if (route.method !== method && !(method === "HEAD" && route.method === "GET"))
|
|
165
|
+
continue;
|
|
166
|
+
const m = route.regex.exec(path);
|
|
167
|
+
if (m)
|
|
168
|
+
return { route, params: Object.fromEntries(route.keys.map((key, i) => [key, decodeURIComponent(m[i + 1])])) };
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
},
|
|
172
|
+
async installModule(mod) {
|
|
173
|
+
checkModules([...modules, mod]);
|
|
174
|
+
const added = [];
|
|
175
|
+
for (const m of mod.models ?? []) {
|
|
176
|
+
addModel(m, `module "${mod.name}"`);
|
|
177
|
+
added.push(m);
|
|
178
|
+
}
|
|
179
|
+
checkRefs();
|
|
180
|
+
for (const m of added)
|
|
181
|
+
for (const a of modelActions(m))
|
|
182
|
+
addAction(a);
|
|
183
|
+
for (const a of moduleActions(mod))
|
|
184
|
+
addAction(a);
|
|
185
|
+
await store.init(added.map((m) => ({ model: m.name, fields: indexedFields(m) })));
|
|
186
|
+
await register(mod);
|
|
187
|
+
await kernel.emit("module.installed", { module: mod.name });
|
|
188
|
+
},
|
|
189
|
+
async call(name, rawInput, { actor, gate }) {
|
|
190
|
+
const started = Date.now();
|
|
191
|
+
let error;
|
|
192
|
+
const action = actions.get(name);
|
|
193
|
+
try {
|
|
194
|
+
if (!action)
|
|
195
|
+
throw new AicmsError("not_found", `No action "${name}"`);
|
|
196
|
+
if (!action.visible(actor)) {
|
|
197
|
+
throw actor.kind === "public"
|
|
198
|
+
? new AicmsError("unauthorized", `"${name}" needs an agent token`)
|
|
199
|
+
: new AicmsError("forbidden", `${actor.id} may not call "${name}"`);
|
|
200
|
+
}
|
|
201
|
+
const perHour = actor.budget?.actionsPerHour;
|
|
202
|
+
if (perHour) {
|
|
203
|
+
const used = await store.countEvents(actor.id, new Date(Date.now() - 3_600_000).toISOString());
|
|
204
|
+
if (used >= perHour)
|
|
205
|
+
throw new AicmsError("budget", `${actor.id} used its budget of ${perHour} actions per hour. Try again later.`);
|
|
206
|
+
}
|
|
207
|
+
const parsed = action.schema(actor).safeParse(rawInput ?? {});
|
|
208
|
+
if (!parsed.success) {
|
|
209
|
+
const issues = parsed.error.issues.map((i) => ({ field: i.path.join(".") || undefined, message: i.message }));
|
|
210
|
+
const first = issues[0];
|
|
211
|
+
throw new AicmsError("invalid", `Invalid input${first?.field ? ` for "${first.field}"` : ""}: ${first?.message}`, { issues });
|
|
212
|
+
}
|
|
213
|
+
return (await action.run(parsed.data, { actor, gate, kernel }));
|
|
214
|
+
}
|
|
215
|
+
catch (e) {
|
|
216
|
+
error = e instanceof Error ? e.message : String(e);
|
|
217
|
+
throw e;
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
// Anonymous reads and Studio's own page loads would flood the log; everything else is recorded.
|
|
221
|
+
// Presence heartbeats are ephemeral and frequent: never logged, never counted against a budget.
|
|
222
|
+
const quiet = !error && (actor.kind === "public" || name === "cms.presence" || (gate === "studio" && action?.readOnly));
|
|
223
|
+
if (!quiet) {
|
|
224
|
+
let logged;
|
|
225
|
+
try {
|
|
226
|
+
logged = rawInput === undefined ? undefined : JSON.stringify(rawInput).slice(0, 2000);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
logged = undefined;
|
|
230
|
+
}
|
|
231
|
+
const ms = Date.now() - started;
|
|
232
|
+
await store.logEvent({ at: new Date().toISOString(), actor: actor.id, gate, action: name, input: logged, ok: !error, error, ms }).catch(() => { });
|
|
233
|
+
publish("action", { actor: actor.id, gate, action: name, ok: !error, ...(error ? { error } : {}), ms });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
},
|
|
237
|
+
tools(actor) {
|
|
238
|
+
return [...actions.values()]
|
|
239
|
+
.filter((a) => a.visible(actor))
|
|
240
|
+
.map((a) => ({
|
|
241
|
+
name: a.name,
|
|
242
|
+
tool: toolName(a.name),
|
|
243
|
+
description: a.description,
|
|
244
|
+
inputSchema: toJsonSchema(a.advertised?.(actor) ?? a.schema(actor)),
|
|
245
|
+
...(a.readOnly ? { readOnly: true } : {}),
|
|
246
|
+
...(a.destructive ? { destructive: true } : {}),
|
|
247
|
+
}));
|
|
248
|
+
},
|
|
249
|
+
actor(name) {
|
|
250
|
+
if (name === "owner")
|
|
251
|
+
return OWNER;
|
|
252
|
+
if (name === "public")
|
|
253
|
+
return { id: "public", kind: "public", scopes: config.public, review: "human" };
|
|
254
|
+
const agent = config.agents[name];
|
|
255
|
+
if (!agent)
|
|
256
|
+
throw new AicmsError("not_found", `No agent "${name}" in aicms.config. Known agents: ${Object.keys(config.agents).join(", ") || "none"}`);
|
|
257
|
+
return { id: name, kind: "agent", scopes: agent.scopes, review: agent.review ?? "human", budget: agent.budget };
|
|
258
|
+
},
|
|
259
|
+
async resolveToken(token) {
|
|
260
|
+
if (!token)
|
|
261
|
+
return kernel.actor("public");
|
|
262
|
+
if (opts.ownerToken && opts.ownerToken.length >= 24 && sameToken(token, opts.ownerToken))
|
|
263
|
+
return OWNER;
|
|
264
|
+
const row = await store.findToken(hashToken(token), new Date().toISOString());
|
|
265
|
+
if (!row)
|
|
266
|
+
throw new AicmsError("unauthorized", "Invalid, expired or revoked token");
|
|
267
|
+
if (row.kind === "login")
|
|
268
|
+
throw new AicmsError("unauthorized", "This is a one-time Studio sign-in code; open the sign-in link instead");
|
|
269
|
+
try {
|
|
270
|
+
return kernel.actor(row.agent);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
throw new AicmsError("unauthorized", `Agent "${row.agent}" is no longer configured`);
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
async createToken(agent) {
|
|
277
|
+
kernel.actor(agent); // throws for unknown agents
|
|
278
|
+
if (agent === "public")
|
|
279
|
+
throw new AicmsError("invalid", "The public actor doesn't use tokens");
|
|
280
|
+
const token = `aicms_${randomBytes(24).toString("base64url")}`;
|
|
281
|
+
await store.createToken({ id: newId("tk"), agent, hash: hashToken(token), createdAt: new Date().toISOString() });
|
|
282
|
+
return token;
|
|
283
|
+
},
|
|
284
|
+
async createLoginCode() {
|
|
285
|
+
const code = randomBytes(24).toString("base64url");
|
|
286
|
+
const at = new Date();
|
|
287
|
+
await store.createToken({ id: newId("lg"), agent: "owner", hash: hashToken(code), createdAt: at.toISOString(), kind: "login", expiresAt: new Date(at.getTime() + LOGIN_TTL_MS).toISOString() });
|
|
288
|
+
return code;
|
|
289
|
+
},
|
|
290
|
+
async startSession(code) {
|
|
291
|
+
const at = new Date();
|
|
292
|
+
const row = code ? await store.findToken(hashToken(code), at.toISOString()) : null;
|
|
293
|
+
if (!row || row.kind !== "login")
|
|
294
|
+
throw new AicmsError("unauthorized", "This sign-in link is invalid or expired. Run `aicms login` for a new one.");
|
|
295
|
+
// Single use: a second click on the same link fails.
|
|
296
|
+
if (!(await store.revokeToken(row.id, at.toISOString())))
|
|
297
|
+
throw new AicmsError("unauthorized", "This sign-in link was already used");
|
|
298
|
+
const token = `aicms_${randomBytes(24).toString("base64url")}`;
|
|
299
|
+
const expiresAt = new Date(at.getTime() + SESSION_TTL_MS).toISOString();
|
|
300
|
+
await store.createToken({ id: newId("ss"), agent: row.agent, hash: hashToken(token), createdAt: at.toISOString(), kind: "session", expiresAt });
|
|
301
|
+
return { token, expiresAt };
|
|
302
|
+
},
|
|
303
|
+
async endSession(token) {
|
|
304
|
+
const row = await store.findToken(hashToken(token), new Date().toISOString());
|
|
305
|
+
if (row?.kind === "session")
|
|
306
|
+
await store.revokeToken(row.id, new Date().toISOString());
|
|
307
|
+
},
|
|
308
|
+
async revokeAgent(agent) {
|
|
309
|
+
const tokens = await store.revokeTokens(agent, new Date().toISOString());
|
|
310
|
+
const pending = await store.listChangesets({ actor: agent, status: ["open", "submitted", "scheduled"], limit: 1000 });
|
|
311
|
+
for (const cs of pending)
|
|
312
|
+
await rejectChangeset(kernel, cs.id, "owner", "Access revoked", true);
|
|
313
|
+
return { tokens, changesets: pending.length };
|
|
314
|
+
},
|
|
315
|
+
on(event, handler) {
|
|
316
|
+
if (!handlers.has(event))
|
|
317
|
+
handlers.set(event, new Set());
|
|
318
|
+
handlers.get(event).add(handler);
|
|
319
|
+
return () => handlers.get(event)?.delete(handler);
|
|
320
|
+
},
|
|
321
|
+
async emit(event, payload) {
|
|
322
|
+
publish(event, payload);
|
|
323
|
+
for (const h of [...(handlers.get(event) ?? []), ...(handlers.get("*") ?? [])]) {
|
|
324
|
+
try {
|
|
325
|
+
await h(event, payload);
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
console.error(`[aicms] handler for ${event} failed:`, e);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
for (const hook of config.webhooks) {
|
|
332
|
+
if (hook.events && !hook.events.includes(event))
|
|
333
|
+
continue;
|
|
334
|
+
const body = JSON.stringify({ event, payload, at: new Date().toISOString() });
|
|
335
|
+
const headers = { "content-type": "application/json", "x-aicms-event": event };
|
|
336
|
+
if (hook.secret)
|
|
337
|
+
headers["x-aicms-signature"] = `sha256=${createHmac("sha256", hook.secret).update(body).digest("hex")}`;
|
|
338
|
+
const sent = fetch(hook.url, { method: "POST", headers, body, signal: AbortSignal.timeout(5000) }).catch((e) => console.warn(`[aicms] webhook ${hook.url} failed: ${e.message}`));
|
|
339
|
+
opts.waitUntil?.(sent);
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
feed,
|
|
343
|
+
presence,
|
|
344
|
+
async publishDue() {
|
|
345
|
+
// One run at a time: a slow merge must not be picked up twice by the next tick.
|
|
346
|
+
if (publishing)
|
|
347
|
+
return publishing;
|
|
348
|
+
publishing = publishDue(kernel).finally(() => (publishing = null));
|
|
349
|
+
return publishing;
|
|
350
|
+
},
|
|
351
|
+
startScheduler(everyMs = 30_000) {
|
|
352
|
+
const tick = () => 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] scheduler failed:", e));
|
|
353
|
+
const timer = setInterval(tick, everyMs);
|
|
354
|
+
timer.unref?.();
|
|
355
|
+
timers.add(timer);
|
|
356
|
+
void tick();
|
|
357
|
+
return () => {
|
|
358
|
+
clearInterval(timer);
|
|
359
|
+
timers.delete(timer);
|
|
360
|
+
};
|
|
361
|
+
},
|
|
362
|
+
close: async () => {
|
|
363
|
+
clearInterval(sweeper);
|
|
364
|
+
for (const t of timers)
|
|
365
|
+
clearInterval(t);
|
|
366
|
+
await store.close();
|
|
367
|
+
},
|
|
368
|
+
};
|
|
369
|
+
let publishing = null;
|
|
370
|
+
const timers = new Set();
|
|
371
|
+
function checkRefs() {
|
|
372
|
+
for (const m of models.values()) {
|
|
373
|
+
for (const [key, f] of Object.entries(m.fields)) {
|
|
374
|
+
if (f.kind === "ref" && !models.has(f.options.model)) {
|
|
375
|
+
throw new Error(`${m.name}.${key} references model "${f.options.model}", which doesn't exist`);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/** Hooks, routes, services and setup: the parts of a module that live outside the registry. */
|
|
381
|
+
async function register(mod) {
|
|
382
|
+
modules.push(mod);
|
|
383
|
+
const system = { id: `module:${mod.name}`, kind: "system", scopes: ["*"], review: "auto" };
|
|
384
|
+
for (const [event, handler] of Object.entries(mod.on ?? {})) {
|
|
385
|
+
kernel.on(event, (ev, payload) => handler({ event: ev, payload, ctx: moduleContext(kernel, mod, system, "internal") }));
|
|
386
|
+
}
|
|
387
|
+
for (const [key, handler] of Object.entries(mod.routes ?? {})) {
|
|
388
|
+
const route = compileRoute(mod.name, key, handler);
|
|
389
|
+
const clash = routes.find((r) => r.method === route.method && r.path === route.path);
|
|
390
|
+
if (clash)
|
|
391
|
+
throw new Error(`Modules "${clash.module}" and "${mod.name}" both serve ${key}`);
|
|
392
|
+
routes.push(route);
|
|
393
|
+
}
|
|
394
|
+
for (const [cap, impl] of Object.entries(mod.services ?? {}))
|
|
395
|
+
services.set(cap, impl);
|
|
396
|
+
await mod.setup?.(moduleContext(kernel, mod, system, "internal"));
|
|
397
|
+
}
|
|
398
|
+
// ---- assemble the registry ----
|
|
399
|
+
checkModules(config.modules);
|
|
400
|
+
for (const m of config.models)
|
|
401
|
+
addModel(m, "config.models");
|
|
402
|
+
for (const mod of config.modules)
|
|
403
|
+
for (const m of mod.models ?? [])
|
|
404
|
+
addModel(m, `module "${mod.name}"`);
|
|
405
|
+
checkRefs();
|
|
406
|
+
for (const a of coreActions())
|
|
407
|
+
addAction(a);
|
|
408
|
+
for (const m of models.values())
|
|
409
|
+
for (const a of modelActions(m))
|
|
410
|
+
addAction(a);
|
|
411
|
+
for (const mod of config.modules)
|
|
412
|
+
for (const a of moduleActions(mod))
|
|
413
|
+
addAction(a);
|
|
414
|
+
await store.init([...models.values()].map((m) => ({ model: m.name, fields: indexedFields(m) })));
|
|
415
|
+
watchBriefs(kernel);
|
|
416
|
+
for (const mod of config.modules)
|
|
417
|
+
await register(mod);
|
|
418
|
+
return kernel;
|
|
419
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type AnyField } from "../schema/fields.ts";
|
|
2
|
+
import type { RegisteredAction } from "./action.ts";
|
|
3
|
+
/** A field as clients need it to render a form or write valid input. */
|
|
4
|
+
export declare function describeField(name: string, f: AnyField, writable?: boolean): Record<string, unknown>;
|
|
5
|
+
export declare function coreActions(): RegisteredAction[];
|