@namzu/sdk 45.1.0 → 46.0.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.
Files changed (118) hide show
  1. package/CHANGELOG.md +111 -0
  2. package/dist/authorization/gate.d.ts +5 -2
  3. package/dist/authorization/gate.d.ts.map +1 -1
  4. package/dist/authorization/gate.js +25 -4
  5. package/dist/authorization/gate.js.map +1 -1
  6. package/dist/authorization/rules.d.ts.map +1 -1
  7. package/dist/authorization/rules.js +19 -0
  8. package/dist/authorization/rules.js.map +1 -1
  9. package/dist/authorization/shell-lexer.d.ts +24 -0
  10. package/dist/authorization/shell-lexer.d.ts.map +1 -1
  11. package/dist/authorization/shell-lexer.js +69 -51
  12. package/dist/authorization/shell-lexer.js.map +1 -1
  13. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  14. package/dist/pricing/catalogue.generated.js +28 -4
  15. package/dist/pricing/catalogue.generated.js.map +1 -1
  16. package/dist/public-runtime.d.ts +3 -3
  17. package/dist/public-runtime.d.ts.map +1 -1
  18. package/dist/public-runtime.js +4 -2
  19. package/dist/public-runtime.js.map +1 -1
  20. package/dist/public-tools.d.ts +3 -2
  21. package/dist/public-tools.d.ts.map +1 -1
  22. package/dist/public-tools.js +5 -2
  23. package/dist/public-tools.js.map +1 -1
  24. package/dist/public-types.d.ts +3 -3
  25. package/dist/public-types.d.ts.map +1 -1
  26. package/dist/registry/tool/callable.d.ts +22 -0
  27. package/dist/registry/tool/callable.d.ts.map +1 -0
  28. package/dist/registry/tool/callable.js +29 -0
  29. package/dist/registry/tool/callable.js.map +1 -0
  30. package/dist/registry/tool/execute.d.ts.map +1 -1
  31. package/dist/registry/tool/execute.js +8 -1
  32. package/dist/registry/tool/execute.js.map +1 -1
  33. package/dist/runtime/query/executor/tool-call-admission.d.ts +37 -11
  34. package/dist/runtime/query/executor/tool-call-admission.d.ts.map +1 -1
  35. package/dist/runtime/query/executor/tool-call-admission.js +38 -12
  36. package/dist/runtime/query/executor/tool-call-admission.js.map +1 -1
  37. package/dist/runtime/query/executor.d.ts +4 -2
  38. package/dist/runtime/query/executor.d.ts.map +1 -1
  39. package/dist/runtime/query/executor.js +18 -5
  40. package/dist/runtime/query/executor.js.map +1 -1
  41. package/dist/runtime/query/review-policy.d.ts +43 -0
  42. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  43. package/dist/runtime/query/review-policy.js +59 -16
  44. package/dist/runtime/query/review-policy.js.map +1 -1
  45. package/dist/skills/registry.d.ts +6 -0
  46. package/dist/skills/registry.d.ts.map +1 -1
  47. package/dist/skills/registry.js +1 -0
  48. package/dist/skills/registry.js.map +1 -1
  49. package/dist/tools/builtins/computer-use-coordinates.d.ts +65 -0
  50. package/dist/tools/builtins/computer-use-coordinates.d.ts.map +1 -0
  51. package/dist/tools/builtins/computer-use-coordinates.js +123 -0
  52. package/dist/tools/builtins/computer-use-coordinates.js.map +1 -0
  53. package/dist/tools/builtins/computer-use-image.d.ts +77 -0
  54. package/dist/tools/builtins/computer-use-image.d.ts.map +1 -0
  55. package/dist/tools/builtins/computer-use-image.js +223 -0
  56. package/dist/tools/builtins/computer-use-image.js.map +1 -0
  57. package/dist/tools/builtins/computer-use.d.ts +519 -14
  58. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  59. package/dist/tools/builtins/computer-use.js +1188 -183
  60. package/dist/tools/builtins/computer-use.js.map +1 -1
  61. package/dist/tools/builtins/index.d.ts +2 -1
  62. package/dist/tools/builtins/index.d.ts.map +1 -1
  63. package/dist/tools/builtins/index.js +1 -1
  64. package/dist/tools/builtins/index.js.map +1 -1
  65. package/dist/tools/builtins/skill.d.ts +74 -0
  66. package/dist/tools/builtins/skill.d.ts.map +1 -1
  67. package/dist/tools/builtins/skill.js +214 -174
  68. package/dist/tools/builtins/skill.js.map +1 -1
  69. package/dist/tools/defineTool.d.ts +2 -0
  70. package/dist/tools/defineTool.d.ts.map +1 -1
  71. package/dist/tools/defineTool.js +7 -0
  72. package/dist/tools/defineTool.js.map +1 -1
  73. package/dist/tools/schedules/present.d.ts.map +1 -1
  74. package/dist/tools/schedules/present.js +2 -0
  75. package/dist/tools/schedules/present.js.map +1 -1
  76. package/dist/tools/schedules/schedule-tool.d.ts +6 -5
  77. package/dist/tools/schedules/schedule-tool.d.ts.map +1 -1
  78. package/dist/tools/schedules/schedule-tool.js +121 -30
  79. package/dist/tools/schedules/schedule-tool.js.map +1 -1
  80. package/dist/tools/schedules/types.d.ts +69 -1
  81. package/dist/tools/schedules/types.d.ts.map +1 -1
  82. package/dist/types/authorization/index.d.ts +21 -0
  83. package/dist/types/authorization/index.d.ts.map +1 -1
  84. package/dist/types/authorization/index.js +5 -0
  85. package/dist/types/authorization/index.js.map +1 -1
  86. package/dist/types/computer-use/index.d.ts +176 -0
  87. package/dist/types/computer-use/index.d.ts.map +1 -1
  88. package/dist/types/computer-use/index.js.map +1 -1
  89. package/dist/types/tool/index.d.ts +19 -0
  90. package/dist/types/tool/index.d.ts.map +1 -1
  91. package/dist/types/tool/index.js.map +1 -1
  92. package/package.json +3 -1
  93. package/src/authorization/gate.ts +25 -4
  94. package/src/authorization/rules.ts +18 -0
  95. package/src/authorization/shell-lexer.ts +73 -45
  96. package/src/pricing/catalogue.generated.ts +28 -4
  97. package/src/pricing/rates.source.json +27 -6
  98. package/src/public-runtime.ts +16 -2
  99. package/src/public-tools.ts +19 -1
  100. package/src/public-types.ts +5 -0
  101. package/src/registry/tool/callable.ts +37 -0
  102. package/src/registry/tool/execute.ts +8 -1
  103. package/src/runtime/query/executor/tool-call-admission.ts +60 -16
  104. package/src/runtime/query/executor.ts +19 -4
  105. package/src/runtime/query/review-policy.ts +103 -15
  106. package/src/skills/registry.ts +8 -0
  107. package/src/tools/builtins/computer-use-coordinates.ts +144 -0
  108. package/src/tools/builtins/computer-use-image.ts +278 -0
  109. package/src/tools/builtins/computer-use.ts +1485 -191
  110. package/src/tools/builtins/index.ts +7 -1
  111. package/src/tools/builtins/skill.ts +304 -174
  112. package/src/tools/defineTool.ts +10 -0
  113. package/src/tools/schedules/present.ts +2 -0
  114. package/src/tools/schedules/schedule-tool.ts +139 -33
  115. package/src/tools/schedules/types.ts +69 -1
  116. package/src/types/authorization/index.ts +21 -0
  117. package/src/types/computer-use/index.ts +202 -0
  118. package/src/types/tool/index.ts +19 -0
@@ -0,0 +1,144 @@
1
+ import type { DisplayInfo, Point, Rect } from '../../types/computer-use/index.js'
2
+
3
+ /**
4
+ * One screenshot the model was shown: its id, the size of the image it saw,
5
+ * and the display that image was made from. Every coordinate the model sends
6
+ * is read against one of these.
7
+ */
8
+ export interface ScreenshotFrame {
9
+ /** `s1`, `s2`, … in the order the tool returned them. */
10
+ readonly id: string
11
+ readonly imageWidth: number
12
+ readonly imageHeight: number
13
+ /** Physical size and virtual-desktop origin of what the image shows. */
14
+ readonly display: DisplayInfo
15
+ }
16
+
17
+ /**
18
+ * The frames this tool instance has returned, newest last. A model reads a
19
+ * coordinate off the screenshot in front of it, which is almost always the
20
+ * latest; `get(id)` covers the one that names an earlier screenshot, and a
21
+ * display whose resolution changed in between is mapped through the frame
22
+ * the model actually looked at.
23
+ */
24
+ export class ScreenshotFrames {
25
+ private readonly frames = new Map<string, ScreenshotFrame>()
26
+ private counter = 0
27
+ private newest: ScreenshotFrame | undefined
28
+
29
+ constructor(private readonly capacity = 32) {}
30
+
31
+ record(image: { width: number; height: number }, display: DisplayInfo): ScreenshotFrame {
32
+ this.counter += 1
33
+ const frame: ScreenshotFrame = {
34
+ id: `s${this.counter}`,
35
+ imageWidth: image.width,
36
+ imageHeight: image.height,
37
+ display,
38
+ }
39
+ this.frames.set(frame.id, frame)
40
+ this.newest = frame
41
+ while (this.frames.size > this.capacity) {
42
+ const oldest = this.frames.keys().next().value
43
+ if (oldest === undefined) break
44
+ this.frames.delete(oldest)
45
+ }
46
+ return frame
47
+ }
48
+
49
+ latest(): ScreenshotFrame | undefined {
50
+ return this.newest
51
+ }
52
+
53
+ get(id: string): ScreenshotFrame | undefined {
54
+ return this.frames.get(id)
55
+ }
56
+ }
57
+
58
+ /** A display for a capture from a host that does not report one. */
59
+ export function assumedDisplay(width: number, height: number): DisplayInfo {
60
+ return { id: 'default', x: 0, y: 0, width, height, scaleFactor: 1, primary: true }
61
+ }
62
+
63
+ /**
64
+ * Whether `point` lies on the frame's image. The far edge is admitted — a
65
+ * model aiming at the last column sometimes says `width` — and is clamped in
66
+ * {@link toDisplayPoint}; anything further out is a coordinate read off some
67
+ * other image, and acting on it would click somewhere the model never saw.
68
+ */
69
+ export function pointOnImage(frame: ScreenshotFrame, point: Point): boolean {
70
+ return point.x >= 0 && point.y >= 0 && point.x <= frame.imageWidth && point.y <= frame.imageHeight
71
+ }
72
+
73
+ function axisToDisplay(value: number, image: number, display: number): number {
74
+ // The centre of image pixel `value`, in display pixels: unbiased, where
75
+ // `value * scale` would lean every click half an image pixel up and left.
76
+ const mapped = Math.floor(((value + 0.5) * display) / image)
77
+ return Math.min(Math.max(mapped, 0), display - 1)
78
+ }
79
+
80
+ function axisToImage(value: number, display: number, image: number): number {
81
+ const mapped = Math.floor(((value + 0.5) * image) / display)
82
+ return Math.min(Math.max(mapped, 0), image - 1)
83
+ }
84
+
85
+ /**
86
+ * A model coordinate (pixels of the frame's image) as the display-relative
87
+ * physical pixel the host acts on. Every image pixel maps to the display
88
+ * pixel at its centre, and {@link toImagePoint} maps that pixel straight
89
+ * back, so a round trip is exact whenever the image is no larger than the
90
+ * display.
91
+ */
92
+ export function toDisplayPoint(frame: ScreenshotFrame, point: Point): Point {
93
+ return {
94
+ x: axisToDisplay(point.x, frame.imageWidth, frame.display.width),
95
+ y: axisToDisplay(point.y, frame.imageHeight, frame.display.height),
96
+ }
97
+ }
98
+
99
+ /** A display-relative physical pixel as the image pixel of `frame` that shows it. */
100
+ export function toImagePoint(frame: ScreenshotFrame, point: Point): Point {
101
+ return {
102
+ x: axisToImage(point.x, frame.display.width, frame.imageWidth),
103
+ y: axisToImage(point.y, frame.display.height, frame.imageHeight),
104
+ }
105
+ }
106
+
107
+ /**
108
+ * An image-space rectangle as the display-relative physical rectangle that
109
+ * covers it completely (outward rounding), clamped to the display. Null when
110
+ * nothing of it is on the display.
111
+ */
112
+ export function toDisplayRect(frame: ScreenshotFrame, rect: Rect): Rect | null {
113
+ const sx = frame.display.width / frame.imageWidth
114
+ const sy = frame.display.height / frame.imageHeight
115
+ const left = Math.max(0, Math.floor(rect.x * sx))
116
+ const top = Math.max(0, Math.floor(rect.y * sy))
117
+ const right = Math.min(frame.display.width, Math.ceil((rect.x + rect.width) * sx))
118
+ const bottom = Math.min(frame.display.height, Math.ceil((rect.y + rect.height) * sy))
119
+ if (right <= left || bottom <= top) return null
120
+ return { x: left, y: top, width: right - left, height: bottom - top }
121
+ }
122
+
123
+ /**
124
+ * Virtual-desktop bounds (a window's) as the part of them visible in
125
+ * `frame`'s image, in its pixels; null when none of it is on that display.
126
+ */
127
+ export function desktopRectOnImage(frame: ScreenshotFrame, bounds: Rect): Rect | null {
128
+ const { display } = frame
129
+ const left = Math.max(bounds.x - display.x, 0)
130
+ const top = Math.max(bounds.y - display.y, 0)
131
+ const right = Math.min(bounds.x + bounds.width - display.x, display.width)
132
+ const bottom = Math.min(bounds.y + bounds.height - display.y, display.height)
133
+ if (right <= left || bottom <= top) return null
134
+ const sx = frame.imageWidth / display.width
135
+ const sy = frame.imageHeight / display.height
136
+ const x = Math.floor(left * sx)
137
+ const y = Math.floor(top * sy)
138
+ return {
139
+ x,
140
+ y,
141
+ width: Math.max(1, Math.ceil(right * sx) - x),
142
+ height: Math.max(1, Math.ceil(bottom * sy) - y),
143
+ }
144
+ }
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Screenshot sizing for `computer_use`.
3
+ *
4
+ * A model sees a screenshot at some size and answers with coordinates in that
5
+ * size. If the host sends a native 3440x1440 capture, the provider shrinks it
6
+ * before the model looks (or, for some computer-use tool results, rejects
7
+ * it), and every coordinate the model returns is in a space the host never
8
+ * observed: clicks land systematically off target. So the tool shrinks each
9
+ * capture itself, to the largest size the model takes without a further
10
+ * resize, remembers that size, and maps coordinates back.
11
+ *
12
+ * The size rule is the vision encoder's published reference implementation
13
+ * (`resizedSize`), ported line for line — it is a policy, not an image
14
+ * operation. The pixels are
15
+ * decoded, resampled and encoded by maintained packages: `fast-png` (PNG
16
+ * codec) and `pica` (Lanczos-3 resampling, pure JS with a bundled WASM
17
+ * kernel). Neither needs a native build, and both load only when a capture
18
+ * actually has to change size.
19
+ */
20
+
21
+ /** Patch edge of the vision encoder: an image costs ⌈w/28⌉ × ⌈h/28⌉ visual tokens. */
22
+ const PATCH_PX = 28
23
+
24
+ /**
25
+ * The limits a screenshot is fitted to: neither padded edge above
26
+ * `maxLongEdge`, and no more than `maxTiles` 28-pixel patches.
27
+ */
28
+ export interface ScreenshotLimits {
29
+ readonly maxLongEdge: number
30
+ readonly maxTiles: number
31
+ }
32
+
33
+ /**
34
+ * Every current vision model takes this without resizing it: the standard
35
+ * tier's limits exactly, and well inside the `detail: "high"` budget of the
36
+ * Responses wire (2048 px, 2 500 32-pixel patches). The default.
37
+ */
38
+ export const STANDARD_SCREENSHOT_LIMITS: ScreenshotLimits = Object.freeze({
39
+ maxLongEdge: 1568,
40
+ maxTiles: 1568,
41
+ })
42
+
43
+ /**
44
+ * The high-resolution tier some newer models accept. Use it only when every
45
+ * model the session can reach is on that tier: a standard-tier model rejects
46
+ * such a screenshot in a tool result, the Responses wire's `high` detail
47
+ * shrinks anything over 2048 px, and a request carrying more than 20 images
48
+ * caps every image at 2000 px.
49
+ */
50
+ export const HIGH_RES_SCREENSHOT_LIMITS: ScreenshotLimits = Object.freeze({
51
+ maxLongEdge: 2576,
52
+ maxTiles: 4784,
53
+ })
54
+
55
+ export interface ImageSize {
56
+ readonly width: number
57
+ readonly height: number
58
+ }
59
+
60
+ function tiles(width: number, height: number): number {
61
+ return Math.ceil(width / PATCH_PX) * Math.ceil(height / PATCH_PX)
62
+ }
63
+
64
+ /** Python's `round()`: exact .5 ties go to the even neighbour, as the live API does. */
65
+ function roundTiesToEven(value: number): number {
66
+ const floor = Math.floor(value)
67
+ if (value - floor !== 0.5) return Math.round(value)
68
+ return floor % 2 === 0 ? floor : floor + 1
69
+ }
70
+
71
+ /**
72
+ * The largest aspect-preserving size within `limits`; the input unchanged
73
+ * when it already fits. Never larger than the input.
74
+ */
75
+ export function screenshotTargetSize(
76
+ width: number,
77
+ height: number,
78
+ limits: ScreenshotLimits = STANDARD_SCREENSHOT_LIMITS,
79
+ ): ImageSize {
80
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width < 1 || height < 1)
81
+ throw new RangeError(`screenshot size must be positive integers, got ${width}x${height}`)
82
+ const fits = (w: number, h: number): boolean =>
83
+ Math.ceil(w / PATCH_PX) * PATCH_PX <= limits.maxLongEdge &&
84
+ Math.ceil(h / PATCH_PX) * PATCH_PX <= limits.maxLongEdge &&
85
+ tiles(w, h) <= limits.maxTiles
86
+ if (fits(width, height)) return { width, height }
87
+ if (height > width) {
88
+ const transposed = screenshotTargetSize(height, width, limits)
89
+ return { width: transposed.height, height: transposed.width }
90
+ }
91
+ const aspect = width / height
92
+ let lo = 1 // always fits
93
+ let hi = width // never fits
94
+ while (lo + 1 < hi) {
95
+ const mid = Math.floor((lo + hi) / 2)
96
+ if (fits(mid, Math.max(roundTiesToEven(mid / aspect), 1))) lo = mid
97
+ else hi = mid
98
+ }
99
+ return { width: lo, height: Math.max(roundTiesToEven(lo / aspect), 1) }
100
+ }
101
+
102
+ /** Width and height from a PNG's IHDR chunk, without decoding it. */
103
+ export function pngSize(data: Uint8Array): ImageSize {
104
+ const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
105
+ if (data.length < 24 || signature.some((byte, index) => data[index] !== byte))
106
+ throw new Error('computer_use: the host returned a screenshot that is not a PNG')
107
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength)
108
+ return { width: view.getUint32(16), height: view.getUint32(20) }
109
+ }
110
+
111
+ /** 8-bit RGBA pixels, row-major, no padding. */
112
+ interface RgbaImage {
113
+ readonly width: number
114
+ readonly height: number
115
+ readonly data: Uint8Array
116
+ }
117
+
118
+ type FastPng = typeof import('fast-png')
119
+ type PicaModule = typeof import('pica')
120
+
121
+ let codec: Promise<{ png: FastPng; resizer: InstanceType<PicaModule['Pica']> }> | undefined
122
+
123
+ function loadCodec(): Promise<{ png: FastPng; resizer: InstanceType<PicaModule['Pica']> }> {
124
+ codec ??= Promise.all([import('fast-png'), import('pica')]).then(([png, picaModule]) => ({
125
+ png,
126
+ // No `ww`/`cib`: those are browser features (Web Workers,
127
+ // createImageBitmap). In Node pica resizes on the calling thread.
128
+ resizer: new picaModule.Pica({ features: ['js', 'wasm'] }),
129
+ }))
130
+ return codec
131
+ }
132
+
133
+ /** For each PNG channel count: where red, green, blue and alpha come from (-1: opaque). */
134
+ const CHANNEL_SOURCES: Readonly<Record<number, readonly [number, number, number, number]>> = {
135
+ 1: [0, 0, 0, -1],
136
+ 2: [0, 0, 0, 1],
137
+ 3: [0, 1, 2, -1],
138
+ 4: [0, 1, 2, 3],
139
+ }
140
+
141
+ async function decodeRgba(data: Uint8Array): Promise<RgbaImage> {
142
+ const { png } = await loadCodec()
143
+ const decoded = png.decode(data)
144
+ const { width, height } = decoded
145
+ let source: ArrayLike<number> = decoded.data
146
+ let channels = decoded.channels
147
+ let depth: number = decoded.depth
148
+ if (decoded.palette) {
149
+ source = png.convertIndexedToRgb(decoded)
150
+ channels = decoded.palette[0]?.length ?? 3
151
+ depth = 8
152
+ }
153
+ const sources = CHANNEL_SOURCES[channels]
154
+ if ((depth !== 8 && depth !== 16) || !sources)
155
+ throw new Error(
156
+ `computer_use: cannot read a ${depth}-bit, ${channels}-channel PNG screenshot; hosts should capture 8-bit RGB or RGBA`,
157
+ )
158
+ // The common capture — 8-bit RGBA — is already the layout the resampler takes.
159
+ if (depth === 8 && channels === 4 && !decoded.palette) {
160
+ const bytes = decoded.data
161
+ return { width, height, data: new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) }
162
+ }
163
+ // Everything else becomes 8-bit RGBA; 16-bit samples keep their high byte.
164
+ // No per-pixel branches: this runs once per pixel of a whole display.
165
+ const shift = depth === 16 ? 8 : 0
166
+ const [r, g, b, a] = sources
167
+ const pixels = width * height
168
+ const rgba = new Uint8Array(pixels * 4)
169
+ if (a < 0) rgba.fill(255)
170
+ for (let i = 0, s = 0, d = 0; i < pixels; i += 1, s += channels, d += 4) {
171
+ rgba[d] = (source[s + r] as number) >> shift
172
+ rgba[d + 1] = (source[s + g] as number) >> shift
173
+ rgba[d + 2] = (source[s + b] as number) >> shift
174
+ }
175
+ if (a >= 0)
176
+ for (let i = 0, s = a, d = 3; i < pixels; i += 1, s += channels, d += 4)
177
+ rgba[d] = (source[s] as number) >> shift
178
+ return { width, height, data: rgba }
179
+ }
180
+
181
+ async function encodePng(image: RgbaImage): Promise<Buffer> {
182
+ const { png } = await loadCodec()
183
+ const { width, height, data } = image
184
+ // An opaque capture (every desktop screenshot) is sent as RGB: a quarter
185
+ // fewer bytes in every request that carries it.
186
+ let opaque = true
187
+ for (let i = 3; i < data.length; i += 4) {
188
+ if (data[i] !== 255) {
189
+ opaque = false
190
+ break
191
+ }
192
+ }
193
+ if (!opaque) return Buffer.from(png.encode({ width, height, data, channels: 4, depth: 8 }))
194
+ const rgb = new Uint8Array(width * height * 3)
195
+ for (let s = 0, d = 0; s < data.length; s += 4, d += 3) {
196
+ rgb[d] = data[s] as number
197
+ rgb[d + 1] = data[s + 1] as number
198
+ rgb[d + 2] = data[s + 2] as number
199
+ }
200
+ return Buffer.from(png.encode({ width, height, data: rgb, channels: 3, depth: 8 }))
201
+ }
202
+
203
+ async function resizeRgba(image: RgbaImage, target: ImageSize): Promise<RgbaImage> {
204
+ if (target.width === image.width && target.height === image.height) return image
205
+ const { resizer } = await loadCodec()
206
+ const data = await resizer.resizeBuffer({
207
+ src: image.data,
208
+ width: image.width,
209
+ height: image.height,
210
+ toWidth: target.width,
211
+ toHeight: target.height,
212
+ filter: 'lanczos3',
213
+ })
214
+ return { width: target.width, height: target.height, data }
215
+ }
216
+
217
+ function cropRgba(
218
+ image: RgbaImage,
219
+ rect: { x: number; y: number; width: number; height: number },
220
+ ): RgbaImage {
221
+ const data = new Uint8Array(rect.width * rect.height * 4)
222
+ for (let row = 0; row < rect.height; row += 1) {
223
+ const from = ((rect.y + row) * image.width + rect.x) * 4
224
+ data.set(image.data.subarray(from, from + rect.width * 4), row * rect.width * 4)
225
+ }
226
+ return { width: rect.width, height: rect.height, data }
227
+ }
228
+
229
+ /** A PNG ready for the model, and the size it was made from. */
230
+ export interface FittedImage {
231
+ readonly data: Buffer
232
+ readonly width: number
233
+ readonly height: number
234
+ readonly sourceWidth: number
235
+ readonly sourceHeight: number
236
+ }
237
+
238
+ /**
239
+ * Fit a PNG capture to `limits`. A capture that already fits is returned
240
+ * byte for byte, without being decoded.
241
+ */
242
+ export async function fitPng(data: Buffer, limits: ScreenshotLimits): Promise<FittedImage> {
243
+ const source = pngSize(data)
244
+ const target = screenshotTargetSize(source.width, source.height, limits)
245
+ if (target.width === source.width && target.height === source.height)
246
+ return { data, ...target, sourceWidth: source.width, sourceHeight: source.height }
247
+ const resized = await resizeRgba(await decodeRgba(data), target)
248
+ return {
249
+ data: await encodePng(resized),
250
+ width: resized.width,
251
+ height: resized.height,
252
+ sourceWidth: source.width,
253
+ sourceHeight: source.height,
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Cut `rect` (pixels of `data`, already clamped to it) out of a PNG and fit
259
+ * the piece to `limits`. Never enlarges: a small region stays at its native
260
+ * size, which is still more detail than the downscaled screenshot showed.
261
+ */
262
+ export async function cropAndFitPng(
263
+ data: Buffer,
264
+ rect: { x: number; y: number; width: number; height: number },
265
+ limits: ScreenshotLimits,
266
+ ): Promise<FittedImage> {
267
+ const decoded = await decodeRgba(data)
268
+ const piece = cropRgba(decoded, rect)
269
+ const target = screenshotTargetSize(piece.width, piece.height, limits)
270
+ const resized = await resizeRgba(piece, target)
271
+ return {
272
+ data: await encodePng(resized),
273
+ width: resized.width,
274
+ height: resized.height,
275
+ sourceWidth: piece.width,
276
+ sourceHeight: piece.height,
277
+ }
278
+ }