buckyos 0.7.159 → 0.7.160

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.
@@ -44,6 +44,68 @@ export interface AiwsReference {
44
44
  export declare function aiwsReferenceUrl(reference: AiwsReference, workspaceId?: string): string;
45
45
  /** The Reference an `obj://aiworkspace/<ws>/entities/<entity_id>[?...]` URL projects. */
46
46
  export declare function parseAiwsReferenceUrl(url: string): AiwsReference;
47
+ export interface AiwsExtBuildParams {
48
+ files: ({
49
+ name: string;
50
+ obj_id: string;
51
+ } | {
52
+ name: string;
53
+ base64: string;
54
+ })[];
55
+ folder_id?: string;
56
+ expect?: {
57
+ def_rev: number;
58
+ dir_rev: number;
59
+ };
60
+ force?: boolean;
61
+ dry_run?: boolean;
62
+ provenance?: {
63
+ pkg_id?: string;
64
+ version?: string;
65
+ digest?: string;
66
+ };
67
+ idempotency_key?: string;
68
+ }
69
+ /** `ext.build` / `ext.import`: one entry per control (`created | rebuilt | unchanged | satisfied`), the first also at the top. */
70
+ export interface AiwsExtBuildResult {
71
+ status: 'accepted' | 'unchanged' | 'checked';
72
+ commit_id?: string;
73
+ seq?: number;
74
+ unchanged?: boolean;
75
+ ident?: string;
76
+ def_entity_id?: string;
77
+ dir_entity_id?: string;
78
+ version?: number;
79
+ def_rev?: number;
80
+ dir_rev?: number;
81
+ action?: string;
82
+ build?: {
83
+ input_digest: string;
84
+ builder_version: string;
85
+ built_at: string;
86
+ };
87
+ controls: Record<string, unknown>[];
88
+ diagnostics: Record<string, unknown>[];
89
+ }
90
+ export interface AiwsLibraryPackage {
91
+ pkg_id: string;
92
+ version: string;
93
+ title: string;
94
+ author: string;
95
+ mode: string;
96
+ installed_at: string;
97
+ controls: {
98
+ ident: string;
99
+ name: string;
100
+ kind: string;
101
+ version: number;
102
+ digest: string;
103
+ dir: string;
104
+ title?: string;
105
+ description?: string;
106
+ catalog?: Record<string, unknown>;
107
+ }[];
108
+ }
47
109
  /** What an executor outside the service reports for a run (M3): results in the Mock executor's shape, or an analysis. */
48
110
  export interface AiwsRunReport {
49
111
  run_id: string;
@@ -82,6 +144,87 @@ export declare class AiWorkspaceClient {
82
144
  /** The three-state commit result (`status: accepted | conflict | rejected`), never thrown. */
83
145
  commit(workspace_id: string, request: Record<string, unknown>): Promise<Record<string, unknown>>;
84
146
  getSubmission(workspace_id: string, epoch: string, idempotency_key: string): Promise<Record<string, unknown>>;
147
+ /** Changes after `after_seq` (`filter.detail: "touched"` for the touched entities only). */
148
+ getChanges(workspace_id: string, epoch: string, after_seq: number, opts?: {
149
+ limit?: number;
150
+ touchedOnly?: boolean;
151
+ }): Promise<Record<string, unknown>>;
152
+ /** Long poll until the head passes `after_seq` (or `timeout_ms`). */
153
+ waitChanges(workspace_id: string, after_seq: number, opts?: {
154
+ epoch?: string;
155
+ timeout_ms?: number;
156
+ }): Promise<{
157
+ epoch: string;
158
+ head_seq: number;
159
+ timed_out: boolean;
160
+ }>;
161
+ /** A whole-Workspace package (`.bcanvas`): `download` names it in the owner's exports bucket. */
162
+ exportDoc(workspace_id: string, mode: 'share' | 'personal_backup', self_contained: boolean, include_notes?: boolean): Promise<Record<string, unknown>>;
163
+ /** Register a FileObject as a staged asset: `{ bucket_id, key }` (the uploader's binding) or `{ obj_id }`. */
164
+ assetImportObject(workspace_id: string, source: {
165
+ bucket_id: string;
166
+ key: string;
167
+ } | {
168
+ obj_id: string;
169
+ }): Promise<{
170
+ object_id: string;
171
+ media_type: string;
172
+ size: number;
173
+ }>;
174
+ controlsList(): Promise<Record<string, unknown>>;
175
+ controlsDescribe(kind: string): Promise<Record<string, unknown>>;
176
+ controlsImport(workspace_id: string, params: Record<string, unknown>): Promise<Record<string, unknown>>;
177
+ controlsExport(workspace_id: string, entity_id: string, format?: 'markdown' | 'opml'): Promise<Record<string, unknown>>;
178
+ /** Build one control's source files into the Workspace; `BUILD_FAILED` carries `data.diagnostics`. */
179
+ extBuild(workspace_id: string, params: AiwsExtBuildParams): Promise<AiwsExtBuildResult>;
180
+ /** The bundle of definitions (`purpose: pull` needs read only and synthesizes the source of never-built ones). */
181
+ extExport(workspace_id: string, entity_ids: string[], purpose?: 'package' | 'pull'): Promise<{
182
+ manifest: Record<string, unknown>;
183
+ controls: Record<string, unknown>[];
184
+ files: {
185
+ path: string;
186
+ obj_id?: string;
187
+ size: number;
188
+ text?: string;
189
+ }[];
190
+ }>;
191
+ /** Into the caller's library: a `.pikg` object, or definitions of a Workspace (`from` + `package`). */
192
+ extInstall(params: {
193
+ pikg?: {
194
+ obj_id: string;
195
+ };
196
+ from?: {
197
+ workspace_id: string;
198
+ entity_ids: string[];
199
+ };
200
+ package?: {
201
+ name: string;
202
+ version?: string;
203
+ title?: string;
204
+ };
205
+ mode?: 'dev';
206
+ }): Promise<{
207
+ pkg_id: string;
208
+ version: string;
209
+ action: string;
210
+ controls: Record<string, unknown>[];
211
+ }>;
212
+ extListLibrary(): Promise<{
213
+ packages: AiwsLibraryPackage[];
214
+ }>;
215
+ extUninstall(pkg_id: string): Promise<Record<string, unknown>>;
216
+ /** A library package's controls with their bytes (base64): what a client relays into a Workspace of another Zone. */
217
+ extLibraryBundle(pkg_id: string, idents?: string[]): Promise<{
218
+ pkg_id: string;
219
+ controls: Record<string, unknown>[];
220
+ }>;
221
+ /** Bring library controls into a Workspace of this Zone (one Commit). */
222
+ extImport(workspace_id: string, items: {
223
+ pkg_id: string;
224
+ ident: string;
225
+ }[], opts?: {
226
+ folder_id?: string;
227
+ }): Promise<AiwsExtBuildResult>;
85
228
  runStart(workspace_id: string, program: string, params: Record<string, unknown>, idempotency_key: string): Promise<Record<string, unknown>>;
86
229
  runGet(workspace_id: string, run_id: string, choices?: Record<string, unknown>): Promise<Record<string, unknown>>;
87
230
  runList(workspace_id: string, wish_id?: string, limit?: number): Promise<Record<string, unknown>>;
@@ -1 +1 @@
1
- {"version":3,"file":"aiworkspace_client.d.ts","sourceRoot":"","sources":["../src/aiworkspace_client.ts"],"names":[],"mappings":"AACA,O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MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM;IAGvF,SAAS,CAAC,YAAY,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;CAC/C"}
@@ -0,0 +1,2 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e="component.json",t="aiws-manifest.json",r=".aiws-build.json";class i extends Error{constructor(e){super(e.filter((e=>"error"===e.severity)).map((e=>`${e.file?`${e.file}: `:""}${e.message}`)).join("; ")||"invalid control source"),this.name="AiwsSourceError",this.diagnostics=e}}const n=new TextEncoder,s=new TextDecoder;function o(e){return e.replace(/[/\\\u0000-\u001f]/g," ").replace(/^\.+/,"").trim().slice(0,80)||"Workspace"}async function a(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),(e=>e.toString(16).padStart(2,"0"))).join("")}async function c(e){const t=[];for(const[r,i]of e)t.push([r,await a(i)]);return t.sort(((e,t)=>e[0]<t[0]?-1:e[0]>t[0]?1:0)),`sha256:${await a(n.encode(JSON.stringify(t)))}`}function l(e){return JSON.stringify([...e].sort(((e,t)=>e.name.localeCompare(t.name))).map((e=>[e.name,e.obj_id??e.etag??""])))}const d=4194304;function f(e){let t="";for(let r=0;r<e.length;r+=32768)t+=String.fromCharCode(...e.subarray(r,r+32768));return btoa(t)}async function u(e,t){var r;const n=[];let s=0;for(const o of t){if(null==(r=o.obj_id)?void 0:r.startsWith("cyfile:")){n.push({name:o.name,obj_id:o.obj_id});continue}if(!o.node_id)throw new i([{file:o.name,severity:"error",message:"the file service did not name this file"}]);const t=new Uint8Array(await(await e.readFile(o.node_id)).arrayBuffer());if(s+=t.length,s>d)throw new i([{file:o.name,severity:"error",message:"a control's files are limited to 4194304 bytes per build"}]);n.push({name:o.name,base64:f(t)})}return n}const p=["manifest_version","ident","kind","title","description","host_api","accepts","allow_no_source","default_size","config_schema","bindings","entry","assets","catalog","agent","deps"],m=["type","enum","default","required","title","description","minimum","maximum","minLength","maxLength","properties","items"],y=/^[a-z0-9][a-z0-9._-]{0,63}$/,g=/^did:[a-z0-9]+:[^/#\s]+$/,h=/^[a-z][a-z0-9_]{0,31}$/;function w(e,t,r){if(e&&"object"==typeof e&&!Array.isArray(e))for(const[i,n]of Object.entries(e))if(m.includes(i)){if("properties"===i&&n&&"object"==typeof n)for(const[e,i]of Object.entries(n))w(i,`${t}/properties/${e}`,r);"items"===i&&w(n,`${t}/items`,r)}else r.push(`${t}/${i}: keyword ${i} is outside the supported subset`);else r.push(`${t}: a schema is an object`)}function _(t,r){const i=[],s=e,o=e=>i.push({file:s,severity:"error",message:e});let a;try{const e=JSON.parse(t);if(!e||"object"!=typeof e||Array.isArray(e))return o("must be a JSON object"),i;a=e}catch(u){return o(u instanceof Error?u.message:String(u)),i}for(const e of Object.keys(a))p.includes(e)||o(`unknown key ${e}`);const c=a.manifest_version;"number"!=typeof c||!Number.isInteger(c)||c<1?o("manifest_version (1) required"):c>1&&o(`manifest_version ${c} is newer than this client reads (1)`);const l=a.ident;if(l&&"object"==typeof l?("string"==typeof l.author_did&&g.test(l.author_did)||o("ident.author_did must be a DID (did:<method>:<id>)"),"string"==typeof l.name&&y.test(l.name)||o("ident.name must be [a-z0-9][a-z0-9._-]{0,63}"),"string"==typeof l.author_did&&"string"==typeof l.name&&n.encode(`${l.author_did}#${l.name}`).length>128&&o("an identity is at most 128 bytes")):o("ident { author_did, name } required"),"declarative"!==a.kind&&"html"!==a.kind&&o("kind must be declarative or html"),("string"!=typeof a.title||!a.title||a.title.length>256)&&o("title: 1…256 characters"),void 0!==a.config_schema){const e=[];w(a.config_schema,"config_schema",e),e.forEach(o)}if(void 0!==a.bindings)if(a.bindings&&"object"==typeof a.bindings)for(const e of Object.keys(a.bindings))h.test(e)&&"props"!==e||o(`binding name ${e}: [a-z][a-z0-9_]{0,31}, not props`);else o("bindings must be an object");Array.isArray(a.deps)&&a.deps.length>0&&o("deps must be empty: dependencies between controls come in a later version");const d=e=>"string"==typeof e&&r.includes(e),f=new Set([s]);if("html"===a.kind){const e=a.entry;if(e&&"object"==typeof e&&"string"==typeof e.html)for(const[t,r]of Object.entries(e))d(r)?f.add(String(r)):o(`entry.${t} ${JSON.stringify(r)} is not in the directory`);else o("entry must be { html, css?, js? }");void 0!==a.host_api&&2!==a.host_api&&o("host_api: the HTML Block host speaks API 2")}else"declarative"===a.kind&&(d(a.entry)?f.add(String(a.entry)):o(`entry ${JSON.stringify(a.entry)} is not in the directory`));for(const e of Array.isArray(a.assets)?a.assets:[])d(e)?f.add(String(e)):o(`asset ${JSON.stringify(e)} is not in the directory`);void 0!==a.agent&&(d(a.agent)?f.add(String(a.agent)):o(`agent ${JSON.stringify(a.agent)} is not in the directory`));for(const e of r)f.has(e)||i.push({file:e,severity:"warning",message:"not named by component.json: kept in the source snapshot only"});return i}function v(e){if(!e||"object"!=typeof e)throw new i([{file:t,severity:"error",message:"must be a JSON object"}]);const r=e,n=r.manifest_version;if("number"!=typeof n||n<1)throw new i([{file:t,severity:"error",message:"manifest_version required"}]);if(n>1)throw new i([{file:t,severity:"error",message:`manifest_version ${n} needs a newer client (this one reads 1)`}]);if("aiws"!==r.purpose)throw new i([{file:t,severity:"error",message:"purpose must be aiws"}]);if(!Array.isArray(r.controls))throw new i([{file:t,severity:"error",message:"controls must be an array"}]);return{manifest_version:n,purpose:"aiws",host_api:r.host_api??{},controls:r.controls,workspace_templates:Array.isArray(r.workspace_templates)?r.workspace_templates:[]}}async function b(e,t,r){const i=/[*?[\]\\]/.test(r)?void 0:r;return(await e.list("string"==typeof t?t:{ref:t},{limit:i?10:1e3,...i?{filter:{name_glob:i}}:{}},["base","ident"])).entries.find((e=>e.name===r))}async function S(e,t){const r=t.split("/").filter(Boolean);if(0===r.length)throw new Error(`not a folder path: ${t}`);let n=(await e.stat(`/${r[0]}`)).ref;for(const s of r.slice(1)){const r=await b(e,n,s);if(r&&"dir"!==r.target.kind)throw new i([{file:s,severity:"error",message:`${s} in ${t} is not a folder`}]);n=r?r.target.ref:(await e.mkdir({ref:n},s)).ref}return n}async function x(e,t){const r=t.split("/").filter(Boolean);if(0===r.length)return null;let i=(await e.stat(`/${r[0]}`)).ref;for(const n of r.slice(1)){const t=await b(e,i,n);if(!t||"dir"!==t.target.kind)return null;i=t.target.ref}return i}async function $(e,t,r,i){const n="string"==typeof t?await S(e,t):t;await e.uploadFile(n,r,i,{overwrite:!0})}const k=e=>new Promise((t=>setTimeout(t,e)));async function j(e,t){var r,n,s;const o=[],a=[];let c;do{const i=await e.list(t,{limit:500,...c?{cursor:c}:{}},["base","ident"]);for(const e of i.entries){if(e.name.startsWith("."))continue;if("file"!==e.target.kind){a.push({file:e.name,severity:"error",message:"a control source folder is flat: move files out of sub-folders"});continue}const t=e.target.ref,i="object"===t.type?t.obj_id:"string"==typeof(null==(r=e.target.attrs)?void 0:r.obj_id)?e.target.attrs.obj_id:void 0;o.push({name:e.name,...i?{obj_id:i}:{},..."live"===t.type?{node_id:t.node_id}:{},..."string"==typeof(null==(n=e.target.attrs)?void 0:n.etag)?{etag:e.target.attrs.etag}:{},..."number"==typeof(null==(s=e.target.attrs)?void 0:s.size)?{size:e.target.attrs.size}:{}})}c=i.truncated?i.next_cursor:void 0}while(c);if(0===o.length&&a.push({file:"",severity:"error",message:`${t} holds no files`}),o.length>64&&a.push({file:"",severity:"error",message:"a control holds at most 64 files"}),a.some((e=>"error"===e.severity)))throw new i(a);return o.sort(((e,t)=>e.name.localeCompare(t.name)))}async function A(e,t){try{const i=await b(e,t,r),n="live"===(null==i?void 0:i.target.ref.type)?i.target.ref.node_id:void 0;if(!n)return null;const s=await e.readFile(n);return await s.json()}catch{return null}}async function I(e,t,i){await $(e,t,r,n.encode(`${JSON.stringify(i,null,2)}\n`))}exports.AIWS_BUILD_STATE_FILE=r,exports.AIWS_COMPONENT_FILE=e,exports.AIWS_DECLARATIVE_API_VERSION=1,exports.AIWS_HTML_API_VERSION=2,exports.AIWS_MANIFEST_FILE=t,exports.AIWS_MANIFEST_VERSION=1,exports.AIWS_MAX_INLINE_BYTES=d,exports.AIWS_MAX_SOURCE_FILES=64,exports.AiwsSourceError=i,exports.aiwsContentDigest=c,exports.buildControl=async function(e,t,r,i,n={}){const s=await j(t,i),o=await A(t,i),a=o&&o.workspace_id===r?{def_rev:o.def_rev,dir_rev:o.dir_rev}:void 0,c=await e.extBuild(r,{files:await u(t,s),...n.folderId?{folder_id:n.folderId}:{},...a?{expect:a}:{},...n.force?{force:!0}:{},...n.dryRun?{dry_run:!0}:{}});return n.dryRun||"string"!=typeof c.def_entity_id||"number"!=typeof c.def_rev||await I(t,i,{workspace_id:r,def_entity_id:c.def_entity_id,def_rev:c.def_rev,dir_rev:Number(c.dir_rev??0),ident:String(c.ident??""),at:(new Date).toISOString()}),{...c,files:s}},exports.buildFiles=u,exports.checkComponent=_,exports.collectSources=j,exports.compatManifest=v,exports.controlSkeleton=function(t){const r=t.title??t.name,i={manifest_version:1,ident:{author_did:t.authorDid,name:t.name},kind:t.kind??"declarative",title:r,description:`${r}: a control of this Workspace`,accepts:["buckyos.table-source","buckyos.record"],allow_no_source:!0,default_size:{w:260,h:140},config_schema:{type:"object",properties:{label:{type:"string",title:"Label",default:r}}},bindings:{data:{accepts:["buckyos.table-source"],title:"Data",description:"The table this control summarizes"}},catalog:{group:"custom",description:`${r}`},agent:"AGENT.md"},n=`# ${r}\n\nBind \`data\` to a table. Config: \`label\` (text).\n`;return"html"===t.kind?{[e]:`${JSON.stringify({...i,host_api:2,entry:{html:"view.html",css:"style.css",js:"behavior.js"}},null,2)}\n`,"view.html":'<div class="card"><div class="label" id="label"></div><div class="value" id="value">—</div></div>\n',"style.css":".card{font:14px system-ui;padding:12px}.label{opacity:.7}.value{font-size:28px;font-weight:600}\n","behavior.js":"document.getElementById('label').textContent = (aiws.context.config || {}).label || ''\nif (aiws.bindings.data) aiws.input('data').rows().then(function (rows) { document.getElementById('value').textContent = String(rows.length) })\n","AGENT.md":n}:{[e]:`${JSON.stringify({...i,entry:"declarative.json"},null,2)}\n`,"declarative.json":`${JSON.stringify({layout:"stack",items:[{kind:"metric",label:r,bind:"data.count",format:"number"},{kind:"text",text:"Rows of the bound table"}]},null,2)}\n`,"AGENT.md":n}},exports.createControlSource=async function(t,r,s){const o=await S(t,r),a=await t.list({ref:o},{limit:500},["base"]).catch((()=>null));if(null==a?void 0:a.entries.some((t=>t.name===e)))throw new i([{file:e,severity:"error",message:`${r} already holds a control`}]);for(const[e,i]of Object.entries(s))await $(t,o,e,n.encode(i));return o},exports.ensureFolder=S,exports.exportBundle=async function(e,r,i,s){const o=await e.extExport(r,i,"package"),a=new Map;a.set(t,n.encode(`${JSON.stringify(o.manifest,null,2)}\n`));for(const t of o.files)a.set(t.path,void 0!==t.text?n.encode(t.text):await s(r,String(t.obj_id)));return{manifest:v(o.manifest),files:a,controls:o.controls}},exports.findFolder=x,exports.folderName=o,exports.hasControlSource=async function(t,r){const i=await x(t,r);return null!==i&&void 0!==await b(t,i,e)},exports.homeControlDir=function(e,t,r){return`/home/${e}/AI Workspace/${o(t)}/controls/${r}`},exports.homeExportDir=function(e,t){return`/home/${e}/AI Workspace/exports/${t}`},exports.joinPath=function(e,t){return`${e.replace(/\/+$/,"")}/${t}`},exports.pullControl=async function(e,t,r,i,s,o){const a=(await e.extExport(r,[i],"pull")).controls[0],c=await S(t,s);for(const d of a.files)await $(t,c,d.name,void 0!==d.text?n.encode(d.text):await o(r,String(d.obj_id)));const l={workspace_id:r,def_entity_id:a.entity_id,def_rev:a.def_rev,dir_rev:a.dir_rev,ident:a.ident,at:(new Date).toISOString()};return await I(t,s,l),{files:a.files.map((e=>e.name)),state:l}},exports.readBuildState=A,exports.sourceStateKey=function(e){return`aiws:src:${e}`},exports.sourcesKey=l,exports.verifyBundle=async function(r){var n,o;const a=r.get(t);if(!a)throw new i([{file:t,severity:"error",message:"missing"}]);let l;try{l=JSON.parse(s.decode(a))}catch(p){throw new i([{file:t,severity:"error",message:String(p)}])}const d=v(l),f=[];d.workspace_templates.length>0&&f.push({file:t,severity:"error",message:"Workspace templates are not supported yet"}),0===d.controls.length&&f.push({file:t,severity:"error",message:"lists no control"});const u=new Set;for(const i of d.controls){if("string"!=typeof i.dir||!/^controls\/[a-z0-9][a-z0-9._-]{0,70}\/$/.test(i.dir)||u.has(i.dir)){f.push({file:t,severity:"error",message:`control ${i.ident}: bad or repeated dir`});continue}u.add(i.dir);const a=[...r].filter((([e])=>e.startsWith(i.dir))).map((([e,t])=>[e.slice(i.dir.length),t]));a.some((([e])=>e.includes("/")))&&f.push({file:i.dir,severity:"error",message:"a control directory is flat"}),await c(a)!==i.digest&&f.push({file:i.dir,severity:"error",message:"the files do not match the manifest digest"});const l=a.find((([t])=>t===e));if(l){for(const e of _(s.decode(l[1]),a.map((([e])=>e))))f.push({...e,file:`${i.dir}${e.file}`});try{const e=JSON.parse(s.decode(l[1]));`${null==(n=e.ident)?void 0:n.author_did}#${null==(o=e.ident)?void 0:o.name}`===i.ident&&e.kind===i.kind||f.push({file:i.dir,severity:"error",message:"ident and kind must match its component.json"})}catch{}}else f.push({file:`${i.dir}${e}`,severity:"error",message:"missing"})}for(const e of r.keys())e===t||[...u].some((t=>e.startsWith(t)))||f.push({file:e,severity:"error",message:"belongs to no control of the manifest"});return{manifest:d,diagnostics:f}},exports.watchControl=async function(e,t,r,i={}){var n,s;let o,a="",c=Promise.resolve();const d=()=>{c=c.then((async()=>{let i;try{i=await j(e,t)}catch{return}const n=l(i);n!==a&&(a=n,await r(i))})).catch((()=>{}))};for(d();!(null==(n=i.signal)?void 0:n.aborted);){const r=await e.list(t,{limit:1},["base"]),n=e.watch({tokens:r.watch_token?[r.watch_token]:[],signal:i.signal});try{for await(const e of n)o&&clearTimeout(o),o=setTimeout(d,i.debounceMs??500)}catch{if(null==(s=i.signal)?void 0:s.aborted)break;await k(2e3)}finally{n.close()}}o&&clearTimeout(o),await c},exports.writeBuildState=I,exports.writeHomeFile=$;
2
+ //# sourceMappingURL=aiws_ext.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiws_ext.cjs","sources":["../src/aiws_ext.ts"],"sourcesContent":["/**\n * AI Workspace extension controls (buckyos src/frame/aiworkspace/README.md “Extension controls”), shared by the\n * Desktop and the CLI: a control's source lives in a (flat) home folder of the Zone file service; `build` lists it\n * over NFSP and hands each file's object to `ext.build`, `pull` writes a Workspace snapshot back, `watch` rebuilds on\n * change; bundles (the AIWS manifest plus `controls/<dir>/<file>`) are what exports, packages and the library carry.\n * Runs in browsers and Deno (fetch, crypto.subtle); no dependencies.\n */\nimport type { AiWorkspaceClient } from './aiworkspace_client'\nimport type { NfspClient, WireRef } from './nfsp'\n\n/** The two service calls these drivers make (an `AiWorkspaceClient`, or a host's own session with the same shape). */\nexport type AiwsExtRpc = Pick<AiWorkspaceClient, 'extBuild' | 'extExport'>\n\nexport const AIWS_COMPONENT_FILE = 'component.json'\nexport const AIWS_MANIFEST_FILE = 'aiws-manifest.json'\n/** A client's own record of the base it last built or pulled (never part of the source snapshot: dot files are not). */\nexport const AIWS_BUILD_STATE_FILE = '.aiws-build.json'\n/** The newest component.json / AIWS manifest version this module reads (older ones stay readable, Q19). */\nexport const AIWS_MANIFEST_VERSION = 1\n/** The HTML Block host API (`window.aiws` v2) and the declarative interpreter version. */\nexport const AIWS_HTML_API_VERSION = 2\nexport const AIWS_DECLARATIVE_API_VERSION = 1\nexport const AIWS_MAX_SOURCE_FILES = 64\n\n/**\n * One file of a source folder. `obj_id` is set when the file service holds it as a named-store FileObject (`cyfile:`):\n * the service then reads it by reference. Files of a native home folder have none (their `obj_id`, when the file\n * service reports one, is a `sha256:` content hash the service cannot fetch): their bytes travel with the build.\n */\nexport interface AiwsSourceFile { name: string; obj_id?: string; node_id?: string; etag?: string; size?: number }\nexport interface AiwsDiagnostic {\n file: string\n line?: number\n col?: number\n severity: 'error' | 'warning'\n message: string\n /** Cells whose contract a rebuild would break. */\n instances?: { entity_id: string; title?: string | null }[]\n}\nexport interface AiwsBuildState { workspace_id: string; def_entity_id: string; def_rev: number; dir_rev: number; ident?: string; at?: string }\nexport interface AiwsManifestControl { ident: string; name: string; kind: string; version: number; digest: string; dir: string; title?: string; description?: string; catalog?: Record<string, unknown> }\nexport interface AiwsManifest { manifest_version: number; purpose: 'aiws'; host_api?: Record<string, number>; controls: AiwsManifestControl[]; workspace_templates: unknown[] }\nexport interface AiwsBundle { manifest: AiwsManifest; files: Map<string, Uint8Array> }\n\n/** A source directory that cannot be built as it is (not a service refusal: `diagnostics` say why). */\nexport class AiwsSourceError extends Error {\n readonly diagnostics: AiwsDiagnostic[]\n constructor(diagnostics: AiwsDiagnostic[]) {\n super(diagnostics.filter((d) => d.severity === 'error').map((d) => `${d.file ? `${d.file}: ` : ''}${d.message}`).join('; ') || 'invalid control source')\n this.name = 'AiwsSourceError'\n this.diagnostics = diagnostics\n }\n}\n\nconst encoder = new TextEncoder()\nconst decoder = new TextDecoder()\n\nexport function joinPath(dir: string, name: string): string {\n return `${dir.replace(/\\/+$/, '')}/${name}`\n}\n\n/** A Workspace title as one folder name (no `/`, no leading dot). */\nexport function folderName(title: string): string {\n const cleaned = title.replace(/[/\\\\\\u0000-\\u001f]/g, ' ').replace(/^\\.+/, '').trim()\n return cleaned.slice(0, 80) || 'Workspace'\n}\n\n/** The suggested home folder of a control (README: a suggestion; the definition never stores it). */\nexport function homeControlDir(owner: string, workspaceTitle: string, name: string): string {\n return `/home/${owner}/AI Workspace/${folderName(workspaceTitle)}/controls/${name}`\n}\n\n/** Where a client writes an export bundle before packing it. */\nexport function homeExportDir(owner: string, pkg: string): string {\n return `/home/${owner}/AI Workspace/exports/${pkg}`\n}\n\n/** `user_state` key under which each person remembers the home folder of a definition. */\nexport function sourceStateKey(defEntityId: string): string {\n return `aiws:src:${defEntityId}`\n}\n\n// ---- digests (same canonical forms as the service: store/src/ext.rs)\n\nasync function sha256Hex(bytes: Uint8Array): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', bytes as unknown as ArrayBuffer)\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** `sha256:` over `[[name, sha256 hex of its bytes], …]` sorted by name: a control's content digest. */\nexport async function aiwsContentDigest(files: Iterable<[string, Uint8Array]>): Promise<string> {\n const pairs: [string, string][] = []\n for (const [name, bytes] of files) pairs.push([name, await sha256Hex(bytes)])\n pairs.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))\n return `sha256:${await sha256Hex(encoder.encode(JSON.stringify(pairs)))}`\n}\n\n/** What a set of sources is, for \"nothing changed since the last build\" (names, objects or versions). */\nexport function sourcesKey(files: AiwsSourceFile[]): string {\n return JSON.stringify([...files].sort((a, b) => a.name.localeCompare(b.name)).map((f) => [f.name, f.obj_id ?? f.etag ?? '']))\n}\n\n/** Bytes a single build may carry inline (the service's limit). */\nexport const AIWS_MAX_INLINE_BYTES = 4 * 1024 * 1024\n\nfunction base64(bytes: Uint8Array): string {\n let binary = ''\n for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n return btoa(binary)\n}\n\n/** The `files` of `ext.build`: FileObjects by reference, everything else read over the file service and sent inline. */\nexport async function buildFiles(nfsp: NfspClient, files: AiwsSourceFile[]): Promise<({ name: string; obj_id: string } | { name: string; base64: string })[]> {\n const out: ({ name: string; obj_id: string } | { name: string; base64: string })[] = []\n let inline = 0\n for (const f of files) {\n if (f.obj_id?.startsWith('cyfile:')) { out.push({ name: f.name, obj_id: f.obj_id }); continue }\n if (!f.node_id) throw new AiwsSourceError([{ file: f.name, severity: 'error', message: 'the file service did not name this file' }])\n const bytes = new Uint8Array(await (await nfsp.readFile(f.node_id)).arrayBuffer())\n inline += bytes.length\n if (inline > AIWS_MAX_INLINE_BYTES) throw new AiwsSourceError([{ file: f.name, severity: 'error', message: `a control's files are limited to ${AIWS_MAX_INLINE_BYTES} bytes per build` }])\n out.push({ name: f.name, base64: base64(bytes) })\n }\n return out\n}\n\n// ---- component.json pre-check (the service's composer is authoritative; this catches the usual mistakes early)\n\nconst COMPONENT_KEYS = ['manifest_version', 'ident', 'kind', 'title', 'description', 'host_api', 'accepts', 'allow_no_source', 'default_size', 'config_schema', 'bindings', 'entry', 'assets', 'catalog', 'agent', 'deps']\nconst SCHEMA_KEYWORDS = ['type', 'enum', 'default', 'required', 'title', 'description', 'minimum', 'maximum', 'minLength', 'maxLength', 'properties', 'items']\nconst NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/\nconst DID = /^did:[a-z0-9]+:[^/#\\s]+$/\nconst BINDING = /^[a-z][a-z0-9_]{0,31}$/\n\nfunction schemaProblems(v: unknown, path: string, out: string[]): void {\n if (!v || typeof v !== 'object' || Array.isArray(v)) { out.push(`${path}: a schema is an object`); return }\n for (const [k, x] of Object.entries(v as Record<string, unknown>)) {\n if (!SCHEMA_KEYWORDS.includes(k)) { out.push(`${path}/${k}: keyword ${k} is outside the supported subset`); continue }\n if (k === 'properties' && x && typeof x === 'object') for (const [n, s] of Object.entries(x as Record<string, unknown>)) schemaProblems(s, `${path}/properties/${n}`, out)\n if (k === 'items') schemaProblems(x, `${path}/items`, out)\n }\n}\n\n/** Check a `component.json` text against the files of its directory. Errors make a build fail; warnings do not. */\nexport function checkComponent(text: string, fileNames: string[]): AiwsDiagnostic[] {\n const out: AiwsDiagnostic[] = []\n const f = AIWS_COMPONENT_FILE\n const error = (message: string) => out.push({ file: f, severity: 'error', message })\n let c: Record<string, unknown>\n try {\n const parsed = JSON.parse(text) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { error('must be a JSON object'); return out }\n c = parsed as Record<string, unknown>\n } catch (e) {\n error(e instanceof Error ? e.message : String(e))\n return out\n }\n for (const k of Object.keys(c)) if (!COMPONENT_KEYS.includes(k)) error(`unknown key ${k}`)\n const mv = c.manifest_version\n if (typeof mv !== 'number' || !Number.isInteger(mv) || mv < 1) error('manifest_version (1) required')\n else if (mv > AIWS_MANIFEST_VERSION) error(`manifest_version ${mv} is newer than this client reads (${AIWS_MANIFEST_VERSION})`)\n const ident = c.ident as Record<string, unknown> | undefined\n if (!ident || typeof ident !== 'object') error('ident { author_did, name } required')\n else {\n if (typeof ident.author_did !== 'string' || !DID.test(ident.author_did)) error('ident.author_did must be a DID (did:<method>:<id>)')\n if (typeof ident.name !== 'string' || !NAME.test(ident.name)) error('ident.name must be [a-z0-9][a-z0-9._-]{0,63}')\n if (typeof ident.author_did === 'string' && typeof ident.name === 'string' && encoder.encode(`${ident.author_did}#${ident.name}`).length > 128) error('an identity is at most 128 bytes')\n }\n if (c.kind !== 'declarative' && c.kind !== 'html') error('kind must be declarative or html')\n if (typeof c.title !== 'string' || !c.title || c.title.length > 256) error('title: 1…256 characters')\n if (c.config_schema !== undefined) { const p: string[] = []; schemaProblems(c.config_schema, 'config_schema', p); p.forEach(error) }\n if (c.bindings !== undefined) {\n if (!c.bindings || typeof c.bindings !== 'object') error('bindings must be an object')\n else for (const n of Object.keys(c.bindings as object)) if (!BINDING.test(n) || n === 'props') error(`binding name ${n}: [a-z][a-z0-9_]{0,31}, not props`)\n }\n if (Array.isArray(c.deps) && c.deps.length > 0) error('deps must be empty: dependencies between controls come in a later version')\n const has = (n: unknown) => typeof n === 'string' && fileNames.includes(n)\n const named = new Set([f])\n if (c.kind === 'html') {\n const e = c.entry as Record<string, unknown> | undefined\n if (!e || typeof e !== 'object' || typeof e.html !== 'string') error('entry must be { html, css?, js? }')\n else for (const [k, n] of Object.entries(e)) { if (!has(n)) error(`entry.${k} ${JSON.stringify(n)} is not in the directory`); else named.add(String(n)) }\n if (c.host_api !== undefined && c.host_api !== AIWS_HTML_API_VERSION) error(`host_api: the HTML Block host speaks API ${AIWS_HTML_API_VERSION}`)\n } else if (c.kind === 'declarative') {\n if (!has(c.entry)) error(`entry ${JSON.stringify(c.entry)} is not in the directory`)\n else named.add(String(c.entry))\n }\n for (const a of Array.isArray(c.assets) ? c.assets : []) { if (!has(a)) error(`asset ${JSON.stringify(a)} is not in the directory`); else named.add(String(a)) }\n if (c.agent !== undefined) { if (!has(c.agent)) error(`agent ${JSON.stringify(c.agent)} is not in the directory`); else named.add(String(c.agent)) }\n for (const n of fileNames) if (!named.has(n)) out.push({ file: n, severity: 'warning', message: 'not named by component.json: kept in the source snapshot only' })\n return out\n}\n\n// ---- bundles (exports, the `aiws` sub-package of a PIKG)\n\n/** Read an AIWS manifest of any supported version as the current one (Q19); a newer one is refused. */\nexport function compatManifest(value: unknown): AiwsManifest {\n if (!value || typeof value !== 'object') throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'must be a JSON object' }])\n const m = value as Record<string, unknown>\n const version = m.manifest_version\n if (typeof version !== 'number' || version < 1) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'manifest_version required' }])\n if (version > AIWS_MANIFEST_VERSION) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: `manifest_version ${version} needs a newer client (this one reads ${AIWS_MANIFEST_VERSION})` }])\n if (m.purpose !== 'aiws') throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'purpose must be aiws' }])\n if (!Array.isArray(m.controls)) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'controls must be an array' }])\n return { manifest_version: version, purpose: 'aiws', host_api: (m.host_api as Record<string, number>) ?? {}, controls: m.controls as AiwsManifestControl[], workspace_templates: Array.isArray(m.workspace_templates) ? m.workspace_templates : [] }\n}\n\n/** Verify a bundle the way an installer does: manifest, each control's digest and component.json, no stray files. */\nexport async function verifyBundle(files: Map<string, Uint8Array>): Promise<{ manifest: AiwsManifest; diagnostics: AiwsDiagnostic[] }> {\n const raw = files.get(AIWS_MANIFEST_FILE)\n if (!raw) throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'missing' }])\n let parsed: unknown\n try { parsed = JSON.parse(decoder.decode(raw)) } catch (e) { throw new AiwsSourceError([{ file: AIWS_MANIFEST_FILE, severity: 'error', message: String(e) }]) }\n const manifest = compatManifest(parsed)\n const diagnostics: AiwsDiagnostic[] = []\n if (manifest.workspace_templates.length > 0) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'Workspace templates are not supported yet' })\n if (manifest.controls.length === 0) diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: 'lists no control' })\n const dirs = new Set<string>()\n for (const c of manifest.controls) {\n if (typeof c.dir !== 'string' || !/^controls\\/[a-z0-9][a-z0-9._-]{0,70}\\/$/.test(c.dir) || dirs.has(c.dir)) { diagnostics.push({ file: AIWS_MANIFEST_FILE, severity: 'error', message: `control ${c.ident}: bad or repeated dir` }); continue }\n dirs.add(c.dir)\n const own: [string, Uint8Array][] = [...files].filter(([p]) => p.startsWith(c.dir)).map(([p, b]) => [p.slice(c.dir.length), b])\n if (own.some(([n]) => n.includes('/'))) diagnostics.push({ file: c.dir, severity: 'error', message: 'a control directory is flat' })\n if (await aiwsContentDigest(own) !== c.digest) diagnostics.push({ file: c.dir, severity: 'error', message: 'the files do not match the manifest digest' })\n const component = own.find(([n]) => n === AIWS_COMPONENT_FILE)\n if (!component) { diagnostics.push({ file: `${c.dir}${AIWS_COMPONENT_FILE}`, severity: 'error', message: 'missing' }); continue }\n for (const d of checkComponent(decoder.decode(component[1]), own.map(([n]) => n))) diagnostics.push({ ...d, file: `${c.dir}${d.file}` })\n try {\n const comp = JSON.parse(decoder.decode(component[1])) as { ident?: { author_did?: string; name?: string }; kind?: string }\n if (`${comp.ident?.author_did}#${comp.ident?.name}` !== c.ident || comp.kind !== c.kind) diagnostics.push({ file: c.dir, severity: 'error', message: 'ident and kind must match its component.json' })\n } catch { /* reported above */ }\n }\n for (const p of files.keys()) if (p !== AIWS_MANIFEST_FILE && ![...dirs].some((d) => p.startsWith(d))) diagnostics.push({ file: p, severity: 'error', message: 'belongs to no control of the manifest' })\n return { manifest, diagnostics }\n}\n\n/** The bundle of Workspace definitions (`ext.export`): the manifest plus every file's bytes. */\nexport async function exportBundle(client: AiwsExtRpc, workspaceId: string, entityIds: string[], fetchAsset: (workspaceId: string, objId: string) => Promise<Uint8Array>): Promise<AiwsBundle & { controls: Record<string, unknown>[] }> {\n const r = await client.extExport(workspaceId, entityIds, 'package')\n const files = new Map<string, Uint8Array>()\n files.set(AIWS_MANIFEST_FILE, encoder.encode(`${JSON.stringify(r.manifest, null, 2)}\\n`))\n for (const f of r.files) files.set(f.path, f.text !== undefined ? encoder.encode(f.text) : await fetchAsset(workspaceId, String(f.obj_id)))\n return { manifest: compatManifest(r.manifest), files, controls: r.controls }\n}\n\n// ---- the home folder over NFSP\n\n/** The entry `name` of a folder, found with a filtered listing (no request fails for a missing name). */\nasync function child(nfsp: NfspClient, folder: WireRef | string, name: string) {\n const glob = /[*?[\\]\\\\]/.test(name) ? undefined : name\n const page = await nfsp.list(typeof folder === 'string' ? folder : { ref: folder }, { limit: glob ? 10 : 1000, ...(glob ? { filter: { name_glob: glob } } : {}) }, ['base', 'ident'])\n return page.entries.find((e) => e.name === name)\n}\n\n/** Make sure a folder exists, creating each missing level below the realm root (`/home`); answers its ref. Levels\n * are looked up by listing their parent, so a missing one is not a failed request. */\nexport async function ensureFolder(nfsp: NfspClient, path: string): Promise<WireRef> {\n const parts = path.split('/').filter(Boolean)\n if (parts.length === 0) throw new Error(`not a folder path: ${path}`)\n let ref = (await nfsp.stat(`/${parts[0]}`)).ref\n for (const name of parts.slice(1)) {\n const hit = await child(nfsp, ref, name)\n if (hit && hit.target.kind !== 'dir') throw new AiwsSourceError([{ file: name, severity: 'error', message: `${name} in ${path} is not a folder` }])\n ref = hit ? hit.target.ref : (await nfsp.mkdir({ ref }, name)).ref\n }\n return ref\n}\n\n/** A folder's ref, or null when it (or a level above it) does not exist — found without failed requests. */\nexport async function findFolder(nfsp: NfspClient, path: string): Promise<WireRef | null> {\n const parts = path.split('/').filter(Boolean)\n if (parts.length === 0) return null\n let ref = (await nfsp.stat(`/${parts[0]}`)).ref\n for (const name of parts.slice(1)) {\n const hit = await child(nfsp, ref, name)\n if (!hit || hit.target.kind !== 'dir') return null\n ref = hit.target.ref\n }\n return ref\n}\n\n/** Whether a folder holds a control source (its component.json). */\nexport async function hasControlSource(nfsp: NfspClient, dir: string): Promise<boolean> {\n const ref = await findFolder(nfsp, dir)\n return ref !== null && (await child(nfsp, ref, AIWS_COMPONENT_FILE)) !== undefined\n}\n\n/** Write one file into a folder (replacing it). */\nexport async function writeHomeFile(nfsp: NfspClient, dir: string | WireRef, name: string, bytes: Uint8Array): Promise<void> {\n const ref = typeof dir === 'string' ? await ensureFolder(nfsp, dir) : dir\n await nfsp.uploadFile(ref, name, bytes, { overwrite: true })\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))\n\n/** The files of a control's source folder (flat; dot files are the client's own and skipped). */\nexport async function collectSources(nfsp: NfspClient, dir: string): Promise<AiwsSourceFile[]> {\n const out: AiwsSourceFile[] = []\n const problems: AiwsDiagnostic[] = []\n let cursor: string | undefined\n do {\n const page = await nfsp.list(dir, { limit: 500, ...(cursor ? { cursor } : {}) }, ['base', 'ident'])\n for (const e of page.entries) {\n if (e.name.startsWith('.')) continue\n if (e.target.kind !== 'file') { problems.push({ file: e.name, severity: 'error', message: 'a control source folder is flat: move files out of sub-folders' }); continue }\n const ref = e.target.ref\n const objId = ref.type === 'object' ? ref.obj_id : typeof e.target.attrs?.obj_id === 'string' ? e.target.attrs.obj_id : undefined\n out.push({\n name: e.name,\n ...(objId ? { obj_id: objId } : {}),\n ...(ref.type === 'live' ? { node_id: ref.node_id } : {}),\n ...(typeof e.target.attrs?.etag === 'string' ? { etag: e.target.attrs.etag } : {}),\n ...(typeof e.target.attrs?.size === 'number' ? { size: e.target.attrs.size } : {}),\n })\n }\n cursor = page.truncated ? page.next_cursor : undefined\n } while (cursor)\n if (out.length === 0) problems.push({ file: '', severity: 'error', message: `${dir} holds no files` })\n if (out.length > AIWS_MAX_SOURCE_FILES) problems.push({ file: '', severity: 'error', message: `a control holds at most ${AIWS_MAX_SOURCE_FILES} files` })\n if (problems.some((p) => p.severity === 'error')) throw new AiwsSourceError(problems)\n return out.sort((a, b) => a.name.localeCompare(b.name))\n}\n\nexport async function readBuildState(nfsp: NfspClient, dir: string): Promise<AiwsBuildState | null> {\n try {\n const entry = await child(nfsp, dir, AIWS_BUILD_STATE_FILE)\n const nodeId = entry?.target.ref.type === 'live' ? entry.target.ref.node_id : undefined\n if (!nodeId) return null\n const response = await nfsp.readFile(nodeId)\n return (await response.json()) as AiwsBuildState\n } catch {\n return null\n }\n}\n\nexport async function writeBuildState(nfsp: NfspClient, dir: string, state: AiwsBuildState): Promise<void> {\n await writeHomeFile(nfsp, dir, AIWS_BUILD_STATE_FILE, encoder.encode(`${JSON.stringify(state, null, 2)}\\n`))\n}\n\nexport interface AiwsBuildOptions { folderId?: string; force?: boolean; dryRun?: boolean }\n\n/**\n * Build the control in `dir` into a Workspace: collect the files, call `ext.build` with the base recorded in\n * `.aiws-build.json` (when it is this Workspace's), and record the new base. Service refusals throw `AiwsFailure`\n * (`BUILD_FAILED` carries `data.diagnostics`); source problems throw `AiwsSourceError`.\n */\nexport async function buildControl(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, dir: string, opts: AiwsBuildOptions = {}): Promise<Record<string, unknown> & { files: AiwsSourceFile[] }> {\n const files = await collectSources(nfsp, dir)\n const state = await readBuildState(nfsp, dir)\n const base = state && state.workspace_id === workspaceId ? { def_rev: state.def_rev, dir_rev: state.dir_rev } : undefined\n const result = await client.extBuild(workspaceId, {\n files: await buildFiles(nfsp, files),\n ...(opts.folderId ? { folder_id: opts.folderId } : {}),\n ...(base ? { expect: base } : {}),\n ...(opts.force ? { force: true } : {}),\n ...(opts.dryRun ? { dry_run: true } : {}),\n })\n if (!opts.dryRun && typeof result.def_entity_id === 'string' && typeof result.def_rev === 'number') {\n await writeBuildState(nfsp, dir, { workspace_id: workspaceId, def_entity_id: result.def_entity_id, def_rev: result.def_rev, dir_rev: Number(result.dir_rev ?? 0), ident: String(result.ident ?? ''), at: new Date().toISOString() })\n }\n return { ...result, files }\n}\n\n/**\n * Write a definition's Workspace snapshot into `outDir` (a definition never built from source gets synthesized\n * files) and record it as the base of the next build.\n */\nexport async function pullControl(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, defEntityId: string, outDir: string, fetchAsset: (workspaceId: string, objId: string) => Promise<Uint8Array>): Promise<{ files: string[]; state: AiwsBuildState }> {\n const r = await client.extExport(workspaceId, [defEntityId], 'pull')\n const control = r.controls[0] as { entity_id: string; ident: string; def_rev: number; dir_rev: number; files: { name: string; obj_id?: string; text?: string }[] }\n const ref = await ensureFolder(nfsp, outDir)\n for (const f of control.files) await writeHomeFile(nfsp, ref, f.name, f.text !== undefined ? encoder.encode(f.text) : await fetchAsset(workspaceId, String(f.obj_id)))\n const state: AiwsBuildState = { workspace_id: workspaceId, def_entity_id: control.entity_id, def_rev: control.def_rev, dir_rev: control.dir_rev, ident: control.ident, at: new Date().toISOString() }\n await writeBuildState(nfsp, outDir, state)\n return { files: control.files.map((f) => f.name), state }\n}\n\n/**\n * Rebuild whenever the folder changes: NFSP watch events (lossy: a `resync` lists again), debounced, and only when\n * the files' objects differ from the last build. Returns when `signal` aborts.\n */\nexport async function watchControl(nfsp: NfspClient, dir: string, onChange: (files: AiwsSourceFile[]) => Promise<void>, opts: { debounceMs?: number; signal?: AbortSignal } = {}): Promise<void> {\n let last = ''\n let timer: ReturnType<typeof setTimeout> | undefined\n let running = Promise.resolve()\n const check = () => {\n running = running.then(async () => {\n let files: AiwsSourceFile[]\n try { files = await collectSources(nfsp, dir) } catch { return }\n const key = sourcesKey(files)\n if (key === last) return\n last = key\n await onChange(files)\n }).catch(() => undefined)\n }\n check()\n while (!opts.signal?.aborted) {\n const listing = await nfsp.list(dir, { limit: 1 }, ['base'])\n const stream = nfsp.watch({ tokens: listing.watch_token ? [listing.watch_token] : [], signal: opts.signal })\n try {\n for await (const _ of stream) {\n if (timer) clearTimeout(timer)\n timer = setTimeout(check, opts.debounceMs ?? 500)\n }\n } catch {\n if (opts.signal?.aborted) break\n await sleep(2_000)\n } finally {\n stream.close()\n }\n }\n if (timer) clearTimeout(timer)\n await running\n}\n\n// ---- skeletons\n\nexport interface AiwsSkeletonOptions { authorDid: string; name: string; title?: string; kind?: 'declarative' | 'html' }\n\n/** The files of a new control: a minimal working declarative or HTML control with one optional binding. */\nexport function controlSkeleton(opts: AiwsSkeletonOptions): Record<string, string> {\n const title = opts.title ?? opts.name\n const base = {\n manifest_version: AIWS_MANIFEST_VERSION,\n ident: { author_did: opts.authorDid, name: opts.name },\n kind: opts.kind ?? 'declarative',\n title,\n description: `${title}: a control of this Workspace`,\n accepts: ['buckyos.table-source', 'buckyos.record'],\n allow_no_source: true,\n default_size: { w: 260, h: 140 },\n config_schema: { type: 'object', properties: { label: { type: 'string', title: 'Label', default: title } } },\n bindings: { data: { accepts: ['buckyos.table-source'], title: 'Data', description: 'The table this control summarizes' } },\n catalog: { group: 'custom', description: `${title}` },\n agent: 'AGENT.md',\n }\n const agent = `# ${title}\\n\\nBind \\`data\\` to a table. Config: \\`label\\` (text).\\n`\n if (opts.kind === 'html') {\n return {\n [AIWS_COMPONENT_FILE]: `${JSON.stringify({ ...base, host_api: AIWS_HTML_API_VERSION, entry: { html: 'view.html', css: 'style.css', js: 'behavior.js' } }, null, 2)}\\n`,\n 'view.html': '<div class=\"card\"><div class=\"label\" id=\"label\"></div><div class=\"value\" id=\"value\">—</div></div>\\n',\n 'style.css': '.card{font:14px system-ui;padding:12px}.label{opacity:.7}.value{font-size:28px;font-weight:600}\\n',\n 'behavior.js': \"document.getElementById('label').textContent = (aiws.context.config || {}).label || ''\\nif (aiws.bindings.data) aiws.input('data').rows().then(function (rows) { document.getElementById('value').textContent = String(rows.length) })\\n\",\n 'AGENT.md': agent,\n }\n }\n return {\n [AIWS_COMPONENT_FILE]: `${JSON.stringify({ ...base, entry: 'declarative.json' }, null, 2)}\\n`,\n 'declarative.json': `${JSON.stringify({ layout: 'stack', items: [{ kind: 'metric', label: title, bind: 'data.count', format: 'number' }, { kind: 'text', text: 'Rows of the bound table' }] }, null, 2)}\\n`,\n 'AGENT.md': agent,\n }\n}\n\n/** Create a control's source folder from a skeleton (refuses to overwrite a folder that has a component.json). */\nexport async function createControlSource(nfsp: NfspClient, dir: string, files: Record<string, string>): Promise<WireRef> {\n const ref = await ensureFolder(nfsp, dir)\n const existing = await nfsp.list({ ref }, { limit: 500 }, ['base']).catch(() => null)\n if (existing?.entries.some((e) => e.name === AIWS_COMPONENT_FILE)) throw new AiwsSourceError([{ file: AIWS_COMPONENT_FILE, severity: 'error', message: `${dir} already holds a control` }])\n for (const [name, text] of Object.entries(files)) await writeHomeFile(nfsp, ref, name, encoder.encode(text))\n return ref\n}\n"],"names":["AIWS_COMPONENT_FILE","AIWS_MANIFEST_FILE","AIWS_BUILD_STATE_FILE","AiwsSourceError","Error","constructor","diagnostics","super","filter","d","severity","map","file","message","join","this","name","encoder","TextEncoder","decoder","TextDecoder","folderName","title","replace","trim","slice","async","sha256Hex","bytes","digest","crypto","subtle","Array","from","Uint8Array","b","toString","padStart","aiwsContentDigest","files","pairs","push","sort","a","encode","JSON","stringify","sourcesKey","localeCompare","f","obj_id","etag","AIWS_MAX_INLINE_BYTES","base64","binary","i","length","String","fromCharCode","subarray","btoa","buildFiles","nfsp","out","inline","_a","startsWith","node_id","readFile","arrayBuffer","COMPONENT_KEYS","SCHEMA_KEYWORDS","NAME","DID","BINDING","schemaProblems","v","path","isArray","k","x","Object","entries","includes","n","s","checkComponent","text","fileNames","error","c","parsed","parse","e","keys","mv","manifest_version","Number","isInteger","ident","author_did","test","kind","config_schema","p","forEach","bindings","deps","has","named","Set","entry","html","add","host_api","assets","agent","compatManifest","value","m","version","purpose","controls","workspace_templates","child","folder","glob","list","ref","limit","name_glob","find","ensureFolder","parts","split","Boolean","stat","hit","target","mkdir","findFolder","writeHomeFile","dir","uploadFile","overwrite","sleep","ms","Promise","r","setTimeout","collectSources","problems","cursor","page","objId","type","attrs","_b","_c","size","truncated","next_cursor","some","readBuildState","nodeId","response","json","writeBuildState","state","client","workspaceId","opts","base","workspace_id","def_rev","dir_rev","result","extBuild","folderId","folder_id","expect","force","dryRun","dry_run","def_entity_id","at","Date","toISOString","authorDid","description","accepts","allow_no_source","default_size","w","h","properties","label","default","data","catalog","group","css","js","layout","items","bind","format","existing","catch","entityIds","fetchAsset","extExport","Map","set","manifest","owner","workspaceTitle","pkg","defEntityId","outDir","control","entity_id","raw","get","decode","dirs","own","component","comp","onChange","timer","last","running","resolve","check","then","key","signal","aborted","listing","stream","watch","tokens","watch_token","_","clearTimeout","debounceMs","close"],"mappings":"gFAaO,MAAMA,EAAsB,iBACtBC,EAAqB,qBAErBC,EAAwB,mBA6B9B,MAAMC,UAAwBC,MAEnC,WAAAC,CAAYC,GACJC,MAAAD,EAAYE,QAAQC,GAAqB,UAAfA,EAAEC,WAAsBC,KAAKF,GAAM,GAAGA,EAAEG,KAAO,GAAGH,EAAEG,SAAW,KAAKH,EAAEI,YAAWC,KAAK,OAAS,0BAC/HC,KAAKC,KAAO,kBACZD,KAAKT,YAAcA,CACrB,EAGF,MAAMW,EAAU,IAAIC,YACdC,EAAU,IAAIC,YAOb,SAASC,EAAWC,GAEzB,OADgBA,EAAMC,QAAQ,sBAAuB,KAAKA,QAAQ,OAAQ,IAAIC,OAC/DC,MAAM,EAAG,KAAO,WACjC,CAmBAC,eAAeC,EAAUC,GACvB,MAAMC,QAAeC,OAAOC,OAAOF,OAAO,UAAWD,GACrD,OAAOI,MAAMC,KAAK,IAAIC,WAAWL,IAAUM,GAAMA,EAAEC,SAAS,IAAIC,SAAS,EAAG,OAAMvB,KAAK,GACzF,CAGAY,eAAsBY,EAAkBC,GACtC,MAAMC,EAA4B,GACvB,IAAA,MAACxB,EAAMY,KAAUW,EAAOC,EAAMC,KAAK,CAACzB,QAAYW,EAAUC,KAE9D,OADPY,EAAME,MAAK,CAACC,EAAGR,IAAO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A,IAAUA,QAAM+G,EAAexF,EAAMgF,EAAG,CAAU,MAAE,MAAO,CACzD,MAAA8F,EAAM7L,EAAWR,GACnBqM,IAAQL,IACLA,EAAAK,QACDP,EAAS9L,GAAK,IACnByK,OAAM,KAAe,GAAA,EAGnB,UAAC,OAAA/I,EAAA0G,EAAKkE,aAAL,EAAA5K,EAAa6K,UAAS,CACtB,MAAAC,QAAgBjL,EAAKiE,KAAKe,EAAK,CAAEb,MAAO,GAAK,CAAC,SAC9C+G,EAASlL,EAAKmL,MAAM,CAAEC,OAAQH,EAAQI,YAAc,CAACJ,EAAQI,aAAe,GAAIN,OAAQlE,EAAKkE,SAC/F,IACF,UAAA,MAAiBO,KAAKJ,EAChBV,GAAOe,aAAaf,GACxBA,EAAQjF,WAAWqF,EAAO/D,EAAK2E,YAAc,IAC/C,CACM,MACF,GAAA,OAAAzF,EAAAc,EAAKkE,aAAQ,EAAAhF,EAAAiF,QAAS,YACpB7F,EAAM,IAAK,CACjB,QACA+F,EAAOO,OACT,CACF,CACIjB,GAAOe,aAAaf,SAClBE,CACR"}
@@ -0,0 +1,169 @@
1
+ /**
2
+ * AI Workspace extension controls (buckyos src/frame/aiworkspace/README.md “Extension controls”), shared by the
3
+ * Desktop and the CLI: a control's source lives in a (flat) home folder of the Zone file service; `build` lists it
4
+ * over NFSP and hands each file's object to `ext.build`, `pull` writes a Workspace snapshot back, `watch` rebuilds on
5
+ * change; bundles (the AIWS manifest plus `controls/<dir>/<file>`) are what exports, packages and the library carry.
6
+ * Runs in browsers and Deno (fetch, crypto.subtle); no dependencies.
7
+ */
8
+ import type { AiWorkspaceClient } from './aiworkspace_client';
9
+ import type { NfspClient, WireRef } from './nfsp';
10
+ /** The two service calls these drivers make (an `AiWorkspaceClient`, or a host's own session with the same shape). */
11
+ export type AiwsExtRpc = Pick<AiWorkspaceClient, 'extBuild' | 'extExport'>;
12
+ export declare const AIWS_COMPONENT_FILE = "component.json";
13
+ export declare const AIWS_MANIFEST_FILE = "aiws-manifest.json";
14
+ /** A client's own record of the base it last built or pulled (never part of the source snapshot: dot files are not). */
15
+ export declare const AIWS_BUILD_STATE_FILE = ".aiws-build.json";
16
+ /** The newest component.json / AIWS manifest version this module reads (older ones stay readable, Q19). */
17
+ export declare const AIWS_MANIFEST_VERSION = 1;
18
+ /** The HTML Block host API (`window.aiws` v2) and the declarative interpreter version. */
19
+ export declare const AIWS_HTML_API_VERSION = 2;
20
+ export declare const AIWS_DECLARATIVE_API_VERSION = 1;
21
+ export declare const AIWS_MAX_SOURCE_FILES = 64;
22
+ /**
23
+ * One file of a source folder. `obj_id` is set when the file service holds it as a named-store FileObject (`cyfile:`):
24
+ * the service then reads it by reference. Files of a native home folder have none (their `obj_id`, when the file
25
+ * service reports one, is a `sha256:` content hash the service cannot fetch): their bytes travel with the build.
26
+ */
27
+ export interface AiwsSourceFile {
28
+ name: string;
29
+ obj_id?: string;
30
+ node_id?: string;
31
+ etag?: string;
32
+ size?: number;
33
+ }
34
+ export interface AiwsDiagnostic {
35
+ file: string;
36
+ line?: number;
37
+ col?: number;
38
+ severity: 'error' | 'warning';
39
+ message: string;
40
+ /** Cells whose contract a rebuild would break. */
41
+ instances?: {
42
+ entity_id: string;
43
+ title?: string | null;
44
+ }[];
45
+ }
46
+ export interface AiwsBuildState {
47
+ workspace_id: string;
48
+ def_entity_id: string;
49
+ def_rev: number;
50
+ dir_rev: number;
51
+ ident?: string;
52
+ at?: string;
53
+ }
54
+ export interface AiwsManifestControl {
55
+ ident: string;
56
+ name: string;
57
+ kind: string;
58
+ version: number;
59
+ digest: string;
60
+ dir: string;
61
+ title?: string;
62
+ description?: string;
63
+ catalog?: Record<string, unknown>;
64
+ }
65
+ export interface AiwsManifest {
66
+ manifest_version: number;
67
+ purpose: 'aiws';
68
+ host_api?: Record<string, number>;
69
+ controls: AiwsManifestControl[];
70
+ workspace_templates: unknown[];
71
+ }
72
+ export interface AiwsBundle {
73
+ manifest: AiwsManifest;
74
+ files: Map<string, Uint8Array>;
75
+ }
76
+ /** A source directory that cannot be built as it is (not a service refusal: `diagnostics` say why). */
77
+ export declare class AiwsSourceError extends Error {
78
+ readonly diagnostics: AiwsDiagnostic[];
79
+ constructor(diagnostics: AiwsDiagnostic[]);
80
+ }
81
+ export declare function joinPath(dir: string, name: string): string;
82
+ /** A Workspace title as one folder name (no `/`, no leading dot). */
83
+ export declare function folderName(title: string): string;
84
+ /** The suggested home folder of a control (README: a suggestion; the definition never stores it). */
85
+ export declare function homeControlDir(owner: string, workspaceTitle: string, name: string): string;
86
+ /** Where a client writes an export bundle before packing it. */
87
+ export declare function homeExportDir(owner: string, pkg: string): string;
88
+ /** `user_state` key under which each person remembers the home folder of a definition. */
89
+ export declare function sourceStateKey(defEntityId: string): string;
90
+ /** `sha256:` over `[[name, sha256 hex of its bytes], …]` sorted by name: a control's content digest. */
91
+ export declare function aiwsContentDigest(files: Iterable<[string, Uint8Array]>): Promise<string>;
92
+ /** What a set of sources is, for "nothing changed since the last build" (names, objects or versions). */
93
+ export declare function sourcesKey(files: AiwsSourceFile[]): string;
94
+ /** Bytes a single build may carry inline (the service's limit). */
95
+ export declare const AIWS_MAX_INLINE_BYTES: number;
96
+ /** The `files` of `ext.build`: FileObjects by reference, everything else read over the file service and sent inline. */
97
+ export declare function buildFiles(nfsp: NfspClient, files: AiwsSourceFile[]): Promise<({
98
+ name: string;
99
+ obj_id: string;
100
+ } | {
101
+ name: string;
102
+ base64: string;
103
+ })[]>;
104
+ /** Check a `component.json` text against the files of its directory. Errors make a build fail; warnings do not. */
105
+ export declare function checkComponent(text: string, fileNames: string[]): AiwsDiagnostic[];
106
+ /** Read an AIWS manifest of any supported version as the current one (Q19); a newer one is refused. */
107
+ export declare function compatManifest(value: unknown): AiwsManifest;
108
+ /** Verify a bundle the way an installer does: manifest, each control's digest and component.json, no stray files. */
109
+ export declare function verifyBundle(files: Map<string, Uint8Array>): Promise<{
110
+ manifest: AiwsManifest;
111
+ diagnostics: AiwsDiagnostic[];
112
+ }>;
113
+ /** The bundle of Workspace definitions (`ext.export`): the manifest plus every file's bytes. */
114
+ export declare function exportBundle(client: AiwsExtRpc, workspaceId: string, entityIds: string[], fetchAsset: (workspaceId: string, objId: string) => Promise<Uint8Array>): Promise<AiwsBundle & {
115
+ controls: Record<string, unknown>[];
116
+ }>;
117
+ /** Make sure a folder exists, creating each missing level below the realm root (`/home`); answers its ref. Levels
118
+ * are looked up by listing their parent, so a missing one is not a failed request. */
119
+ export declare function ensureFolder(nfsp: NfspClient, path: string): Promise<WireRef>;
120
+ /** A folder's ref, or null when it (or a level above it) does not exist — found without failed requests. */
121
+ export declare function findFolder(nfsp: NfspClient, path: string): Promise<WireRef | null>;
122
+ /** Whether a folder holds a control source (its component.json). */
123
+ export declare function hasControlSource(nfsp: NfspClient, dir: string): Promise<boolean>;
124
+ /** Write one file into a folder (replacing it). */
125
+ export declare function writeHomeFile(nfsp: NfspClient, dir: string | WireRef, name: string, bytes: Uint8Array): Promise<void>;
126
+ /** The files of a control's source folder (flat; dot files are the client's own and skipped). */
127
+ export declare function collectSources(nfsp: NfspClient, dir: string): Promise<AiwsSourceFile[]>;
128
+ export declare function readBuildState(nfsp: NfspClient, dir: string): Promise<AiwsBuildState | null>;
129
+ export declare function writeBuildState(nfsp: NfspClient, dir: string, state: AiwsBuildState): Promise<void>;
130
+ export interface AiwsBuildOptions {
131
+ folderId?: string;
132
+ force?: boolean;
133
+ dryRun?: boolean;
134
+ }
135
+ /**
136
+ * Build the control in `dir` into a Workspace: collect the files, call `ext.build` with the base recorded in
137
+ * `.aiws-build.json` (when it is this Workspace's), and record the new base. Service refusals throw `AiwsFailure`
138
+ * (`BUILD_FAILED` carries `data.diagnostics`); source problems throw `AiwsSourceError`.
139
+ */
140
+ export declare function buildControl(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, dir: string, opts?: AiwsBuildOptions): Promise<Record<string, unknown> & {
141
+ files: AiwsSourceFile[];
142
+ }>;
143
+ /**
144
+ * Write a definition's Workspace snapshot into `outDir` (a definition never built from source gets synthesized
145
+ * files) and record it as the base of the next build.
146
+ */
147
+ export declare function pullControl(client: AiwsExtRpc, nfsp: NfspClient, workspaceId: string, defEntityId: string, outDir: string, fetchAsset: (workspaceId: string, objId: string) => Promise<Uint8Array>): Promise<{
148
+ files: string[];
149
+ state: AiwsBuildState;
150
+ }>;
151
+ /**
152
+ * Rebuild whenever the folder changes: NFSP watch events (lossy: a `resync` lists again), debounced, and only when
153
+ * the files' objects differ from the last build. Returns when `signal` aborts.
154
+ */
155
+ export declare function watchControl(nfsp: NfspClient, dir: string, onChange: (files: AiwsSourceFile[]) => Promise<void>, opts?: {
156
+ debounceMs?: number;
157
+ signal?: AbortSignal;
158
+ }): Promise<void>;
159
+ export interface AiwsSkeletonOptions {
160
+ authorDid: string;
161
+ name: string;
162
+ title?: string;
163
+ kind?: 'declarative' | 'html';
164
+ }
165
+ /** The files of a new control: a minimal working declarative or HTML control with one optional binding. */
166
+ export declare function controlSkeleton(opts: AiwsSkeletonOptions): Record<string, string>;
167
+ /** Create a control's source folder from a skeleton (refuses to overwrite a folder that has a component.json). */
168
+ export declare function createControlSource(nfsp: NfspClient, dir: string, files: Record<string, string>): Promise<WireRef>;
169
+ //# sourceMappingURL=aiws_ext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiws_ext.d.ts","sourceRoot":"","sources":["../src/aiws_ext.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAA;AAC7D,OAAO,KAAK,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAA;AAEjD,sHAAsH;AACtH,MAAM,MAAM,UAAU,GAAG,IAAI,CAAC,iBAAiB,EAAE,UAAU,GAAG,WAAW,CAAC,CAAA;AAE1E,eAAO,MAAM,mBAAmB,mBAAmB,CAAA;AACnD,eAAO,MAAM,kBAAkB,uBAAuB,CAAA;AACtD,wHAAwH;AACxH,eAAO,MAAM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