@try-works/tool-mode-runtime-litert 0.0.0-stage → 0.1.1

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 (50) hide show
  1. package/lib/ear-frontend.d.ts +113 -0
  2. package/lib/ear-frontend.d.ts.map +1 -0
  3. package/lib/ear-frontend.js +258 -0
  4. package/lib/ear.d.ts +51 -0
  5. package/lib/ear.d.ts.map +1 -0
  6. package/lib/ear.js +296 -0
  7. package/lib/emo-tokenizer.d.ts +87 -0
  8. package/lib/emo-tokenizer.d.ts.map +1 -0
  9. package/lib/emo-tokenizer.js +365 -0
  10. package/lib/emo.d.ts +53 -0
  11. package/lib/emo.d.ts.map +1 -0
  12. package/lib/emo.js +218 -0
  13. package/lib/errors.d.ts +14 -0
  14. package/lib/errors.d.ts.map +1 -0
  15. package/lib/errors.js +29 -0
  16. package/lib/index.d.ts +28 -0
  17. package/lib/index.d.ts.map +1 -0
  18. package/lib/index.js +34 -0
  19. package/lib/model.d.ts +103 -0
  20. package/lib/model.d.ts.map +1 -0
  21. package/lib/model.js +112 -0
  22. package/lib/moderator.d.ts +59 -0
  23. package/lib/moderator.d.ts.map +1 -0
  24. package/lib/moderator.js +189 -0
  25. package/lib/pillow.d.ts +75 -0
  26. package/lib/pillow.d.ts.map +1 -0
  27. package/lib/pillow.js +187 -0
  28. package/lib/png.d.ts +27 -0
  29. package/lib/png.d.ts.map +1 -0
  30. package/lib/png.js +176 -0
  31. package/lib/processor.d.ts +43 -0
  32. package/lib/processor.d.ts.map +1 -0
  33. package/lib/processor.js +48 -0
  34. package/lib/provider-factory.d.ts +44 -0
  35. package/lib/provider-factory.d.ts.map +1 -0
  36. package/lib/provider-factory.js +219 -0
  37. package/lib/runtime.d.ts +41 -0
  38. package/lib/runtime.d.ts.map +1 -0
  39. package/lib/runtime.js +66 -0
  40. package/lib/shapes.d.ts +28 -0
  41. package/lib/shapes.d.ts.map +1 -0
  42. package/lib/shapes.js +187 -0
  43. package/lib/shim.d.ts +45 -0
  44. package/lib/shim.d.ts.map +1 -0
  45. package/lib/shim.js +215 -0
  46. package/lib/wav.d.ts +39 -0
  47. package/lib/wav.d.ts.map +1 -0
  48. package/lib/wav.js +134 -0
  49. package/package.json +47 -4
  50. package/README.md +0 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pillow.d.ts","sourceRoot":"","sources":["../src/pillow.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,uEAAuE;AACvE,eAAO,MAAM,SAAS,MAAM,CAAA;AAE5B,yEAAyE;AACzE,eAAO,MAAM,qBAAqB,QAAa,CAAA;AAE/C,0EAA0E;AAC1E,eAAO,MAAM,eAAe,4BAA6B,CAAA;AAEzD,0DAA0D;AAC1D,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,UAAU,GAAG,UAAU,CAAA;AAE/D,8FAA8F;AAC9F,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,QAAQ,EAAE,CAAC,GAAG,CAAC,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAA;CAC5B;AAED,sFAAsF;AACtF,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB;AAED,4DAA4D;AAC5D,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;IACjC,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAA;IACjC,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;IACnC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CACvB;AAKD;;;;;;GAMG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,MAAM,EAAE,SAAS,MAAM,KAAG,YA+B9D,CAAA;AAQD;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,WAAW,EAAE,IAAI,MAAM,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,KAAG,UA8DzF,CAAA;AAED,kEAAkE;AAClE,eAAO,MAAM,UAAU,GAAI,MAAM,UAAU,EAAE,MAAM,MAAM,KAAG,UAa3D,CAAA;AAED,0EAA0E;AAC1E,eAAO,MAAM,WAAW,GAAI,OAAO,MAAM,EAAE,QAAQ,MAAM,EAAE,SAAS,gBAAgB,KAAG,SAAS,UAAU,EAezG,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,SAAS,GAAI,OAAO,WAAW,EAAE,SAAS,gBAAgB,KAAG,SAAS,UAAU,EAM5F,CAAA"}
package/lib/pillow.js ADDED
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Bit-exact port of The Pillow Group's BILINEAR resampler as used by the moderator
3
+ * preprocessing (libImaging/Resample.c), plus the crop geometry around it.
4
+ *
5
+ * PRIMARY SOURCE (Desert-Ant-Labs/desert-ant-core @ main, fetched 2026-11-14):
6
+ * - Sources/Moderator/Preprocess.swift:9 side = 384
7
+ * - Sources/Moderator/Preprocess.swift:10 zooms = [0.85, 0.70, 0.55]
8
+ * - Sources/Moderator/Preprocess.swift:32-38 windows: fast = center square of the short
9
+ * side; balanced = the whole image letterboxed onto a black square, plus center squares
10
+ * at 85/70/55% of the short side; accurate adds each tile's mirror.
11
+ * - Sources/Moderator/Preprocess.swift:40-50 mirror (horizontal RGB flip)
12
+ * - Sources/Moderator/Preprocess.swift:54 precisionBits = 32 - 8 - 2 = 22
13
+ * - Sources/Moderator/Preprocess.swift:65-94 fixed-point taps, including the exact
14
+ * operation order and the Int32 rounding of each weight.
15
+ * - Sources/Moderator/Preprocess.swift:96-100 clip8: arithmetic shift then clamp 0..255.
16
+ * - Sources/Moderator/Preprocess.swift:104-162 two-pass resample; pixels outside the
17
+ * source window read as black, which is how the letterbox is produced.
18
+ *
19
+ * THE CONTRACT IS BIT-EXACTNESS, so this file preserves the Swift operation order,
20
+ * integer truncation and fixed-point precision rather than "improving" any of it.
21
+ */
22
+ /** The square side every crop is resampled to (Preprocess.swift:9). */
23
+ export const TILE_SIDE = 384;
24
+ /** Pillow's fixed-point precision for BILINEAR (Preprocess.swift:54). */
25
+ export const PILLOW_PRECISION_BITS = 32 - 8 - 2;
26
+ /** Balanced-mode zoom factors of the short side (Preprocess.swift:10). */
27
+ export const MODERATOR_ZOOMS = [0.85, 0.7, 0.55];
28
+ const PRECISION_SCALE = 1 << PILLOW_PRECISION_BITS;
29
+ const PRECISION_HALF = 1 << (PILLOW_PRECISION_BITS - 1);
30
+ /**
31
+ * Precompute the fixed-point tap table (Preprocess.swift:65-94).
32
+ *
33
+ * The arithmetic is deliberately the same as the Swift (and Pillow's C): double-precision
34
+ * weights accumulated in the same order, divided by the total, scaled by 1 << 22 and rounded
35
+ * with +0.5 (or -0.5 for the impossible negative case) before Int32 truncation.
36
+ */
37
+ export const bilinearTaps = (inSize, outSize) => {
38
+ const scale = inSize / outSize;
39
+ const filterScale = Math.max(scale, 1);
40
+ const support = filterScale;
41
+ const ss = 1 / filterScale;
42
+ const ksize = Math.ceil(support) * 2 + 1;
43
+ const start = [];
44
+ const count = [];
45
+ const weights = new Array(outSize * ksize).fill(0);
46
+ const k = new Array(ksize).fill(0);
47
+ for (let xx = 0; xx < outSize; xx += 1) {
48
+ const center = (xx + 0.5) * scale;
49
+ const xmin = Math.max(Math.trunc(center - support + 0.5), 0);
50
+ const xmax = Math.min(Math.trunc(center + support + 0.5), inSize) - xmin;
51
+ let total = 0;
52
+ for (let x = 0; x < xmax; x += 1) {
53
+ const distance = Math.abs((x + xmin - center + 0.5) * ss);
54
+ const value = distance < 1 ? 1 - distance : 0;
55
+ k[x] = value;
56
+ total += value;
57
+ }
58
+ for (let x = 0; x < xmax; x += 1) {
59
+ const value = k[x] ?? 0;
60
+ const normalized = total !== 0 ? value / total : value;
61
+ const fixed = normalized * PRECISION_SCALE;
62
+ weights[xx * ksize + x] = Math.trunc(normalized < 0 ? fixed - 0.5 : fixed + 0.5);
63
+ }
64
+ start.push(xmin);
65
+ count.push(xmax);
66
+ }
67
+ return { start, count, weights, ksize };
68
+ };
69
+ /** Arithmetic shift then clamp, exactly Preprocess.swift:96-100. */
70
+ const clip8 = (value) => {
71
+ const shifted = value >> PILLOW_PRECISION_BITS;
72
+ return shifted <= 0 ? 0 : shifted >= 255 ? 255 : shifted;
73
+ };
74
+ /**
75
+ * Resample one square source window to TILE_SIDE x TILE_SIDE RGB.
76
+ *
77
+ * Two separable passes, horizontal into a scratch band of only the rows the vertical pass
78
+ * reads, then vertical, exactly as Preprocess.swift:104-162. Source pixels outside the image
79
+ * are skipped (black); out-of-window rows leave the scratch band zeroed.
80
+ */
81
+ export const resampleWindow = (image, x0, y0, size) => {
82
+ const horizontal = bilinearTaps(size, TILE_SIDE);
83
+ const vertical = bilinearTaps(size, TILE_SIDE);
84
+ const rowFirst = vertical.start[0] ?? 0;
85
+ const lastStart = vertical.start[TILE_SIDE - 1] ?? 0;
86
+ const lastCount = vertical.count[TILE_SIDE - 1] ?? 0;
87
+ const rows = lastStart + lastCount - rowFirst;
88
+ const channels = image.channels;
89
+ const width = image.width;
90
+ const height = image.height;
91
+ const scratch = new Uint8Array(rows * TILE_SIDE * 3);
92
+ for (let r = 0; r < rows; r += 1) {
93
+ const sy = y0 + rowFirst + r;
94
+ if (sy < 0 || sy >= height)
95
+ continue;
96
+ const rowBase = sy * width * channels;
97
+ for (let xx = 0; xx < TILE_SIDE; xx += 1) {
98
+ let s0 = PRECISION_HALF;
99
+ let s1 = PRECISION_HALF;
100
+ let s2 = PRECISION_HALF;
101
+ const kBase = xx * horizontal.ksize;
102
+ const first = horizontal.start[xx] ?? 0;
103
+ const taps = horizontal.count[xx] ?? 0;
104
+ for (let x = 0; x < taps; x += 1) {
105
+ const sx = x0 + first + x;
106
+ if (sx < 0 || sx >= width)
107
+ continue;
108
+ const p = rowBase + sx * channels;
109
+ const weight = horizontal.weights[kBase + x] ?? 0;
110
+ s0 += (image.pixels[p] ?? 0) * weight;
111
+ s1 += (image.pixels[p + 1] ?? 0) * weight;
112
+ s2 += (image.pixels[p + 2] ?? 0) * weight;
113
+ }
114
+ const out = (r * TILE_SIDE + xx) * 3;
115
+ scratch[out] = clip8(s0);
116
+ scratch[out + 1] = clip8(s1);
117
+ scratch[out + 2] = clip8(s2);
118
+ }
119
+ }
120
+ const result = new Uint8Array(TILE_SIDE * TILE_SIDE * 3);
121
+ for (let yy = 0; yy < TILE_SIDE; yy += 1) {
122
+ const kBase = yy * vertical.ksize;
123
+ const first = (vertical.start[yy] ?? 0) - rowFirst;
124
+ const taps = vertical.count[yy] ?? 0;
125
+ for (let xx = 0; xx < TILE_SIDE; xx += 1) {
126
+ let s0 = PRECISION_HALF;
127
+ let s1 = PRECISION_HALF;
128
+ let s2 = PRECISION_HALF;
129
+ for (let y = 0; y < taps; y += 1) {
130
+ const p = ((first + y) * TILE_SIDE + xx) * 3;
131
+ const weight = vertical.weights[kBase + y] ?? 0;
132
+ s0 += (scratch[p] ?? 0) * weight;
133
+ s1 += (scratch[p + 1] ?? 0) * weight;
134
+ s2 += (scratch[p + 2] ?? 0) * weight;
135
+ }
136
+ const out = (yy * TILE_SIDE + xx) * 3;
137
+ result[out] = clip8(s0);
138
+ result[out + 1] = clip8(s1);
139
+ result[out + 2] = clip8(s2);
140
+ }
141
+ }
142
+ return result;
143
+ };
144
+ /** Horizontal mirror of one RGB tile (Preprocess.swift:40-50). */
145
+ export const mirrorTile = (tile, side) => {
146
+ const out = new Uint8Array(tile.length);
147
+ for (let y = 0; y < side; y += 1) {
148
+ const row = y * side * 3;
149
+ for (let x = 0; x < side; x += 1) {
150
+ const src = row + (side - 1 - x) * 3;
151
+ const dst = row + x * 3;
152
+ out[dst] = tile[src] ?? 0;
153
+ out[dst + 1] = tile[src + 1] ?? 0;
154
+ out[dst + 2] = tile[src + 2] ?? 0;
155
+ }
156
+ }
157
+ return out;
158
+ };
159
+ /** The square source windows for one quality (Preprocess.swift:32-38). */
160
+ export const cropWindows = (width, height, quality) => {
161
+ const short = Math.min(width, height);
162
+ const square = (size) => ({
163
+ x0: Math.trunc((width - size) / 2),
164
+ y0: Math.trunc((height - size) / 2),
165
+ size,
166
+ });
167
+ if (quality === 'fast')
168
+ return [square(short)];
169
+ const long = Math.max(width, height);
170
+ // Same integer inset as -((long - w) / 2), written on the non-negative side so a zero
171
+ // inset is +0 rather than -0 (deep equality and JSON both prefer +0).
172
+ return [
173
+ { x0: Math.trunc((width - long) / 2), y0: Math.trunc((height - long) / 2), size: long },
174
+ ...MODERATOR_ZOOMS.map((zoom) => square(Math.trunc(short * zoom))),
175
+ ];
176
+ };
177
+ /**
178
+ * The RGB tiles one image is scored on: resample every window, and for accurate follow each
179
+ * tile with its mirror (Preprocess.swift:14-28).
180
+ */
181
+ export const cropTiles = (image, quality) => {
182
+ const tiles = cropWindows(image.width, image.height, quality).map((window) => resampleWindow(image, window.x0, window.y0, window.size));
183
+ if (quality !== 'accurate')
184
+ return tiles;
185
+ return tiles.flatMap((tile) => [tile, mirrorTile(tile, TILE_SIDE)]);
186
+ };
187
+ //# sourceMappingURL=pillow.js.map
package/lib/png.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Minimal, honest PNG decoding for the moderator tool (PHASE4: v1 decodes PNG only).
3
+ *
4
+ * SCOPE, BY DESIGN: 8-bit RGB (colour type 2) and 8-bit RGBA (colour type 6), non-interlaced,
5
+ * with every chunk CRC checked. Everything else is REFUSED BY NAME rather than guessed:
6
+ * JPEG, 16-bit, palette, grayscale, interlaced, corrupt CRC, missing IDAT, truncated data.
7
+ * The alpha channel is dropped, which is what the moderator's ImagePixels does
8
+ * (Sources/Moderator/Moderator.swift:3-31).
9
+ *
10
+ * NO IMAGE LIBRARY IS ADDED: node:zlib inflates the IDAT stream and the five PNG scanline
11
+ * filters are implemented here.
12
+ */
13
+ /** A decoded image: width * height * 3 RGB bytes, row-major from the top-left. */
14
+ export interface DecodedRgb {
15
+ readonly width: number;
16
+ readonly height: number;
17
+ readonly rgb: Uint8Array;
18
+ }
19
+ /**
20
+ * Decode a PNG to raw 8-bit RGB.
21
+ *
22
+ * @param bytes - the file bytes.
23
+ * @returns the decoded raster.
24
+ * @throws Error with a named refusal for every unsupported or corrupt input.
25
+ */
26
+ export declare const decodePngToRgb: (bytes: Uint8Array) => DecodedRgb;
27
+ //# sourceMappingURL=png.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"png.d.ts","sourceRoot":"","sources":["../src/png.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,kFAAkF;AAClF,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAA;CACzB;AA6ED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,OAAO,UAAU,KAAG,UAwElD,CAAA"}
package/lib/png.js ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Minimal, honest PNG decoding for the moderator tool (PHASE4: v1 decodes PNG only).
3
+ *
4
+ * SCOPE, BY DESIGN: 8-bit RGB (colour type 2) and 8-bit RGBA (colour type 6), non-interlaced,
5
+ * with every chunk CRC checked. Everything else is REFUSED BY NAME rather than guessed:
6
+ * JPEG, 16-bit, palette, grayscale, interlaced, corrupt CRC, missing IDAT, truncated data.
7
+ * The alpha channel is dropped, which is what the moderator's ImagePixels does
8
+ * (Sources/Moderator/Moderator.swift:3-31).
9
+ *
10
+ * NO IMAGE LIBRARY IS ADDED: node:zlib inflates the IDAT stream and the five PNG scanline
11
+ * filters are implemented here.
12
+ */
13
+ import { inflateSync } from 'node:zlib';
14
+ const PNG_SIGNATURE = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
15
+ const MAX_PIXELS = 50_000_000;
16
+ const crcTable = (() => {
17
+ const table = new Uint32Array(256);
18
+ for (let index = 0; index < 256; index += 1) {
19
+ let value = index;
20
+ for (let bit = 0; bit < 8; bit += 1) {
21
+ value = (value & 1) === 1 ? 0xedb88320 ^ (value >>> 1) : value >>> 1;
22
+ }
23
+ table[index] = value >>> 0;
24
+ }
25
+ return table;
26
+ })();
27
+ const crc32 = (bytes, start, end) => {
28
+ let crc = 0xffffffff;
29
+ for (let index = start; index < end; index += 1) {
30
+ crc = (crcTable[(crc ^ (bytes[index] ?? 0)) & 0xff] ?? 0) ^ (crc >>> 8);
31
+ }
32
+ return (crc ^ 0xffffffff) >>> 0;
33
+ };
34
+ const paeth = (a, b, c) => {
35
+ const p = a + b - c;
36
+ const pa = Math.abs(p - a);
37
+ const pb = Math.abs(p - b);
38
+ const pc = Math.abs(p - c);
39
+ if (pa <= pb && pa <= pc)
40
+ return a;
41
+ if (pb <= pc)
42
+ return b;
43
+ return c;
44
+ };
45
+ /** Fail as a never-returning call, so control-flow analysis prunes the branches. */
46
+ function fail(message) {
47
+ throw new Error(message);
48
+ }
49
+ const signatureMatches = (bytes) => {
50
+ if (bytes.length < PNG_SIGNATURE.length)
51
+ return false;
52
+ for (let index = 0; index < PNG_SIGNATURE.length; index += 1) {
53
+ if (bytes[index] !== PNG_SIGNATURE[index])
54
+ return false;
55
+ }
56
+ return true;
57
+ };
58
+ const readHeader = (view, offset, length) => {
59
+ if (length !== 13)
60
+ fail('the PNG IHDR chunk must be 13 bytes');
61
+ const width = view.getUint32(offset + 8);
62
+ const height = view.getUint32(offset + 12);
63
+ const bitDepth = view.getUint8(offset + 16);
64
+ const colorType = view.getUint8(offset + 17);
65
+ const compression = view.getUint8(offset + 18);
66
+ const filterMethod = view.getUint8(offset + 19);
67
+ const interlace = view.getUint8(offset + 20);
68
+ if (width === 0 || height === 0)
69
+ fail('the PNG has zero width or height');
70
+ if (width * height > MAX_PIXELS)
71
+ fail('the PNG is larger than the ' + String(MAX_PIXELS) + '-pixel decode limit');
72
+ if (interlace !== 0)
73
+ fail('interlaced PNGs are not supported');
74
+ if (compression !== 0 || filterMethod !== 0)
75
+ fail('unsupported PNG compression or filter method');
76
+ if (bitDepth !== 8) {
77
+ fail(bitDepth === 16 ? '16-bit PNGs are not supported; the decoder accepts 8-bit PNG only' : String(bitDepth) + '-bit PNGs are not supported');
78
+ }
79
+ if (colorType === 3)
80
+ fail('palette PNGs are not supported; the decoder accepts 8-bit RGB or RGBA');
81
+ if (colorType === 0 || colorType === 4)
82
+ fail('grayscale PNGs are not supported; the decoder accepts 8-bit RGB or RGBA');
83
+ if (colorType === 2)
84
+ return { width, height, channels: 3 };
85
+ if (colorType === 6)
86
+ return { width, height, channels: 4 };
87
+ return fail('PNG colour type ' + String(colorType) + ' is not supported');
88
+ };
89
+ /**
90
+ * Decode a PNG to raw 8-bit RGB.
91
+ *
92
+ * @param bytes - the file bytes.
93
+ * @returns the decoded raster.
94
+ * @throws Error with a named refusal for every unsupported or corrupt input.
95
+ */
96
+ export const decodePngToRgb = (bytes) => {
97
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) {
98
+ fail('JPEG input is not supported in v1; only 8-bit non-interlaced PNG is accepted');
99
+ }
100
+ if (!signatureMatches(bytes))
101
+ fail('the image is not a PNG (bad signature)');
102
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
103
+ const decoded = new TextDecoder('latin1');
104
+ let header;
105
+ let sawIend = false;
106
+ const idat = [];
107
+ let offset = PNG_SIGNATURE.length;
108
+ while (offset < bytes.length) {
109
+ if (offset + 8 > bytes.length)
110
+ fail('truncated PNG: a chunk header is incomplete');
111
+ const length = view.getUint32(offset);
112
+ if (length > bytes.length - offset - 12)
113
+ fail('truncated PNG: a chunk body is incomplete');
114
+ const type = decoded.decode(bytes.subarray(offset + 4, offset + 8));
115
+ const dataStart = offset + 8;
116
+ const dataEnd = dataStart + length;
117
+ const expectedCrc = view.getUint32(dataEnd);
118
+ const actualCrc = crc32(bytes, offset + 4, dataEnd);
119
+ if (expectedCrc !== actualCrc)
120
+ fail('PNG chunk CRC mismatch in "' + type + '"');
121
+ if (type === 'IHDR') {
122
+ header = readHeader(view, offset, length);
123
+ }
124
+ else if (type === 'IDAT') {
125
+ idat.push(bytes.subarray(dataStart, dataEnd));
126
+ }
127
+ else if (type === 'IEND') {
128
+ sawIend = true;
129
+ }
130
+ offset = dataEnd + 4;
131
+ }
132
+ if (header === undefined)
133
+ fail('truncated PNG: no IHDR chunk');
134
+ if (!sawIend)
135
+ fail('truncated PNG: no IEND chunk');
136
+ if (idat.length === 0)
137
+ fail('the PNG has no IDAT chunk');
138
+ const stride = header.width * header.channels;
139
+ const expected = header.height * (stride + 1);
140
+ const total = idat.reduce((sum, part) => sum + part.length, 0);
141
+ const compressed = new Uint8Array(total);
142
+ let cursor = 0;
143
+ for (const part of idat) {
144
+ compressed.set(part, cursor);
145
+ cursor += part.length;
146
+ }
147
+ const raw = inflateSync(compressed, { maxOutputLength: expected });
148
+ if (raw.length !== expected)
149
+ fail('the PNG pixel data is ' + String(raw.length) + ' bytes; expected ' + String(expected));
150
+ const pixels = new Uint8Array(header.height * stride);
151
+ for (let y = 0; y < header.height; y += 1) {
152
+ const filter = raw[y * (stride + 1)] ?? 0;
153
+ if (filter > 4)
154
+ fail('unsupported PNG filter type ' + String(filter));
155
+ const rowStart = y * (stride + 1) + 1;
156
+ const outRow = y * stride;
157
+ for (let index = 0; index < stride; index += 1) {
158
+ const value = raw[rowStart + index] ?? 0;
159
+ const left = index >= header.channels ? (pixels[outRow + index - header.channels] ?? 0) : 0;
160
+ const above = y > 0 ? (pixels[outRow - stride + index] ?? 0) : 0;
161
+ const aboveLeft = y > 0 && index >= header.channels ? (pixels[outRow - stride + index - header.channels] ?? 0) : 0;
162
+ const predictor = filter === 1 ? left : filter === 2 ? above : filter === 3 ? (left + above) >> 1 : filter === 4 ? paeth(left, above, aboveLeft) : 0;
163
+ pixels[outRow + index] = (value + predictor) & 0xff;
164
+ }
165
+ }
166
+ if (header.channels === 3)
167
+ return { width: header.width, height: header.height, rgb: pixels };
168
+ const rgb = new Uint8Array(header.width * header.height * 3);
169
+ for (let index = 0; index < header.width * header.height; index += 1) {
170
+ rgb[index * 3] = pixels[index * 4] ?? 0;
171
+ rgb[index * 3 + 1] = pixels[index * 4 + 1] ?? 0;
172
+ rgb[index * 3 + 2] = pixels[index * 4 + 2] ?? 0;
173
+ }
174
+ return { width: header.width, height: header.height, rgb };
175
+ };
176
+ //# sourceMappingURL=png.js.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The processor seam between the declarative recipe factory and one model's JSON contract.
3
+ *
4
+ * A recipe names a processor id; the engine package owns the processors it implements. Each
5
+ * processor validates the tool input, maps it onto tensors, drives LitertSession, and returns
6
+ * exactly the keys its tool schema declares. The factory knows nothing about any one model.
7
+ */
8
+ import type { Effect } from 'effect';
9
+ import type { InvocationContextV1, JsonObject } from '@try-works/tool-mode-extension-sdk';
10
+ import { InferenceFailed, InvalidInput, RuntimeUnavailable } from '@try-works/tool-mode-runtime-core';
11
+ import type { LitertSession } from './runtime.ts';
12
+ /** The recipe limits in force for one invocation. */
13
+ export interface ProcessorLimits {
14
+ readonly maxInputBytes: number;
15
+ readonly timeoutMs: number;
16
+ }
17
+ /** One tool invocation, already carrying the host-granted call context. */
18
+ export interface ProcessorInvocation {
19
+ readonly input: Readonly<JsonObject>;
20
+ readonly context: InvocationContextV1;
21
+ readonly limits: ProcessorLimits;
22
+ /**
23
+ * The verified asset-set directory the model artifact was resolved from. Processors whose
24
+ * deployment ships sibling files (the ear mel bank and language list) read them here; the
25
+ * files are part of the same host-verified asset set as the model.
26
+ */
27
+ readonly assetDirectory: string;
28
+ }
29
+ /** One model's processor: the recipe selects it by id. */
30
+ export interface RecipeProcessor {
31
+ readonly id: string;
32
+ readonly features: readonly string[];
33
+ readonly invoke: (invocation: ProcessorInvocation) => Effect.Effect<JsonObject, InvalidInput | InferenceFailed | RuntimeUnavailable, LitertSession>;
34
+ }
35
+ /** Render a typed failure, or any thrown value, as one readable sentence. */
36
+ export declare function describeFailure(cause: unknown): string;
37
+ /** The JSON byte size of a tool input. */
38
+ export declare function inputBytes(input: Readonly<JsonObject>): number;
39
+ /** Refuse an input over the recipe's byte ceiling. */
40
+ export declare function inputCeilingFailure(input: Readonly<JsonObject>, limits: ProcessorLimits): InvalidInput | undefined;
41
+ /** Refuse any input key outside the tool schema's closed key set. */
42
+ export declare function closedKeyFailure(input: Readonly<JsonObject>, allowed: ReadonlySet<string>, accepts: string): InvalidInput | undefined;
43
+ //# sourceMappingURL=processor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"processor.d.ts","sourceRoot":"","sources":["../src/processor.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAEpC,OAAO,KAAK,EAAE,mBAAmB,EAAE,UAAU,EAAE,MAAM,oCAAoC,CAAA;AACzF,OAAO,EACL,eAAe,EACf,YAAY,EACZ,kBAAkB,EACnB,MAAM,mCAAmC,CAAA;AAG1C,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAEjD,qDAAqD;AACrD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;CAC3B;AAED,2EAA2E;AAC3E,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,CAAA;IACpC,QAAQ,CAAC,OAAO,EAAE,mBAAmB,CAAA;IACrC,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAChC;;;;OAIG;IACH,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA;CAChC;AAED,0DAA0D;AAC1D,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAA;IACnB,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAA;IACpC,QAAQ,CAAC,MAAM,EAAE,CACf,UAAU,EAAE,mBAAmB,KAC5B,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,YAAY,GAAG,eAAe,GAAG,kBAAkB,EAAE,aAAa,CAAC,CAAA;CACnG;AAED,6EAA6E;AAC7E,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAMtD;AAED,0CAA0C;AAC1C,wBAAgB,UAAU,CAAC,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,GAAG,MAAM,CAE9D;AAED,sDAAsD;AACtD,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,eAAe,GAAG,YAAY,GAAG,SAAS,CAOlH;AAED,qEAAqE;AACrE,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,QAAQ,CAAC,UAAU,CAAC,EAC3B,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC,EAC5B,OAAO,EAAE,MAAM,GACd,YAAY,GAAG,SAAS,CAU1B"}
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The processor seam between the declarative recipe factory and one model's JSON contract.
3
+ *
4
+ * A recipe names a processor id; the engine package owns the processors it implements. Each
5
+ * processor validates the tool input, maps it onto tensors, drives LitertSession, and returns
6
+ * exactly the keys its tool schema declares. The factory knows nothing about any one model.
7
+ */
8
+ import { InferenceFailed, InvalidInput, RuntimeUnavailable, } from '@try-works/tool-mode-runtime-core';
9
+ import { describeCause } from "./errors.js";
10
+ /** Render a typed failure, or any thrown value, as one readable sentence. */
11
+ export function describeFailure(cause) {
12
+ if (cause instanceof InvalidInput)
13
+ return cause.field + ': ' + cause.message;
14
+ if (cause instanceof InferenceFailed)
15
+ return cause.phase + ': ' + cause.message;
16
+ if (cause instanceof RuntimeUnavailable)
17
+ return cause.reason;
18
+ if (cause instanceof Error)
19
+ return cause.message.length > 0 ? cause.message : cause.name;
20
+ return describeCause(cause);
21
+ }
22
+ /** The JSON byte size of a tool input. */
23
+ export function inputBytes(input) {
24
+ return Buffer.byteLength(JSON.stringify(input) ?? '', 'utf8');
25
+ }
26
+ /** Refuse an input over the recipe's byte ceiling. */
27
+ export function inputCeilingFailure(input, limits) {
28
+ const bytes = inputBytes(input);
29
+ if (bytes <= limits.maxInputBytes)
30
+ return undefined;
31
+ return new InvalidInput({
32
+ field: 'input',
33
+ message: 'the input is ' + String(bytes) + ' bytes, over the ' + String(limits.maxInputBytes) + '-byte input limit',
34
+ });
35
+ }
36
+ /** Refuse any input key outside the tool schema's closed key set. */
37
+ export function closedKeyFailure(input, allowed, accepts) {
38
+ for (const key of Object.keys(input)) {
39
+ if (!allowed.has(key)) {
40
+ return new InvalidInput({
41
+ field: key,
42
+ message: 'the input accepts only ' + accepts + '; received ' + JSON.stringify(key),
43
+ });
44
+ }
45
+ }
46
+ return undefined;
47
+ }
48
+ //# sourceMappingURL=processor.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * The declarative provider factory (Phase 2, docs/runtime/PHASE2.md).
3
+ *
4
+ * A code-free package names this engine in its recipe, and the host -- which declares no
5
+ * engine dependency (AT-25) -- calls the factory with the parsed recipe and the host-verified
6
+ * asset map. The factory owns the engine and the PROCESSORS; the recipe supplies the artifact
7
+ * location, the limits, the tool schemas and the processor id.
8
+ *
9
+ * PROCESSORS IMPLEMENTED HERE (the models live in their own modules):
10
+ * - shapes/points-v1 -> src/shapes.ts (stroke -> 128 points -> 13 classes)
11
+ * - moderator/crops-v1 -> src/moderator.ts (PNG -> Pillow crops -> 5 NSFW heads)
12
+ *
13
+ * THE SDK BOUNDARY IS PROMISE-BASED, THE ENGINE IS EFFECT-BASED. This module keeps that
14
+ * mismatch in one place: a ManagedRuntime wraps the LiteRT session, load() forces the lazy
15
+ * runtime into existence so a broken deployment is reported at load time, and invoke() runs
16
+ * the selected processor, which maps the recipe's JSON contract onto serialized inference.
17
+ *
18
+ * TYPED FAILURES: internally every failure is InvalidInput, RuntimeUnavailable or
19
+ * InferenceFailed. The SDK declares Promise methods, and a Schema.TaggedError carries an EMPTY
20
+ * Error.message, so the boundary throws a readable Error whose cause is the typed value. The
21
+ * typed error is therefore still inspectable (error.cause) while a host log is not blank.
22
+ */
23
+ import type { ModelProviderV1, PreparedAssetMapV1 } from '@try-works/tool-mode-extension-sdk';
24
+ import type { ModelRuntimeRecipe } from '@try-works/tool-mode-runtime-recipes';
25
+ import type { LitertBoot } from './model.ts';
26
+ /** Test seam: a fake engine boot; production callers never pass it. */
27
+ export interface ProviderFactoryOptions {
28
+ readonly boot?: LitertBoot;
29
+ }
30
+ /**
31
+ * Build the SDK provider for one validated, code-free model-runtime recipe.
32
+ *
33
+ * Creation is lightweight (EXT-19): it validates what can be validated statically and reads
34
+ * nothing. Assets are resolved at load() time, preferring the map the SDK hands to load()
35
+ * over the map captured at creation, because the host may build the factory before a
36
+ * preparation completes.
37
+ *
38
+ * @param recipe - the parsed, frozen model-runtime recipe.
39
+ * @param assets - the host-verified asset map captured at creation.
40
+ * @param options - test seams (a fake engine boot); production callers omit it.
41
+ * @returns the SDK's Promise-based provider.
42
+ */
43
+ export declare function createProviderFromRecipe(recipe: ModelRuntimeRecipe, assets: Readonly<PreparedAssetMapV1>, options?: ProviderFactoryOptions): ModelProviderV1;
44
+ //# sourceMappingURL=provider-factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-factory.d.ts","sourceRoot":"","sources":["../src/provider-factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAcH,OAAO,KAAK,EAGV,eAAe,EACf,kBAAkB,EAEnB,MAAM,oCAAoC,CAAA;AAK3C,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,sCAAsC,CAAA;AAK9E,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAkB5C,uEAAuE;AACvE,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,IAAI,CAAC,EAAE,UAAU,CAAA;CAC3B;AAyED;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE,kBAAkB,EAC1B,MAAM,EAAE,QAAQ,CAAC,kBAAkB,CAAC,EACpC,OAAO,GAAE,sBAA2B,GACnC,eAAe,CAiIjB"}