@reqvire-org/ads 0.3.39 → 0.3.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/bun-compiler.mjs +1 -1
  2. package/dist/config.mjs +4 -1
  3. package/dist/investigations.mjs +27 -8
  4. package/dist/mcp/build-status.mjs +27 -16
  5. package/dist/mcp/context.mjs +1 -1
  6. package/dist/mcp/drafts.mjs +1 -1
  7. package/dist/mcp/execution-context.mjs +38 -0
  8. package/dist/mcp/execution-coordinator.mjs +220 -0
  9. package/dist/mcp/execution-results.mjs +107 -48
  10. package/dist/mcp/mutations.mjs +2 -0
  11. package/dist/mcp/preview-widget.bundle.js +2 -2
  12. package/dist/mcp/resource-loader.js +3 -2
  13. package/dist/mcp/server.mjs +42 -13
  14. package/dist/preview-failure.mjs +20 -0
  15. package/dist/preview-resources.mjs +69 -21
  16. package/dist/scenarios-compiler.mjs +7 -6
  17. package/dist/showcase/client.bundle.js +43 -41
  18. package/dist/showcase/index.html +15 -1
  19. package/dist/showcase/preview-state.js +2 -1
  20. package/dist/showcase/style.css +4 -1
  21. package/dist/skills/ads-break-ui/references/behaviors.md +4 -5
  22. package/dist/skills/ads-break-ui/references/evidence.md +12 -8
  23. package/dist/skills/ads-break-ui/references/validation.md +33 -0
  24. package/dist/skills/ads-designer/references/behaviors.md +4 -5
  25. package/dist/skills/ads-designer/references/evidence.md +12 -8
  26. package/dist/skills/ads-designer/references/validation.md +33 -0
  27. package/dist/skills/ads-import/references/behaviors.md +4 -5
  28. package/dist/skills/ads-import/references/evidence.md +12 -8
  29. package/dist/skills/ads-import/references/validation.md +33 -0
  30. package/dist/skills/ads-motion/references/behaviors.md +4 -5
  31. package/dist/skills/ads-motion/references/evidence.md +12 -8
  32. package/dist/skills/ads-motion/references/validation.md +33 -0
  33. package/dist/skills/ads-port/references/behaviors.md +4 -5
  34. package/dist/skills/ads-port/references/evidence.md +12 -8
  35. package/dist/skills/ads-port/references/validation.md +33 -0
  36. package/dist/validation-checks.mjs +6 -2
  37. package/dist/validation.mjs +8 -2
  38. package/dist/verification.mjs +7 -3
  39. package/docs/ARCHITECTURE.md +21 -3
  40. package/docs/CHANGELOG.md +40 -28
  41. package/docs/MCP.md +66 -12
  42. package/docs/plans/execution-coordination.md +57 -0
  43. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { compactAcceptance, compactRow, jsonBytes, resultBudgets, resultPage, resultRecord } from "./result-pages.mjs";
5
5
 
@@ -21,7 +21,7 @@ function outcome(item) {
21
21
  investigation: { unit:item.unit, check:item.check, runId:item.runId, resourceUri:investigation?.resourceUri } };
22
22
  }
23
23
 
24
- function snapshot(kind, raw) {
24
+ function snapshot(kind, raw, resultId = randomUUID()) {
25
25
  const outcomes = raw.results ?? raw.behavior?.results ?? (raw.checks ?? []).flatMap(check => check.results ?? []);
26
26
  const sections = {
27
27
  outcomes: outcomes.map(outcome),
@@ -30,13 +30,12 @@ function snapshot(kind, raw) {
30
30
  captures: raw.screenshots?.captures ?? [], selection: [{unit:raw.unit,units:raw.units,transaction:raw.transaction,...raw.selection}],
31
31
  acceptance: raw.acceptance ? [raw.acceptance] : [], investigation: raw.investigation ? [raw.investigation] : [],
32
32
  };
33
- const resultId = randomUUID();
34
33
  return { schemaVersion: 1, resultId, kind, createdAt: new Date().toISOString(), ok: !!raw.ok,
35
34
  ...(raw.applied !== undefined ? { applied: raw.applied } : {}), ...(raw.unit ? { unit: raw.unit } : {}),
36
35
  ...(raw.units ? { units: raw.units } : {}), ...(raw.transaction ? { transaction: true } : {}),
37
36
  ...(raw.draft ? {draft:raw.draft,draftRevision:raw.revision,draftEvent:raw.event?{id:raw.event.id,state:raw.event.state}:null,updatedDependents:raw.updatedDependents??[]} : {}),
38
37
  ...(kind === "validation" ? {policy:raw.policy,scope:raw.scope,requestedScope:raw.requestedScope,sourceRevision:raw.sourceRevision,current:raw.current,elapsedMs:raw.elapsedMs,...(raw.fallback?{fallback:raw.fallback}:{})} : {}),
39
- acceptance: raw.acceptance, investigation: raw.investigation,
38
+ acceptance: raw.acceptance, investigation: raw.investigation, execution:raw.execution,
40
39
  sections: Object.fromEntries(Object.entries(sections).map(([key, rows]) => [key, rows.map((row, recordIndex) => ({ recordIndex, ...(row && typeof row === "object" ? row : {message:row}) }))])),
41
40
  counts: { outcomes: count(outcomes), checks: count(sections.checks), diagnostics: sections.diagnostics.length,
42
41
  advisories: sections.advisories.length, warnings: sections.warnings.length, changes: sections.changes.length, captures: sections.captures.length },
@@ -53,6 +52,7 @@ function summary(value, storageWarning) {
53
52
  ...(value.draft?{draft:value.draft,draftRevision:value.draftRevision,draftEvent:value.draftEvent,updatedDependentCount:value.updatedDependents.length}:{}),
54
53
  acceptance: compactAcceptance(value.acceptance), failures: value.failurePreview ?? failureRows.slice(0, 3).map(item => compactRow({recordIndex:item.recordIndex,unit:item.unit,check:item.check,status:item.status,rule:item.rule,file:item.file,failure:item.failure,message:item.message},640)),
55
54
  failureCount: value.failureCount ?? failureRows.length, resourceUri,
55
+ ...(value.execution?{execution:compactRow(value.execution,1100)}:{}),
56
56
  next: value.detailsUnavailable ? null : { tool: "ads_results", arguments: { resultId, section, ...(section === "outcomes" && failedOutcomes.length ? { status: "not_passed" } : {}) } },
57
57
  ...((storageWarning ?? value.storageWarning) ? { storageWarning: storageWarning ?? value.storageWarning } : {}), byteLimit: resultBudgets.summary };
58
58
  if (jsonBytes(result) > resultBudgets.summary) {
@@ -70,60 +70,119 @@ function summary(value, storageWarning) {
70
70
  return result;
71
71
  }
72
72
 
73
- /** One immutable, replaceable snapshot per execution kind. No result history. */
74
- export function createExecutionResults(root) {
73
+ export const defaultResultRetention = {maxRuns:50,maxAgeDays:7,maxBytesMb:256};
74
+ /** Immutable run snapshots plus bounded latest indexes; no history lives in heap. */
75
+ export function createExecutionResults(root,{retention=()=>defaultResultRetention}={}) {
75
76
  root = path.resolve(root);
76
- const folder = path.join(root, ".ds/tool-results"), memory = new Map();
77
- function file(kind) { return path.join(folder, `${kind}.json`); }
77
+ const folder = path.join(root, ".ds/tool-results"), history=path.join(folder,"runs"),memory=new Map();
78
+ let collection={overBudget:false};
79
+ const settings=()=>({...defaultResultRetention,...(typeof retention==="function"?retention():retention)});
80
+ const file=kind=>path.join(folder,`${kind}.json`);
81
+ function readJson(target,limit=maxStoredBytes) {
82
+ try {const stat=lstatSync(target);if(realpathSync(target)!==target||!stat.isFile()||stat.nlink!==1||stat.size>limit)return undefined;return JSON.parse(readFileSync(target,"utf8"));}catch{return undefined;}
83
+ }
84
+ function atomic(target,value) {
85
+ let ancestor=path.dirname(target);
86
+ while(!existsSync(ancestor))ancestor=path.dirname(ancestor);
87
+ if(realpathSync(ancestor)!==ancestor)throw new Error("Result output cannot resolve through a symlink.");
88
+ mkdirSync(path.dirname(target),{recursive:true});
89
+ if(realpathSync(path.dirname(target))!==path.dirname(target))throw new Error("Result output cannot resolve through a symlink.");
90
+ const staged=`${target}.${randomUUID()}.tmp`;
91
+ try {writeFileSync(staged,JSON.stringify(value));renameSync(staged,target);}finally{rmSync(staged,{force:true});}
92
+ }
93
+ function entries(){
94
+ const rows=readJson(path.join(folder,"index.json"),4*1024*1024)?.entries;
95
+ return Array.isArray(rows)?rows.filter(row=>row&&uuid(row.resultId)&&kinds.includes(row.kind)&&Number.isFinite(Date.parse(row.createdAt))&&Number.isSafeInteger(row.bytes)&&row.bytes>=0).map(row=>({...row,owned:Array.isArray(row.owned)?row.owned.filter(file=>typeof file==="string"&&/^\.ds\/(?:verification|investigation-runs)\/[a-f0-9-]{36}(?:\.json)?$/.test(file)):[]})):[];
96
+ }
97
+ function valid(value){return value?.schemaVersion===1&&kinds.includes(value.kind)&&uuid(value.resultId)&&resultSections.every(section=>Array.isArray(value.sections?.[section]));}
78
98
  function read(kind) {
79
- const temporary = memory.get(kind);
80
- if (temporary?.memoryOnly) return temporary.value;
81
- const target = file(kind);
82
- try {
83
- if (realpathSync(target) !== target || !lstatSync(target).isFile() || lstatSync(target).nlink !== 1 || lstatSync(target).size > maxStoredBytes) return undefined;
84
- const value = JSON.parse(readFileSync(target, "utf8"));
85
- return value.schemaVersion === 1 && value.kind === kind && uuid(value.resultId) && resultSections.every(section => Array.isArray(value.sections?.[section])) ? value : undefined;
86
- } catch { return undefined; }
99
+ const pending=memory.get(kind);if(pending?.memoryOnly)return pending.value;
100
+ const value=readJson(file(kind));return valid(value)?value:undefined;
87
101
  }
88
102
  function find(resultId) {
89
- if (!uuid(resultId)) throw new Error("Use an exact resultId returned by an execution summary.");
90
- const value = kinds.map(read).find(value => value?.resultId === resultId);
91
- if (!value) throw new Error("Result is unavailable or superseded. Only the latest completed result of each kind is retained; discover its ID with ads_status.");
92
- return value;
103
+ if(!uuid(resultId))throw new Error("Use an exact resultId returned by an execution summary.");
104
+ const value=readJson(path.join(history,`${resultId}.json`))??kinds.map(read).find(value=>value?.resultId===resultId);
105
+ if(valid(value))return value;
106
+ if((readJson(path.join(folder,"expired.json"))?.ids??[]).includes(resultId))throw Object.assign(new Error("Execution result expired under this project's retention policy."),{code:"ADS_RESULT_EXPIRED"});
107
+ throw Object.assign(new Error("Execution result is unavailable. Use an exact retained run/result ID."),{code:"ADS_RESULT_UNAVAILABLE"});
108
+ }
109
+ function bytes(directory) {
110
+ try {const stat=lstatSync(directory);if(stat.isSymbolicLink())return 0;if(stat.isFile())return stat.size;if(!stat.isDirectory())return 0;return readdirSync(directory).reduce((n,name)=>n+bytes(path.join(directory,name)),0);}catch{return 0;}
111
+ }
112
+ function removeOwned(relative) {
113
+ if(typeof relative!=="string"||!/^\.ds\/(?:verification|investigation-runs)\/[a-f0-9-]{36}(?:\.json)?$/.test(relative))return;
114
+ const target=path.join(root,relative);
115
+ try {if(realpathSync(target)===target)rmSync(target,{recursive:true,force:true});}catch{/* Already collected. */}
93
116
  }
94
117
  return {
95
- save(kind, raw) {
96
- if (!kinds.includes(kind)) throw new Error("Unknown execution kind.");
97
- const value = snapshot(kind, raw);
98
- let content = JSON.stringify(value);
99
- if (Buffer.byteLength(content) > maxStoredBytes) {
100
- const preview=summary(value);
101
- value.failurePreview=preview.failures;value.failureCount=preview.failureCount;
102
- value.sections=Object.fromEntries(resultSections.map(section=>[section,[]]));
103
- value.acceptance=preview.acceptance;delete value.investigation;
104
- value.detailsUnavailable=true;
105
- value.storageWarning="Result details exceeded the 8 MiB retention limit. Only this summary is retained; execution and applied state above are unchanged.";
106
- content=JSON.stringify(value);
118
+ has(id){try{find(id);return true;}catch{return false;}},
119
+ save(kind,raw,{resultId=randomUUID()}={}) {
120
+ if(!kinds.includes(kind)||!uuid(resultId))throw new Error("Unknown execution kind or invalid result ID.");
121
+ if(this.has(resultId))throw new Error("Execution result IDs are immutable.");
122
+ const value=snapshot(kind,raw,resultId);
123
+ if(Buffer.byteLength(JSON.stringify(value))>maxStoredBytes){
124
+ const preview=summary(value);value.failurePreview=preview.failures;value.failureCount=preview.failureCount;
125
+ value.sections=Object.fromEntries(resultSections.map(section=>[section,[]]));value.acceptance=preview.acceptance;delete value.investigation;
126
+ value.detailsUnavailable=true;value.storageWarning="Result details exceeded the 8 MiB retention limit. Only this summary is retained; execution and applied state above are unchanged.";
107
127
  }
128
+ const outcomes=raw.results??raw.behavior?.results??(raw.checks??[]).flatMap(check=>check.results??[]);
129
+ const owned=[...new Set([...(raw.execution?.artifacts??[]).filter(file=>/^\.ds\/verification\/[a-f0-9-]{36}$/.test(file)),...outcomes.flatMap(row=>[...(uuid(row.runId)?[`.ds/investigation-runs/${row.runId}.json`]:[]),...(typeof row.report==="string"&&/^\.ds\/verification\/[a-f0-9-]{36}\//.test(row.report)?[row.report.split("/").slice(0,3).join("/")]:[])])])];
108
130
  let storageWarning;
109
- try {
110
- let ancestor=folder;
111
- while(true){try{lstatSync(ancestor);break;}catch(error){if(error.code!=="ENOENT")throw error;ancestor=path.dirname(ancestor);}}
112
- if(realpathSync(ancestor)!==ancestor)throw new Error("Result output cannot resolve through a symlink.");
113
- mkdirSync(folder, { recursive: true });
114
- if (realpathSync(folder) !== folder) throw new Error("Result output cannot resolve through a symlink.");
115
- const staged = `${file(kind)}.${randomUUID()}.tmp`;
116
- try { writeFileSync(staged, content); renameSync(staged, file(kind)); } finally { rmSync(staged, { force: true }); }
117
- memory.set(kind, { value, memoryOnly: false });
118
- } catch {
119
- memory.set(kind, { value: JSON.parse(content), memoryOnly: true });
120
- storageWarning = "Result details are available in this server's memory only; storage failed. Execution and applied state above are unchanged.";
131
+ try{
132
+ atomic(path.join(history,`${resultId}.json`),value);atomic(file(kind),value);
133
+ atomic(path.join(folder,"index.json"),{schemaVersion:1,entries:[...entries(),{resultId,kind,createdAt:value.createdAt,owned,bytes:Buffer.byteLength(JSON.stringify(value))}]});
134
+ memory.set(kind,{memoryOnly:false});
135
+ }catch{
136
+ memory.set(kind,{value,memoryOnly:true});storageWarning="Result details are available in this server's memory only; storage failed. Execution and applied state above are unchanged.";
137
+ }
138
+ return summary(value,storageWarning);
139
+ },
140
+ latest(kind){const value=read(kind);return value?summary(value,memory.get(kind)?.memoryOnly?"Result details are in server memory only.":undefined):null;},
141
+ retentionStatus(){return {...settings(),...collection};},
142
+ collect({protectedIds=[]}={}) {
143
+ if(existsSync(history)&&realpathSync(history)!==history)throw new Error("Result archive cannot resolve through a symlink.");
144
+ const policy=settings(),protectedSet=new Set(protectedIds),all=entries().reverse().sort((a,b)=>Number(protectedSet.has(b.resultId))-Number(protectedSet.has(a.resultId))||b.createdAt.localeCompare(a.createdAt));
145
+ const kept=[],removed=[];let used=0;
146
+ for(const entry of all){
147
+ const size=entry.bytes+(entry.owned??[]).reduce((n,item)=>n+bytes(path.join(root,item)),0);
148
+ const expired=Date.now()-Date.parse(entry.createdAt)>policy.maxAgeDays*86400000;
149
+ if(!protectedSet.has(entry.resultId)&&(expired||kept.length>=policy.maxRuns||used+size>policy.maxBytesMb*1024*1024)){removed.push(entry);continue;}
150
+ kept.push(entry);used+=size;
151
+ }
152
+ const retainedOwned=new Set(kept.flatMap(entry=>entry.owned??[]));
153
+ if(removed.length){
154
+ const expired=readJson(path.join(folder,"expired.json"))?.ids??[];
155
+ atomic(path.join(folder,"expired.json"),{ids:[...new Set([...expired,...removed.map(entry=>entry.resultId)])].slice(-4096)});
156
+ for(const entry of removed){
157
+ rmSync(path.join(history,`${entry.resultId}.json`),{force:true});
158
+ const journal=path.join(root,".ds/execution-runs",`${entry.resultId}.json`);
159
+ if(!protectedSet.has(entry.resultId)&&(!existsSync(journal)||realpathSync(journal)===journal))rmSync(journal,{force:true});
160
+ rmSync(path.join(root,".ds/execution-runs",`${entry.resultId}.baseline.json`),{force:true});
161
+ for(const owned of entry.owned??[])if(!retainedOwned.has(owned))removeOwned(owned);
162
+ if(read(entry.kind)?.resultId===entry.resultId){const next=kept.find(item=>item.kind===entry.kind);const value=next&&readJson(path.join(history,`${next.resultId}.json`));if(value)atomic(file(entry.kind),value);else rmSync(file(entry.kind),{force:true});}
163
+ }
164
+ const index=path.join(root,".ds/investigations.json"),investigations=readJson(index,2*1024*1024);
165
+ if(investigations?.bundles){
166
+ const expiredRuns=new Set(removed.flatMap(entry=>entry.owned??[]).filter(item=>item.startsWith(".ds/investigation-runs/")&&!retainedOwned.has(item)).map(item=>path.basename(item,".json")));
167
+ investigations.bundles=Object.fromEntries(Object.entries(investigations.bundles).filter(([,value])=>!expiredRuns.has(value.runId)));
168
+ atomic(index,investigations);
169
+ }
170
+ atomic(path.join(folder,"index.json"),{schemaVersion:1,entries:kept});
171
+ }
172
+ // Orphan reports from abandoned executions are collected only after the age
173
+ // window and while no run is active. Never inspect arbitrary temp folders.
174
+ if(!protectedIds.length){
175
+ const reports=path.join(root,".ds/verification");
176
+ if(existsSync(reports)&&realpathSync(reports)===reports)for(const name of readdirSync(reports)){
177
+ const rel=`.ds/verification/${name}`,target=path.join(root,rel);
178
+ if(uuid(name)&&!retainedOwned.has(rel)&&Date.now()-lstatSync(target).mtimeMs>policy.maxAgeDays*86400000)removeOwned(rel);
179
+ }
121
180
  }
122
- return summary(value, storageWarning);
181
+ collection={retainedRuns:kept.length,retainedBytes:used,overBudget:used>policy.maxBytesMb*1024*1024||kept.length>policy.maxRuns};
182
+ return collection;
123
183
  },
124
- latest(kind) { const value = read(kind); return value ? summary(value, memory.get(kind)?.memoryOnly ? "Result details are in server memory only." : undefined) : null; },
125
- index() { return { retention: "latest-per-kind", results: kinds.map(kind => this.latest(kind)).filter(Boolean).map(({resultId,kind,ok,applied,createdAt,counts,resourceUri})=>({resultId,kind,ok,applied,createdAt,counts,resourceUri})) }; },
126
- fingerprint() { return kinds.map(kind=>{if(memory.get(kind)?.memoryOnly)return memory.get(kind).value.resultId;try{const stat=lstatSync(file(kind));return `${kind}:${stat.mtimeMs}:${stat.size}`;}catch{return `${kind}:missing`;}}).join("\n"); },
184
+ index(){return {retention:"bounded-runs",...this.retentionStatus(),results:kinds.map(kind=>this.latest(kind)).filter(Boolean).map(({resultId,kind,ok,applied,createdAt,counts,resourceUri})=>({resultId,kind,ok,applied,createdAt,counts,resourceUri}))};},
185
+ fingerprint(){return [...kinds.map(kind=>read(kind)?.resultId??`${kind}:missing`),...entries().map(entry=>entry.resultId)].join("\n");},
127
186
  page({ resultId, section = "outcomes", status = "all", cursor, limit, recordIndex, offset, chars } = {}) {
128
187
  const value = find(resultId);
129
188
  if(value.detailsUnavailable)throw new Error("This result exceeded the 8 MiB retention limit; only its summary is available.");
@@ -1,3 +1,4 @@
1
+ import { trackExecutionWorkspace } from "./execution-context.mjs";
1
2
  import { createHash, randomUUID } from "node:crypto";
2
3
  import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
4
  import path from "node:path";
@@ -199,6 +200,7 @@ export function createMutationController(directory, { captures = createCaptureCo
199
200
  mkdirSync(cache, { recursive: true });
200
201
  if (realpathSync(cache) !== path.join(realpathSync(root), ".ds")) throw fail("mutation-path", "The .ds directory cannot resolve through a symlink.");
201
202
  temporary = mkdtempSync(path.join(cache, "mutation-"));
203
+ trackExecutionWorkspace(temporary);
202
204
  const candidate = path.join(temporary, "project");
203
205
  mkdirSync(candidate);
204
206
  const patchPaths=plans.flatMap(plan=>plan.entries.map(entry=>entry.path));
@@ -103,10 +103,10 @@ Boolean requesting whether a visible border and background is provided by the ho
103
103
  - omitted: host decides border`)}),zz=l({method:u("ui/request-display-mode"),params:l({mode:Ks.describe("The display mode being requested.")})}),g_=l({mode:Ks.describe("The display mode that was actually set. May differ from requested if not supported.")}).passthrough(),S_=v([u("model"),u("app")]).describe("Tool visibility scope - who can access the tool."),wz=l({resourceUri:s().optional(),visibility:h(S_).optional().describe(`Who can access this tool. Default: ["model", "app"]
104
104
  - "model": Tool visible to and callable by the agent
105
105
  - "app": Tool callable by the app from this server only`),csp:Oc().optional(),permissions:Oc().optional()}),Rz=l({mimeTypes:h(s()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),xz=l({method:u("ui/download-file"),params:l({contents:h(v([Zt,Dt])).describe("Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.")})}),Pz=l({method:u("ui/message"),params:l({role:u("user").describe('Message role, currently only "user" is supported.'),content:h(Ce).describe("Message content blocks (text, image, etc.).")})}),Tz=l({method:u("ui/notifications/sandbox-resource-ready"),params:l({html:s().describe("HTML content to load into the inner iframe."),sandbox:s().optional().describe("Optional override for the inner iframe's sandbox attribute."),csp:rl.optional().describe("CSP configuration from resource metadata."),permissions:nl.optional().describe("Sandbox permissions from resource metadata.")})}),__=l({method:u("ui/notifications/tool-result"),params:at.describe("Standard MCP tool execution result.")}),zm=l({toolInfo:l({id:Re.optional().describe("JSON-RPC id of the tools/call request."),tool:it.describe("Tool definition including name, inputSchema, etc.")}).optional().describe("Metadata of the tool call that instantiated this App."),theme:t_.optional().describe("Current color theme preference."),styles:d_.optional().describe("Style configuration for theming the app."),displayMode:Ks.optional().describe("How the UI is currently displayed."),availableDisplayModes:h(Ks).optional().describe("Display modes the host supports."),containerDimensions:v([l({height:_().describe("Fixed container height in pixels.")}),l({maxHeight:v([_(),Ic()]).optional().describe("Maximum container height in pixels.")})]).and(v([l({width:_().describe("Fixed container width in pixels.")}),l({maxWidth:v([_(),Ic()]).optional().describe("Maximum container width in pixels.")})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
106
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s().optional().describe("User's timezone in IANA format."),userAgent:s().optional().describe("Host application identifier."),platform:v([u("web"),u("desktop"),u("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:l({touch:z().optional().describe("Whether the device supports touch input."),hover:z().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:l({top:_().describe("Top safe area inset in pixels."),right:_().describe("Right safe area inset in pixels."),bottom:_().describe("Bottom safe area inset in pixels."),left:_().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),y_=l({method:u("ui/notifications/host-context-changed"),params:zm.describe("Partial context update containing only changed fields.")}),Ez=l({method:u("ui/update-model-context"),params:l({content:h(Ce).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:b(s(),P().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),kz=l({method:u("ui/initialize"),params:l({appInfo:ke.describe("App identification (name and version)."),appCapabilities:f_.describe("Features and capabilities this app provides."),protocolVersion:s().describe("Protocol version this app supports.")})}),b_=l({protocolVersion:s().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ke.describe("Host application identification and version."),hostCapabilities:m_.describe("Features and capabilities provided by the host."),hostContext:zm.describe("Rich context about the host environment.")}).passthrough(),v_={target:"draft-2020-12"};async function Sm(e,t){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[t](v_);throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function _m(e,t,o=""){let r=await e["~standard"].validate(t);if(r.issues){let n=r.issues.map((i)=>{let a=i.path?.map((c)=>typeof c==="object"?c.key:c).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(o+n)}return r.value}function z_(e,t){let o={...e,...t};if(t.experimental!==void 0)o.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)o.tools={...e.tools,...t.tools};return o}class va extends ol{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new ym;_methods=new bm;setRequestHandler=(...e)=>{let[t,...o]=fm("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...o)};setNotificationHandler=(...e)=>{let[t,...o]=fm("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...o)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:a_,toolinputpartial:c_,toolresult:__,toolcancelled:l_,hostcontextchanged:y_};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!va.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>{let r=o;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...r};this._events.dispatch(e,r)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,o){if(t&&o)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},o={autoResize:!0}){super(o);if(this._appInfo=e,this._appCapabilities=t,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval)le({jitless:!0});this.replaceRequestHandler("ping",(r)=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=z_(this._appCapabilities,e)}registerTool(e,t,o){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,n=()=>{if(r._initializedSent&&r._appCapabilities.tools?.listChanged)r.sendToolListChanged()},i=t.inputSchema!==void 0,a={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){if(r._registeredTools[e]!==a)return;delete r._registeredTools[e],n()},handler:async(c,d)=>{if(!a.enabled)throw Error(`Tool ${e} is disabled`);let p;if(i){let m=a.inputSchema,f=m?await _m(m,c??{},`Invalid input for tool ${e}: `):c??{};p=await o(f,d)}else p=await o(d);if(a.outputSchema&&!p.isError)p.structuredContent=await _m(a.outputSchema,p.structuredContent,`Invalid output for tool ${e}: `);return p}};if(this._registeredTools[e]=a,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let o=this._registeredTools[e.name];if(!o)throw Error(`Tool ${e.name} not found`);return o.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await Sm(r.inputSchema,"input"):{type:"object",properties:{}}};if(r.outputSchema)n.outputSchema=await Sm(r.outputSchema,"output");if(r.annotations)n.annotations=r.annotations;if(r._meta)n._meta=r._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:p_.shape.params,result:h_},(t,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,o)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},i_,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},st,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},n_,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},s_,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},g_,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,o=0,r=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let i=document.documentElement,a=i.style.height;i.style.height="max-content";let c=Math.ceil(i.getBoundingClientRect().height);i.style.height=a;let d=Math.ceil(window.innerWidth);if(d!==t||c!==o)t=d,o=c,this.sendSizeChanged({width:d,height:c})})};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new vm(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:XS}},b_,t);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);if(this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}function wm(e,t){let o=[],r=new Set;function n(i){if(r.has(i))return;r.add(i);let a=e.get(i);if(!a)throw Error(`Missing preview dependency metadata: ${i}`);for(let c of[...a.imports,...a.styles,...a.references])n(c);o.push(i)}return n(t),o}function Rm(e,t){if(!e||e.revision===t.revision)return[];let o=(r,n)=>{let i=new Map(Object.entries(r.assets));return JSON.stringify(wm(i,n.module).map((a)=>[a,i.get(a)]))};return t.scenarios.filter((r)=>{let n=e.scenarios.find((i)=>i.id===r.id);return!n||o(e,n)!==o(t,r)}).map((r)=>r.id)}class sl{constructor(e){this.read=e,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.importing=Promise.resolve(),this.generation=0,this.prefetchGeneration=0,this.closed=!1,globalThis.__dsPreviewImport=(t)=>this.importModule(t)}register(e){if(e.schemaVersion!==1||!Array.isArray(e.scenarios)||!e.assets||typeof e.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");for(let[t,o]of Object.entries(e.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(t)||!/^sha256:[a-f0-9]{64}$/.test(o.digest)||!["imports","dynamicImports","styles","references"].every((r)=>Array.isArray(o[r])&&o[r].every((n)=>Object.hasOwn(e.assets,n))))throw Error("Invalid preview dependency graph.");if(this.records.has(t)&&this.records.get(t).digest!==o.digest)throw Error("An immutable preview resource changed its content.");this.records.set(t,o)}}async resource(e){if(!this.bytes.has(e)){let t=(async()=>{let o=this.records.get(e);if(!o)throw Error(`Unknown preview dependency: ${e}`);let r;try{r=await this.read(e)}catch(d){throw Object.assign(Error(`Preview resource read failed for ${e}: ${d.message}`,{cause:d}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:e})}if(this.closed)throw Error("The preview App was closed.");let n=r.contents.find((d)=>d.uri===e);if(!n)throw Object.assign(Error(`Missing preview dependency: ${e}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:e});let i=typeof n.text==="string"?new TextEncoder().encode(n.text):Uint8Array.from(atob(n.blob),(d)=>d.charCodeAt(0)),a=await crypto.subtle.digest("SHA-256",i),c="sha256:"+[...new Uint8Array(a)].map((d)=>d.toString(16).padStart(2,"0")).join("");if(i.length!==o.size||c!==o.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build",resourceUri:e});return i})();this.bytes.set(e,t),t.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}closure(e){return wm(this.records,e)}async prefetch(e,t){if(this.closed)return;this.register(e);let o=++this.prefetchGeneration,r=new Set,n=[],i=0;for(let p of t){let m=e.scenarios.find((S)=>S.id===p);if(!m)continue;let f=this.closure(m.module).filter((S)=>!this.bytes.has(S)&&!r.has(S)),y=f.reduce((S,w)=>S+this.records.get(w).size,0);if(i+y>16777216||r.size+f.length>256)continue;i+=y,n.push(p);for(let S of f)r.add(S)}let a=[...r],c=0,d=async()=>{while(!this.closed&&o===this.prefetchGeneration&&c<a.length)await this.resource(a[c++])};return await Promise.all(Array.from({length:Math.min(3,a.length)},d)),{scenarios:n,resources:a.length}}async materialize(e){let t=this.closure(e);await Promise.all(t.map((r)=>this.resource(r)));let o={};for(let r of t){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(r))continue;let n=this.records.get(r),i=await this.resource(r);if(n.kind==="module"||n.mimeType==="text/css"||n.mimeType==="text/javascript"){let c=new TextDecoder().decode(i);for(let d of n.references){let p=this.urls.get(d);if(!p)throw Error("Unsupported cyclic asset reference.");c=c.replaceAll(d,p)}i=c}let a=URL.createObjectURL(new Blob([i],{type:n.mimeType}));if(this.urls.set(r,a),n.kind==="module")o[r]=a}if(Object.keys(o).length){let r=document.createElement("script");r.type="importmap",r.textContent=JSON.stringify({imports:o}),document.head.append(r)}return t}async importModule(e){let t=this.importing.then(()=>this.materialize(e));this.importing=t.catch(()=>{});let o=await t;await this.attachStyles(o);try{let r=await import(e);return this.loadedModules.add(e),r}catch(r){throw Error(`Preview module import failed for ${e}: ${r.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:r})}}async attachStyles(e){for(let t of e){if(this.records.get(t).mimeType!=="text/css")continue;if(this.styles.has(t)){await this.styleReady.get(t);continue}let r=document.createElement("link");r.rel="stylesheet",r.href=this.urls.get(t),this.styles.set(t,r);let n=new Promise((i,a)=>{r.onload=i,r.onerror=()=>a(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(t,n),document.head.append(r);try{await n}catch(i){throw r.remove(),this.styles.delete(t),this.styleReady.delete(t),i}}}async refreshStyles(e,t){let o=[e],r=new Set,n=new Set;for(let i=0;i<o.length;i++){let a=o[i];if(r.has(a))continue;r.add(a);for(let c of await this.materialize(a)){n.add(c);for(let d of this.records.get(c).dynamicImports)if(this.loadedModules.has(d))o.push(d)}}if(await this.attachStyles([...n]),t!==this.generation||this.closed)return!1;for(let[i,a]of this.styles)if(!n.has(i))a.remove(),this.styles.delete(i),this.styleReady.delete(i);for(let i of n)if(this.styles.has(i))document.head.append(this.styles.get(i));return!0}async mount(e,t,o){let r=++this.generation;this.register(e);let n=e.scenarios.find((d)=>d.id===t);if(!n)throw Error("The selected scenario is no longer registered.");let i=JSON.stringify(this.closure(n.module).map((d)=>[d,this.records.get(d)]));if(this.mounted?.id===t&&this.mounted.container===o&&this.mounted.signature===i)return this.refreshStyles(n.module,r);if(this.revisions.add(n.module),this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release modules retained across 20 build revisions."),{code:"ADS_PREVIEW_REOPEN"});let a=await this.importModule(n.module);if(r!==this.generation)return!1;let c=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await c?.(),r!==this.generation||this.closed)return!1;if(o.replaceChildren(),!await this.refreshStyles(n.module,r))return!1;if(typeof a.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=a.mount(o),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:t,container:o,signature:i},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.unmount?.(),this.mounted=void 0;for(let e of this.styles.values())e.remove();for(let e of this.urls.values())URL.revokeObjectURL(e);this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),delete globalThis.__dsPreviewImport}}function xm(e){return Array.isArray(e)&&e.length>0&&e.every((t)=>t&&typeof t==="object"&&typeof t.token==="string"&&/^--[\w-]+$/.test(t.token)&&typeof t.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(t.property)&&typeof t.probe==="string"&&t.probe.trim().length>0)&&new Set(e.map((t)=>`${t.token}:${t.property}`)).size===e.length}function Pm(e,t){let o=t.getComputedStyle(e),r=e.getBoundingClientRect();if(o.display==="none"||o.visibility!=="visible"||!e.getClientRects().length||!(r.width||r.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(t.getComputedStyle(n).opacity)===0)return!1;return!0}function Tm(e,t){if(!xm(t))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let o=e.ownerDocument,{defaultView:r,documentElement:n}=o,i=[],a=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],d=new Set(t.map((p)=>`${p.token}:${p.property}`));for(let p of c)if(!d.has(`${p.dataset.adsToken}:${p.dataset.adsProperty}`))i.push(`Undeclared rendered token sample ${p.dataset.adsToken}:${p.dataset.adsProperty}.`);for(let p of t){if(!r.CSS.supports(p.property,p.probe)){i.push(`${p.token}: the fixture probe is invalid for ${p.property}.`);continue}let m=r.getComputedStyle(n).getPropertyValue(p.token).trim();if(!m||!r.CSS.supports(p.property,m)){i.push(`${p.token}: its current value is invalid for the fixture's ${p.property} binding.`);continue}let f=c.filter((S)=>S.dataset.adsToken===p.token&&S.dataset.adsProperty===p.property);if(!f.length){i.push(`${p.token} needs a rendered ${p.property} sample, not only a name/value label.`);continue}let y=!1;for(let S of f){let w=[];for(let C=S.parentElement;C&&C!==e;C=C.parentElement)if(C.tagName==="DETAILS"&&!C.open)C.open=!0,w.push(C);let x=n.getAttribute("style"),R=S.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(p.property))S.style.setProperty("transition","none","important");let C=r.getComputedStyle(S).getPropertyValue(p.property),N=Pm(S,r);n.style.setProperty(p.token,p.probe,"important");let O=r.getComputedStyle(S).getPropertyValue(p.property);y=Boolean(O&&O!==C&&(N||Pm(S,r)))}finally{if(x===null)n.removeAttribute("style");else n.setAttribute("style",x);if(R===null)S.removeAttribute("style");else S.setAttribute("style",R);for(let C of w)C.open=!1}if(y)break}if(y)a.push(p);else i.push(`${p.token} has no visible ${p.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!i.length,verified:a,diagnostics:i}}function Em({container:e=document.getElementById("root"),bindings:t=[],auditResources:o=!1}={}){let r=[],n=[],i=[];if(!e||!Array.isArray(t)||t.length>100)return{ok:!1,diagnostics:["Invalid bounded paint-audit descriptor."],verified:n};let a=e.ownerDocument,c=a.defaultView,d=["color","fill","stroke","stop-color","background-color","border-top-color","border-right-color","border-bottom-color","border-left-color"];function p(f,y,S,w=new Set){if(f=f.trim(),["none","currentColor"].includes(f))return!0;let x=/^var\(\s*(--[\w-]+)\s*\)$/.exec(f);if(x){let N=x[1];if(!S.tokens.includes(N)||w.has(N))return!1;let O=c.getComputedStyle(y).getPropertyValue(N).trim();return!!O&&c.CSS.supports("color",O)}let R=/^light-dark\(\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*,\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*\)$/.exec(f);if(R)return c.CSS.supports("color",f)&&p(R[1],y,S,w)&&p(R[2],y,S,w);let C=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(f);if(C&&c.CSS.supports("fill",f)){let N=[...a.querySelectorAll("[id]")].filter((O)=>O.id===C[2]);return N.length===1&&["linearGradient","radialGradient","pattern"].includes(N[0].localName)&&y.contains(N[0])}return!1}for(let f of t){if(!f||typeof f.scope!=="string"||!Array.isArray(f.tokens)||typeof f.prefix!=="string"||typeof f.suffix!=="string"){r.push("Invalid paint binding metadata; rebuild previews.");continue}let y;try{y=[...e.querySelectorAll(f.scope)]}catch{r.push(`${f.owner}: invalid binding scope.`);continue}if(y.length>20)i.push(`${f.owner}: only the first 20 instances were audited; use a focused scenario for complete evidence.`);for(let S of y.slice(0,20)){let w=[S,...S.querySelectorAll("*")];if(w.length>1000){i.push(`${f.owner}: instance exceeds 1000 elements; paint effects are not established.`);continue}let x=[...S.style].filter((R)=>R.startsWith(f.prefix)&&R.endsWith(f.suffix));if(x.length>100)i.push(`${f.owner}: only the first 100 binding keys were audited.`);for(let R of x.slice(0,100)){let C=S.style.getPropertyValue(R).trim(),N=R.slice(f.prefix.length,f.suffix?-f.suffix.length:void 0);if(!/^[A-Za-z0-9_-]+$/.test(N)||!p(C,S,f)){r.push(`${f.owner}: invalid or inaccessible paint ${R}: ${C}. Use an accessible token, instance-local SVG paint server, none or currentColor.`);continue}let O=S.getAttribute("style"),q=w.map((L)=>L.getAttribute("style"));try{for(let V of w)V.style.setProperty("transition","none","important");let L=w.map((V)=>d.map((ae)=>c.getComputedStyle(V).getPropertyValue(ae)));S.style.setProperty(R,"rgb(17, 103, 211)","important");let j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)S.style.setProperty(R,"rgb(211, 67, 23)","important"),j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)i.push(`${f.owner}: ${R} has no observed paint effect in its current instance. A written variable alone is not rendering evidence; check the relevant selected/visible consumer.`);else n.push({owner:f.owner,binding:f.name,variable:R})}finally{if(w.forEach((L,j)=>{if(q[j]===null)L.removeAttribute("style");else L.setAttribute("style",q[j])}),O===null)S.removeAttribute("style");else S.setAttribute("style",O)}}for(let R of w)for(let C of["fill","stroke","stop-color"]){let N=R.getAttribute(C);if(!N)continue;let O=/^var\(\s*(--[\w-]+)\s*\)$/.exec(N);if(O&&O[1].startsWith(f.prefix)&&O[1].endsWith(f.suffix)&&!x.includes(O[1]))r.push(`${f.owner}: ${O[1]} is consumed without a value in this instance.`);if(N.startsWith("url(")&&!p(N,S,f))r.push(`${f.owner}: missing, duplicated or out-of-instance local paint resource ${N}.`)}}}let m=o?[...e.querySelectorAll("[fill], [stroke], [style]")]:[];if(m.length>1000)i.push("Only the first 1000 potential SVG paint consumers were audited.");for(let f of m.slice(0,1000))for(let y of["fill","stroke"]){let S=f.getAttribute(y)??f.style.getPropertyValue(y);if(!S?.startsWith("url("))continue;let w=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(S)?.[2],x=w?[...a.querySelectorAll("[id]")].filter((C)=>C.id===w):[],R=f.ownerSVGElement??(f.localName==="svg"?f:null);if(x.length!==1||!R?.contains(x[0])||!["linearGradient","radialGradient","pattern"].includes(x[0]?.localName))r.push(`Invalid, missing, duplicated or nonlocal SVG paint resource ${S}. Keep IDs isolated per rendered instance.`)}return{ok:!r.length,complete:!i.length,verified:n,diagnostics:r.slice(0,40),limits:i.slice(0,20),scope:"observed App instances and current input; repeat after updates"}}var ye=new va({name:"ADS resource preview",version:"1.0.0"},{},{autoResize:!0}),Bt=document.getElementById("root"),il=document.getElementById("ads-preview-status"),ll,pl=async(e)=>{if(!ye.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");try{return await ye.readServerResource({uri:ll?ll+encodeURIComponent(e):e},{timeout:15000})}catch(t){if(t.code===-32601||t.message==="Method not found")throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");throw t}},ei=new sl(pl),He,$m,Gt,ul,hl,al=!1,lt=0,Ys={},_e="",Qs=!1,cl,km,Cm=new Set;function Im(e){if(ye.getHostVersion()?.name!=="ADS showcase")return;let t=km;if(km=e,!t)return;let o=Rm(t,e).filter((r)=>r!==He&&Cm.has(r));if(!o.length)return;ei.prefetch(e,o).then((r)=>ut("prefetched",{revision:e.revision,...r})).catch((r)=>console.warn("ADS preview prefetch",r.message))}function Oe(e,t=!1){il.textContent=e,il.hidden=!e||ye.getHostVersion()?.name==="ADS showcase",il.setAttribute("role",t?"alert":"status")}async function ut(e,t={}){try{if(ye.getHostCapabilities()?.logging)await ye.sendLog({level:e==="error"?"error":"info",logger:"ads-preview",data:{state:e,id:He,...t}})}catch{}}function Om(e){if(Ys={...Ys,...e,styles:{...Ys.styles,...e.styles}},["light","dark"].includes(Ys.theme))document.documentElement.dataset.theme=Ys.theme}async function dl(e="ads://preview/manifest"){let t;try{t=await pl(e)}catch(o){throw Object.assign(Error(o.message,{cause:o}),{code:"ADS_MANIFEST_READ",category:"transport"})}return JSON.parse(t.contents.find((o)=>typeof o.text==="string").text)}async function Xs(e,t,o=!1,r="",n=!1){let i=o||n;if(!r&&e===He&&t&&t===Gt&&i===Qs){Oe(_e||(i?"Checking changes…":""),Boolean(_e)),await ut(_e?"error":i?"checking":"ready",_e?{message:_e}:{revision:Gt});return}let a=++lt;++ei.generation,He=e,Cm.add(e),document.documentElement.dataset.adsScenario=e,document.documentElement.dataset.adsPreviewState="loading";for(let c of["adsPreviewErrorCategory","adsPreviewErrorCode","adsPreviewResourceUri"])delete document.documentElement.dataset[c];_e="",Oe(""),await ut(r?"reverting":"loading");try{let c=await dl(o?"ads://preview/live":"ads://preview/manifest");if(t&&c.revision!==t){if(a===lt)Oe("Updating preview…"),await ut("loading",{code:"ADS_PREVIEW_CHANGED"});return}if(a!==lt)return;if(!await ei.mount(c,e,Bt)||a!==lt)return;if(Gt=c.revision,ul=c.session,Qs=i,await new Promise((m)=>requestAnimationFrame(()=>requestAnimationFrame(m))),await document.fonts.ready,a!==lt)return;let p=c.scenarios.find((m)=>m.id===e);if(Bt.dataset.adsPaintBindings=JSON.stringify(p?.paintBindings??[]),Bt.dataset.adsPaintAudit=String(Boolean(p?.paintAudit)),Bt.dataset.adsPaintAuditComplete="not-requested",p?.paintBindings?.length||p?.paintAudit){let m=Em({container:Bt,bindings:p.paintBindings??[],auditResources:Boolean(p.paintAudit)});if(!m.ok)throw Object.assign(Error(`Paint binding verification failed:
106
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:s().optional().describe("User's language and region preference in BCP 47 format."),timeZone:s().optional().describe("User's timezone in IANA format."),userAgent:s().optional().describe("Host application identifier."),platform:v([u("web"),u("desktop"),u("mobile")]).optional().describe("Platform type for responsive design decisions."),deviceCapabilities:l({touch:z().optional().describe("Whether the device supports touch input."),hover:z().optional().describe("Whether the device supports hover interactions.")}).optional().describe("Device input capabilities."),safeAreaInsets:l({top:_().describe("Top safe area inset in pixels."),right:_().describe("Right safe area inset in pixels."),bottom:_().describe("Bottom safe area inset in pixels."),left:_().describe("Left safe area inset in pixels.")}).optional().describe("Mobile safe area boundaries in pixels.")}).passthrough(),y_=l({method:u("ui/notifications/host-context-changed"),params:zm.describe("Partial context update containing only changed fields.")}),Ez=l({method:u("ui/update-model-context"),params:l({content:h(Ce).optional().describe("Context content blocks (text, image, etc.)."),structuredContent:b(s(),P().describe("Structured content for machine-readable context data.")).optional().describe("Structured content for machine-readable context data.")})}),kz=l({method:u("ui/initialize"),params:l({appInfo:ke.describe("App identification (name and version)."),appCapabilities:f_.describe("Features and capabilities this app provides."),protocolVersion:s().describe("Protocol version this app supports.")})}),b_=l({protocolVersion:s().describe('Negotiated protocol version string (e.g., "2025-11-21").'),hostInfo:ke.describe("Host application identification and version."),hostCapabilities:m_.describe("Features and capabilities provided by the host."),hostContext:zm.describe("Rich context about the host environment.")}).passthrough(),v_={target:"draft-2020-12"};async function Sm(e,t){let o=e["~standard"];if(o.jsonSchema)return o.jsonSchema[t](v_);throw Error(`Schema (vendor: ${o.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function _m(e,t,o=""){let r=await e["~standard"].validate(t);if(r.issues){let n=r.issues.map((i)=>{let a=i.path?.map((c)=>typeof c==="object"?c.key:c).join(".");return a?`${a}: ${i.message}`:i.message}).join("; ");throw Error(o+n)}return r.value}function z_(e,t){let o={...e,...t};if(t.experimental!==void 0)o.experimental={...e.experimental,...t.experimental};if(t.tools!==void 0)o.tools={...e.tools,...t.tools};return o}class va extends ol{_appInfo;_appCapabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_registeredEvents=new Set;_events=new ym;_methods=new bm;setRequestHandler=(...e)=>{let[t,...o]=fm("request",e)??e;this._methods.claim(t,"setRequestHandler"),super.setRequestHandler.call(this,t,...o)};setNotificationHandler=(...e)=>{let[t,...o]=fm("notification",e)??e;this._methods.claim(t,"setNotificationHandler"),super.setNotificationHandler.call(this,t,...o)};removeRequestHandler=(e)=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=(e)=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:a_,toolinputpartial:c_,toolresult:__,toolcancelled:l_,hostcontextchanged:y_};static ONE_SHOT_EVENTS=new Set(["toolinput","toolinputpartial","toolresult","toolcancelled"]);_everHadListener=new Set;_assertHandlerTiming(e){if(!va.ONE_SHOT_EVENTS.has(e)||this._everHadListener.has(e))return;if(this._everHadListener.add(e),!this._initializedSent)return;let t=`[ext-apps] "${String(e)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(t);console.warn(t)}setEventHandler(e,t){if(t)this._assertHandlerTiming(e);this._ensureEventSlot(e),this._events.setHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},(o)=>{let r=o;if(e==="hostcontextchanged")this._hostContext={...this._hostContext,...r};this._events.dispatch(e,r)}),this._registeredEvents.add(e)}getEventHandler(e){return this._events.getHandler(e)}warnIfRequestHandlerReplaced(e,t,o){if(t&&o)console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t={},o={autoResize:!0}){super(o);if(this._appInfo=e,this._appCapabilities=t,this.options=o,this._methods.replace("notifications/cancelled"),this._methods.replace("notifications/progress"),!o.allowUnsafeEval)le({jitless:!0});this.replaceRequestHandler("ping",(r)=>(console.log("Received ping:",r.params),{})),this.setEventHandler("hostcontextchanged",void 0)}buildContext(e){return e}registerAppCapabilities(e){if(this.transport)throw Error("Cannot register capabilities after transport is established");this._appCapabilities=z_(this._appCapabilities,e)}registerTool(e,t,o){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,n=()=>{if(r._initializedSent&&r._appCapabilities.tools?.listChanged)r.sendToolListChanged()},i=t.inputSchema!==void 0,a={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,n()},disable(){this.enabled=!1,n()},update(c){Object.assign(this,c),n()},remove(){if(r._registeredTools[e]!==a)return;delete r._registeredTools[e],n()},handler:async(c,d)=>{if(!a.enabled)throw Error(`Tool ${e} is disabled`);let p;if(i){let m=a.inputSchema,f=m?await _m(m,c??{},`Invalid input for tool ${e}: `):c??{};p=await o(f,d)}else p=await o(d);if(a.outputSchema&&!p.isError)p.structuredContent=await _m(a.outputSchema,p.structuredContent,`Invalid output for tool ${e}: `);return p}};if(this._registeredTools[e]=a,!this._appCapabilities.tools&&!this.transport)this.registerAppCapabilities({tools:{listChanged:!0}});return this.ensureToolHandlersInitialized(),n(),a}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){if(this._toolHandlersInitialized)return;this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let o=this._registeredTools[e.name];if(!o)throw Error(`Tool ${e.name} not found`);return o.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([o,r])=>r.enabled).map(async([o,r])=>{let n={name:o,title:r.title,description:r.description,inputSchema:r.inputSchema?await Sm(r.inputSchema,"input"):{type:"object",properties:{}}};if(r.outputSchema)n.outputSchema=await Sm(r.outputSchema,"output");if(r.annotations)n.annotations=r.annotations;if(r._meta)n._meta=r._meta;return n}))})}async sendToolListChanged(e={}){this._assertInitialized("sendToolListChanged"),await this.notification({method:"notifications/tools/list_changed",params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler("toolinput")}set ontoolinput(e){this.setEventHandler("toolinput",e)}get ontoolinputpartial(){return this.getEventHandler("toolinputpartial")}set ontoolinputpartial(e){this.setEventHandler("toolinputpartial",e)}get ontoolresult(){return this.getEventHandler("toolresult")}set ontoolresult(e){this.setEventHandler("toolresult",e)}get ontoolcancelled(){return this.getEventHandler("toolcancelled")}set ontoolcancelled(e){this.setEventHandler("toolcancelled",e)}get onhostcontextchanged(){return this.getEventHandler("hostcontextchanged")}set onhostcontextchanged(e){this.setEventHandler("hostcontextchanged",e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced("onteardown",this._onteardown,e),this._onteardown=e,this.replaceRequestHandler("ui/resource-teardown",{params:p_.shape.params,result:h_},(t,o)=>{if(!this._onteardown)throw Error("No onteardown handler set");return this._onteardown(t,o)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced("oncalltool",this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler("tools/call",(t,o)=>{if(!this._oncalltool)throw Error("No oncalltool handler set");return this._oncalltool(t.params,o)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced("onlisttools",this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler("tools/list",(t,o)=>{if(!this._onlisttools)throw Error("No onlisttools handler set");return this._onlisttools(t.params,o)})}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case"tools/call":case"tools/list":if(!this._appCapabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;default:return}}assertNotificationCapability(e){}async callServerTool(e,t){if(this._assertInitialized("callServerTool"),typeof e==="string")throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:"tools/call",params:e},{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized("readServerResource"),await this.request({method:"resources/read",params:e},t)}async listServerResources(e,t){return this._assertInitialized("listServerResources"),await this.request({method:"resources/list",params:e},t)}async createSamplingMessage(e,t){return this._assertInitialized("createSamplingMessage"),await this.request({method:"sampling/createMessage",params:e},t)}sendMessage(e,t){return this._assertInitialized("sendMessage"),this.request({method:"ui/message",params:e},i_,t)}sendLog(e){return this.notification({method:"notifications/message",params:e})}updateModelContext(e,t){return this._assertInitialized("updateModelContext"),this.request({method:"ui/update-model-context",params:e},st,t)}openLink(e,t){return this._assertInitialized("openLink"),this.request({method:"ui/open-link",params:e},n_,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized("downloadFile"),this.request({method:"ui/download-file",params:e},s_,t)}requestTeardown(e={}){return this.notification({method:"ui/notifications/request-teardown",params:e})}requestDisplayMode(e,t){return this._assertInitialized("requestDisplayMode"),this.request({method:"ui/request-display-mode",params:e},g_,t)}sendSizeChanged(e){return this.notification({method:"ui/notifications/size-changed",params:e})}setupSizeChangedNotifications(){let e=!1,t=0,o=0,r=()=>{if(e)return;e=!0,requestAnimationFrame(()=>{e=!1;let i=document.documentElement,a=i.style.height;i.style.height="max-content";let c=Math.ceil(i.getBoundingClientRect().height);i.style.height=a;let d=Math.ceil(window.innerWidth);if(d!==t||c!==o)t=d,o=c,this.sendSizeChanged({width:d,height:c})})};r();let n=new ResizeObserver(r);return n.observe(document.documentElement),n.observe(document.body),()=>n.disconnect()}async connect(e=new vm(window.parent,window.parent),t){if(this.transport)throw Error("App is already connected. Call close() before connecting again.");this._initializedSent=!1;try{await super.connect(e);let o=await this.request({method:"ui/initialize",params:{appCapabilities:this._appCapabilities,appInfo:this._appInfo,protocolVersion:XS}},b_,t);if(o===void 0)throw Error(`Server sent invalid initialize result: ${o}`);if(this._hostCapabilities=o.hostCapabilities,this._hostInfo=o.hostInfo,this._hostContext=o.hostContext,await this.notification({method:"ui/notifications/initialized"}),this._initializedSent=!0,this.options?.autoResize)this.setupSizeChangedNotifications()}catch(o){throw this.close(),o}}}function wm(e,t){let o=[],r=new Set;function n(i){if(r.has(i))return;r.add(i);let a=e.get(i);if(!a)throw Error(`Missing preview dependency metadata: ${i}`);for(let c of[...a.imports,...a.styles,...a.references])n(c);o.push(i)}return n(t),o}function Rm(e,t){if(!e||e.revision===t.revision)return[];let o=(r,n)=>{let i=new Map(Object.entries(r.assets));return JSON.stringify(wm(i,n.module).map((a)=>[a,i.get(a)]))};return t.scenarios.filter((r)=>{let n=e.scenarios.find((i)=>i.id===r.id);return!n||o(e,n)!==o(t,r)}).map((r)=>r.id)}class sl{constructor(e){this.read=e,this.records=new Map,this.bytes=new Map,this.urls=new Map,this.styles=new Map,this.styleReady=new Map,this.revisions=new Set,this.loadedModules=new Set,this.importing=Promise.resolve(),this.generation=0,this.prefetchGeneration=0,this.closed=!1,globalThis.__dsPreviewImport=(t)=>this.importModule(t)}register(e){if(e.schemaVersion!==1||!Array.isArray(e.scenarios)||!e.assets||typeof e.revision!=="string")throw Error("Unsupported preview manifest. Rebuild previews with the installed ADS version.");for(let[t,o]of Object.entries(e.assets)){if(!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(t)||!/^sha256:[a-f0-9]{64}$/.test(o.digest)||!["imports","dynamicImports","styles","references"].every((r)=>Array.isArray(o[r])&&o[r].every((n)=>Object.hasOwn(e.assets,n))))throw Error("Invalid preview dependency graph.");if(this.records.has(t)&&this.records.get(t).digest!==o.digest)throw Object.assign(Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."),{code:"ADS_RESOURCE_IDENTITY",category:"build",resourceUri:t})}for(let[t,o]of Object.entries(e.assets))this.records.set(t,o)}async resource(e){if(!this.bytes.has(e)){let t=(async()=>{let o=this.records.get(e);if(!o)throw Error(`Unknown preview dependency: ${e}`);let r;try{r=await this.read(e)}catch(d){throw Object.assign(Error(`Preview resource read failed for ${e}: ${d.message}`,{cause:d}),{code:"ADS_RESOURCE_READ",category:"transport",resourceUri:e})}if(this.closed)throw Error("The preview App was closed.");let n=r.contents.find((d)=>d.uri===e);if(!n)throw Object.assign(Error(`Missing preview dependency: ${e}`),{code:"ADS_RESOURCE_CONTENT",category:"build",resourceUri:e});let i=typeof n.text==="string"?new TextEncoder().encode(n.text):Uint8Array.from(atob(n.blob),(d)=>d.charCodeAt(0)),a=await crypto.subtle.digest("SHA-256",i),c="sha256:"+[...new Uint8Array(a)].map((d)=>d.toString(16).padStart(2,"0")).join("");if(i.length!==o.size||c!==o.digest)throw Object.assign(Error("Preview resource integrity check failed. Rebuild and reopen the preview."),{code:"ADS_RESOURCE_INTEGRITY",category:"build",resourceUri:e});return i})();this.bytes.set(e,t),t.catch(()=>this.bytes.delete(e))}return this.bytes.get(e)}closure(e){return wm(this.records,e)}async prefetch(e,t){if(this.closed)return;this.register(e);let o=++this.prefetchGeneration,r=new Set,n=[],i=0;for(let p of t){let m=e.scenarios.find((S)=>S.id===p);if(!m)continue;let f=this.closure(m.module).filter((S)=>!this.bytes.has(S)&&!r.has(S)),y=f.reduce((S,w)=>S+this.records.get(w).size,0);if(i+y>16777216||r.size+f.length>256)continue;i+=y,n.push(p);for(let S of f)r.add(S)}let a=[...r],c=0,d=async()=>{while(!this.closed&&o===this.prefetchGeneration&&c<a.length)await this.resource(a[c++])};return await Promise.all(Array.from({length:Math.min(3,a.length)},d)),{scenarios:n,resources:a.length}}async materialize(e){let t=this.closure(e);await Promise.all(t.map((r)=>this.resource(r)));let o={};for(let r of t){if(this.closed)throw Error("The preview App was closed.");if(this.urls.has(r))continue;let n=this.records.get(r),i=await this.resource(r);if(n.kind==="module"||n.mimeType==="text/css"||n.mimeType==="text/javascript"){let c=new TextDecoder().decode(i);for(let d of n.references){let p=this.urls.get(d);if(!p)throw Error("Unsupported cyclic asset reference.");c=c.replaceAll(d,p)}i=c}let a=URL.createObjectURL(new Blob([i],{type:n.mimeType}));if(this.urls.set(r,a),n.kind==="module")o[r]=a}if(Object.keys(o).length){let r=document.createElement("script");r.type="importmap",r.textContent=JSON.stringify({imports:o}),document.head.append(r)}return t}async importModule(e){let t=this.importing.then(()=>this.materialize(e));this.importing=t.catch(()=>{});let o=await t;await this.attachStyles(o);try{let r=await import(e);return this.loadedModules.add(e),r}catch(r){throw Error(`Preview module import failed for ${e}: ${r.message}. Inspect the App resource bridge, browser network/CSP diagnostics and current build.`,{cause:r})}}async attachStyles(e){for(let t of e){if(this.records.get(t).mimeType!=="text/css")continue;if(this.styles.has(t)){await this.styleReady.get(t);continue}let r=document.createElement("link");r.rel="stylesheet",r.href=this.urls.get(t),this.styles.set(t,r);let n=new Promise((i,a)=>{r.onload=i,r.onerror=()=>a(Error("The host CSP blocked a preview stylesheet."))});this.styleReady.set(t,n),document.head.append(r);try{await n}catch(i){throw r.remove(),this.styles.delete(t),this.styleReady.delete(t),i}}}async refreshStyles(e,t){let o=[e],r=new Set,n=new Set;for(let i=0;i<o.length;i++){let a=o[i];if(r.has(a))continue;r.add(a);for(let c of await this.materialize(a)){n.add(c);for(let d of this.records.get(c).dynamicImports)if(this.loadedModules.has(d))o.push(d)}}if(await this.attachStyles([...n]),t!==this.generation||this.closed)return!1;for(let[i,a]of this.styles)if(!n.has(i))a.remove(),this.styles.delete(i),this.styleReady.delete(i);for(let i of n)if(this.styles.has(i))document.head.append(this.styles.get(i));return!0}async mount(e,t,o){let r=++this.generation;this.register(e);let n=e.scenarios.find((d)=>d.id===t);if(!n)throw Error("The selected scenario is no longer registered.");let i=JSON.stringify(this.closure(n.module).map((d)=>[d,this.records.get(d)]));if(this.mounted?.id===t&&this.mounted.container===o&&this.mounted.signature===i)return this.refreshStyles(n.module,r);if(this.revisions.add(n.module),this.revisions.size>20)throw Object.assign(Error("Reopen the preview to release modules retained across 20 build revisions."),{code:"ADS_PREVIEW_REOPEN"});let a=await this.importModule(n.module);if(r!==this.generation)return!1;let c=this.unmount;if(this.unmount=void 0,this.mounted=void 0,await c?.(),r!==this.generation||this.closed)return!1;if(o.replaceChildren(),!await this.refreshStyles(n.module,r))return!1;if(typeof a.mount!=="function")throw Error("The compiled scenario has no mount adapter.");if(this.unmount=a.mount(o),typeof this.unmount!=="function")throw Error("The scenario mount adapter must return an unmount callback.");return this.mounted={id:t,container:o,signature:i},!0}async dispose(){if(this.closed)return;this.closed=!0,++this.generation,++this.prefetchGeneration,await this.unmount?.(),this.mounted=void 0;for(let e of this.styles.values())e.remove();for(let e of this.urls.values())URL.revokeObjectURL(e);this.styles.clear(),this.styleReady.clear(),this.urls.clear(),this.bytes.clear(),this.records.clear(),this.revisions.clear(),this.loadedModules.clear(),delete globalThis.__dsPreviewImport}}function xm(e){return Array.isArray(e)&&e.length>0&&e.every((t)=>t&&typeof t==="object"&&typeof t.token==="string"&&/^--[\w-]+$/.test(t.token)&&typeof t.property==="string"&&/^-?[a-z][a-z0-9-]*$/.test(t.property)&&typeof t.probe==="string"&&t.probe.trim().length>0)&&new Set(e.map((t)=>`${t.token}:${t.property}`)).size===e.length}function Pm(e,t){let o=t.getComputedStyle(e),r=e.getBoundingClientRect();if(o.display==="none"||o.visibility!=="visible"||!e.getClientRects().length||!(r.width||r.height))return!1;for(let n=e;n;n=n.parentElement)if(Number(t.getComputedStyle(n).opacity)===0)return!1;return!0}function Tm(e,t){if(!xm(t))return{ok:!1,diagnostics:["Token preview needs explicit { token, property, probe } samples from the project fixture. Rebuild with the current compiler."]};let o=e.ownerDocument,{defaultView:r,documentElement:n}=o,i=[],a=[],c=[...e.querySelectorAll("[data-ads-token], [data-ads-property]")],d=new Set(t.map((p)=>`${p.token}:${p.property}`));for(let p of c)if(!d.has(`${p.dataset.adsToken}:${p.dataset.adsProperty}`))i.push(`Undeclared rendered token sample ${p.dataset.adsToken}:${p.dataset.adsProperty}.`);for(let p of t){if(!r.CSS.supports(p.property,p.probe)){i.push(`${p.token}: the fixture probe is invalid for ${p.property}.`);continue}let m=r.getComputedStyle(n).getPropertyValue(p.token).trim();if(!m||!r.CSS.supports(p.property,m)){i.push(`${p.token}: its current value is invalid for the fixture's ${p.property} binding.`);continue}let f=c.filter((S)=>S.dataset.adsToken===p.token&&S.dataset.adsProperty===p.property);if(!f.length){i.push(`${p.token} needs a rendered ${p.property} sample, not only a name/value label.`);continue}let y=!1;for(let S of f){let w=[];for(let C=S.parentElement;C&&C!==e;C=C.parentElement)if(C.tagName==="DETAILS"&&!C.open)C.open=!0,w.push(C);let x=n.getAttribute("style"),R=S.getAttribute("style");try{if(!/^(?:-[a-z]+-)?transition(?:-|$)/.test(p.property))S.style.setProperty("transition","none","important");let C=r.getComputedStyle(S).getPropertyValue(p.property),N=Pm(S,r);n.style.setProperty(p.token,p.probe,"important");let O=r.getComputedStyle(S).getPropertyValue(p.property);y=Boolean(O&&O!==C&&(N||Pm(S,r)))}finally{if(x===null)n.removeAttribute("style");else n.setAttribute("style",x);if(R===null)S.removeAttribute("style");else S.setAttribute("style",R);for(let C of w)C.open=!1}if(y)break}if(y)a.push(p);else i.push(`${p.token} has no visible ${p.property} sample that responds to its value. Hardcoded copies do not satisfy coverage.`)}return{ok:!i.length,verified:a,diagnostics:i}}function Em({container:e=document.getElementById("root"),bindings:t=[],auditResources:o=!1}={}){let r=[],n=[],i=[];if(!e||!Array.isArray(t)||t.length>100)return{ok:!1,diagnostics:["Invalid bounded paint-audit descriptor."],verified:n};let a=e.ownerDocument,c=a.defaultView,d=["color","fill","stroke","stop-color","background-color","border-top-color","border-right-color","border-bottom-color","border-left-color"];function p(f,y,S,w=new Set){if(f=f.trim(),["none","currentColor"].includes(f))return!0;let x=/^var\(\s*(--[\w-]+)\s*\)$/.exec(f);if(x){let N=x[1];if(!S.tokens.includes(N)||w.has(N))return!1;let O=c.getComputedStyle(y).getPropertyValue(N).trim();return!!O&&c.CSS.supports("color",O)}let R=/^light-dark\(\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*,\s*(var\(\s*--[\w-]+\s*\)|currentColor)\s*\)$/.exec(f);if(R)return c.CSS.supports("color",f)&&p(R[1],y,S,w)&&p(R[2],y,S,w);let C=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(f);if(C&&c.CSS.supports("fill",f)){let N=[...a.querySelectorAll("[id]")].filter((O)=>O.id===C[2]);return N.length===1&&["linearGradient","radialGradient","pattern"].includes(N[0].localName)&&y.contains(N[0])}return!1}for(let f of t){if(!f||typeof f.scope!=="string"||!Array.isArray(f.tokens)||typeof f.prefix!=="string"||typeof f.suffix!=="string"){r.push("Invalid paint binding metadata; rebuild previews.");continue}let y;try{y=[...e.querySelectorAll(f.scope)]}catch{r.push(`${f.owner}: invalid binding scope.`);continue}if(y.length>20)i.push(`${f.owner}: only the first 20 instances were audited; use a focused scenario for complete evidence.`);for(let S of y.slice(0,20)){let w=[S,...S.querySelectorAll("*")];if(w.length>1000){i.push(`${f.owner}: instance exceeds 1000 elements; paint effects are not established.`);continue}let x=[...S.style].filter((R)=>R.startsWith(f.prefix)&&R.endsWith(f.suffix));if(x.length>100)i.push(`${f.owner}: only the first 100 binding keys were audited.`);for(let R of x.slice(0,100)){let C=S.style.getPropertyValue(R).trim(),N=R.slice(f.prefix.length,f.suffix?-f.suffix.length:void 0);if(!/^[A-Za-z0-9_-]+$/.test(N)||!p(C,S,f)){r.push(`${f.owner}: invalid or inaccessible paint ${R}: ${C}. Use an accessible token, instance-local SVG paint server, none or currentColor.`);continue}let O=S.getAttribute("style"),q=w.map((L)=>L.getAttribute("style"));try{for(let V of w)V.style.setProperty("transition","none","important");let L=w.map((V)=>d.map((ae)=>c.getComputedStyle(V).getPropertyValue(ae)));S.style.setProperty(R,"rgb(17, 103, 211)","important");let j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)S.style.setProperty(R,"rgb(211, 67, 23)","important"),j=w.some((V,ae)=>d.some((Y,ge)=>c.getComputedStyle(V).getPropertyValue(Y)!==L[ae][ge]));if(!j)i.push(`${f.owner}: ${R} has no observed paint effect in its current instance. A written variable alone is not rendering evidence; check the relevant selected/visible consumer.`);else n.push({owner:f.owner,binding:f.name,variable:R})}finally{if(w.forEach((L,j)=>{if(q[j]===null)L.removeAttribute("style");else L.setAttribute("style",q[j])}),O===null)S.removeAttribute("style");else S.setAttribute("style",O)}}for(let R of w)for(let C of["fill","stroke","stop-color"]){let N=R.getAttribute(C);if(!N)continue;let O=/^var\(\s*(--[\w-]+)\s*\)$/.exec(N);if(O&&O[1].startsWith(f.prefix)&&O[1].endsWith(f.suffix)&&!x.includes(O[1]))r.push(`${f.owner}: ${O[1]} is consumed without a value in this instance.`);if(N.startsWith("url(")&&!p(N,S,f))r.push(`${f.owner}: missing, duplicated or out-of-instance local paint resource ${N}.`)}}}let m=o?[...e.querySelectorAll("[fill], [stroke], [style]")]:[];if(m.length>1000)i.push("Only the first 1000 potential SVG paint consumers were audited.");for(let f of m.slice(0,1000))for(let y of["fill","stroke"]){let S=f.getAttribute(y)??f.style.getPropertyValue(y);if(!S?.startsWith("url("))continue;let w=/^url\(\s*(["']?)#([^\s"'()#\\\p{Cc}]+)\1\s*\)$/u.exec(S)?.[2],x=w?[...a.querySelectorAll("[id]")].filter((C)=>C.id===w):[],R=f.ownerSVGElement??(f.localName==="svg"?f:null);if(x.length!==1||!R?.contains(x[0])||!["linearGradient","radialGradient","pattern"].includes(x[0]?.localName))r.push(`Invalid, missing, duplicated or nonlocal SVG paint resource ${S}. Keep IDs isolated per rendered instance.`)}return{ok:!r.length,complete:!i.length,verified:n,diagnostics:r.slice(0,40),limits:i.slice(0,20),scope:"observed App instances and current input; repeat after updates"}}var ye=new va({name:"ADS resource preview",version:"1.0.0"},{},{autoResize:!0}),Bt=document.getElementById("root"),il=document.getElementById("ads-preview-status"),ll,pl=async(e)=>{if(!ye.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");try{return await ye.readServerResource({uri:ll?ll+encodeURIComponent(e):e},{timeout:15000})}catch(t){if(t.code===-32601||t.message==="Method not found")throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");throw t}},ei=new sl(pl),He,$m,Gt,ul,hl,al=!1,lt=0,Ys={},_e="",Qs=!1,cl,km,Cm=new Set;function Im(e){if(ye.getHostVersion()?.name!=="ADS showcase")return;let t=km;if(km=e,!t)return;let o=Rm(t,e).filter((r)=>r!==He&&Cm.has(r));if(!o.length)return;ei.prefetch(e,o).then((r)=>ut("prefetched",{revision:e.revision,...r})).catch((r)=>console.warn("ADS preview prefetch",r.message))}function Oe(e,t=!1){il.textContent=e,il.hidden=!e||ye.getHostVersion()?.name==="ADS showcase",il.setAttribute("role",t?"alert":"status")}async function ut(e,t={}){try{if(ye.getHostCapabilities()?.logging)await ye.sendLog({level:e==="error"?"error":"info",logger:"ads-preview",data:{state:e,id:He,...t}})}catch{}}function Om(e){if(Ys={...Ys,...e,styles:{...Ys.styles,...e.styles}},["light","dark"].includes(Ys.theme))document.documentElement.dataset.theme=Ys.theme}async function dl(e="ads://preview/manifest"){let t;try{t=await pl(e)}catch(o){throw Object.assign(Error(o.message,{cause:o}),{code:"ADS_MANIFEST_READ",category:"transport"})}return JSON.parse(t.contents.find((o)=>typeof o.text==="string").text)}async function Xs(e,t,o=!1,r="",n=!1){let i=o||n;if(!r&&e===He&&t&&t===Gt&&i===Qs){Oe(_e||(i?"Checking changes…":""),Boolean(_e)),await ut(_e?"error":i?"checking":"ready",_e?{message:_e}:{revision:Gt});return}let a=++lt;++ei.generation,He=e,Cm.add(e),document.documentElement.dataset.adsScenario=e,document.documentElement.dataset.adsPreviewState="loading";for(let c of["adsPreviewErrorCategory","adsPreviewErrorCode","adsPreviewResourceUri"])delete document.documentElement.dataset[c];_e="",Oe(""),await ut(r?"reverting":"loading");try{let c=await dl(o?"ads://preview/live":"ads://preview/manifest");if(t&&c.revision!==t){if(a===lt)Oe("Updating preview…"),await ut("loading",{code:"ADS_PREVIEW_CHANGED"});return}if(a!==lt)return;if(!await ei.mount(c,e,Bt)||a!==lt)return;if(Gt=c.revision,ul=c.session,Qs=i,await new Promise((m)=>requestAnimationFrame(()=>requestAnimationFrame(m))),await document.fonts.ready,a!==lt)return;let p=c.scenarios.find((m)=>m.id===e);if(Bt.dataset.adsPaintBindings=JSON.stringify(p?.paintBindings??[]),Bt.dataset.adsPaintAudit=String(Boolean(p?.paintAudit)),Bt.dataset.adsPaintAuditComplete="not-requested",p?.paintBindings?.length||p?.paintAudit){let m=Em({container:Bt,bindings:p.paintBindings??[],auditResources:Boolean(p.paintAudit)});if(!m.ok)throw Object.assign(Error(`Paint binding verification failed:
107
107
  ${m.diagnostics.join(`
108
108
  `)}`),{code:"ADS_PAINT_BINDING",category:"assertion"});if(Bt.dataset.adsPaintAuditComplete=String(m.complete),!m.complete)await ut("audit-limited",{limits:m.limits})}if(p?.kind==="tokens"){let m=Tm(Bt,p.samples);if(!m.ok)throw _e=`Token preview verification failed:
109
109
  ${m.diagnostics.slice(0,20).join(`
110
- `)}`,Object.assign(Error(_e),{code:"ADS_TOKEN_SAMPLE",category:"assertion"})}if(a===lt){if(document.documentElement.dataset.adsPreviewRevision=Gt,document.documentElement.dataset.adsPreviewState=r?"error":i?"checking":"ready",Oe(r||(i?"Checking changes…":""),Boolean(r)),await ut(r?"error":i?"checking":"ready",{revision:Gt,selectionRevision:$m,...r?{message:r}:{}}),!i&&!r)Im(c)}}catch(c){if(a===lt){if(document.documentElement.dataset.adsPreviewState="error",document.documentElement.dataset.adsPreviewErrorCategory=c.category??"runner",document.documentElement.dataset.adsPreviewErrorCode=c.code??"ADS_PREVIEW_STARTUP",c.resourceUri)document.documentElement.dataset.adsPreviewResourceUri=c.resourceUri;Oe(c.message,!0),await ut("error",{message:c.message,...c.code?{code:c.code}:{}})}}}async function w_(){if(!He||al||document.visibilityState==="hidden")return;al=!0;try{let e=JSON.parse((await pl("ads://project/build")).contents.find((o)=>typeof o.text==="string").text);cl=void 0;let t=e.previews.find((o)=>o.id===He);if(t?.live&&!t.current)if(t.live.revision!==Gt||e.session!==ul||!Qs)await Xs(He,t.live.revision,!0);else Oe(_e||"Checking changes…",Boolean(_e));else if(!t||!t.current){let o=t?.diagnostics?.[0]?.message;if(o&&Qs){let r=await dl();await Xs(He,r.revision,!1,`Build failed. Showing the previous preview.
110
+ `)}`,Object.assign(Error(_e),{code:"ADS_TOKEN_SAMPLE",category:"assertion"})}if(a===lt){if(document.documentElement.dataset.adsPreviewRevision=Gt,document.documentElement.dataset.adsPreviewState=r?"error":i?"checking":"ready",Oe(r||(i?"Checking changes…":""),Boolean(r)),await ut(r?"error":i?"checking":"ready",{revision:Gt,selectionRevision:$m,...r?{message:r}:{}}),!i&&!r)Im(c)}}catch(c){if(a===lt){if(document.documentElement.dataset.adsPreviewState="error",document.documentElement.dataset.adsPreviewErrorCategory=c.category??"runner",document.documentElement.dataset.adsPreviewErrorCode=c.code??"ADS_PREVIEW_STARTUP",c.resourceUri)document.documentElement.dataset.adsPreviewResourceUri=c.resourceUri;Oe(c.message,!0),await ut("error",{message:c.message,...c.code?{code:c.code}:{},...c.category?{category:c.category}:{},...c.resourceUri?{resourceUri:c.resourceUri}:{}})}}}async function w_(){if(!He||al||document.visibilityState==="hidden")return;al=!0;try{let e=JSON.parse((await pl("ads://project/build")).contents.find((o)=>typeof o.text==="string").text);cl=void 0;let t=e.previews.find((o)=>o.id===He);if(t?.live&&!t.current)if(t.live.revision!==Gt||e.session!==ul||!Qs)await Xs(He,t.live.revision,!0);else Oe(_e||"Checking changes…",Boolean(_e));else if(!t||!t.current){let o=t?.diagnostics?.[0]?.message;if(o&&Qs){let r=await dl();await Xs(He,r.revision,!1,`Build failed. Showing the previous preview.
111
111
  ${o}`)}Oe(o?`Build failed. Showing the previous preview.
112
112
  ${o}`:"Rebuilding. This is the previous preview.",Boolean(o))}else{let o=await dl();if(o.revision!==Gt||o.session!==ul||Qs)await Xs(He,o.revision);else Oe(_e,Boolean(_e)),Im(o)}}catch(e){let t=`Preview freshness unavailable: ${e.message}`;if(Oe(t,!0),cl!==t)cl=t,await ut("error",{message:t})}finally{al=!1}}ye.ontoolresult=(e)=>{ll=e.structuredContent?.draftScope;let t=e.structuredContent?.previewResult?.structuredContent??e.structuredContent;if(t?.scenario?.id)$m=t.manifestRevision,Xs(t.scenario.id,t.manifestRevision,t.manifestUri==="ads://preview/live","",t.build?.current===!1)};ye.onhostcontextchanged=Om;ye.onteardown=async()=>(++lt,clearInterval(hl),await ei.dispose(),{});try{if(await ye.connect(),Om(ye.getHostContext()??{}),!ye.getHostCapabilities()?.serverResources)throw Error("This host does not forward MCP resource reads. Open the same preview in the ADS showcase.");hl=setInterval(()=>{w_()},150);let e=document.getElementById("ads-preview-selection");if(e)Xs(JSON.parse(e.textContent).id)}catch(e){Oe(e.message,!0)}window.addEventListener("pagehide",()=>{clearInterval(hl),ei.dispose()},{once:!0});
@@ -39,9 +39,10 @@ export class PreviewResourceLoader {
39
39
  for (const [uri, record] of Object.entries(manifest.assets)) {
40
40
  if (!/^ads:\/\/assets\/[a-f0-9]{64}\.[a-z0-9]+$/.test(uri) || !/^sha256:[a-f0-9]{64}$/.test(record.digest)
41
41
  || !["imports", "dynamicImports", "styles", "references"].every(key => Array.isArray(record[key]) && record[key].every(ref => Object.hasOwn(manifest.assets, ref)))) throw new Error("Invalid preview dependency graph.");
42
- if (this.records.has(uri) && this.records.get(uri).digest !== record.digest) throw new Error("An immutable preview resource changed its content.");
43
- this.records.set(uri, record);
42
+ if (this.records.has(uri) && this.records.get(uri).digest !== record.digest) throw Object.assign(new Error("An immutable preview resource changed its content. Rebuild previews with the current ADS version."), {code:"ADS_RESOURCE_IDENTITY", category:"build", resourceUri:uri});
44
43
  }
44
+ // A rejected graph must not leave a partially registered revision behind.
45
+ for (const [uri, record] of Object.entries(manifest.assets)) this.records.set(uri, record);
45
46
  }
46
47
  async resource(uri) {
47
48
  if (!this.bytes.has(uri)) {
@@ -1,3 +1,6 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { executionContext } from "./execution-context.mjs";
3
+ import { createExecutionCoordinator } from "./execution-coordinator.mjs";
1
4
  import { existsSync, readFileSync, statSync, watch } from "node:fs";
2
5
  import path from "node:path";
3
6
  import { Server, ProtocolError, INVALID_PARAMS, ResourceNotFoundError } from "@modelcontextprotocol/server";
@@ -81,7 +84,11 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
81
84
  startPreview: workspace => startAdsMcp(workspace, { stdio: false, mutations: false, previewWork: cache.previewWork }) });
82
85
  const verification = cache.verification ??= createVerificationController(root, { previewWork: cache.previewWork });
83
86
  const validation = cache.validation ??= createValidationController(root, { previewWork: cache.previewWork });
84
- const executionResults = cache.executionResults ??= createExecutionResults(root);
87
+ const executionResults = cache.executionResults ??= createExecutionResults(root,{retention:()=>{try{cache.resultRetention=loadConfig(root).config.mcp.resultRetention;}catch{/* Keep the last valid policy during config edits. */}return cache.resultRetention;}});
88
+ const executionObservers=cache.executionObservers??=new Set();
89
+ const coordinator=cache.coordinator??=createExecutionCoordinator(root,{results:executionResults,onChange:()=>{for(const observer of executionObservers)observer();}});
90
+ const connectionId=randomUUID();
91
+ void coordinator.ready().catch(error=>process.stderr.write(`ads mcp: execution recovery: ${error.message}\n`));
85
92
  const reports = cache.reports ??= createReportStore(root, { context: reportContext, resolveEvidence: reportEvidence });
86
93
  let options = loadConfig(root);
87
94
  const signature = `${root}:${JSON.stringify(options.config)}`;
@@ -296,6 +303,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
296
303
  build: summarizeBuild(builds()),
297
304
  previews: previews(), skills: skills.skills.map(({ uri, frontmatter }) => ({ uri, name: frontmatter.name, description: frontmatter.description })),
298
305
  scenarios: { count: registry.scenarios.length, diagnostics: registry.diagnostics, resourceUri: `${PROJECT_URI}/scenarios`, tool: "ads_show_scenario" },
306
+ execution: coordinator.status(),
299
307
  validation: { ...validation.status(), tool: "ads_validate", lastResult: executionResults.latest("validation") },
300
308
  behaviors: { resourceUri: BEHAVIOR_URI, discoveryTool: "ads_behaviors", verificationTool: "ads_verify", investigationTool: "ads_investigate", investigationResourceUri: INVESTIGATIONS_URI, ...behaviorState, progress: compactProgress(behaviorState.progress), lastResult: executionResults.latest("verification"), resultsTool: "ads_results", resultsResourceUri: RESULTS_URI },
301
309
  captures: { resourceUri: CAPTURES_URI, tool: "ads_capture", clearTool: "ads_capture_clear", ...captures.status() },
@@ -391,12 +399,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
391
399
  }
392
400
 
393
401
  async function finishExecution(kind, result) {
402
+ if(executionContext.getStore()?.record.instanceId===coordinator.status().instanceId)return result;
394
403
  const summary = executionResults.save(kind, result);
395
404
  try { await refresh(); } catch (error) { process.stderr.write(`ads mcp: result saved; notification failed: ${error.message}\n`); }
396
405
  return { ...json(summary), ...(!result.ok ? { isError: true } : {}) };
397
406
  }
398
407
  async function applyEdits(args,signal,progress) {
399
- if (validation.status().busy) throw new Error("Wait for the active validation run before editing source.");
400
408
  const result = await edits.apply(args,signal,progress);
401
409
  if (result.screenshots) await refresh();
402
410
  if (result.applied) {
@@ -425,7 +433,6 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
425
433
  { name:"ads_update_draft", description:"Update marked draft source or register new/deleted canonical target paths. Pass the current revision from ads_drafts. Source is UTF-8 unless encoding:base64; content:null proposes deletion. refresh:true rebases onto current accepted source using stored baselines; non-overlapping edits merge and overlapping edits leave the draft unchanged with diagnostics. Use changes with refresh only for explicit resolved contents of existing draft files; refresh separately from dependency changes. Optional dependencies replaces the draft dependency list. Normal local file edits need no iteration tool. Accepted source remains unchanged; ownership and all required checks run at acceptance.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema,refresh:z.boolean().default(false),dependencies:z.array(draftIdSchema).max(8).optional(),changes:z.array(z.object({unit:z.string().max(256),path:z.string().min(1).max(500),content:z.string().max(256*1024).nullable(),encoding:z.enum(["utf8","base64"]).optional()}).strict()).max(32).default([])}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,idempotentHint:false},call:async args=>{const result=drafts.update(args);if(observeChanges)await refresh();return json(result);} },
426
434
  { name:"ads_drop_draft",description:"Delete an exact tracked draft and its generated preview. This is Drop, not a separate refusal workflow. Accepted source is unchanged. Dependents report a missing dependency until corrected.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async args=>{const result=await drafts.drop(args);if(observeChanges)await refresh();return json(result);} },
427
435
  { name:"ads_accept",title:"Accept a reviewed draft",description:"Auto-mode acceptance: validate and apply the exact rendered/reviewed draft revision in one operation. Accept dependency drafts first; dependent drafts automatically switch to their final @ds implementations. Mandatory ADS guards and acceptance.checks run once on the candidate; affected registered tests gate acceptance when acceptance.behaviorChecks is true. Draft/source changes invalidate acceptance. On failure retain the draft and inspect ads_results; on success apply normal source, remove the draft and publish an event. No additional human approval or manual Apply step.",schema:z.object({id:draftIdSchema,revision:draftRevisionSchema}).strict(),_meta:{ui:{visibility:["model"]}},annotations:{...annotations,readOnlyHint:false,destructiveHint:true,idempotentHint:false},call:async(args,signal,progress)=>{
428
- if(validation.status().busy||verification.status().running)throw new Error("Wait for validation/verification before acceptance.");
429
436
  const result=await drafts.accept(args,signal,progress);
430
437
  if(result.applied){await previewWatch?.invalidate?.();await refresh(true);}else await refresh();
431
438
  return finishExecution("mutation",result);
@@ -505,16 +512,14 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
505
512
  return json({ widget: { resourceUri: TOKENS_APP_URI }, category: null, tokenCount: inspectTokens(root).tokens.length, dataUri: `${PROJECT_URI}/tokens`, showcaseUrl: getShowcaseUrl() });
506
513
  } },
507
514
  { name: "ads_behaviors", description: "Discover behavior owners, then page an exact unit's checks, guarantees, subjects, demonstrations or profiles. Summary listings never embed runner logs. Default 10/max 20 entries and 8 KiB JSON per page; continue with nextCursor and identical filters. Cursors expire when discovery/evidence changes. Read sourceFile with ads_read_file for a complete contract. Metadata and reachable calls do not prove execution; use ads_verify for registered checks.", schema: z.object({ query: z.string().max(200).optional(), unit: z.string().min(1).max(256).optional(), api: z.string().max(200).optional(), section: z.enum(behaviorSections).optional(), ...paged }).strict(), call: args => json(behaviorPage(options,args)) },
508
- { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Only the latest validation, verification and mutation snapshots are retained; replaced IDs fail explicitly. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
515
+ { name: "ads_results", title: "Read execution outcomes", description: "Read saved ads_validate/ads_verify/ads_apply_patch/ads_apply_transaction outcomes without rerunning anything. Pass the returned resultId; select outcomes, checks, diagnostics, advisories, warnings, changes, captures, acceptance, investigation or selection. Default 10/max 20 rows, at most 8 KiB JSON per page. Follow nextCursor with identical section/status. Rows marked detailTruncated can be read in full using recordIndex and offset/chars (max 2000); follow nextOffset. Results are retained by immutable run ID with bounded age/count/disk retention, including after reconnect or other clients finish. Expired IDs fail with ADS_RESULT_EXPIRED. For one outcome's browser evidence use ads_investigate with its exact unit/check/runId.", schema: z.object({ resultId: z.string().uuid(), section: z.enum(resultSections).optional(), status: z.enum(["all","passed","not_passed"]).optional(), ...paged, ...recordRange }).strict(), call: args => json(executionResults.page(args)) },
509
516
  { name:"ads_report_bug",title:"Report a suspected ADS defect",description:"Record an unexpected ADS guard, preview, build, transport or runner behavior after targeted investigation. Provide expected/observed behavior, minimal steps and frequency; keep suspectedCause separate. Evidence optionally selects a returned resultId or exact unit/check/runId. ADS snapshots compact evidence, version, configured framework and revisions. A report is an untriaged agent claim, not proof of an ADS cause. Returns a small receipt with the report ID and local file path; submitted reports cannot be read through MCP. Stored locally under .ds/reports/ with deduplication, no automatic expiry and no upload. Read ads://guides/reporting; ordinary valid guard rejections should be fixed in their owner.",schema:bugReportSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("bug",args) },
510
517
  { name:"ads_request_feature",title:"Request an ADS capability",description:"Record a legitimate workflow that needs a missing ADS capability. Provide workflow, capability and impact; proposal is optional. Preserve valid design/API rather than weakening guards or inventing workaround props. Optional evidence references an existing execution/check, not pasted files/logs. ADS attaches compact context and returns a receipt with the report ID and local file path. Intake is submission-only; no report-reading tools or resources. Shared local report store: deduplicated, untriaged, no automatic expiry or upload. Read ads://guides/reporting; use ads_report_bug for suspected broken existing behavior.",schema:featureRequestSchema,annotations:{readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false},call:args=>submitReport("feature",args) },
511
- { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Only the latest bundle per check is retained, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
518
+ { name: "ads_investigate", title: "Inspect check evidence", description: "Read a summary for an exact unit/check, or list latest investigations when no check is selected. Pass the outcome's runId to reject superseded evidence. Summary is at most 4 KiB JSON; details, requests, browserErrors and artifacts are separate paged sections (default 10/max 20 entries, 8 KiB). Read truncated rows with recordIndex/offset/chars and the exact runId. Artifact URIs are read separately. Does not rerun checks or infer root cause. Lists latest checks; an exact runId reads retained historical evidence, including candidate runs.", schema: z.object({unit:z.string().min(1).max(256).optional(),check:z.string().min(1).max(100).optional(),runId:z.string().min(1).max(100).optional(),section:z.enum(investigationSections).optional(),...paged,...recordRange}).strict(), call: args => json(investigationPage(root,args)) },
512
519
  { name: "ads_validate", description: "Run mandatory ADS architecture/freshness guards and the selected project policy. policy defaults to validation: its configured scripts, preview freshness and optional registered behavior checks. policy acceptance runs acceptance.checks and acceptance.behaviorChecks without applying source, for direct editing. No script names are inferred. scope changed selects affected registered checks from this policy's own successful full baseline; broad changes expand to all. Project scripts keep full scope. Draft edit/show never triggers policies. Reports skipped stages honestly and a bounded resultId; use ads_results for details. Read ads://guides/validation. Trusted configured commands run; nothing is installed.", schema: z.object({scope:z.enum(["all","changed"]).default("all"),policy:z.enum(["acceptance","validation"]).default("validation")}).strict(), annotations: {readOnlyHint:false,destructiveHint:false,idempotentHint:false,openWorldHint:false}, call: async (args,signal,progress) => {
513
- if (verification.status().running || edits.status().busy) throw new Error("Wait for the active verification or guarded edit before validating.");
514
520
  return finishExecution("validation",await validation.run(args,signal,progress));
515
521
  } },
516
522
  { name: "ads_verify", description: "Run one owner's registered development behavior checks using its configured runner/profile. Executes trusted project commands with bounded output, cancellation and process-tree cleanup; installs nothing. Progress and per-check timings are available through ads_status; a profile timeout bounds the whole run. Browser profiles use an isolated managed showcase/MCP App. React StrictMode requires a project development harness, not a production widget. Missing/skipped cases, stale inputs and process exit alone cannot produce passing evidence. Replies contain counts, acceptance, at most three failure summaries and a resultId (4 KiB JSON maximum). Page outcomes with ads_results; inspect one exact unit/check/runId with ads_investigate. Discover exact unit/check IDs with ads_behaviors first.", schema: z.object({ unit: z.string().min(1).max(256), checks: z.array(z.string().min(1).max(100)).min(1).max(100).optional() }).strict(), annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false }, call: async (args, signal, progress) => {
517
- if (validation.status().busy) throw new Error("Wait for the active validation run before verifying separately.");
518
523
  const result = await verification.run(args, signal, progress);
519
524
  return finishExecution("verification", {unit:args.unit,...result});
520
525
  } },
@@ -556,10 +561,26 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
556
561
  let progress = 0;
557
562
  const token = context.mcpReq._meta?.progressToken;
558
563
  const notify = token === undefined ? undefined : value => {
559
- void context.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: ++progress, message: value.message ?? `${value.profile}: ${value.completed}/${value.total} completed; ${(value.active ?? []).slice(0,3).map(item => `${item.unit}#${item.check}`).join(", ") || "no active check reported"}; ${value.elapsedMs} ms elapsed` } }).catch(() => {});
564
+ void context.mcpReq.notify({ method: "notifications/progress", params: { progressToken: token, progress: ++progress, message: value.message ?? (value.stage?`${value.stage}: ${value.elapsedMs??0} ms elapsed`:`${value.profile}: ${value.completed}/${value.total} completed; ${(value.active ?? []).slice(0,3).map(item => `${item.unit}#${item.check}`).join(", ") || "no active check reported"}; ${value.elapsedMs} ms elapsed`) } }).catch(() => {});
560
565
  };
561
- try { return await tool.call(input.data, context.mcpReq.signal, notify); }
562
- catch (error) { return { isError: true, content: [{ type: "text", text: error.message }], structuredContent: {ok:false,message:error.message,failure:failure(error.build?"build":"runner",error.build?"preview-build":"tool-execution",error.build?.code??"ADS_TOOL_ERROR",{certainty:"observed-boundary"}),...(error.build?{build:error.build}:{})} }; }
566
+ try {
567
+ const kinds={ads_validate:"validation",ads_verify:"verification",ads_apply_patch:"mutation",ads_apply_transaction:"mutation",ads_accept:"mutation"};
568
+ const kind=kinds[name];
569
+ if(!kind)return await tool.call(input.data,context.mcpReq.signal,notify);
570
+ const client=server.getClientVersion?.();
571
+ const label=context.mcpReq._meta?.["ads/clientId"];
572
+ const owner={clientId:typeof label==="string"?label.slice(0,100):null,clientName:client?.name?.slice(0,100)??null,connectionId};
573
+ const args=input.data;
574
+ const selection={...(args.policy?{policy:args.policy}:{}),...(args.scope?{requestedScope:args.scope,scope:args.scope}:{}),units:args.units??args.patches?.map(row=>row.unit)??(args.unit?[args.unit]:[]),...(args.id?{draft:args.id}:{}),...(args.checks?{checks:args.checks}:{})};
575
+ const summary=await coordinator.execute({operation:name,kind,owner,selection,watchSource:kind!=="mutation"},context.mcpReq.signal,notify,(signal,progress)=>{
576
+ if(name==="ads_accept")progress({stage:"selection",policy:"acceptance",scope:"changed",units:drafts.inspect(args.id).manifest.units});
577
+ return tool.call(args,signal,progress);
578
+ });
579
+ const {isError,...value}=summary;
580
+ await refresh();
581
+ return {...json(value),...(isError?{isError:true}:{})};
582
+ }
583
+ catch (error) { return { isError: true, content: [{ type: "text", text: error.message }], structuredContent: {ok:false,message:error.message,...(error.code?{code:error.code}:{}),...(error.lock?{lock:error.lock}:{}),failure:failure(error.build?"build":"runner",error.build?"preview-build":"tool-execution",error.build?.code??error.code??"ADS_TOOL_ERROR",{certainty:"observed-boundary"}),...(error.build?{build:error.build}:{})} }; }
563
584
  });
564
585
  server.setRequestHandler("resources/list", ({ params = {} }) => {
565
586
  previewWatch?.start();
@@ -625,6 +646,12 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
625
646
  const draftBuilds = () => new Map(drafts.previewStatuses().map(build => [build.resourceUri, JSON.stringify(build)]));
626
647
  const investigationFingerprint=()=>fileFingerprint([path.join(root,".ds/investigations.json")]);
627
648
  let previousInvestigations, previousResults, observing=false;
649
+ const executionChanged=()=>{
650
+ const uri=`${PROJECT_URI}/status`;
651
+ if(notifications)notifications.resourceUpdated(uri);
652
+ else if(subscribed.has(uri))void server.sendResourceUpdated({uri}).catch(()=>{});
653
+ };
654
+ executionObservers.add(executionChanged);
628
655
  function initializeObservation() {
629
656
  if (observing) return;
630
657
  previous=fingerprint();previousArtifacts=artifactFingerprint();previousAssets=assetFingerprint();previousBuild=JSON.stringify(builds());
@@ -724,9 +751,9 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
724
751
  const timer = pollInterval > 0 ? setInterval(() => { if (!observationClosed) refresh().catch(error => { if (!observationClosed) process.stderr.write(`ads mcp: ${error.message}\n`); }); }, pollInterval) : null;
725
752
  timer?.unref();
726
753
  if (observeChanges) draftObservers.add(refresh);
727
- const stopObservation = () => { observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
754
+ const stopObservation = () => { executionObservers.delete(executionChanged);observationClosed = true; draftObservers.delete(refresh); if (timer) clearInterval(timer); };
728
755
  server.oninitialized = () => previewWatch?.start();
729
- server.onclose = stopObservation;
756
+ server.onclose = () => {stopObservation();if(!inspection)void coordinator.close().catch(()=>{});};
730
757
  async function warmScenarios(ids, signal) {
731
758
  if (!previewWatch) return;
732
759
  const apps = allApps(), selected = new Set(ids);
@@ -739,7 +766,7 @@ export function createAdsMcp(directory, { era = "legacy", skillDirectory, pollIn
739
766
  await previewWatch.warm(files);
740
767
  for (const file of files) await previewWatch.ensure(file, signal);
741
768
  }
742
- return { server, refresh, warmScenarios, buildAll(signal, options) { previewWatch.setApps(allApps()); return previewWatch.buildAll(signal, options); }, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { stopObservation(); if (!inspection) { await cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
769
+ return { server, refresh, warmScenarios, buildAll(signal, options) { previewWatch.setApps(allApps()); return previewWatch.buildAll(signal, options); }, readResource:read, async callTool(name,args,signal){const tool=tools().find(tool=>tool.name===name);if(!tool)throw new Error("Unknown preview tool.");return tool.call(tool.schema.parse(args),signal);}, async close() { executionObservers.delete(executionChanged);stopObservation(); if (!inspection) { await coordinator.close(); await cache.registryInspector?.close(); await drafts.close(); await validation.close(); await verification.close(); await captures.close(); } await server.close(); } };
743
770
  }
744
771
 
745
772
  export async function startAdsMcp(directory = process.cwd(), { stdio = true, showcase = true, port = 0, mutations = false, previewWork = createPreviewWork(), previewBuildTimeoutMs = 30000, prewarm = stdio } = {}) {
@@ -784,8 +811,10 @@ export async function startAdsMcp(directory = process.cwd(), { stdio = true, sho
784
811
  buildListeners.clear();
785
812
  clearTimeout(buildChangeTimer); buildWatcher?.close();
786
813
  inspection.edits?.cancel();
814
+ const executionClosing=inspection.coordinator?.close();
787
815
  // Stop every owned resource even if another close fails or has in-flight RPCs.
788
816
  const results = await Promise.allSettled([
817
+ executionClosing,
789
818
  Promise.resolve().then(() => host?.close()),
790
819
  previewWatch.stop(),
791
820
  Promise.resolve().then(() => inspection.validation?.close()),