suppa-mcp-2 1.44.4 → 1.45.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/README.md +16 -3
- package/dist/codeForm/api.js +150 -0
- package/dist/codeForm/typecheck.js +324 -0
- package/dist/codeForm/workspace.js +356 -0
- package/dist/httpClient.js +131 -6
- package/dist/projection.js +18 -3
- package/dist/server.js +49 -3
- package/dist/toolTable.js +1 -1
- package/dist/tools/automation.js +16 -1
- package/dist/tools/docs.js +5 -1
- package/dist/tools/entity.js +16 -6
- package/dist/tools/formCode.js +644 -0
- package/dist/tools/formV2.js +53 -41
- package/dist/tools/forms.js +4 -3
- package/dist/tools/tasks.js +7 -7
- package/package.json +5 -3
- package/skills/suppa-cli/SKILL.md +1 -1
- package/skills/suppa-form-v2/SKILL.md +7 -0
- package/skills/suppa-form-v2/code-form/SOURCE.json +19 -0
- package/skills/suppa-form-v2/code-form/sdk/index.d.ts +55926 -0
- package/skills/suppa-form-v2/references/code-form.md +174 -0
- package/skills/suppa-form-v2/scripts/code-form/code-form-core.mjs +562 -0
- package/skills/writing-suppa-sql/references/language.md +1 -1
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A form's Code Form project mirrored to disk, so the agent edits it with its own file tools — the fb-live
|
|
3
|
+
* workspace (fb-live-mcp 0.4.0 code/workspace.js), fed from the tenant instead of a browser tab.
|
|
4
|
+
*
|
|
5
|
+
* Everything but `src/` is regenerated: the typings the builder's code editor checks against, a tsconfig with
|
|
6
|
+
* the editor's options, and the manifest that remembers what each file held when it was last synchronised with
|
|
7
|
+
* the tenant — the base a push is judged against.
|
|
8
|
+
*/
|
|
9
|
+
import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
11
|
+
export const MANIFEST_PATH = ".suppa-code/manifest.json";
|
|
12
|
+
export const CONFLICTS_DIR = ".suppa-code/conflicts";
|
|
13
|
+
export const SDK_PATH = "node_modules/@suppa/frontend-sdk/index.d.ts";
|
|
14
|
+
export const SDK_PACKAGE_PATH = "node_modules/@suppa/frontend-sdk/package.json";
|
|
15
|
+
export const GLOBALS_PATH = "generated/globals.d.ts";
|
|
16
|
+
export const ENVIRONMENT_PATH = "generated/environment.d.ts";
|
|
17
|
+
export const SHARED_MODULES_PATH = "generated/shared-modules.d.ts";
|
|
18
|
+
export const ENTRY_PATH = "src/index.ts";
|
|
19
|
+
const SRC_DIR = "src";
|
|
20
|
+
const toPosix = (path) => path.split(sep).join("/");
|
|
21
|
+
/** The tenant's own rule (FE useCodeFormFiles TS_PATH_PATTERN), plus every segment a real name: no empty, `.` or `..` one, which the disk would fold away. */
|
|
22
|
+
export function isSourcePath(path) {
|
|
23
|
+
return (typeof path === "string" &&
|
|
24
|
+
/^src\/[\w./-]+\.ts$/.test(path) &&
|
|
25
|
+
path.split("/").every((segment) => segment !== "" && segment !== "." && segment !== ".."));
|
|
26
|
+
}
|
|
27
|
+
/** A host as a folder name: `dev.suppa.me` stays, anything else becomes `_`. */
|
|
28
|
+
export function hostFolder(host) {
|
|
29
|
+
return host.toLowerCase().replace(/[^a-z0-9.-]/g, "_").replace(/^\.+/, "_") || "tenant";
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Where the workspaces live: `dir` > `SUPPA_CODE_WORKSPACE` > `<cwd>/agent-context/suppa-code` when the project
|
|
33
|
+
* has an `agent-context/` folder > `<cwd>/.suppa-code` > `<home>/code` when the working folder cannot be written
|
|
34
|
+
* (a desktop client starts the server in a system folder).
|
|
35
|
+
*/
|
|
36
|
+
export function workspaceRoot(options) {
|
|
37
|
+
if (options.dir)
|
|
38
|
+
return resolve(options.dir);
|
|
39
|
+
if (options.env)
|
|
40
|
+
return resolve(options.env);
|
|
41
|
+
const agentContext = join(options.cwd, "agent-context");
|
|
42
|
+
const local = existsSync(agentContext) ? join(agentContext, "suppa-code") : join(options.cwd, ".suppa-code");
|
|
43
|
+
try {
|
|
44
|
+
mkdirSync(local, { recursive: true });
|
|
45
|
+
// A folder this server made inside someone's project: never committed by accident.
|
|
46
|
+
const ignore = join(local, ".gitignore");
|
|
47
|
+
if (!existsSync(ignore))
|
|
48
|
+
writeFileSync(ignore, "*\n");
|
|
49
|
+
return local;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return join(options.home, "code");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** The folder of one form: `<root>/<host>/form-<id>`. Only a positive integer id reaches the path. */
|
|
56
|
+
export function workspaceDir(root, host, formId) {
|
|
57
|
+
if (!Number.isSafeInteger(formId) || formId <= 0)
|
|
58
|
+
throw new Error(`form_id must be a positive integer, not ${formId}`);
|
|
59
|
+
return join(root, hostFolder(host), `form-${formId}`);
|
|
60
|
+
}
|
|
61
|
+
function walk(dir, base, found) {
|
|
62
|
+
if (!existsSync(dir))
|
|
63
|
+
return;
|
|
64
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
65
|
+
const full = join(dir, entry.name);
|
|
66
|
+
if (entry.isDirectory())
|
|
67
|
+
walk(full, base, found);
|
|
68
|
+
else if (entry.isFile() && entry.name.endsWith(".ts"))
|
|
69
|
+
found[toPosix(relative(base, full))] = readFileSync(full, "utf8");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/** Every `src/**\/*.ts` of the workspace, by its project path (`src/utils/x.ts`). */
|
|
73
|
+
export function readSources(dir) {
|
|
74
|
+
const found = {};
|
|
75
|
+
walk(join(dir, SRC_DIR), dir, found);
|
|
76
|
+
return found;
|
|
77
|
+
}
|
|
78
|
+
export function readManifest(dir) {
|
|
79
|
+
const path = join(dir, MANIFEST_PATH);
|
|
80
|
+
if (!existsSync(path))
|
|
81
|
+
return null;
|
|
82
|
+
try {
|
|
83
|
+
const manifest = JSON.parse(readFileSync(path, "utf8"));
|
|
84
|
+
return manifest?.version === 1 && Number.isSafeInteger(manifest.formId) && manifest.base && typeof manifest.base === "object"
|
|
85
|
+
? manifest
|
|
86
|
+
: null;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Every write of the workspace goes through here, and nothing lands outside `dir`: the file paths come from the tenant. */
|
|
93
|
+
export function writeFile(dir, path, content) {
|
|
94
|
+
const root = resolve(dir);
|
|
95
|
+
const full = resolve(root, path);
|
|
96
|
+
const rel = relative(root, full);
|
|
97
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel))
|
|
98
|
+
throw new Error(`refused to write "${path}" outside the workspace ${root}`);
|
|
99
|
+
mkdirSync(dirname(full), { recursive: true });
|
|
100
|
+
writeFileSync(full, content);
|
|
101
|
+
}
|
|
102
|
+
export function writeManifest(dir, manifest) {
|
|
103
|
+
writeFile(dir, MANIFEST_PATH, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
104
|
+
}
|
|
105
|
+
/** What the agent changed on disk since the last synchronisation: an edited, a new and a deleted file each carry the base it was made over. */
|
|
106
|
+
export function localChanges(dir, manifest) {
|
|
107
|
+
const disk = readSources(dir);
|
|
108
|
+
const changes = [];
|
|
109
|
+
for (const [path, content] of Object.entries(disk)) {
|
|
110
|
+
const base = manifest.base[path] ?? null;
|
|
111
|
+
if (content !== base)
|
|
112
|
+
changes.push({ path, content, base });
|
|
113
|
+
}
|
|
114
|
+
for (const [path, base] of Object.entries(manifest.base)) {
|
|
115
|
+
if (!(path in disk))
|
|
116
|
+
changes.push({ path, content: null, base });
|
|
117
|
+
}
|
|
118
|
+
return changes.sort((a, b) => a.path.localeCompare(b.path));
|
|
119
|
+
}
|
|
120
|
+
/** Edits in `src/` the tenant does not have: the local changes, or — for a folder with sources but no manifest — every file there. */
|
|
121
|
+
export function unsyncedEdits(dir, manifest) {
|
|
122
|
+
if (manifest)
|
|
123
|
+
return localChanges(dir, manifest);
|
|
124
|
+
return Object.entries(readSources(dir)).map(([path, content]) => ({ path, content, base: null }));
|
|
125
|
+
}
|
|
126
|
+
/** The typings, the SDK only when its copy is missing or from another front commit (it is ~7 MB). */
|
|
127
|
+
export function writeTypings(dir, typings) {
|
|
128
|
+
if (typings.sdk) {
|
|
129
|
+
let current = null;
|
|
130
|
+
try {
|
|
131
|
+
current = JSON.parse(readFileSync(join(dir, SDK_PACKAGE_PATH), "utf8"))?.version ?? null;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
current = null;
|
|
135
|
+
}
|
|
136
|
+
const sdkFile = join(dir, SDK_PATH);
|
|
137
|
+
const stale = current !== typings.sdk.stamp || !existsSync(sdkFile) || statSync(sdkFile).size !== statSync(typings.sdk.source).size;
|
|
138
|
+
if (stale) {
|
|
139
|
+
mkdirSync(dirname(sdkFile), { recursive: true });
|
|
140
|
+
copyFileSync(typings.sdk.source, sdkFile);
|
|
141
|
+
writeFile(dir, SDK_PACKAGE_PATH, `${JSON.stringify({ name: "@suppa/frontend-sdk", version: typings.sdk.stamp, types: "index.d.ts" }, null, 2)}\n`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
writeFile(dir, GLOBALS_PATH, typings.globals);
|
|
145
|
+
writeFile(dir, ENVIRONMENT_PATH, typings.environment);
|
|
146
|
+
writeFile(dir, SHARED_MODULES_PATH, typings.sharedModules);
|
|
147
|
+
}
|
|
148
|
+
const README = `# Code Form workspace (suppa-mcp-2)
|
|
149
|
+
|
|
150
|
+
The form's Code Form as the tenant holds its DRAFT — TypeScript against the typed global \`formAPI\`.
|
|
151
|
+
|
|
152
|
+
- Edit \`src/**\` with your own file tools — \`src/index.ts\` is the entry point; files import each other
|
|
153
|
+
relatively, plus type-only imports from \`@suppa/frontend-sdk\`.
|
|
154
|
+
- \`suppa_form_code mode='check'\` type-checks the way the builder's code editor does: the form's elements and
|
|
155
|
+
variables (\`generated/\`), the SDK (\`node_modules/@suppa/frontend-sdk\`), the editor's options (\`tsconfig.json\`).
|
|
156
|
+
- \`suppa_form_code mode='api'\` answers what an element, a type or \`formAPI\` offers — never read the SDK file.
|
|
157
|
+
- \`suppa_push_form_code\` saves your changes into the form's draft (confirm=true); the server builds the
|
|
158
|
+
code on that save and only a clean build runs. Nothing is published.
|
|
159
|
+
- \`suppa_form_code mode='rules'\` — the rules. Everything outside \`src/\` is regenerated; \`.suppa-code/\` is bookkeeping.
|
|
160
|
+
`;
|
|
161
|
+
/**
|
|
162
|
+
* The tenant's files the workspace can hold: a Code Form path, and not one a case-insensitive disk (Windows,
|
|
163
|
+
* macOS) would merge with another — the same path in another case, or a folder of an earlier file spelled in
|
|
164
|
+
* another case (`src/Utils/a.ts` beside `src/utils/b.ts` lands both in one folder, and reads back renamed).
|
|
165
|
+
*/
|
|
166
|
+
export function partitionFiles(files) {
|
|
167
|
+
const accepted = [];
|
|
168
|
+
const skipped = [];
|
|
169
|
+
const seen = new Set();
|
|
170
|
+
const folders = new Map();
|
|
171
|
+
for (const file of files) {
|
|
172
|
+
const path = typeof file?.path === "string" ? file.path : "";
|
|
173
|
+
const folded = path.toLowerCase();
|
|
174
|
+
const dirs = path.split("/").slice(0, -1).map((_, i, parts) => parts.slice(0, i + 1).join("/"));
|
|
175
|
+
const clash = dirs.some((d) => folders.has(d.toLowerCase()) && folders.get(d.toLowerCase()) !== d);
|
|
176
|
+
if (!isSourcePath(file?.path) || typeof file.content !== "string" || seen.has(folded) || clash || folders.has(folded)) {
|
|
177
|
+
skipped.push(String(file?.path));
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
seen.add(folded);
|
|
181
|
+
for (const d of dirs)
|
|
182
|
+
folders.set(d.toLowerCase(), d);
|
|
183
|
+
accepted.push(file);
|
|
184
|
+
}
|
|
185
|
+
return { accepted, skipped };
|
|
186
|
+
}
|
|
187
|
+
/** Files under `src/` a pull would delete that are not Code Form sources (`notes.md`, `x.tsx`, `A.TS`) — the change tracking never sees them. */
|
|
188
|
+
export function strayFiles(dir) {
|
|
189
|
+
const out = [];
|
|
190
|
+
const walkAll = (d) => {
|
|
191
|
+
if (!existsSync(d))
|
|
192
|
+
return;
|
|
193
|
+
for (const entry of readdirSync(d, { withFileTypes: true })) {
|
|
194
|
+
const full = join(d, entry.name);
|
|
195
|
+
if (entry.isDirectory())
|
|
196
|
+
walkAll(full);
|
|
197
|
+
else if (!entry.name.endsWith(".ts"))
|
|
198
|
+
out.push(toPosix(relative(dir, full)));
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
walkAll(join(dir, SRC_DIR));
|
|
202
|
+
return out.sort();
|
|
203
|
+
}
|
|
204
|
+
const originsOf = (files) => {
|
|
205
|
+
const out = {};
|
|
206
|
+
for (const f of files) {
|
|
207
|
+
if (f.origin && typeof f.origin === "object") {
|
|
208
|
+
out[f.path] = { formId: Number.isSafeInteger(f.origin.formId) ? f.origin.formId : null, modified: f.origin.modified === true };
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return Object.keys(out).length ? out : undefined;
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* Replaces the workspace's `src/` with the tenant's files and records them as the new base. The caller has made
|
|
215
|
+
* sure nothing unpushed is lost. The manifest goes FIRST: a pull that fails halfway (a locked file, a path the disk
|
|
216
|
+
* cannot hold) must not leave the old base beside a half-rewritten `src/`, or the next push would send the
|
|
217
|
+
* difference as edits nobody made. Without a manifest a push refuses and a pull needs force. What the disk cannot
|
|
218
|
+
* hold faithfully is skipped and listed; anything else that does not read back as written throws.
|
|
219
|
+
*/
|
|
220
|
+
export function writeWorkspace(dir, pull) {
|
|
221
|
+
const { accepted, skipped } = partitionFiles(pull.files);
|
|
222
|
+
rmSync(join(dir, MANIFEST_PATH), { force: true });
|
|
223
|
+
rmSync(join(dir, SRC_DIR), { recursive: true, force: true });
|
|
224
|
+
rmSync(join(dir, CONFLICTS_DIR), { recursive: true, force: true });
|
|
225
|
+
for (const file of accepted)
|
|
226
|
+
writeFile(dir, file.path, file.content);
|
|
227
|
+
writeTypings(dir, pull.typings);
|
|
228
|
+
writeFile(dir, "tsconfig.json", `${JSON.stringify({ compilerOptions: pull.compilerOptions, include: ["src/**/*.ts", "generated/*.d.ts"] }, null, 2)}\n`);
|
|
229
|
+
writeFile(dir, "README.md", README);
|
|
230
|
+
const origins = originsOf(accepted);
|
|
231
|
+
const manifest = {
|
|
232
|
+
version: 1,
|
|
233
|
+
host: pull.host,
|
|
234
|
+
formId: pull.formId,
|
|
235
|
+
formName: pull.formName,
|
|
236
|
+
revision: pull.revision,
|
|
237
|
+
pulledAt: new Date().toISOString(),
|
|
238
|
+
entry: ENTRY_PATH,
|
|
239
|
+
frontCommit: pull.frontCommit,
|
|
240
|
+
base: Object.fromEntries(accepted.map((file) => [file.path, file.content])),
|
|
241
|
+
...(origins ? { origins } : {}),
|
|
242
|
+
...(skipped.length ? { skipped } : {}),
|
|
243
|
+
};
|
|
244
|
+
const drift = localChanges(dir, manifest);
|
|
245
|
+
if (drift.length) {
|
|
246
|
+
throw new Error(`the workspace did not read back as written (${drift.map((c) => c.path).join(", ")}) — check ${dir} and pull again with force=true`);
|
|
247
|
+
}
|
|
248
|
+
writeManifest(dir, manifest);
|
|
249
|
+
return manifest;
|
|
250
|
+
}
|
|
251
|
+
/** Files where the tenant's draft holds something other than the base: someone saved them since the last pull or push. Skipped paths do not count. */
|
|
252
|
+
export function divergedFiles(current, manifest) {
|
|
253
|
+
const skipped = new Set(manifest.skipped ?? []);
|
|
254
|
+
const tenant = new Map(current.filter((f) => isSourcePath(f.path) && !skipped.has(f.path)).map((f) => [f.path, f.content]));
|
|
255
|
+
const paths = new Set([...tenant.keys(), ...Object.keys(manifest.base)]);
|
|
256
|
+
return [...paths].filter((path) => (tenant.get(path) ?? null) !== (manifest.base[path] ?? null)).sort();
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* After a save: the draft as the save answered it is the new base — AND the disk. A save keeps every file someone
|
|
260
|
+
* else changed, added or deleted since the pull (the PUT carries the tenant's list with only this push's changes
|
|
261
|
+
* applied); those files must reach the disk too, or the next push reads the old disk copies as edits and silently
|
|
262
|
+
* reverts that person's work. Every path this push did not change holds, on disk, exactly the old base (that is
|
|
263
|
+
* what "not changed" means), so overwriting it with the tenant's version loses nothing of the agent's.
|
|
264
|
+
*/
|
|
265
|
+
export function recordPushed(dir, manifest, changes, saved, revision) {
|
|
266
|
+
const { accepted, skipped } = partitionFiles(saved);
|
|
267
|
+
const changed = new Set(changes.map((c) => c.path));
|
|
268
|
+
const tenant = new Map(accepted.map((f) => [f.path, f.content]));
|
|
269
|
+
for (const [path, content] of tenant) {
|
|
270
|
+
if (!changed.has(path))
|
|
271
|
+
writeFile(dir, path, content);
|
|
272
|
+
}
|
|
273
|
+
for (const path of Object.keys(manifest.base)) {
|
|
274
|
+
if (!changed.has(path) && !tenant.has(path))
|
|
275
|
+
rmSync(join(dir, path), { force: true });
|
|
276
|
+
}
|
|
277
|
+
const origins = originsOf(accepted);
|
|
278
|
+
const next = {
|
|
279
|
+
...manifest,
|
|
280
|
+
revision,
|
|
281
|
+
base: Object.fromEntries(tenant),
|
|
282
|
+
};
|
|
283
|
+
delete next.refused;
|
|
284
|
+
if (origins)
|
|
285
|
+
next.origins = origins;
|
|
286
|
+
else
|
|
287
|
+
delete next.origins;
|
|
288
|
+
if (skipped.length)
|
|
289
|
+
next.skipped = skipped;
|
|
290
|
+
else
|
|
291
|
+
delete next.skipped;
|
|
292
|
+
writeManifest(dir, next);
|
|
293
|
+
return next;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* A refused push: the tenant's current version of each conflicting file goes to `.suppa-code/conflicts/<path>`
|
|
297
|
+
* and becomes the base the next push is judged against, and what the agent tried is remembered — pushing exactly
|
|
298
|
+
* that again is a push that did not merge. Returns the conflict files written.
|
|
299
|
+
*/
|
|
300
|
+
export function recordConflicts(dir, manifest, current, conflicts) {
|
|
301
|
+
const tenant = new Map(current.map((f) => [f.path, f.content]));
|
|
302
|
+
const base = { ...manifest.base };
|
|
303
|
+
const refused = { ...(manifest.refused ?? {}) };
|
|
304
|
+
const written = [];
|
|
305
|
+
for (const change of conflicts) {
|
|
306
|
+
refused[change.path] = change.content;
|
|
307
|
+
const theirs = tenant.get(change.path);
|
|
308
|
+
if (typeof theirs !== "string") {
|
|
309
|
+
delete base[change.path];
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
const path = `${CONFLICTS_DIR}/${change.path}`;
|
|
313
|
+
writeFile(dir, path, theirs);
|
|
314
|
+
base[change.path] = theirs;
|
|
315
|
+
written.push(path);
|
|
316
|
+
}
|
|
317
|
+
writeManifest(dir, { ...manifest, base, refused });
|
|
318
|
+
return written;
|
|
319
|
+
}
|
|
320
|
+
/** Changes that repeat what was refused, path for path — pushed again without merging. `overwrite` names the ones meant to replace the other version. */
|
|
321
|
+
export function unmergedConflicts(manifest, changes, overwrite = new Set()) {
|
|
322
|
+
const refused = manifest.refused ?? {};
|
|
323
|
+
return changes.filter((c) => c.path in refused && refused[c.path] === c.content && !overwrite.has(c.path));
|
|
324
|
+
}
|
|
325
|
+
/** Inline files from an agent that cannot reach the workspace folder: written into `src/` first, then pushed like any edit. */
|
|
326
|
+
export function writeInlineSources(dir, files) {
|
|
327
|
+
for (const file of files) {
|
|
328
|
+
if (!isSourcePath(file.path))
|
|
329
|
+
throw new Error(`"${file.path}" is not a Code Form file — files live under src/ and end in .ts`);
|
|
330
|
+
if (file.content === null)
|
|
331
|
+
rmSync(join(dir, file.path), { force: true });
|
|
332
|
+
else
|
|
333
|
+
writeFile(dir, file.path, file.content);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
/** The whole `code` list a save sends: the tenant's current files with the changes applied (the PUT replaces the list). */
|
|
337
|
+
export function applyChanges(current, changes) {
|
|
338
|
+
const byPath = new Map();
|
|
339
|
+
const order = [];
|
|
340
|
+
for (const f of current) {
|
|
341
|
+
if (typeof f?.path !== "string" || typeof f.content !== "string" || byPath.has(f.path))
|
|
342
|
+
continue;
|
|
343
|
+
byPath.set(f.path, f.content);
|
|
344
|
+
order.push(f.path);
|
|
345
|
+
}
|
|
346
|
+
for (const c of changes) {
|
|
347
|
+
if (c.content === null) {
|
|
348
|
+
byPath.delete(c.path);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (!byPath.has(c.path))
|
|
352
|
+
order.push(c.path);
|
|
353
|
+
byPath.set(c.path, c.content);
|
|
354
|
+
}
|
|
355
|
+
return order.filter((p) => byPath.has(p)).map((path) => ({ path, language: "ts", content: byPath.get(path) }));
|
|
356
|
+
}
|
package/dist/httpClient.js
CHANGED
|
@@ -4,7 +4,11 @@
|
|
|
4
4
|
* Faithful 1:1 port of the Python `suppa_mcp/http_client.py`. Uses the native
|
|
5
5
|
* global `fetch` in place of `urllib`, with an AbortController for timeouts.
|
|
6
6
|
*/
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { join } from "node:path";
|
|
7
10
|
import { config } from "./config.js";
|
|
11
|
+
import { homeDir } from "./registry.js";
|
|
8
12
|
import { assertMergeLists, elideEchoedResponse, stripAccessMetadata } from "./utils.js";
|
|
9
13
|
import * as tenants from "./tenants.js";
|
|
10
14
|
import { lastRefreshError } from "./sessionDiag.js";
|
|
@@ -644,21 +648,138 @@ function invalidProjectionPaths(e) {
|
|
|
644
648
|
f.location === "fields")
|
|
645
649
|
.map((f) => f.path);
|
|
646
650
|
}
|
|
651
|
+
// ---------------------------------------------------------------------------
|
|
652
|
+
// A read is checked BEFORE it is sent
|
|
653
|
+
//
|
|
654
|
+
// Every 400 lands in the platform's error log. Learning a tenant's fields from its
|
|
655
|
+
// 400s cost one per process start, per user, per tenant: on 2026-11-10/11 the
|
|
656
|
+
// suppa_get_task / suppa_search_tasks projection (`author` beside `createdBy`)
|
|
657
|
+
// put 79 of them in entity-builder's log from ~10 people, and 53 more came from
|
|
658
|
+
// projections agents wrote themselves (`author { fullName }`, a `name` that does
|
|
659
|
+
// not exist). POST /data/:entity/select/validate answers 200 with the same
|
|
660
|
+
// invalidFields the select would refuse with (entity-builder data.controller.ts,
|
|
661
|
+
// @HttpCode(OK), 1000 calls a minute; the select runs the same validator), so the
|
|
662
|
+
// read is checked there first:
|
|
663
|
+
// - a path of THIS SERVER's projection the tenant lacks is dropped before sending;
|
|
664
|
+
// - anything else invalid — a caller's projection, a filter, an order — is refused
|
|
665
|
+
// here with the platform's own words, and nothing reaches the platform.
|
|
666
|
+
// The verdict is kept per tenant, entity and query SHAPE (paths and comparators,
|
|
667
|
+
// never values): in memory for the process, and for this server's own reads also
|
|
668
|
+
// on disk for a day, so a new process does not ask again.
|
|
669
|
+
// ---------------------------------------------------------------------------
|
|
670
|
+
const READ_CHECK_TTL_MS = 24 * 60 * 60 * 1000;
|
|
671
|
+
/** `sha1(host|entity|shape)` -> the paths the platform's validator rejected (none = valid). */
|
|
672
|
+
const checkedReads = new Map();
|
|
673
|
+
/** The structure of a condition tree without its values: what the validator judges. */
|
|
674
|
+
function conditionShape(node) {
|
|
675
|
+
if (Array.isArray(node))
|
|
676
|
+
return node.map(conditionShape);
|
|
677
|
+
if (node === null || typeof node !== "object")
|
|
678
|
+
return typeof node;
|
|
679
|
+
const o = node;
|
|
680
|
+
if (Array.isArray(o.filters))
|
|
681
|
+
return { operator: o.operator ?? null, filters: o.filters.map(conditionShape) };
|
|
682
|
+
return { field: o.field ?? null, comparator: o.comparator ?? null };
|
|
683
|
+
}
|
|
684
|
+
function readCheckKey(ctx, entity, body) {
|
|
685
|
+
const shape = JSON.stringify({ fields: body.fields ?? null, orderBy: body.orderBy ?? null, conditions: conditionShape(body.conditions ?? null) });
|
|
686
|
+
return createHash("sha1").update(`${ctx.host}|${entity}|${shape}`).digest("hex");
|
|
687
|
+
}
|
|
688
|
+
function readCheckFile(key) {
|
|
689
|
+
return join(homeDir(), "cache", "select-validate", `${key}.json`);
|
|
690
|
+
}
|
|
691
|
+
function loadReadCheck(key) {
|
|
692
|
+
try {
|
|
693
|
+
const file = readCheckFile(key);
|
|
694
|
+
if (Date.now() - statSync(file).mtimeMs > READ_CHECK_TTL_MS)
|
|
695
|
+
return undefined;
|
|
696
|
+
const invalid = JSON.parse(readFileSync(file, "utf-8"));
|
|
697
|
+
return Array.isArray(invalid) ? invalid : undefined;
|
|
698
|
+
}
|
|
699
|
+
catch {
|
|
700
|
+
return undefined; // no verdict on disk, or an unreadable one: ask the validator
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
function saveReadCheck(key, invalid) {
|
|
704
|
+
try {
|
|
705
|
+
const file = readCheckFile(key);
|
|
706
|
+
mkdirSync(join(file, ".."), { recursive: true });
|
|
707
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
708
|
+
writeFileSync(tmp, JSON.stringify(invalid));
|
|
709
|
+
renameSync(tmp, file);
|
|
710
|
+
}
|
|
711
|
+
catch {
|
|
712
|
+
// a verdict that cannot be kept costs one validator call next process, nothing else
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
/** The validator's verdict on a read, or null when it cannot answer (then the read goes as it was). */
|
|
716
|
+
async function validateRead(entity, body, ctx) {
|
|
717
|
+
const check = { fields: body.fields };
|
|
718
|
+
if (body.conditions !== undefined && body.conditions !== null)
|
|
719
|
+
check.conditions = body.conditions;
|
|
720
|
+
if (Array.isArray(body.orderBy) && body.orderBy.length > 0)
|
|
721
|
+
check.orderBy = body.orderBy;
|
|
722
|
+
let answer;
|
|
723
|
+
try {
|
|
724
|
+
// No retry: a validator that is busy or down is skipped, never paid for twice.
|
|
725
|
+
answer = await makeRequest("POST", dataUrl(entity, "select/validate"), check, { ctx, retryTransient: false });
|
|
726
|
+
}
|
|
727
|
+
catch (e) {
|
|
728
|
+
debug(`${entity}: select/validate did not answer (${e instanceof Error ? e.message : String(e)}) — the read goes unchecked`);
|
|
729
|
+
return null;
|
|
730
|
+
}
|
|
731
|
+
if (answer === null || typeof answer !== "object" || Array.isArray(answer))
|
|
732
|
+
return null;
|
|
733
|
+
const list = answer.invalidFields;
|
|
734
|
+
return Array.isArray(list) ? list.filter((f) => Boolean(f) && typeof f === "object") : [];
|
|
735
|
+
}
|
|
736
|
+
/** What the platform would have answered, said here — nothing was sent. */
|
|
737
|
+
function refusedBeforeSending(entity, invalid) {
|
|
738
|
+
const paths = invalid.map((f) => (f.location && f.location !== "fields" ? `${f.path} (${f.location})` : String(f.path))).join(", ");
|
|
739
|
+
return new ApiError(400, "Bad Request", JSON.stringify({
|
|
740
|
+
statusCode: 400,
|
|
741
|
+
code: "request.invalid",
|
|
742
|
+
message: `Select query on ${entity} references invalid fields: ${paths}. Checked with the platform's own ` +
|
|
743
|
+
"validator before sending — nothing was sent. suppa_describe_entity lists the entity's fields.",
|
|
744
|
+
invalidFields: invalid,
|
|
745
|
+
checkedBeforeSending: true,
|
|
746
|
+
}));
|
|
747
|
+
}
|
|
647
748
|
/**
|
|
648
|
-
* POST an entity read,
|
|
749
|
+
* POST an entity read, checked first and trimmed to fit the tenant (see above).
|
|
649
750
|
*
|
|
650
|
-
* The
|
|
651
|
-
*
|
|
652
|
-
*
|
|
751
|
+
* The 400 path below is the safety net for what the check cannot see — a field
|
|
752
|
+
* removed since its verdict was kept, or a validator that did not answer: the
|
|
753
|
+
* platform names the offending paths in its 400, they are dropped, the read is
|
|
754
|
+
* retried once, and the verdict is corrected.
|
|
653
755
|
*/
|
|
654
756
|
async function postEntityRead(entity, path, body, fields, opts = {}) {
|
|
655
757
|
const ctx = opts.ctx ?? tenants.current();
|
|
656
758
|
const own = fields !== null && isOwnProjection(fields);
|
|
759
|
+
const checkKey = readCheckKey(ctx, entity, body);
|
|
760
|
+
let invalid = checkedReads.get(checkKey) ?? (own ? loadReadCheck(checkKey) : undefined);
|
|
761
|
+
if (invalid === undefined) {
|
|
762
|
+
const verdict = await validateRead(entity, body, ctx);
|
|
763
|
+
if (verdict !== null) {
|
|
764
|
+
invalid = verdict;
|
|
765
|
+
if (own)
|
|
766
|
+
saveReadCheck(checkKey, verdict);
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
if (invalid !== undefined)
|
|
770
|
+
checkedReads.set(checkKey, invalid);
|
|
657
771
|
let payload = body;
|
|
772
|
+
if (invalid !== undefined && invalid.length > 0) {
|
|
773
|
+
// Only this server's projection bends: a caller's, a filter or an order is the question asked.
|
|
774
|
+
const refused = own ? invalid.filter((f) => f.location !== "fields") : invalid;
|
|
775
|
+
if (refused.length > 0)
|
|
776
|
+
throw refusedBeforeSending(entity, refused);
|
|
777
|
+
payload = { ...body, fields: withoutPaths(fields, invalid.map((f) => String(f.path))) };
|
|
778
|
+
}
|
|
658
779
|
if (own) {
|
|
659
780
|
const known = rejectedFields.get(rejectKey(ctx, entity));
|
|
660
781
|
if (known && known.size > 0) {
|
|
661
|
-
payload = { ...
|
|
782
|
+
payload = { ...payload, fields: withoutPaths(payload.fields, known) };
|
|
662
783
|
}
|
|
663
784
|
}
|
|
664
785
|
// A projection this server wrote also comes back without the platform's
|
|
@@ -685,8 +806,12 @@ async function postEntityRead(entity, path, body, fields, opts = {}) {
|
|
|
685
806
|
if (known.size === before) {
|
|
686
807
|
throw e; // the retry named the same fields — the problem is elsewhere
|
|
687
808
|
}
|
|
809
|
+
// The kept verdict was wrong (or there was none): correct it, so the next read is checked right.
|
|
810
|
+
const corrected = [...(invalid ?? []), ...bad.map((p) => ({ path: p, location: "fields" }))];
|
|
811
|
+
checkedReads.set(checkKey, corrected);
|
|
812
|
+
saveReadCheck(checkKey, corrected);
|
|
688
813
|
debug(`${entity}: this tenant has no ${bad.join(", ")} — retrying without them`);
|
|
689
|
-
return shaped(await makeRequest("POST", path, { ...
|
|
814
|
+
return shaped(await makeRequest("POST", path, { ...payload, fields: withoutPaths(payload.fields, known) }, opts));
|
|
690
815
|
}
|
|
691
816
|
}
|
|
692
817
|
export async function searchEntity(entity, filters = null, fields = null, limit = 50, offset = 0, orderBy = null, searchValue = "", operator = "and", deletedScope = DEFAULT_DELETED_SCOPE, includeDeletedRelations = DEFAULT_INCLUDE_DELETED_RELATIONS) {
|
package/dist/projection.js
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
* Which field projections belong to THIS SERVER, and how to trim one.
|
|
3
3
|
*
|
|
4
4
|
* A tenant's entities are editable, so a field this server names may simply not
|
|
5
|
-
* be there — `Tasks.author`
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* be there — `Tasks.author` (now gone everywhere, `createdBy` replaced it) once
|
|
6
|
+
* failed every task read with an opaque 400 about a projection the user never
|
|
7
|
+
* chose and could not change. httpClient checks such a read with the platform's
|
|
8
|
+
* validator first and drops the missing paths before sending.
|
|
8
9
|
*
|
|
9
10
|
* A projection tagged here may be trimmed to fit the tenant. One a caller
|
|
10
11
|
* supplied never is: quietly returning everything except what someone asked for
|
|
@@ -20,6 +21,20 @@ export function ownProjection(fields) {
|
|
|
20
21
|
OWN_PROJECTIONS.add(fields);
|
|
21
22
|
return fields;
|
|
22
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* Every projection this server owns, with the entity it reads — what scripts/check-own-projections.mjs checks against
|
|
26
|
+
* a tenant's schema before a release, so a field that does not exist (as `Tasks.author` did) is found by a check, not
|
|
27
|
+
* by a 400 in the platform's log.
|
|
28
|
+
*/
|
|
29
|
+
export const OWN_PROJECTION_REGISTRY = [];
|
|
30
|
+
/** Register named own projections as reads of `entity` (call it right after their declarations). */
|
|
31
|
+
export function registerOwnProjections(entity, named) {
|
|
32
|
+
for (const [name, fields] of Object.entries(named)) {
|
|
33
|
+
if (!OWN_PROJECTIONS.has(fields))
|
|
34
|
+
throw new Error(`${name} is not an own projection — wrap it in ownProjection()`);
|
|
35
|
+
OWN_PROJECTION_REGISTRY.push({ entity, name, fields });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
23
38
|
/** True when `fields` is a projection this server owns. */
|
|
24
39
|
export function isOwnProjection(fields) {
|
|
25
40
|
return OWN_PROJECTIONS.has(fields);
|
package/dist/server.js
CHANGED
|
@@ -17,6 +17,7 @@ import * as customFieldSets from "./tools/customFieldSets.js";
|
|
|
17
17
|
import * as customFieldsAsCode from "./tools/customFieldsAsCode.js";
|
|
18
18
|
import * as entityCode from "./tools/entityCode.js";
|
|
19
19
|
import * as formV2 from "./tools/formV2.js";
|
|
20
|
+
import * as formCode from "./tools/formCode.js";
|
|
20
21
|
import * as formLifecycle from "./tools/formLifecycle.js";
|
|
21
22
|
import * as fieldTypeChange from "./tools/fieldTypeChange.js";
|
|
22
23
|
import { houseRulesDigest } from "./tools/entityCode.js";
|
|
@@ -2458,7 +2459,7 @@ export function buildToolTable() {
|
|
|
2458
2459
|
reg("suppa_get_form", {
|
|
2459
2460
|
description: "Get a form by ID. 2.x: the builder's read — schema, settings, variables, localizations, the\n" +
|
|
2460
2461
|
" Code Form's files (`code`), `revision`; saved to a file, the gate's baseline and a\n" +
|
|
2461
|
-
" suppa_write_form_draft draft. Suppa 1.0: the row's `data
|
|
2462
|
+
" suppa_write_form_draft draft (its code: suppa_form_code). Suppa 1.0: the row's `data`.",
|
|
2462
2463
|
inputSchema: {
|
|
2463
2464
|
form_id: z.number().int(),
|
|
2464
2465
|
version: z.enum(["draft", "published"]).default("draft").describe("2.x: published = what THIS user sees, read-only."),
|
|
@@ -2711,8 +2712,8 @@ export function buildToolTable() {
|
|
|
2711
2712
|
" failed read is how a saved mobile layout and code-form vanish on a call returning 200.\n" +
|
|
2712
2713
|
" Writes schema and settings; `variables` only when the draft lists some — the list is the\n" +
|
|
2713
2714
|
" FULL state (an omitted variable is deleted), so an empty one is never sent and one that\n" +
|
|
2714
|
-
" drops the form's default variable is refused. mobileSchema, code
|
|
2715
|
-
" alias and parent are never sent;
|
|
2715
|
+
" drops the form's default variable is refused. mobileSchema, code (suppa_push_form_code),\n" +
|
|
2716
|
+
" localizations, entity, alias and parent are never sent; `schema.overrides` is preserved.\n\n" +
|
|
2716
2717
|
" Refuses: someone else's lock (lockedBy), another form's file, a child's layer over a root,\n" +
|
|
2717
2718
|
" a merged tree over a child, an emptied form, a published read. The file's `revision` (or\n" +
|
|
2718
2719
|
" expected_revision) guards it: a form that moved is refused, not overwritten.",
|
|
@@ -2736,6 +2737,49 @@ export function buildToolTable() {
|
|
|
2736
2737
|
},
|
|
2737
2738
|
annotations: _MUT,
|
|
2738
2739
|
}, async (a) => text(await formV2.writeFormDraft(a.form_id, a.path, a.confirm ?? false, a.normalize ?? false, a.expected_revision ?? null)));
|
|
2740
|
+
reg("suppa_form_code", {
|
|
2741
|
+
description: "A 2.x form's Code Form (TypeScript against the global formAPI), checked as the builder's code\n" +
|
|
2742
|
+
" editor checks it. rules (once) → pull → api → edit src/** → check → suppa_push_form_code.\n\n" +
|
|
2743
|
+
" rules how form code is written, its traps; topic = one section\n" +
|
|
2744
|
+
" pull the DRAFT's code into a workspace folder with the editor's typings (SDK, this form's\n" +
|
|
2745
|
+
" elements and variables, tsconfig)\n" +
|
|
2746
|
+
" api what code may call: path 'formAPI.elements.<name>' | 'formAPI…', or type\n" +
|
|
2747
|
+
" '<elementType>'; member = one in full, filter = a word. Never read the SDK file\n" +
|
|
2748
|
+
" check tsc as the editor runs it + imports, invented events, the agent's deny list",
|
|
2749
|
+
inputSchema: {
|
|
2750
|
+
mode: z.enum(["rules", "pull", "api", "check"]),
|
|
2751
|
+
form_id: z.number().optional().describe("Forms row id."),
|
|
2752
|
+
dir: z.string().optional().describe("Workspace root (default SUPPA_CODE_WORKSPACE or <project>/.suppa-code)."),
|
|
2753
|
+
path: z.string().optional(),
|
|
2754
|
+
type: z.string().optional(),
|
|
2755
|
+
member: z.string().optional(),
|
|
2756
|
+
filter: z.string().optional(),
|
|
2757
|
+
topic: z.string().optional(),
|
|
2758
|
+
force: z.boolean().optional().describe("pull: discard unsaved workspace edits."),
|
|
2759
|
+
inline: z.boolean().optional().describe("pull: also print the files."),
|
|
2760
|
+
},
|
|
2761
|
+
annotations: _DOWNLOAD,
|
|
2762
|
+
}, async (a) => text(await formCode.formCode(a)));
|
|
2763
|
+
reg("suppa_push_form_code", {
|
|
2764
|
+
description: "Save the workspace's Code Form changes to the form's DRAFT: only `code` (PUT\n" +
|
|
2765
|
+
" /core/forms/:id/schema), revision-guarded, re-read and re-checked first. The server builds it;\n" +
|
|
2766
|
+
" a failed build is reported and the previous build keeps running. Refused: a file someone\n" +
|
|
2767
|
+
" saved since your pull (theirs in .suppa-code/conflicts/), a @shared-import file, type errors\n" +
|
|
2768
|
+
" in changed files, another user's lock. Never publishes.",
|
|
2769
|
+
inputSchema: {
|
|
2770
|
+
form_id: z.number(),
|
|
2771
|
+
dir: z.string().optional(),
|
|
2772
|
+
files: z
|
|
2773
|
+
.array(z.object({ path: z.string(), content: z.string().nullable() }))
|
|
2774
|
+
.max(100)
|
|
2775
|
+
.optional()
|
|
2776
|
+
.describe("Written into src/ first (null deletes)."),
|
|
2777
|
+
overwrite: z.array(z.string()).max(100).optional().describe("Conflicting files to replace on purpose (user agreed)."),
|
|
2778
|
+
allow_errors: z.boolean().optional().describe("Save despite type errors (the vendored SDK lags; say so)."),
|
|
2779
|
+
confirm: z.boolean().default(false).describe("true = save; omitted = the plan."),
|
|
2780
|
+
},
|
|
2781
|
+
annotations: _MUT,
|
|
2782
|
+
}, async (a) => text(await formCode.push(a.form_id, a.dir ?? null, a.files ?? null, a.overwrite ?? null, a.allow_errors === true, a.confirm ?? false)));
|
|
2739
2783
|
reg("suppa_create_form_v2", {
|
|
2740
2784
|
description: "Create a Suppa 2.0 form: the row and its draft in one transaction (POST /core/forms/schema),\n" +
|
|
2741
2785
|
" as the builder does — isFormBuilderV2 stamped. The default variable of a form with an\n" +
|
|
@@ -3105,6 +3149,8 @@ async function healthCheck(deep = true) {
|
|
|
3105
3149
|
form_v2_gate: formV2.skillFile("scripts", "validate-form-schema.mjs") ? "present" : "MISSING",
|
|
3106
3150
|
form_v2_widget_compiler: await formV2.widgetCompilerStatus(),
|
|
3107
3151
|
form_v2_cell_rules: await formV2.cellRulesStatus(),
|
|
3152
|
+
// Loaded: the generators, the SDK file and TypeScript — suppa_form_code needs all three.
|
|
3153
|
+
code_form: await formCode.codeFormStatus(),
|
|
3108
3154
|
entity_code_validator: await entityCode.validatorStatus(),
|
|
3109
3155
|
sql_skill: sqlKb.sqlSkillFile("SKILL.md") && sqlKb.sqlSkillFile("references") ? "present" : "MISSING",
|
|
3110
3156
|
// A path, not "present": the skill is files an agent reads and scripts it runs by path.
|
package/dist/toolTable.js
CHANGED
|
@@ -11,7 +11,7 @@ export const PROFILES = {
|
|
|
11
11
|
// entity-builder canvas — the `schema` COLUMN on the row since 2.1, 57 component
|
|
12
12
|
// types — and share nothing with them.
|
|
13
13
|
forms: ["create_form", "get_form", "list_forms", "update_form", "add_field_to_form", "generate_form_schema", "list_form_field_types", "form_kb", "validate_form_schema",
|
|
14
|
-
"write_form_draft", "create_form_v2", "form_versions", "form_lifecycle"],
|
|
14
|
+
"write_form_draft", "create_form_v2", "form_versions", "form_lifecycle", "form_code", "push_form_code"],
|
|
15
15
|
automation: ["create_automation", "get_automation", "update_automation", "delete_automation", "list_automations", "publish_automation", "unpublish_automation", "list_automation_runs", "get_automation_run", "get_automation_node_schema", "list_automation_node_types"],
|
|
16
16
|
};
|
|
17
17
|
const BY_NAME = new Map();
|