@reqvire-org/ads 0.3.37 → 0.3.38
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 +3 -1
- package/dist/bootstrap-ds/README.md +2 -2
- package/dist/bootstrap-ds/package.json +1 -1
- package/dist/cli.mjs +9 -1
- package/dist/config.mjs +4 -2
- package/dist/mcp/preview-owner-guard.mjs +7 -4
- package/dist/mcp/preview-widget.bundle.js +46 -47
- package/dist/mcp/project-widget.bundle.js +45 -46
- package/dist/mcp/server.mjs +5 -0
- package/dist/mcp/widget.bundle.js +47 -48
- package/dist/preview-bun.mjs +5 -2
- package/dist/resource-limits.mjs +146 -0
- package/dist/runtime-requirements.mjs +21 -0
- package/dist/scenarios-compiler.mjs +4 -3
- package/dist/showcase/client.bundle.js +56 -57
- package/dist/showcase/sandbox.bundle.js +1 -1
- package/dist/skills/ads-break-ui/SKILL.md +3 -2
- package/dist/skills/ads-break-ui/references/runtimes.md +85 -1
- package/dist/skills/ads-designer/SKILL.md +3 -2
- package/dist/skills/ads-designer/assets/bootstrap-ds/README.md +2 -2
- package/dist/skills/ads-designer/assets/bootstrap-ds/package.json +1 -1
- package/dist/skills/ads-designer/references/cli.md +2 -2
- package/dist/skills/ads-designer/references/runtimes.md +85 -1
- package/dist/skills/ads-import/SKILL.md +3 -2
- package/dist/skills/ads-import/references/cli.md +2 -2
- package/dist/skills/ads-import/references/runtimes.md +85 -1
- package/dist/skills/ads-motion/SKILL.md +3 -2
- package/dist/skills/ads-motion/references/runtimes.md +85 -1
- package/dist/skills/ads-port/SKILL.md +3 -2
- package/dist/skills/ads-port/references/cli.md +2 -2
- package/dist/skills/ads-port/references/runtimes.md +85 -1
- package/dist/verification/browser.mjs +8 -8
- package/docs/CHANGELOG.md +33 -13
- package/docs/GUIDE.md +1 -1
- package/docs/MCP.md +22 -2
- package/package.json +2 -2
package/dist/preview-bun.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { createPreviewResources } from "./preview-resources.mjs";
|
|
|
12
12
|
import { previewSourceRevision } from "./preview-inputs.mjs";
|
|
13
13
|
import { linariaTagResolver } from "./linaria.mjs";
|
|
14
14
|
import {createPreviewImportOptimizer} from "./preview-imports.mjs";
|
|
15
|
+
import { assertBunRuntime } from "./runtime-requirements.mjs";
|
|
15
16
|
|
|
16
17
|
const hash = value => createHash("sha256").update(value).digest("hex");
|
|
17
18
|
const fileHash = file => { try { return hash(readFileSync(file)); } catch { return null; } };
|
|
@@ -44,7 +45,7 @@ function pureClassComposition(code,file){
|
|
|
44
45
|
* Only the current transform for each source file is retained between builds.
|
|
45
46
|
* Publication, source fencing and verification remain the shared scheduler's job. */
|
|
46
47
|
export function createBunPreviewBuilder() {
|
|
47
|
-
|
|
48
|
+
assertBunRuntime();
|
|
48
49
|
const cache = new TransformCacheCollection(), transformed = new Map(), workerResults = new Map();
|
|
49
50
|
let directory, context, previous, closed = false, workerQueue=Promise.resolve();
|
|
50
51
|
const builder = async (entries, options, track, {watched = false, workerEntry, workerAncestors=[], sourceRevision=previewSourceRevision(options)} = {}) => {
|
|
@@ -179,7 +180,9 @@ export function createBunPreviewBuilder() {
|
|
|
179
180
|
build.onLoad({filter:/\.[cm]?[jt]sx?$/},async args=>({contents:await source(args.path,ancestors,args.defer),loader:args.path.endsWith("tsx")?"tsx":args.path.endsWith("jsx")?"jsx":/\.([cm]?ts)$/.test(args.path)?"ts":"js"}));
|
|
180
181
|
}};
|
|
181
182
|
}
|
|
182
|
-
|
|
183
|
+
// The MCP resource loader owns dependency fetching and lazy imports. Bun's
|
|
184
|
+
// HTTP modulepreload table adds self-references that cannot become blob URLs.
|
|
185
|
+
const result=await Bun.build({entrypoints:workerEntry?[workerEntry]:[...mounts.keys()],root:workerEntry?path.dirname(workerEntry):directory,target:"browser",format:workerEntry?"iife":"esm",jsx:{runtime:"automatic",importSource:options.config.framework},splitting:!workerEntry,modulePreload:false,metafile:true,minify:!watched,plugins:[plugin(new Set(workerAncestors))],define:{"process.env.NODE_ENV":JSON.stringify(watched?"development":"production")}});
|
|
183
186
|
if(!result.success)throw buildFailure(result.logs);
|
|
184
187
|
metadata(result);
|
|
185
188
|
if(workerEntry)return{inputs:[...inputs],outputs:await Promise.all(result.outputs.map(async artifact=>({kind:artifact.kind,path:artifact.path,bytes:Buffer.from(await artifact.arrayBuffer()).toString("base64")}))),assets:[...workerAssets.values()].map(asset=>({...asset,source:Buffer.from(asset.source).toString("base64")}))};
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { spawn, execFile } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
const MiB = 1024 * 1024;
|
|
8
|
+
const execute = (command, args) => new Promise(resolve => execFile(command, args, {timeout:5000,windowsHide:true,maxBuffer:8*MiB}, (error, stdout) => resolve(error ? null : stdout)));
|
|
9
|
+
|
|
10
|
+
function hostMemory() {
|
|
11
|
+
let available = os.freemem(), parentLimit = Infinity;
|
|
12
|
+
if (process.platform === "linux") {
|
|
13
|
+
try { available = Number(readFileSync("/proc/meminfo","utf8").match(/^MemAvailable:\s+(\d+)/m)[1])*1024; } catch { /* Use OS free memory. */ }
|
|
14
|
+
try {
|
|
15
|
+
const group = readFileSync("/proc/self/cgroup","utf8").match(/^0::(.*)$/m)[1];
|
|
16
|
+
let folder = path.join("/sys/fs/cgroup", group);
|
|
17
|
+
while(folder.startsWith("/sys/fs/cgroup")) {
|
|
18
|
+
try { const value=readFileSync(path.join(folder,"memory.max"),"utf8").trim(); if(value!=="max")parentLimit=Math.min(parentLimit,Number(value)); } catch { /* Not every ancestor has a memory controller. */ }
|
|
19
|
+
if(folder==="/sys/fs/cgroup")break;folder=path.dirname(folder);
|
|
20
|
+
}
|
|
21
|
+
} catch { /* A watchdog can still enforce the process budget. */ }
|
|
22
|
+
}
|
|
23
|
+
return {totalMb:os.totalmem()/MiB,availableMb:available/MiB,parentLimitMb:parentLimit/MiB};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function resolveMemoryBudget(resources={}, host=hostMemory()) {
|
|
27
|
+
const automatic=Math.max(128,Math.floor(Math.min(6144,host.totalMb/4,Math.max(128,host.availableMb-1024))));
|
|
28
|
+
return Math.max(64,Math.floor(Math.min(resources.memoryLimitMb??automatic,host.parentLimitMb??Infinity)));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function inheritedScope() {
|
|
32
|
+
const folder=process.env.ADS_MEMORY_SCOPE;
|
|
33
|
+
const budget=Number(process.env.ADS_MEMORY_LIMIT_MB);
|
|
34
|
+
return folder&&Number.isInteger(budget)&&budget>=64&&["cgroup","inherited-cgroup","watchdog"].includes(process.env.ADS_MEMORY_ENFORCEMENT)&&path.basename(folder).startsWith("ads-memory-")&&existsSync(folder)?folder:null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function resourceLimitsStatus(resources) {
|
|
38
|
+
const inherited=inheritedScope();
|
|
39
|
+
return {memoryLimitMb:inherited?Number(process.env.ADS_MEMORY_LIMIT_MB):resolveMemoryBudget(resources),
|
|
40
|
+
enforcement:inherited?process.env.ADS_MEMORY_ENFORCEMENT:"host-managed",
|
|
41
|
+
scope:inherited?"ADS command and descendants":"embedding host",hardLimit:!!inherited&&["cgroup","inherited-cgroup"].includes(process.env.ADS_MEMORY_ENFORCEMENT)};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function processes() {
|
|
45
|
+
if(process.platform==="linux") {
|
|
46
|
+
const values=new Map();
|
|
47
|
+
for(const name of readdirSync("/proc"))if(/^\d+$/.test(name))try{
|
|
48
|
+
const text=readFileSync(`/proc/${name}/stat`,"utf8"),fields=text.slice(text.lastIndexOf(")")+2).split(" ");
|
|
49
|
+
values.set(Number(name),{parent:Number(fields[1]),start:fields[19]});
|
|
50
|
+
}catch{/* A process may exit during sampling. */}
|
|
51
|
+
return values;
|
|
52
|
+
}
|
|
53
|
+
const output=process.platform==="win32"
|
|
54
|
+
?await execute("powershell.exe",["-NoProfile","-Command","Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize,CreationDate | ConvertTo-Json -Compress"])
|
|
55
|
+
:await execute("ps",["-axo","pid=,ppid=,rss=,lstart="]);
|
|
56
|
+
if(output===null)throw new Error("Cannot sample process-tree memory.");
|
|
57
|
+
if(process.platform==="win32")return new Map([JSON.parse(output)].flat().map(row=>[row.ProcessId,{parent:row.ParentProcessId,rss:Number(row.WorkingSetSize),start:String(row.CreationDate)}]));
|
|
58
|
+
return new Map(output.trim().split("\n").filter(Boolean).map(line=>{const [pid,parent,rss,...date]=line.trim().split(/\s+/);return[Number(pid),{parent:Number(parent),rss:Number(rss)*1024,start:date.join(" ")}];}));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export async function sampleMemoryTree(pid, owned=new Map()) {
|
|
62
|
+
const current=await processes();
|
|
63
|
+
for(const [id,start]of owned)if(current.get(id)?.start!==start)owned.delete(id);
|
|
64
|
+
if(current.has(pid))owned.set(pid,current.get(pid).start);
|
|
65
|
+
for(let pass=0;pass<100;pass++) {
|
|
66
|
+
const before=owned.size;for(const [id,value]of current)if(owned.has(value.parent))owned.set(id,value.start);
|
|
67
|
+
if(owned.size===before)break;
|
|
68
|
+
}
|
|
69
|
+
let bytes=0;
|
|
70
|
+
for(const id of owned.keys())try{
|
|
71
|
+
bytes+=current.get(id).rss??Number(readFileSync(`/proc/${id}/status`,"utf8").match(/^VmRSS:\s+(\d+)/m)?.[1]??0)*1024;
|
|
72
|
+
}catch{/* An exited process no longer consumes memory. */}
|
|
73
|
+
return {bytes,owned};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Dedicated CLI supervision; embedded APIs retain their host's resource policy. */
|
|
77
|
+
export async function runWithMemoryBudget(command,args,{cwd=process.cwd(),memoryLimitMb,kernel=true}={}) {
|
|
78
|
+
const budget=memoryLimitMb??resolveMemoryBudget();
|
|
79
|
+
if(!Number.isInteger(budget)||budget<64||budget>1048576)throw new Error("A process memory budget must be 64–1048576 MiB.");
|
|
80
|
+
const folder=mkdtempSync(path.join(os.tmpdir(),"ads-memory-")), marker=path.join(folder,"started.json");
|
|
81
|
+
const unit=`ads-memory-${process.pid}-${path.basename(folder).slice(-6)}.scope`;
|
|
82
|
+
let interrupted=false,exceeded=false,monitorError=false,child,guard,observing=false,timer,peak=0;
|
|
83
|
+
const stop=()=>{interrupted=true;guard?.stdin.end("cleanup\n");};
|
|
84
|
+
for(const signal of ["SIGINT","SIGTERM"])process.on(signal,stop);
|
|
85
|
+
async function launch(mode) {
|
|
86
|
+
const enforced=mode==="cgroup";
|
|
87
|
+
let pending="",started=false,done=false;
|
|
88
|
+
const env={...process.env,ADS_MEMORY_SCOPE:folder,ADS_MEMORY_LIMIT_MB:String(budget),ADS_MEMORY_ENFORCEMENT:mode};
|
|
89
|
+
child=spawn(enforced?"systemd-run":command,enforced?["--user","--scope","--quiet",`--unit=${unit}`,"-p",`MemoryMax=${budget}M`,"-p","MemorySwapMax=0","-p","OOMPolicy=kill","--",command,...args]:args,
|
|
90
|
+
{cwd,env,stdio:["inherit","inherit","pipe"],detached:process.platform!=="win32",windowsHide:true});
|
|
91
|
+
const active=child;
|
|
92
|
+
if(child.pid){
|
|
93
|
+
guard=spawn(process.execPath,[fileURLToPath(new URL("./mcp/preview-owner-guard.mjs",import.meta.url)),String(child.pid),"--tree"],{stdio:["pipe","ignore","ignore"],windowsHide:true});
|
|
94
|
+
guard.stdin.on("error",()=>{});
|
|
95
|
+
guard.on("error",()=>{monitorError=true;active.kill("SIGKILL");});
|
|
96
|
+
guard.once("exit",()=>{if(!done&&!interrupted&&!exceeded&&!monitorError){monitorError=true;active.kill("SIGKILL");}});
|
|
97
|
+
if(mode==="watchdog"){
|
|
98
|
+
const owned=new Map();
|
|
99
|
+
timer=setInterval(async()=>{
|
|
100
|
+
if(observing)return;observing=true;
|
|
101
|
+
try{
|
|
102
|
+
const {bytes}=await sampleMemoryTree(active.pid,owned);peak=Math.max(peak,bytes);
|
|
103
|
+
if(bytes>budget*MiB){exceeded=true;guard.stdin.end("kill\n");}
|
|
104
|
+
}catch{monitorError=true;guard.stdin.end("kill\n");}
|
|
105
|
+
finally{observing=false;}
|
|
106
|
+
},200);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function forward(bytes) {
|
|
110
|
+
if(!process.stderr.write(bytes)){active.stderr.pause();process.stderr.once("drain",()=>active.stderr.resume());}
|
|
111
|
+
}
|
|
112
|
+
child.stderr.on("data",bytes=>{
|
|
113
|
+
if(!enforced||started||existsSync(marker)){started=true;if(pending){forward(pending);pending="";}forward(bytes);}
|
|
114
|
+
else pending=(pending+bytes.toString()).slice(-8000);
|
|
115
|
+
});
|
|
116
|
+
const result=await new Promise(resolve=>{child.once("error",error=>resolve({code:1,error}));child.once("close",(code,signal)=>resolve({code:code??(signal?1:0),signal}));});
|
|
117
|
+
done=true;clearInterval(timer);guard?.stdin.end("cleanup\n");
|
|
118
|
+
if(enforced&&!existsSync(marker)&&!interrupted)return null;
|
|
119
|
+
if(pending)forward(pending);
|
|
120
|
+
if(enforced){
|
|
121
|
+
const status=await execute("systemctl",["--user","show",unit,"--property=Result","--value"]);
|
|
122
|
+
exceeded=status?.trim()==="oom-kill";
|
|
123
|
+
await execute("systemctl",["--user","reset-failed",unit]);
|
|
124
|
+
}
|
|
125
|
+
if(exceeded)process.stderr.write(`ADS_MEMORY_LIMIT: ADS command exceeded its ${budget} MiB process-tree memory budget${peak?` (sampled ${Math.ceil(peak/MiB)} MiB RSS)`:""}. This invocation failed; inspect retained results before retrying.\n`);
|
|
126
|
+
if(monitorError)process.stderr.write("ADS_MEMORY_MONITOR_FAILED: resource supervision failed; command stopped.\n");
|
|
127
|
+
return exceeded||monitorError?1:interrupted?0:result.code;
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
const parentLimit=hostMemory().parentLimitMb;
|
|
131
|
+
// A new user scope would move the command out of a caller's existing budget.
|
|
132
|
+
// Preserve finite parent envelopes; add monitoring only for a lower local cap.
|
|
133
|
+
if(kernel&&process.platform==="linux"&&Number.isFinite(parentLimit))return await launch(parentLimit<=budget?"inherited-cgroup":"watchdog");
|
|
134
|
+
if(kernel&&process.platform==="linux") {const result=await launch("cgroup");if(result!==null)return result;}
|
|
135
|
+
return await launch("watchdog");
|
|
136
|
+
}finally{
|
|
137
|
+
clearInterval(timer);for(const signal of ["SIGINT","SIGTERM"])process.removeListener(signal,stop);
|
|
138
|
+
rmSync(folder,{recursive:true,force:true});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function enterMemoryBudget(config,args) {
|
|
143
|
+
const inherited=inheritedScope();
|
|
144
|
+
if(inherited){const file=path.join(inherited,"started.json");if(!existsSync(file))writeFileSync(file,JSON.stringify({pid:process.pid}));return null;}
|
|
145
|
+
return runWithMemoryBudget(process.execPath,[process.argv[1],...args],{memoryLimitMb:resolveMemoryBudget(config.resources)});
|
|
146
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const minimumBunVersion = "1.4.1";
|
|
2
|
+
|
|
3
|
+
export function supportsBunVersion(version) {
|
|
4
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(?:\+[\w.-]+)?$/.exec(version ?? "");
|
|
5
|
+
if (!match) return false;
|
|
6
|
+
const actual = match.slice(1).map(Number), minimum = minimumBunVersion.split(".").map(Number);
|
|
7
|
+
for (let index = 0; index < minimum.length; index++) {
|
|
8
|
+
if (actual[index] !== minimum[index]) return actual[index] > minimum[index];
|
|
9
|
+
}
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function assertBunRuntime(version = process.versions.bun) {
|
|
14
|
+
if (!supportsBunVersion(version)) throw new Error(`ADS requires Bun >=${minimumBunVersion}; ${version ? `running Bun ${version}` : "this process is not running Bun"} (${process.execPath}). Upgrade the Bun executable used to launch ADS. The consuming application can keep its own runtime.`);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// Bun's emulated Node version can stay unchanged across compiler upgrades.
|
|
18
|
+
// Fingerprint both so an upgrade never reuses output from the old bundler.
|
|
19
|
+
export function previewRuntimeFingerprint() {
|
|
20
|
+
return `${process.version}/bun:${process.versions.bun ?? "none"}/${process.platform}/${process.arch}`;
|
|
21
|
+
}
|
|
@@ -12,6 +12,7 @@ import { previewFileIgnored, previewWatchDirectories } from "./preview-files.mjs
|
|
|
12
12
|
import { createScenarioInspector } from "./scenario-inspector.mjs";
|
|
13
13
|
import { configurationFiles } from "./units.mjs";
|
|
14
14
|
import { validationInputFiles } from "./validation-inputs.mjs";
|
|
15
|
+
import { previewRuntimeFingerprint } from "./runtime-requirements.mjs";
|
|
15
16
|
|
|
16
17
|
const digest = value => createHash("sha256").update(value).digest("hex");
|
|
17
18
|
const fileDigest = file => { try { return digest(readFileSync(file)); } catch { return null; } };
|
|
@@ -22,7 +23,7 @@ const cacheVersion = 3, maxCacheBytes = 8 * 1024 * 1024;
|
|
|
22
23
|
export function createPreviewCache(options, compilerFiles = []) {
|
|
23
24
|
const { root } = options;
|
|
24
25
|
const key = file => isInside(import.meta.dirname,file) ? `ads-tool/${path.relative(import.meta.dirname,file)}` : isInside(root,file) ? `project/${path.relative(root,file)}` : file;
|
|
25
|
-
const adapterFiles = [import.meta.filename, ...["preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
|
|
26
|
+
const adapterFiles = [import.meta.filename, ...["runtime-requirements.mjs", "preview-builder.mjs", "preview-workers.mjs", "preview-files.mjs", "preview-inputs.mjs", "preview-resources.mjs", "preview-scope.mjs", "scenario-groups.mjs", "scenario-inspector.mjs", "scenario-registry.mjs", "scenarios-vite.mjs", "linaria.mjs", "linaria/atomic-css.cjs", "linaria/atomic-styled.cjs", "linaria/preserve-values.cjs"].map(file => path.join(import.meta.dirname, file)), ...compilerFiles,
|
|
26
27
|
...["package.json", "package-lock.json", "bun.lock", "bun.lockb", "node_modules/.package-lock.json"].map(file => path.join(root, file))];
|
|
27
28
|
const adapterDigest = () => digest(JSON.stringify(adapterFiles.map(file => [key(file), fileDigest(file)])));
|
|
28
29
|
const loadedAdapter = adapterDigest();
|
|
@@ -38,7 +39,7 @@ export function createPreviewCache(options, compilerFiles = []) {
|
|
|
38
39
|
}
|
|
39
40
|
reload();
|
|
40
41
|
function inputs() {
|
|
41
|
-
const rows = [["project-inputs",previewSourceRevision(options)],["
|
|
42
|
+
const rows = [["project-inputs",previewSourceRevision(options)],["runtime",previewRuntimeFingerprint()]];
|
|
42
43
|
for (const file of compilerFiles) rows.push([key(file), fileDigest(file)]);
|
|
43
44
|
// Tool upgrades invalidate validation even when the project's lockfile is unchanged.
|
|
44
45
|
for (const name of readdirSync(import.meta.dirname).filter(name => name.endsWith(".mjs"))) {
|
|
@@ -78,7 +79,7 @@ export function createPreviewCache(options, compilerFiles = []) {
|
|
|
78
79
|
...compilerInputs(),
|
|
79
80
|
["installed-packages", fileDigest(path.join(root, "node_modules/.package-lock.json"))],
|
|
80
81
|
["scheduler", fileDigest(import.meta.filename)],
|
|
81
|
-
["
|
|
82
|
+
["runtime", previewRuntimeFingerprint()],
|
|
82
83
|
]));
|
|
83
84
|
function reusable(entry, expectedHtml, inspection) {
|
|
84
85
|
const cached = value.entries[entry.id];
|