@yodaos-pkg/aix 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,455 @@
1
+ # @yodaos-pkg/aix
2
+
3
+ `@yodaos-pkg/aix` is a library for reading and managing **.aix** (AI eXecutable) packages in the web environment using WASM. The `.aix` format is an extension of the [Open Agent Format (OAF)](https://openagentformat.com/spec.html), designed to package AI agents with rich UI/UX capabilities powered by Ink Mini Programs.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @yodaos-pkg/aix
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ Here is a quick example of how to load an `.aix` package:
14
+
15
+ ```typescript
16
+ import { AIX } from '@yodaos-pkg/aix';
17
+
18
+ // Option 1: Load from a URL
19
+ async function fromUrl() {
20
+ const response = await fetch('https://example.com/my-agent.aix');
21
+ const buffer = await response.arrayBuffer();
22
+ const aix = await AIX.From(new Uint8Array(buffer));
23
+ console.log('App Title:', aix.getTitle());
24
+ }
25
+
26
+ // Option 2: Load from a File object (e.g., from an <input type="file">)
27
+ async function fromFile(file: File) {
28
+ const aix = await AIX.From(file);
29
+ console.log('App Title:', aix.getTitle());
30
+ }
31
+ ```
32
+
33
+ ## WASM Loading
34
+
35
+ By default, `AIX.From()` and all instance methods initialize a separate reader-only WASM.
36
+ They do not load image codecs, script minification, or source/schema checking.
37
+ The optional `AIX.From(data, limits, true)` check also loads the full tooling module.
38
+ The first pack, optimize, or source-check call lazily loads the full module;
39
+ concurrent tooling calls share initialization. Existing reader instances remain
40
+ valid after tooling loads, and tooling-only calls do not fetch reader WASM.
41
+
42
+ The generated distribution includes `pkg-reader/` and `pkg/`; self-host both
43
+ with their adjacent JS/WASM files. The existing raw `pkg/aix_web.js` exports
44
+ remain complete and the npm CLI keeps its synchronous full Node.js bundle.
45
+ Rust builds default to the `tooling` feature; `--no-default-features` produces
46
+ reader exports without the packer dependency. `npm run build` builds both web
47
+ artifacts; `npm run build:wasm:reader` builds only the reader artifact.
48
+
49
+ Local measurements reduced reader WASM from 5,514,021 to 355,365 bytes. Mixed
50
+ reader/tooling workflows load both binaries and retain two module memories.
51
+ See the repository's `docs/wasm.md` for baseline samples, timing limits, the
52
+ compatibility plan, and reproduction commands.
53
+
54
+ ## Archive Resource Limits
55
+
56
+ Pass caller-selected budgets when reading untrusted packages:
57
+
58
+ ```typescript
59
+ const aix = await AIX.From(file, {
60
+ maxEntries: 1024,
61
+ maxEntryBytes: 8 * 1024 * 1024,
62
+ maxTotalBytes: 32 * 1024 * 1024,
63
+ });
64
+ ```
65
+
66
+ All limits are inclusive non-negative safe integers. Directories and signature
67
+ metadata count too. Metadata is rejected before extraction if over budget;
68
+ extraction also bounds output and retains CRC and size checks. `maxTotalBytes`
69
+ is the sum of declared uncompressed sizes, not a cumulative read budget.
70
+ Zero allows no entries or bytes. Omitted fields and the original `AIX.From(data)`
71
+ call remain unlimited for compatibility; set all three limits for untrusted
72
+ packages. The input archive buffer, parsed objects, and retained copies need
73
+ separate budgets. This policy applies to readers, not `AIX.optimize`.
74
+
75
+ Direct WASM consumers can call `AixReaderWasm.with_limits(data, limits)` using
76
+ the same fields. The existing `new AixReaderWasm(data)` constructor is unchanged.
77
+
78
+ ## Open and Check
79
+
80
+ Pass `true` as the third `AIX.From` argument to run the source checker before
81
+ receiving the package. The second argument remains the optional read limits;
82
+ pass `undefined` there when no limits are needed.
83
+
84
+ ```typescript
85
+ import { AIX, AixCheckError } from '@yodaos-pkg/aix';
86
+
87
+ async function openCheckedPackage(file: File) {
88
+ try {
89
+ return await AIX.From(file, undefined, true);
90
+ } catch (error) {
91
+ if (error instanceof AixCheckError) console.table(error.diagnostics);
92
+ throw error;
93
+ }
94
+ }
95
+ ```
96
+
97
+ Warnings alone pass. Error diagnostics reject with the exported `AixCheckError`
98
+ (`name: 'AixCheckError'`), an `Error` subclass with the complete `CheckReport` in
99
+ `report` and the same diagnostic array in `diagnostics`, including warnings.
100
+ The check uses `checkFromSource` on the package's source files without running
101
+ project code. It adds work and retains extracted check inputs; read limits still
102
+ apply but do not bound total checker memory. Archive, extraction, loading, and
103
+ collection failures retain their original operation errors rather than a check
104
+ report. Omitting the third argument or passing `false` preserves the existing
105
+ reader-only behavior.
106
+
107
+ ## Check Source Files
108
+
109
+ The Web SDK and npm CLI use the same complete in-memory check engine:
110
+
111
+ ```typescript
112
+ import { AIX, type CheckReport } from '@yodaos-pkg/aix';
113
+
114
+ const encode = (source: string) => new TextEncoder().encode(source);
115
+ const report: CheckReport = await AIX.checkFromSource([
116
+ { path: 'app.json', data: encode('{"pages":[]}') },
117
+ { path: 'main.ts', data: encode('const count: number = ;') },
118
+ ], { onProgress: (event) => console.log(event.type) });
119
+ console.log(report.diagnostics); // AIX029: invalid TypeScript syntax at main.ts:1
120
+
121
+ // Files from an <input type="file" webkitdirectory> selection also work.
122
+ const fileReport = await AIX.checkFromFiles(Array.from(input.files ?? []));
123
+ ```
124
+
125
+ Checks cover JSON/config validity, Page/Widget structure, component references
126
+ and cycles, JS/TS syntax, statically recognizable permissions, and Page JSON Schemas. Each diagnostic has `code`, `severity`, `path`,
127
+ `line`, `column`, and `message`. Source errors are returned in the report;
128
+ invalid input paths or collection failures reject the promise.
129
+
130
+ `checkFromSource` takes paths relative to the application root. `checkFromFiles`
131
+ uses `webkitRelativePath`, removing the selected directory's outer folder.
132
+ Both apply nested `.aixignore` rules and exclude local `.aix` caches. The shared
133
+ check adapter loads only when checking is first requested. It uses the WASM
134
+ engine without a Node filesystem, Node polyfills, or dependency downloads.
135
+ The same API also works in a Web Worker.
136
+
137
+ Both methods accept `CheckOptions` with an optional `onProgress` callback.
138
+ `CheckProgressEvent` reports checker loading, source/schema validation (input
139
+ file count), and diagnostic collection. These are stage notifications, not a
140
+ percentage estimate. Browser checks are synchronous after loading; run the API
141
+ in a Web Worker to keep a browser progress display responsive.
142
+
143
+ `check_finished` events carry an exported `CheckResult` with `id`, `label`,
144
+ `status` (`passed`, `warning`, `failed`, or `skipped`), `errors`, `warnings`, and
145
+ an optional `detail` explaining incomplete/skipped checks. The CLI uses the same
146
+ results for its final checklist. The returned `CheckReport` remains a diagnostic
147
+ report, so JSON callers do not need to parse terminal output.
148
+
149
+ JavaScript and TypeScript are syntax-checked, including `.ts`, `.mts`, `.cts`,
150
+ and Ink `<script lang="ts">` blocks. Inline diagnostics retain their original
151
+ Ink file locations. TypeScript semantic, import-resolution, and compiler-option
152
+ checks are currently excluded. No type environment is loaded, and checks do not
153
+ emit or run code.
154
+
155
+ Page `schema.data` is validated against `$schema` (2020-12 by default), including
156
+ nested keywords, patterns, and local references. Missing/null schemas remain
157
+ accepted. External schema resources are not fetched. These checks validate
158
+ schema declarations, not runtime data; packing and reader semantics are unchanged.
159
+
160
+ ## Using Play
161
+
162
+ The official browser lab now lives in the docs site at `/play`.
163
+
164
+ If you are developing inside this repository, install dependencies in `crates/aix-web` first:
165
+
166
+ ```bash
167
+ npm install
168
+ ```
169
+
170
+ 1. Build the local `aix-web` package:
171
+
172
+ ```bash
173
+ npm run build
174
+ ```
175
+
176
+ This step builds the `aix-web` WebAssembly bundle and TypeScript output into `dist/`, which is what the docs-integrated Package Lab loads.
177
+
178
+ 2. Install the docs dependencies:
179
+
180
+ ```bash
181
+ cd ../../docs
182
+ npm install
183
+ ```
184
+
185
+ 3. Start the docs site:
186
+
187
+ ```bash
188
+ npm run dev
189
+ ```
190
+
191
+ 4. Open the local VitePress URL shown in the terminal, then navigate to `/play`, usually:
192
+
193
+ ```text
194
+ http://localhost:5173/aix/play
195
+ ```
196
+
197
+ 5. Upload an `.aix` file in the page to inspect:
198
+
199
+ - package title and version
200
+ - parsed `pages`
201
+ - generated OpenAI-compatible `tools`
202
+ - package file list and raw file contents
203
+
204
+ This is useful for verifying whether `app.json`, page schemas, and `getTools()` output match expectations while developing or debugging an AIX package inside the official docs experience.
205
+
206
+ ### Pack and Optimize
207
+
208
+ The Web package includes the same in-memory packer and pure Rust resource
209
+ optimizer used by the npm CLI:
210
+
211
+ ```ts
212
+ const packed = await AIX.pack(
213
+ [{ path: "app.json", data: new TextEncoder().encode('{"pages":[]}') }],
214
+ { optimize: { level: 2 } },
215
+ );
216
+
217
+ const optimized = await AIX.optimize(packed.data, { level: 3 });
218
+ ```
219
+
220
+ Both methods return the generated `Uint8Array` and a structured per-file report.
221
+
222
+ Use `packFromSource` when the input represents an unpacked application tree.
223
+ It applies the same path normalization and nested `.aixignore` behavior as the
224
+ native and npm CLIs, and can report structured progress:
225
+
226
+ ```ts
227
+ const packed = await AIX.packFromSource(
228
+ [
229
+ { path: ".aixignore", data: new TextEncoder().encode("*.tmp\n") },
230
+ { path: "app.json", data: new TextEncoder().encode('{"pages":[]}') },
231
+ { path: "scratch.tmp", data: new Uint8Array() },
232
+ ],
233
+ {
234
+ optimize: { level: 2 },
235
+ onProgress(event) {
236
+ console.log(event.type);
237
+ },
238
+ },
239
+ );
240
+ ```
241
+
242
+ Use `pack` only when the caller has already normalized and filtered its input
243
+ files and wants to invoke the low-level packer directly.
244
+
245
+ ## API Reference
246
+
247
+ ### `AIX` Class
248
+
249
+ The main class to interact with an AIX package.
250
+
251
+ #### `static async From(data: Uint8Array | File, limits?: AixReadLimits, check?: boolean): Promise<AIX>`
252
+ Initializes the WASM module and creates an AIX instance from the given `.aix` file content. It supports both `Uint8Array` and the standard Web `File` object.
253
+ `check` defaults to `false`. Set it to `true` to check before returning and reject
254
+ with `AixCheckError` when errors are reported; see [Open and Check](#open-and-check).
255
+ ```typescript
256
+ // From Uint8Array
257
+ const aix = await AIX.From(new Uint8Array(buffer));
258
+
259
+ // From File (Web API)
260
+ const aix = await AIX.From(file);
261
+ ```
262
+
263
+ #### `list(): AixEntry[]`
264
+ Lists all files in the AIX package.
265
+ ```typescript
266
+ const files = aix.list();
267
+ // [{ name: "app.json", size: 123, compressed_size: 45 }, ...]
268
+ ```
269
+
270
+ #### `readFile(name: string): Uint8Array`
271
+ Reads the raw content of a specific file from the package.
272
+ ```typescript
273
+ const content = aix.readFile('app.json');
274
+ const text = new TextDecoder().decode(content);
275
+ ```
276
+
277
+ #### `getVersion(): string | undefined`
278
+ Returns the version metadata from the `VERSION` file in the package.
279
+ ```typescript
280
+ const version = aix.getVersion();
281
+ ```
282
+
283
+ #### `getTitle(): string | undefined`
284
+ Extracts the navigation bar title from the `app.json`.
285
+ ```typescript
286
+ const title = aix.getTitle();
287
+ ```
288
+
289
+ #### `getPermissions(): string[]`
290
+ Returns the permission names declared in `app.json.permissions`, preserving their
291
+ order, duplicates, and custom names. An omitted or empty list returns `[]`.
292
+ Throws if `app.json` is missing, unreadable, invalid, or `permissions` is not an
293
+ array of strings. This reads declarations without querying authorization or
294
+ prompting for access.
295
+ ```typescript
296
+ const permissions = aix.getPermissions();
297
+ // e.g. ['GEOLOCATION', 'CAMERA']
298
+ ```
299
+
300
+ #### `getPages(): PageInfo[]`
301
+ Returns information about all pages defined in the package, including their paths, titles, and data schemas.
302
+ ```typescript
303
+ const pages = aix.getPages();
304
+ /*
305
+ [{
306
+ name: "pages/index/index",
307
+ title: "Home",
308
+ description: null,
309
+ data_schema: { ... },
310
+ size: { width: 480, height: 168 }
311
+ }]
312
+ */
313
+ ```
314
+
315
+ #### `getWidgets(locale?): WidgetInfo[]`
316
+ Returns widget declarations after verifying that every path resolves to an `.ink` entry in the package. When `locale` is provided, merges `displayName` and `description` from the matching `app.<locale>.json` overlay. Throws when a declared entry is missing or the selected locale file is invalid.
317
+ ```typescript
318
+ const widgets = aix.getWidgets('en-US');
319
+ // [{ path: "widgets/clock/index", family: "1x1", placement: "persistent", displayName: "Clock", description: "Shows the current time." }]
320
+ ```
321
+
322
+ #### `resolveMetadata(): MetadataResolution`
323
+
324
+ Returns `{ pages, tools, diagnostics }` synchronously. Missing/unreadable resources,
325
+ UTF-8 errors, and malformed page metadata produce `{ path, message }` diagnostics,
326
+ one per failed page. Failed pages are excluded from both result lists; other
327
+ pages retain declaration order. A valid empty page list has no diagnostics;
328
+ invalid/unreadable `app.json.pages` produces an `app.json` diagnostic.
329
+
330
+ ```typescript
331
+ const result = aix.resolveMetadata();
332
+ console.log(result.diagnostics);
333
+ const tools = result.tools; // only successfully resolved pages
334
+ // For all-or-nothing acceptance, require result.diagnostics.length === 0.
335
+ ```
336
+
337
+ This API requires readable `.ink`, or both `.json` and `.wxml` for traditional
338
+ pages, and checks ZIP integrity and UTF-8 for resources it reads. It deserializes
339
+ page JSON and complete Ink `<script def>` blocks. Optional definitions, schemas,
340
+ and styles may be absent; present styles must be readable (`.wcss` before `.wxss`).
341
+ A broken Ink entry never falls back to traditional files. Use source checking
342
+ for full syntax, component, and JSON Schema validation. Runtime execution and
343
+ packing validation are unchanged.
344
+
345
+ `getPages()`/`getTools()` remain tolerant and can return default metadata/tools
346
+ even for missing resources. Page, Widget, and title fields are parsed separately;
347
+ invalid Widget fields no longer hide valid pages. `getWidgets()` still reports
348
+ Widget errors. Direct WASM consumers use `reader.resolve_metadata()`.
349
+
350
+ Exported `MetadataResolution` has `pages: PageInfo[]`, `tools: Tool[]`, and
351
+ `diagnostics: MetadataDiagnostic[]`; `MetadataDiagnostic` has `path` and `message`
352
+ string fields.
353
+
354
+ #### `getTools(): Tool[]`
355
+ Generates a list of OpenAI-compatible tool definitions based on the pages and their schemas.
356
+ ```typescript
357
+ const tools = aix.getTools();
358
+ /*
359
+ [{
360
+ type: "function",
361
+ target: "_blank",
362
+ layout: { width: 480, height: 168 },
363
+ function: {
364
+ name: "pages_index_index",
365
+ description: "Home",
366
+ parameters: { ... }
367
+ }
368
+ }]
369
+ */
370
+ ```
371
+
372
+ ## Data Types
373
+
374
+ ### `AixEntry`
375
+ ```typescript
376
+ interface AixEntry {
377
+ name: string;
378
+ size: number;
379
+ compressed_size: number;
380
+ }
381
+ ```
382
+
383
+ ### JSON and layout types
384
+ ```typescript
385
+ type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;
386
+ interface JsonObject { [key: string]: JsonValue }
387
+ type JsonSchema = JsonValue;
388
+ interface PageConstraint { width: number; height: number }
389
+ type ToolTarget = '_current' | '_blank';
390
+ type WidgetPlacement = 'persistent' | 'overlay';
391
+ ```
392
+
393
+ `JsonSchema` retains arbitrary JSON, including boolean schemas and unvalidated
394
+ legacy values. Use `AIX.checkFromSource()` for schema validation. Page `size`
395
+ and tool `layout` both contain numeric width/height constraints.
396
+
397
+ ### `PageInfo`
398
+ ```typescript
399
+ interface PageInfo {
400
+ name: string;
401
+ title: string | null;
402
+ description: string | null;
403
+ data_schema: JsonSchema;
404
+ size: PageConstraint;
405
+ }
406
+ ```
407
+
408
+ ### `WidgetInfo`
409
+ ```typescript
410
+ interface WidgetInfo {
411
+ path: string;
412
+ family: string;
413
+ placement: WidgetPlacement;
414
+ displayName: string | null;
415
+ description: string | null;
416
+ }
417
+ ```
418
+
419
+ ### `Tool`
420
+ OpenAI compatible tool format.
421
+ ```typescript
422
+ interface Tool {
423
+ type: string;
424
+ target: ToolTarget;
425
+ layout: PageConstraint;
426
+ function: FunctionDefinition;
427
+ }
428
+ interface FunctionDefinition {
429
+ name: string;
430
+ description: string | null;
431
+ parameters: JsonSchema;
432
+ }
433
+ ```
434
+
435
+ Metadata fields above are always present. Missing strings and nested JSON null
436
+ values now remain `null` through raw WASM, SDK getters, and `resolveMetadata()`,
437
+ matching native Rust JSON. Earlier WASM builds returned `undefined` for these
438
+ values; update explicit `=== undefined` checks to `=== null` when migrating
439
+ metadata consumers. Standalone `getTitle()` and `getVersion()` retain their
440
+ `string | undefined` return type. Tools currently emit `type: "function"` and
441
+ underscore-prefixed targets; `current`/`blank` are input aliases only.
442
+
443
+ ## Build
444
+
445
+ To build the library for distribution:
446
+
447
+ ```bash
448
+ npm run build
449
+ ```
450
+
451
+ The output will be generated in the `dist` directory, including WASM binaries and TypeScript definitions.
452
+
453
+ ## License
454
+
455
+ MIT
@@ -0,0 +1,77 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ export class AixReaderWasm {
5
+ free(): void;
6
+ [Symbol.dispose](): void;
7
+ get_agent_id(): string | undefined;
8
+ get_pages(): any;
9
+ get_permissions(): any;
10
+ get_title(): string | undefined;
11
+ get_tools(): any;
12
+ get_version(): string | undefined;
13
+ get_widgets(locale?: string | null): any;
14
+ list(): any;
15
+ /**
16
+ * Compatibility constructor without caller resource budgets.
17
+ */
18
+ constructor(data: Uint8Array);
19
+ read_file(name: string): Uint8Array;
20
+ /**
21
+ * Resolve readable pages/tools and expose per-resource failures as diagnostics.
22
+ */
23
+ resolve_metadata(): any;
24
+ supports_engine(current_version: string): boolean;
25
+ /**
26
+ * Create a reader with inclusive caller budgets. Omitted fields are unlimited.
27
+ */
28
+ static with_limits(data: Uint8Array, limits: any): AixReaderWasm;
29
+ }
30
+
31
+ export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
32
+
33
+ export interface InitOutput {
34
+ readonly memory: WebAssembly.Memory;
35
+ readonly __wbg_aixreaderwasm_free: (a: number, b: number) => void;
36
+ readonly aixreaderwasm_get_agent_id: (a: number) => [number, number, number, number];
37
+ readonly aixreaderwasm_get_pages: (a: number) => [number, number, number];
38
+ readonly aixreaderwasm_get_permissions: (a: number) => [number, number, number];
39
+ readonly aixreaderwasm_get_title: (a: number) => [number, number];
40
+ readonly aixreaderwasm_get_tools: (a: number) => [number, number, number];
41
+ readonly aixreaderwasm_get_version: (a: number) => [number, number];
42
+ readonly aixreaderwasm_get_widgets: (a: number, b: number, c: number) => [number, number, number];
43
+ readonly aixreaderwasm_list: (a: number) => [number, number, number];
44
+ readonly aixreaderwasm_new: (a: number, b: number) => [number, number, number];
45
+ readonly aixreaderwasm_read_file: (a: number, b: number, c: number) => [number, number, number, number];
46
+ readonly aixreaderwasm_resolve_metadata: (a: number) => [number, number, number];
47
+ readonly aixreaderwasm_supports_engine: (a: number, b: number, c: number) => [number, number, number];
48
+ readonly aixreaderwasm_with_limits: (a: number, b: number, c: any) => [number, number, number];
49
+ readonly __wbindgen_malloc: (a: number, b: number) => number;
50
+ readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
51
+ readonly __wbindgen_externrefs: WebAssembly.Table;
52
+ readonly __externref_table_dealloc: (a: number) => void;
53
+ readonly __wbindgen_free: (a: number, b: number, c: number) => void;
54
+ readonly __wbindgen_start: () => void;
55
+ }
56
+
57
+ export type SyncInitInput = BufferSource | WebAssembly.Module;
58
+
59
+ /**
60
+ * Instantiates the given `module`, which can either be bytes or
61
+ * a precompiled `WebAssembly.Module`.
62
+ *
63
+ * @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
64
+ *
65
+ * @returns {InitOutput}
66
+ */
67
+ export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
68
+
69
+ /**
70
+ * If `module_or_path` is {RequestInfo} or {URL}, makes a request and
71
+ * for everything else, calls `WebAssembly.instantiate` directly.
72
+ *
73
+ * @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
74
+ *
75
+ * @returns {Promise<InitOutput>}
76
+ */
77
+ export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;