@nhtio/adk 0.1.0-master-9557685c → 0.1.0-master-74266e68

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 (57) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/batteries/media/contracts.cjs.map +1 -1
  3. package/batteries/media/contracts.d.ts +93 -2
  4. package/batteries/media/contracts.mjs.map +1 -1
  5. package/batteries/media/engines/execa_executor.cjs +285 -13
  6. package/batteries/media/engines/execa_executor.cjs.map +1 -1
  7. package/batteries/media/engines/execa_executor.d.ts +113 -8
  8. package/batteries/media/engines/execa_executor.mjs +285 -13
  9. package/batteries/media/engines/execa_executor.mjs.map +1 -1
  10. package/batteries/media/lint.cjs +1 -1
  11. package/batteries/media/lint.mjs +1 -1
  12. package/batteries/orchestration/executor.cjs +1 -1
  13. package/batteries/orchestration/executor.mjs +1 -1
  14. package/batteries/orchestration.cjs +4 -4
  15. package/batteries/orchestration.mjs +4 -4
  16. package/batteries/sandbox/contracts/policy_enforcer.d.ts +12 -6
  17. package/batteries/sandbox/executor.d.ts +28 -10
  18. package/batteries/sandbox/js.cjs +1 -1
  19. package/batteries/sandbox/js.mjs +1 -1
  20. package/batteries/sandbox/node/index.d.ts +1 -1
  21. package/batteries/sandbox/node/srt_enforcer.d.ts +74 -0
  22. package/batteries/sandbox/node.cjs +98 -5
  23. package/batteries/sandbox/node.cjs.map +1 -1
  24. package/batteries/sandbox/node.mjs +98 -6
  25. package/batteries/sandbox/node.mjs.map +1 -1
  26. package/batteries/sandbox.cjs +11 -11
  27. package/batteries/sandbox.cjs.map +1 -1
  28. package/batteries/sandbox.mjs +11 -11
  29. package/batteries/sandbox.mjs.map +1 -1
  30. package/batteries/skills.cjs +1 -1
  31. package/batteries/skills.mjs +1 -1
  32. package/batteries/tools/scrapper.cjs +1 -1
  33. package/batteries/tools/scrapper.mjs +1 -1
  34. package/batteries/tools/searxng.cjs +1 -1
  35. package/batteries/tools/searxng.mjs +1 -1
  36. package/batteries/tools.cjs +2 -2
  37. package/batteries/tools.mjs +2 -2
  38. package/batteries.cjs +2 -2
  39. package/batteries.mjs +2 -2
  40. package/eslint/rules.cjs +1 -1
  41. package/eslint/rules.mjs +1 -1
  42. package/eslint.cjs +2 -2
  43. package/eslint.mjs +2 -2
  44. package/index.cjs +1 -1
  45. package/index.mjs +1 -1
  46. package/mcp/adk-docs-corpus.json +2 -2
  47. package/package.json +310 -310
  48. package/{scrapper-CwkQjQBS.cjs → scrapper-Boc6kq2v.cjs} +2 -2
  49. package/{scrapper-CwkQjQBS.cjs.map → scrapper-Boc6kq2v.cjs.map} +1 -1
  50. package/{scrapper-_40wh9LI.mjs → scrapper-D2Gy9Jhv.mjs} +2 -2
  51. package/{scrapper-_40wh9LI.mjs.map → scrapper-D2Gy9Jhv.mjs.map} +1 -1
  52. package/{searxng-DVvFdVow.cjs → searxng-DOy3eBDH.cjs} +2 -2
  53. package/{searxng-DVvFdVow.cjs.map → searxng-DOy3eBDH.cjs.map} +1 -1
  54. package/{searxng-D0NEAks7.mjs → searxng-cCb0lAcN.mjs} +2 -2
  55. package/{searxng-D0NEAks7.mjs.map → searxng-cCb0lAcN.mjs.map} +1 -1
  56. package/server.json +2 -2
  57. package/skills/adk-assembly/SKILL.md +2 -2
package/CHANGELOG.md CHANGED
@@ -15,6 +15,129 @@ you *when* you got it, not *what changed*: a `^` range will float across battery
15
15
  breaking changes, so pin an exact version if you need stability and read the entry before
16
16
  upgrading.
17
17
 
18
+ ## Unreleased
19
+
20
+ ### Fixed
21
+
22
+ - **`@nhtio/adk/batteries/media/engines/execa_executor` — oversized escalation delays no longer busy-loop.** Deadline timers are capped at Node's maximum timer delay and re-armed against the monotonic deadline; `forceKillAfterDelay: Infinity` disables escalation.
23
+
24
+ ### Added
25
+
26
+ - **`@nhtio/adk/batteries/sandbox/node` — `srtBinarySandbox(enforcer, opts?)`, the concrete
27
+ `BinarySandbox` implementor for the SRT enforcer** (closes issue #37, closes issue #20). The sandbox
28
+ battery could refuse and narrate invocations, but there was no bundled way to actually wrap a
29
+ media-era `BinaryExecutor` call with OS enforcement; this factory provides one, derived from an
30
+ existing `srtEnforcer` rather than a second SRT adapter. It reuses the enforcer's single live
31
+ `SandboxManager` session, its validated `binShell`, its one `mapPolicy` translation point, its
32
+ network-divergence admission gate and its host-env allow-list — the "admission + quote +
33
+ `wrapWithSandboxArgv`" part of `run()` was factored into an internal step both execution routes
34
+ call, so the streaming shell path and the settled media path cannot drift. The wrap result sets
35
+ `cmd` to the wrapper binary and `args` to the rest of the generated argv (the caller's argv is
36
+ already inside it — it is never appended twice), overlays the caller's explicit `env` ON TOP of the
37
+ host-env allow-list (which — never `process.env` wholesale — is what controls host inheritance), and
38
+ carries `cwd`, `timeoutMs`, `signal` and the kill controls through. The wrap computes ONE effective
39
+ directory — the invocation's `cwd`, else the factory's `cwd`,
40
+ else `process.cwd()` — and uses it for both the SRT profile and the returned invocation's `cwd`, so
41
+ the profile and the spawn can never disagree. A wrap-time policy must repeat the session's network section exactly (or differ only on
42
+ the FILESYSTEM axis), or the same `E_SANDBOX_NETWORK_GRANT_UNSUPPORTED` the streaming path throws
43
+ fires before anything runs. Exported from `@nhtio/adk/batteries/sandbox/node` only — deliberately
44
+ not re-exported from the node-free `batteries/sandbox` barrel.
45
+ - **`@nhtio/adk/batteries/media/contracts` — `BinaryInvocation` carries `cwd`, `env`, `extendEnv`,
46
+ `killSignal` and `forceKillAfterDelay`; `BinaryExecResult` carries `signalCode`.** `cwd` is
47
+ exec-style and threaded by the bundled executor; `env` holds the caller's own explicit values,
48
+ applied last, with the same semantics the sandbox enforcer contract gives it. The host-env
49
+ allow-list is what controls inheritance from `process.env`, and an adapter must not let `env`
50
+ (or anything else) cause host variables beyond its allow-list to reach the child; explicit values
51
+ may add names or override allow-listed ones. `extendEnv: false` is the inheritance cut-off a
52
+ sandbox needs: execa's `extendEnv: true` default merges the whole `process.env` back in, which
53
+ would silently defeat any host-env allow-list, so `srtBinarySandbox` sets it and `execaExecutor`
54
+ maps it to execa's own `extendEnv: false`.
55
+ `killSignal` (default `'SIGTERM'`) and
56
+ `forceKillAfterDelay` (ms before `SIGKILL`; `false` disables escalation) are the kill controls.
57
+ `signalCode` is optional and additive — absent means the process exited on its own. The type stays
58
+ browser-safe: the signal is typed `string`, no `NodeJS` import.
59
+ - **`@nhtio/adk/batteries/media/engines/execa_executor` — `detached` threads through the whole
60
+ termination path, plus `cwd`/`env`/`extendEnv` forwarding and executor-level `defaultKillSignal` /
61
+ `defaultForceKillAfterDelay`.**
62
+ Invocations are now spawned `detached` (the child leads its own process group) and every abort and
63
+ timeout path terminates the WHOLE group — `process.kill(-pid, signal)`, escalating to `SIGKILL`
64
+ after `forceKillAfterDelay` — so a binary hidden behind a wrapper (sandbox → shell → command) dies
65
+ too, mirroring what `srtEnforcer.run` already did for its own spawns. Group kill needs the process
66
+ handle: `ExecaLike`'s return type now exposes an optional `pid` and the promise, and a BYO
67
+ substitute without a `pid` falls back to execa's own kill rather than failing. With
68
+ `detached: false` the child leads no group, so every path signals, probes and escalates against the
69
+ DIRECT child only (`subprocess.kill`, `process.kill(pid, 0)`) — a group probe there would report the
70
+ target dead and silently skip the escalation — and escalation is cancelled at settlement in this
71
+ direct-child mode, because the reaped child leaves nothing to escalate against and its pid could
72
+ be recycled.
73
+ `process.kill`
74
+ throwing (`ESRCH` on an already-reaped group) is swallowed, abort listeners are removed on settle,
75
+ and no path leaves an unhandled rejection. Non-zero exits remain data and are never thrown.
76
+ - **`@nhtio/adk/batteries/media/engines/execa_executor` — configurable settlement escalation.**
77
+ `BinaryInvocation.settleEscalation` and executor `defaultSettleEscalation` configure how escalation
78
+ behaves after abort/timeout: `'wait'` (default), `'cancel'`, or `'poll'`. Wait holds settlement until
79
+ the detached group is empty or receives its SIGKILL, so no descendant survives at the cost of
80
+ latency bounded by the remaining escalation delay; cancel returns fastest and drops escalation; poll
81
+ returns fastest and watches survivors later with unref'd probes every ~100 ms until the original
82
+ deadline, latching off at the first empty observation. Both group-probing modes retain the narrow
83
+ PGID-reuse risk between probes; wait bounds it to before return. `detached: false` degrades to cancel.
84
+
85
+ ### Changed
86
+
87
+ - **`@nhtio/adk/batteries/media/engines/execa_executor` — detached process groups are now the default.**
88
+ `execaExecutor` spawns children detached as process-group leaders, so terminal-generated
89
+ `SIGINT`/`SIGQUIT` (Ctrl-C) no longer reaches them; they are terminated only through the
90
+ invocation's `signal` or `timeoutMs`. Callers that relied on Ctrl-C reaching children should
91
+ pass an abort signal, or opt out with `execaExecutor({ detached: false })`, which then terminates
92
+ the direct child only (its own `signal`/`timeoutMs` kill, liveness probe and `SIGKILL` escalation)
93
+ and gives up group-killing wrapped grandchildren.
94
+ - **BREAKING `@nhtio/adk/batteries/sandbox` — the `BinarySandbox` contract now takes and returns the
95
+ plain `BinaryInvocation`; the wrapper returns cmd+args and quoting is the wrapper's job** (closes
96
+ issue #37). The previous shape threaded `BinaryInvocation & { command: string }` — a fully-quoted
97
+ shell command line the adapter produced with `quoteShellArgs` — and `sandboxedExecutor` then ran
98
+ `inner.exec({ ...wrapped, cmd: wrapped.command })`, executing the whole quoted command line AS the
99
+ binary name while still appending the original `args`. Nothing in the repo implemented the old
100
+ contract (the only implementation ships in this change), so the break is contained to the interface
101
+ itself: `wrap(invocation)` now receives the invocation verbatim and returns the invocation the
102
+ inner executor should run, whose `cmd`/`args` ARE the wrapped argv. Bypass behaviour is unchanged
103
+ (audit-only, `cmd`-only predicate, loud event). Consumers who implemented `BinarySandbox` against
104
+ the old shape must drop the `command` field handling and return `cmd`/`args` instead — see
105
+ [the media executor docs](/batteries/sandbox/media-executor).
106
+
107
+ ### Fixed
108
+
109
+ - **`@nhtio/adk/batteries/media/engines/execa_executor` — disabled timeouts no longer kill
110
+ immediately.** Executor-owned deadlines now preserve execa 9's `timeout: 0` no-timeout
111
+ semantics; `Infinity` also means no deadline. Finite values above Node's 2,147,483,647 ms timer
112
+ limit likewise disable the deadline rather than being overflow-clamped to 1 ms and terminating
113
+ the process immediately. Negative values and `NaN` reject before spawn, matching execa 9's
114
+ validation behavior.
115
+ - **`@nhtio/adk/batteries/media/engines/execa_executor` — the `SIGKILL` escalation deadline is now
116
+ measured on a MONOTONIC clock, and a deadline timer that fires early RE-ARMS instead of dropping
117
+ out.** The escalation stored `deadline = Date.now() + delay` (wall clock) while arming
118
+ `setTimeout(check, delay)` (monotonic), and `check()` returned without re-arming whenever
119
+ `Date.now() < deadline`. Two reachable cases made that permanent: Node's timers can fire about
120
+ 1ms early, and a backward NTP step puts `Date.now()` behind the arm-time wall clock for as long
121
+ as the step lasts. Either way the deadline timer silently died. Before settlement nothing else
122
+ drove `check()`, so a `detached: true` group whose grandchild ignored the first signal and held
123
+ the stdout pipe never got its `SIGKILL` — execa cannot settle until the pipes close, so `exec()`
124
+ HUNG instead of escalating. The deadline is now
125
+ `performance.now()`-based and never touches `Date.now()`; a `check()` that finds the deadline not
126
+ yet due clears the previous deadline timer and re-arms for the remaining monotonic milliseconds
127
+ (unref'd), so the deadline can never be left unwatched while the escalation is `armed`. The
128
+ deadline is fixed once at `arm()` and never re-based; escalation timers are cancelled on return
129
+ in either detached mode, and every timer is unref'd and fully cleared on cancel/fire.
130
+ - **`@nhtio/adk/batteries/sandbox` — `sandboxedExecutor` no longer mis-executes wrapped commands**
131
+ (closes issue #37, closes issue #20). This is the runtime face of the `BinarySandbox` contract
132
+ change above: `inner.exec({ ...wrapped, cmd: wrapped.command })` used the sandbox's fully-quoted
133
+ shell string as argv[0] — so `bash -c "sh -c 'printf hello'"` looked for an executable literally
134
+ named `sh -c 'printf hello'` (exit 127) — while the caller's original args were appended a second
135
+ time behind it. The adapter now runs the wrapped invocation the `BinarySandbox` returns as-is: the
136
+ wrapped `cmd`/`args` are the complete argv, `quoteShellArgs` is no longer called in the adapter
137
+ itself (quoting belongs to whichever wrapper is in use), and the original args are never re-appended.
138
+ A regression suite pins the passthrough: the wrapper receives the invocation verbatim, the inner
139
+ executor receives exactly `cmd`/`args` back, and bypass skips wrapping unchanged.
140
+
18
141
  ## 2026-10-03
19
142
 
20
143
  ### Fixed
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.cjs","names":[],"sources":["../../../src/batteries/media/contracts.ts"],"sourcesContent":["/**\n * Generic engine contracts for the media pipeline battery — the seams every implementation\n * (bundled or BYO) plugs into.\n *\n * @module @nhtio/adk/batteries/media/contracts\n *\n * @remarks\n * Engines are seams, not policies. An engine is a self-declaring capability provider: it\n * states exactly which transforms it supports — {@link ConvertCapability} edges (input MIME\n * patterns to output format tokens), {@link MutateCapability} groups (same-format content\n * transforms), and {@link EditCapability} groups (structural document operations) — and the\n * pipeline dispatches against those declarations. There are only three capability shapes\n * because there are only three things a media engine ever does: change the format, change the\n * content, or restructure the document. OCR is a convert (image to text). Transcription is a\n * convert (PCM to text). Decoding audio is a convert (container to PCM). Generating a blank\n * file is a convert (from {@link EMPTY_MIME} — the source format happens to be nothing).\n * Resizing is a mutate. Inserting a worksheet row is an edit. A new capability is a new edge\n * in the data, never a new contract.\n *\n * Engines are supplied to `createMediaPipeline` as a flat ordered array and resolved eagerly\n * at construction (declarations drive verb narrowing, so they must be known up front).\n * Bundled engines stay cheap to resolve: their heavy peer dependencies load lazily inside\n * the capability methods, on first actual use.\n *\n * All contracts are duck-typed: validation guards check structure, not class identity, so a\n * consumer can implement an interface from scratch or adapt an existing client. Contracts are\n * enforced at runtime — construction validates every engine and every declared capability and\n * throws `E_INVALID_MEDIA_PIPELINE_CONFIG` naming the offending index when a value fails.\n *\n * Two further contracts exist so that even \"run a binary\" and \"give a binary a file\" are\n * movable seams rather than Node assumptions:\n *\n * - {@link BinaryExecutor} — how an invocation runs. The bundled `execa_executor` wraps execa;\n * a browser/remote/sandbox executor satisfies the same contract.\n * - {@link ScratchWorkspace} — bytes ⇄ executor-visible paths. A sibling of `ByteStore`, NOT a\n * `ByteStore`: byte stores promise in-process readers, while binaries are foreign processes\n * that need real paths. The bundled `fs_workspace` uses `node:fs/promises` via an async\n * resolver; any implementation whose paths the chosen executor can see is valid — that\n * compatibility is the consumer's composition decision.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\n\n// ── shared helper shapes ─────────────────────────────────────────────────────\n\n/**\n * A value-or-resolver: the canonical way to supply an engine. Resolvers may be sync or async\n * (dynamic import) and may resolve to the value directly or a `{ default: value }` module\n * namespace. Engine resolvers run eagerly at pipeline construction — the engine module itself\n * is cheap; heavy peer dependencies load lazily inside capability methods.\n */\nexport type EngineResolver<T = MediaEngine> =\n | T\n | (() => T | { default: T } | Promise<T | { default: T }>)\n\n/** Common result shape for engines that transform bytes to bytes. */\nexport interface EngineBytesResult {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type. */\n mimeType: string\n}\n\n// ── process execution + scratch filesystem ──────────────────────────────────\n\n/** A single binary invocation handed to a {@link BinaryExecutor}. */\nexport interface BinaryInvocation {\n /** The command to run (an absolute path or a name the executor can resolve). */\n cmd: string\n /** Arguments, exec-style (no shell interpolation). */\n args: string[]\n /** Wall-clock timeout in milliseconds. */\n timeoutMs?: number\n /** Abort signal to cancel the invocation. */\n signal?: AbortSignal\n}\n\n/** The settled result of a {@link BinaryExecutor.exec} call. */\nexport interface BinaryExecResult {\n /** The process exit code (or -1 when the process failed to start). */\n exitCode: number\n /** Captured standard output. */\n stdout: string\n /** Captured standard error. */\n stderr: string\n /** `true` when the invocation failed (non-zero exit, spawn failure, timeout, abort). */\n failed: boolean\n}\n\n/**\n * Runs a binary invocation to completion. How and where it runs — local child process, remote\n * runner, sandbox, container, a browser-side WASI shim — is the implementation's business.\n */\nexport interface BinaryExecutor {\n /**\n * Run one invocation to completion and report the result. Implementations must not throw on\n * non-zero exits — report via `failed`/`exitCode` so callers map failures to readable errors.\n *\n * @param invocation - The command, args, and limits to run.\n * @returns The settled result.\n */\n exec(invocation: BinaryInvocation): Promise<BinaryExecResult>\n}\n\n/**\n * Bytes ⇄ executor-visible paths. The seam that lets binary-backed engines exchange files\n * with the process (or remote runner) that executes them.\n */\nexport interface ScratchWorkspace {\n /**\n * Write `bytes` into the workspace under `filename` and return the absolute path the\n * paired executor can open.\n *\n * @param bytes - The content to materialize.\n * @param filename - The basename to use (extension matters to format-sniffing binaries).\n * @returns The absolute path.\n */\n materialize(bytes: Uint8Array, filename: string): Promise<string>\n /**\n * Read a file the executor produced inside the workspace.\n *\n * @param path - The absolute path to read.\n * @returns The file bytes.\n */\n read(path: string): Promise<Uint8Array>\n /** The workspace root directory, for `--outdir`-style binary arguments. */\n dir(): string\n /** List the files currently in the workspace root (basenames). */\n list(): Promise<string[]>\n /** Remove the workspace and everything in it. Engines call this in `finally`. */\n dispose(): Promise<void>\n}\n\n/**\n * A factory for per-execution scratch workspaces. Engines mint one workspace per invocation\n * so concurrent executions never share a directory.\n */\nexport type ScratchWorkspaceFactory = () => ScratchWorkspace | Promise<ScratchWorkspace>\n\n// ── the format vocabulary ────────────────────────────────────────────────────\n\n/**\n * An input-matching pattern: an exact MIME type (`application/pdf`), a family wildcard\n * (`image/*`), or a virtual MIME such as {@link PCM_MIME}.\n */\nexport type MimePattern = string\n\n/**\n * The virtual MIME type for decoded mono PCM audio — the intermediate between an audio\n * container and a transcription. Bytes are little-endian Float32 samples in `[-1, 1]`;\n * a {@link ConvertOutput} carrying PCM must set `meta.sampleRate` (Hz).\n */\nexport const PCM_MIME = 'audio/x-adk-pcm'\n\n/**\n * The virtual source MIME type for media generation — the single seam through which new media\n * comes into existence. An engine that can mint a blank/seed file declares\n * `converts: [{ from: [EMPTY_MIME], to: [...] }]` and receives a {@link ConvertRequest} with\n * zero bytes; the format token in `to` names what gets created.\n *\n * @remarks\n * Generating an .xlsx, a blank canvas, or a second of silence IS media generation — it is\n * *deterministic* generation (same inputs, same bytes). *Model-based semantic* generation\n * (diffusion, TTS) is the same edge with different machinery: a BYO engine declares\n * `from: [EMPTY_MIME]` and consumes a prompt from `request.options`. Both kinds ride one\n * declaration shape, which is exactly why this is a MIME and not a special API. `EMPTY_MIME`\n * can never become a conversion intermediate: no engine declares `to: 'empty'`, so the\n * pathfinder only ever sees it as a source.\n */\nexport const EMPTY_MIME = 'application/x-adk-empty'\n\n/**\n * Pack PCM samples into transport bytes for a {@link ConvertOutput}.\n *\n * @remarks\n * A `Float32Array` view over arbitrary `Uint8Array` bytes requires 4-byte alignment, which\n * sliced buffers do not guarantee — this helper (and {@link bytesToPcm}) copy-normalize so\n * neither side has to think about alignment.\n *\n * @param pcm - Mono PCM samples in `[-1, 1]`.\n * @returns The samples as little-endian Float32 bytes.\n */\nexport const pcmToBytes = (pcm: Float32Array): Uint8Array => {\n const copy = new Float32Array(pcm)\n return new Uint8Array(copy.buffer, 0, copy.byteLength)\n}\n\n/**\n * Read PCM samples back out of transport bytes.\n *\n * @param bytes - Little-endian Float32 bytes (as produced by {@link pcmToBytes}).\n * @returns The mono PCM samples.\n */\nexport const bytesToPcm = (bytes: Uint8Array): Float32Array => {\n const aligned = new Uint8Array(bytes.length)\n aligned.set(bytes)\n return new Float32Array(aligned.buffer, 0, Math.floor(bytes.length / 4))\n}\n\n// ── convert options (typed, augmentable) ─────────────────────────────────────\n\n/** Options understood by OCR-flavored converts (`image/*` → `txt`/`hocr`/`json`). */\nexport interface OcrConvertOptions {\n /** Recognition language hints (e.g. `['eng','deu']`). */\n languages?: readonly string[]\n}\n\n/** Options understood by transcription-flavored converts ({@link PCM_MIME} → `txt`/`srt`/`vtt`/`json`). */\nexport interface AsrConvertOptions {\n /** Source-language hint (BCP-47-ish). */\n lang?: string\n /** Translate the transcription to English. */\n translate?: boolean\n}\n\n/** Options understood by embedded-image extraction converts (`application/pdf` → `images`). */\nexport interface ImagesConvertOptions {\n /**\n * Preferred output encoding token (`jpg`, `png`, …). An extractor that can emit it natively\n * should; outputs in other encodings are re-encoded downstream by the requesting step.\n */\n format?: string\n}\n\n/**\n * The options bag carried by a {@link ConvertRequest} — one typed, augmentable interface\n * merging every documented convention.\n *\n * @remarks\n * Consumers add their own keys via declaration merging against this module:\n *\n * ```ts\n * declare module '@nhtio/adk/batteries/media/contracts' {\n * interface ConvertOptions {\n * watermark?: { text: string }\n * }\n * }\n * ```\n *\n * Typo'd keys become excess-property compile errors at literal call sites; the runtime stays\n * open — engines must ignore keys they don't understand (multi-hop conversion forwards one\n * bag to every hop). The namespace is flat and globally merged, so BYO keys should be named\n * to avoid collisions (prefix by engine where ambiguous).\n */\nexport interface ConvertOptions\n extends OcrConvertOptions, AsrConvertOptions, ImagesConvertOptions {}\n\n// ── the three capabilities ───────────────────────────────────────────────────\n\n/** A format-changing request handed to a {@link ConvertCapability}. */\nexport interface ConvertRequest {\n /** The input content bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The input filename (extension informs format sniffing). */\n filename: string\n /** The target format token (`pdf`, `docx`, `txt`, `pcm`, `images`, …). */\n to: string\n /** Capability-specific options — see {@link ConvertOptions}. */\n options?: ConvertOptions\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** One output of a convert — most converts yield exactly one; `images` yields many. */\nexport interface ConvertOutput {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type (honest — native encoding, no silent re-encode). */\n mimeType: string\n /** Output metadata (e.g. `{ sampleRate: 44100 }` on {@link PCM_MIME} outputs). */\n meta?: Record<string, unknown>\n}\n\n/** The settled result of a convert. */\nexport interface ConvertResult {\n /** The outputs, in source order. */\n outputs: readonly ConvertOutput[]\n}\n\n/**\n * One uniform block of an engine's conversion matrix: every format token in `to` is\n * producible from every input matching `from`.\n *\n * @remarks\n * Declarations are plain data — the registry reads them without calling engine code. An\n * input-dependent matrix (LibreOffice: docx→pdf yes, docx→xlsx no, ods→xlsx yes) is expressed\n * as several capability groups, each a uniform from×to block.\n */\nexport interface ConvertCapability {\n /** Input patterns this block accepts. */\n from: readonly MimePattern[]\n /** Format tokens producible from every `from` member. */\n to: readonly string[]\n /**\n * Perform the conversion.\n *\n * @param request - The input bytes, target token, and options.\n * @returns The conversion outputs.\n */\n convert(request: ConvertRequest): Promise<ConvertResult>\n}\n\n/**\n * A same-format content transform handed to a {@link MutateCapability} — the fused image\n * request: adjacent `image.*` steps fold into ONE request so a resize→rotate→format chain\n * costs a single decode/encode.\n */\nexport interface MutateRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** Resize, when requested. */\n resize?: {\n width?: number\n height?: number\n fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside'\n }\n /** Clockwise rotation in degrees. */\n rotate?: 90 | 180 | 270\n /** Flip axes. */\n flip?: { horizontal?: boolean; vertical?: boolean }\n /** Remove EXIF/ICC metadata. */\n stripMetadata?: boolean\n /** Vector annotation primitives, rendered over the image. */\n annotate?: readonly ImageAnnotation[]\n /** Re-encode target, when requested (rides the same fused call). */\n format?: { to: string; quality?: number }\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** A same-format content-transform capability group. */\n/** A primitive rendered by the image annotation operation. */\nexport type ImageAnnotation =\n | {\n type: 'rect'\n x: number\n y: number\n width: number\n height: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'line' | 'arrow'\n x1: number\n y1: number\n x2: number\n y2: number\n color?: string\n strokeWidth?: number\n }\n | {\n type: 'ellipse'\n cx: number\n cy: number\n rx: number\n ry: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'text'\n x: number\n y: number\n text: string\n color?: string\n size?: number\n font?: string\n }\n\n/** A same-format content-transform capability group. */\nexport interface MutateCapability {\n /** Input patterns this block mutates. */\n over: readonly MimePattern[]\n /** Content operations supported (`resize`, `rotate`, `flip`, `strip_metadata`, `annotate`). */\n ops: readonly string[]\n /** Format tokens reachable via `request.format` in the same fused call. */\n encodes: readonly string[]\n /**\n * Apply the fused transform.\n *\n * @param request - The folded operations and input bytes.\n * @returns The transformed bytes.\n */\n mutate(request: MutateRequest): Promise<EngineBytesResult>\n}\n\n/**\n * A structural document operation handed to an {@link EditCapability}: one named op with its\n * verb-table args, applied to in-memory bytes. Unlike the fused {@link MutateRequest} (which\n * folds adjacent image transforms into one decode/encode), edits run one op per request — a\n * worksheet splice is not a pixel pass and gains nothing from fusion.\n */\nexport interface EditRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The operation name, namespaced as in the verb table (`sheet.update_cells`, …). */\n op: string\n /** The op's arguments, in the verb table's declared shapes. */\n args: Record<string, unknown>\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** Counts an edit reports back for result summaries. */\nexport interface EditSummary {\n /** Items added (rows, columns, sheets…). */\n added?: number\n /** Items removed. */\n removed?: number\n /** Items modified. */\n modified?: number\n /** Non-fatal notes surfaced to the model. */\n warnings?: string[]\n}\n\n/** The settled result of an edit: the restructured bytes plus optional change counts. */\nexport interface EditResult extends EngineBytesResult {\n /** Change counts for result summaries. */\n summary?: EditSummary\n}\n\n/**\n * A structural document-editing capability group: every op in `ops` is applicable to every\n * input matching `over`.\n *\n * @remarks\n * Two engines may declare the same ops over the same patterns with different fidelity — e.g.\n * an ExcelJS-backed editor preserves styling while a SheetJS CE-backed one strips it. The\n * registry does not rank fidelity; supply order (or selection middleware) decides, which makes\n * the trade-off the consumer's visible composition decision.\n */\nexport interface EditCapability {\n /** Input patterns this block edits. */\n over: readonly MimePattern[]\n /** Operation names supported (`sheet.update_cells`, `sheet.add_rows`, …). */\n ops: readonly string[]\n /**\n * Apply one structural operation.\n *\n * @param request - The op, its args, and the input bytes.\n * @returns The restructured bytes plus optional change counts.\n */\n edit(request: EditRequest): Promise<EditResult>\n}\n\n/**\n * A self-declaring media engine: an id for error messages plus the capabilities it provides.\n * At least one capability entry is required.\n */\nexport interface MediaEngine {\n /** Stable identifier used in config and dispatch error messages (`jimp`, `soffice`, …). */\n readonly id: string\n /** Format-changing capability groups. */\n readonly converts?: readonly ConvertCapability[]\n /** Same-format content-transform capability groups. */\n readonly mutates?: readonly MutateCapability[]\n /** Structural document-editing capability groups. */\n readonly edits?: readonly EditCapability[]\n}\n\n// ── duck-typed guards ────────────────────────────────────────────────────────\n\nconst hasFns = (value: unknown, names: readonly string[]): boolean =>\n isObject(value) && names.every((n) => typeof (value as Record<string, unknown>)[n] === 'function')\n\nconst isStringArray = (value: unknown): boolean =>\n Array.isArray(value) && value.every((v) => typeof v === 'string')\n\n/** `true` when `value` structurally implements {@link BinaryExecutor}. */\nexport const implementsBinaryExecutor = (value: unknown): value is BinaryExecutor =>\n hasFns(value, ['exec'])\n\n/** `true` when `value` structurally implements {@link ScratchWorkspace}. */\nexport const implementsScratchWorkspace = (value: unknown): value is ScratchWorkspace =>\n hasFns(value, ['materialize', 'read', 'dir', 'list', 'dispose'])\n\n/** `true` when `value` structurally implements {@link ConvertCapability}. */\nexport const implementsConvertCapability = (value: unknown): value is ConvertCapability =>\n hasFns(value, ['convert']) &&\n isStringArray((value as ConvertCapability).from) &&\n isStringArray((value as ConvertCapability).to)\n\n/** `true` when `value` structurally implements {@link MutateCapability}. */\nexport const implementsMutateCapability = (value: unknown): value is MutateCapability =>\n hasFns(value, ['mutate']) &&\n isStringArray((value as MutateCapability).over) &&\n isStringArray((value as MutateCapability).ops) &&\n isStringArray((value as MutateCapability).encodes)\n\n/** `true` when `value` structurally implements {@link EditCapability}. */\nexport const implementsEditCapability = (value: unknown): value is EditCapability =>\n hasFns(value, ['edit']) &&\n isStringArray((value as EditCapability).over) &&\n isStringArray((value as EditCapability).ops)\n\n/**\n * `true` when `value` structurally implements {@link MediaEngine}: a string id plus at least\n * one well-formed capability entry. Every declared entry must pass its capability guard.\n */\nexport const implementsMediaEngine = (value: unknown): value is MediaEngine => {\n if (!isObject(value)) return false\n const engine = value as unknown as MediaEngine\n if (typeof engine.id !== 'string' || engine.id.length === 0) return false\n const converts = engine.converts\n const mutates = engine.mutates\n const edits = engine.edits\n if (converts !== undefined) {\n if (!Array.isArray(converts) || !converts.every(implementsConvertCapability)) return false\n }\n if (mutates !== undefined) {\n if (!Array.isArray(mutates) || !mutates.every(implementsMutateCapability)) return false\n }\n if (edits !== undefined) {\n if (!Array.isArray(edits) || !edits.every(implementsEditCapability)) return false\n }\n const convertCount = Array.isArray(converts) ? converts.length : 0\n const mutateCount = Array.isArray(mutates) ? mutates.length : 0\n const editCount = Array.isArray(edits) ? edits.length : 0\n return convertCount + mutateCount + editCount > 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,IAAa,WAAW;;;;;;;;;;;;;;;;AAiBxB,IAAa,aAAa;;;;;;;;;;;;AAa1B,IAAa,cAAc,QAAkC;CAC3D,MAAM,OAAO,IAAI,aAAa,GAAG;CACjC,OAAO,IAAI,WAAW,KAAK,QAAQ,GAAG,KAAK,UAAU;AACvD;;;;;;;AAQA,IAAa,cAAc,UAAoC;CAC7D,MAAM,UAAU,IAAI,WAAW,MAAM,MAAM;CAC3C,QAAQ,IAAI,KAAK;CACjB,OAAO,IAAI,aAAa,QAAQ,QAAQ,GAAG,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;AACzE;AAkRA,IAAM,UAAU,OAAgB,UAC9B,eAAA,SAAS,KAAK,KAAK,MAAM,OAAO,MAAM,OAAQ,MAAkC,OAAO,UAAU;AAEnG,IAAM,iBAAiB,UACrB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;;AAGlE,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC;;AAGxB,IAAa,8BAA8B,UACzC,OAAO,OAAO;CAAC;CAAe;CAAQ;CAAO;CAAQ;AAAS,CAAC;;AAGjE,IAAa,+BAA+B,UAC1C,OAAO,OAAO,CAAC,SAAS,CAAC,KACzB,cAAe,MAA4B,IAAI,KAC/C,cAAe,MAA4B,EAAE;;AAG/C,IAAa,8BAA8B,UACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,KACxB,cAAe,MAA2B,IAAI,KAC9C,cAAe,MAA2B,GAAG,KAC7C,cAAe,MAA2B,OAAO;;AAGnD,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC,KACtB,cAAe,MAAyB,IAAI,KAC5C,cAAe,MAAyB,GAAG;;;;;AAM7C,IAAa,yBAAyB,UAAyC;CAC7E,IAAI,CAAC,eAAA,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,OAAO,YAAY,OAAO,GAAG,WAAW,GAAG,OAAO;CACpE,MAAM,WAAW,OAAO;CACxB,MAAM,UAAU,OAAO;CACvB,MAAM,QAAQ,OAAO;CACrB,IAAI,aAAa,KAAA;MACX,CAAC,MAAM,QAAQ,QAAQ,KAAK,CAAC,SAAS,MAAM,2BAA2B,GAAG,OAAO;CAAA;CAEvF,IAAI,YAAY,KAAA;MACV,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,MAAM,0BAA0B,GAAG,OAAO;CAAA;CAEpF,IAAI,UAAU,KAAA;MACR,CAAC,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,MAAM,wBAAwB,GAAG,OAAO;CAAA;CAE9E,MAAM,eAAe,MAAM,QAAQ,QAAQ,IAAI,SAAS,SAAS;CACjE,MAAM,cAAc,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS;CAC9D,MAAM,YAAY,MAAM,QAAQ,KAAK,IAAI,MAAM,SAAS;CACxD,OAAO,eAAe,cAAc,YAAY;AAClD"}
1
+ {"version":3,"file":"contracts.cjs","names":[],"sources":["../../../src/batteries/media/contracts.ts"],"sourcesContent":["/**\n * Generic engine contracts for the media pipeline battery — the seams every implementation\n * (bundled or BYO) plugs into.\n *\n * @module @nhtio/adk/batteries/media/contracts\n *\n * @remarks\n * Engines are seams, not policies. An engine is a self-declaring capability provider: it\n * states exactly which transforms it supports — {@link ConvertCapability} edges (input MIME\n * patterns to output format tokens), {@link MutateCapability} groups (same-format content\n * transforms), and {@link EditCapability} groups (structural document operations) — and the\n * pipeline dispatches against those declarations. There are only three capability shapes\n * because there are only three things a media engine ever does: change the format, change the\n * content, or restructure the document. OCR is a convert (image to text). Transcription is a\n * convert (PCM to text). Decoding audio is a convert (container to PCM). Generating a blank\n * file is a convert (from {@link EMPTY_MIME} — the source format happens to be nothing).\n * Resizing is a mutate. Inserting a worksheet row is an edit. A new capability is a new edge\n * in the data, never a new contract.\n *\n * Engines are supplied to `createMediaPipeline` as a flat ordered array and resolved eagerly\n * at construction (declarations drive verb narrowing, so they must be known up front).\n * Bundled engines stay cheap to resolve: their heavy peer dependencies load lazily inside\n * the capability methods, on first actual use.\n *\n * All contracts are duck-typed: validation guards check structure, not class identity, so a\n * consumer can implement an interface from scratch or adapt an existing client. Contracts are\n * enforced at runtime — construction validates every engine and every declared capability and\n * throws `E_INVALID_MEDIA_PIPELINE_CONFIG` naming the offending index when a value fails.\n *\n * Two further contracts exist so that even \"run a binary\" and \"give a binary a file\" are\n * movable seams rather than Node assumptions:\n *\n * - {@link BinaryExecutor} — how an invocation runs. The bundled `execa_executor` wraps execa;\n * a browser/remote/sandbox executor satisfies the same contract.\n * - {@link ScratchWorkspace} — bytes ⇄ executor-visible paths. A sibling of `ByteStore`, NOT a\n * `ByteStore`: byte stores promise in-process readers, while binaries are foreign processes\n * that need real paths. The bundled `fs_workspace` uses `node:fs/promises` via an async\n * resolver; any implementation whose paths the chosen executor can see is valid — that\n * compatibility is the consumer's composition decision.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\n\n// ── shared helper shapes ─────────────────────────────────────────────────────\n\n/**\n * A value-or-resolver: the canonical way to supply an engine. Resolvers may be sync or async\n * (dynamic import) and may resolve to the value directly or a `{ default: value }` module\n * namespace. Engine resolvers run eagerly at pipeline construction — the engine module itself\n * is cheap; heavy peer dependencies load lazily inside capability methods.\n */\nexport type EngineResolver<T = MediaEngine> =\n | T\n | (() => T | { default: T } | Promise<T | { default: T }>)\n\n/** Common result shape for engines that transform bytes to bytes. */\nexport interface EngineBytesResult {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type. */\n mimeType: string\n}\n\n// ── process execution + scratch filesystem ──────────────────────────────────\n\n/** A single binary invocation handed to a {@link BinaryExecutor}. */\nexport interface BinaryInvocation {\n /** The command to run (an absolute path or a name the executor can resolve). */\n cmd: string\n /** Arguments, exec-style (no shell interpolation). */\n args: string[]\n /**\n * Working directory for the process. Omitted means the executor's own default.\n *\n * @remarks\n * Exec-style, like `args`: the executor passes it to the process launcher and never interprets\n * it as shell text. A sandbox wrapper that rewrites the invocation carries the caller's `cwd`\n * through unchanged — the profile it generates is what decides whether that directory is\n * reachable at all.\n */\n cwd?: string\n /**\n * The caller's own EXPLICIT environment values, applied last.\n *\n * @remarks\n * The same semantics as `SandboxPolicyEnforcer.run`'s `env`: these are the caller's own values —\n * not a host-inheritance control — and a sandbox decides host inheritance separately through its\n * allow-list. They are applied last, so they may add names or override inherited ones, and an\n * adapter must not let them (or anything else) pull host variables beyond its allow-list into the\n * child. They do not replace the executor's environment — unless the invocation clears\n * {@link BinaryInvocation.extendEnv}, in which case this object IS the whole environment.\n */\n env?: Record<string, string>\n /**\n * Whether {@link BinaryInvocation.env} extends the executor's own environment (`true`, the\n * default) or replaces it entirely (`false`).\n *\n * @remarks\n * This field exists for sandboxes. A sandbox decides what a child may inherit from the host\n * (usually an allow-list, on the explicit grounds that anything inherited is readable back into\n * the model's context by running `env`), so it must be able to say \"this is the entire\n * environment\". An executor that always merged its own ambient environment back in would\n * silently defeat that allow-list — execa's `extendEnv: true` default does exactly this — which\n * is why the SRT wrapper sets it to `false` and the bundled executor maps it to\n * `extendEnv: false`. Leave it unset for an ordinary, unsandboxed invocation.\n */\n extendEnv?: boolean\n /**\n * Wall-clock timeout in milliseconds.\n *\n * @remarks\n * `0`, `Infinity`, and finite values above 2,147,483,647 disable the deadline.\n * Negative values and `NaN` reject the invocation before spawning.\n */\n timeoutMs?: number\n /** Abort signal to cancel the invocation. */\n signal?: AbortSignal\n /**\n * The signal used to terminate the invocation when {@link BinaryInvocation.signal} aborts or\n * {@link BinaryInvocation.timeoutMs} elapses. `'SIGTERM'` by default.\n *\n * @remarks\n * Typed as `string` (not `NodeJS.Signals`) so that this contract stays browser-safe: it is a\n * plain signal NAME, and an executor that runs somewhere without POSIX signals decides what to\n * do with it. With the bundled executor's default `detached: true`, it signals the whole process\n * group; with `detached: false`, it signals only the direct child.\n */\n killSignal?: string\n /**\n * Milliseconds to wait after {@link BinaryInvocation.killSignal} before escalating to `SIGKILL`;\n * `false` and `Infinity` disable escalation and never send `SIGKILL`.\n *\n * @remarks\n * Settlement follows {@link BinaryInvocation.settleEscalation}: `'wait'` holds `exec()` until the\n * escalation completes, `'cancel'` stops escalation when `exec()` returns, and `'poll'` may send\n * `SIGKILL` after return. Omitted means the executor's default. Negative values and `NaN` reject\n * before spawning.\n */\n forceKillAfterDelay?: number | false\n /**\n * How escalation behaves when an abort or executor-owned timeout fires and the invocation settles\n * while escalation is armed. Defaults to `'wait'`. `'wait'` delays settlement until the target is\n * empty or SIGKILL is sent (nothing survives, at the cost of latency up to the escalation delay);\n * `'cancel'` returns fastest but descendants may survive; `'poll'` returns fastest and may kill\n * survivors later, with a narrow process-group reuse risk after return. A normal exit never waits\n * or polls. Applies only with finite escalation and a known pid; `detached: false` cancels at\n * settlement in every mode. Wait also has a narrow numeric PGID-reuse risk between probes,\n * bounded to before return. The value is a browser-safe string union.\n */\n settleEscalation?: 'wait' | 'cancel' | 'poll'\n}\n\n/** The settled result of a {@link BinaryExecutor.exec} call. */\nexport interface BinaryExecResult {\n /** The process exit code (or -1 when the process failed to start). */\n exitCode: number\n /** Captured standard output. */\n stdout: string\n /** Captured standard error. */\n stderr: string\n /** `true` when the invocation failed (non-zero exit, spawn failure, timeout, abort). */\n failed: boolean\n /**\n * The signal that terminated the process, when one did.\n *\n * @remarks\n * Omitted on a normal exit, so a consumer must treat absence as \"exited on its own\". An executor\n * that cannot surface it simply leaves it off.\n */\n signalCode?: string\n}\n\n/**\n * Runs a binary invocation to completion. How and where it runs — local child process, remote\n * runner, sandbox, container, a browser-side WASI shim — is the implementation's business.\n */\nexport interface BinaryExecutor {\n /**\n * Run one invocation to completion and report the result. Implementations must not throw on\n * non-zero exits — report via `failed`/`exitCode` so callers map failures to readable errors.\n *\n * @remarks\n * When `invocation.signal` aborts or `invocation.timeoutMs` elapses, an implementation MUST\n * terminate the process it started and settle, rather than leaving it running with this promise\n * pending. A binary that spawns children of its own is the caller's hazard: the bundled executor\n * spawns the child as its own process-group leader and signals the WHOLE group\n * ({@link BinaryInvocation.killSignal}, escalating to `SIGKILL` per\n * {@link BinaryInvocation.forceKillAfterDelay}) so a wrapper cannot outlive the invocation.\n *\n * @param invocation - The command, args, working directory, environment, and limits to run.\n * @returns The settled result.\n */\n exec(invocation: BinaryInvocation): Promise<BinaryExecResult>\n}\n\n/**\n * Bytes ⇄ executor-visible paths. The seam that lets binary-backed engines exchange files\n * with the process (or remote runner) that executes them.\n */\nexport interface ScratchWorkspace {\n /**\n * Write `bytes` into the workspace under `filename` and return the absolute path the\n * paired executor can open.\n *\n * @param bytes - The content to materialize.\n * @param filename - The basename to use (extension matters to format-sniffing binaries).\n * @returns The absolute path.\n */\n materialize(bytes: Uint8Array, filename: string): Promise<string>\n /**\n * Read a file the executor produced inside the workspace.\n *\n * @param path - The absolute path to read.\n * @returns The file bytes.\n */\n read(path: string): Promise<Uint8Array>\n /** The workspace root directory, for `--outdir`-style binary arguments. */\n dir(): string\n /** List the files currently in the workspace root (basenames). */\n list(): Promise<string[]>\n /** Remove the workspace and everything in it. Engines call this in `finally`. */\n dispose(): Promise<void>\n}\n\n/**\n * A factory for per-execution scratch workspaces. Engines mint one workspace per invocation\n * so concurrent executions never share a directory.\n */\nexport type ScratchWorkspaceFactory = () => ScratchWorkspace | Promise<ScratchWorkspace>\n\n// ── the format vocabulary ────────────────────────────────────────────────────\n\n/**\n * An input-matching pattern: an exact MIME type (`application/pdf`), a family wildcard\n * (`image/*`), or a virtual MIME such as {@link PCM_MIME}.\n */\nexport type MimePattern = string\n\n/**\n * The virtual MIME type for decoded mono PCM audio — the intermediate between an audio\n * container and a transcription. Bytes are little-endian Float32 samples in `[-1, 1]`;\n * a {@link ConvertOutput} carrying PCM must set `meta.sampleRate` (Hz).\n */\nexport const PCM_MIME = 'audio/x-adk-pcm'\n\n/**\n * The virtual source MIME type for media generation — the single seam through which new media\n * comes into existence. An engine that can mint a blank/seed file declares\n * `converts: [{ from: [EMPTY_MIME], to: [...] }]` and receives a {@link ConvertRequest} with\n * zero bytes; the format token in `to` names what gets created.\n *\n * @remarks\n * Generating an .xlsx, a blank canvas, or a second of silence IS media generation — it is\n * *deterministic* generation (same inputs, same bytes). *Model-based semantic* generation\n * (diffusion, TTS) is the same edge with different machinery: a BYO engine declares\n * `from: [EMPTY_MIME]` and consumes a prompt from `request.options`. Both kinds ride one\n * declaration shape, which is exactly why this is a MIME and not a special API. `EMPTY_MIME`\n * can never become a conversion intermediate: no engine declares `to: 'empty'`, so the\n * pathfinder only ever sees it as a source.\n */\nexport const EMPTY_MIME = 'application/x-adk-empty'\n\n/**\n * Pack PCM samples into transport bytes for a {@link ConvertOutput}.\n *\n * @remarks\n * A `Float32Array` view over arbitrary `Uint8Array` bytes requires 4-byte alignment, which\n * sliced buffers do not guarantee — this helper (and {@link bytesToPcm}) copy-normalize so\n * neither side has to think about alignment.\n *\n * @param pcm - Mono PCM samples in `[-1, 1]`.\n * @returns The samples as little-endian Float32 bytes.\n */\nexport const pcmToBytes = (pcm: Float32Array): Uint8Array => {\n const copy = new Float32Array(pcm)\n return new Uint8Array(copy.buffer, 0, copy.byteLength)\n}\n\n/**\n * Read PCM samples back out of transport bytes.\n *\n * @param bytes - Little-endian Float32 bytes (as produced by {@link pcmToBytes}).\n * @returns The mono PCM samples.\n */\nexport const bytesToPcm = (bytes: Uint8Array): Float32Array => {\n const aligned = new Uint8Array(bytes.length)\n aligned.set(bytes)\n return new Float32Array(aligned.buffer, 0, Math.floor(bytes.length / 4))\n}\n\n// ── convert options (typed, augmentable) ─────────────────────────────────────\n\n/** Options understood by OCR-flavored converts (`image/*` → `txt`/`hocr`/`json`). */\nexport interface OcrConvertOptions {\n /** Recognition language hints (e.g. `['eng','deu']`). */\n languages?: readonly string[]\n}\n\n/** Options understood by transcription-flavored converts ({@link PCM_MIME} → `txt`/`srt`/`vtt`/`json`). */\nexport interface AsrConvertOptions {\n /** Source-language hint (BCP-47-ish). */\n lang?: string\n /** Translate the transcription to English. */\n translate?: boolean\n}\n\n/** Options understood by embedded-image extraction converts (`application/pdf` → `images`). */\nexport interface ImagesConvertOptions {\n /**\n * Preferred output encoding token (`jpg`, `png`, …). An extractor that can emit it natively\n * should; outputs in other encodings are re-encoded downstream by the requesting step.\n */\n format?: string\n}\n\n/**\n * The options bag carried by a {@link ConvertRequest} — one typed, augmentable interface\n * merging every documented convention.\n *\n * @remarks\n * Consumers add their own keys via declaration merging against this module:\n *\n * ```ts\n * declare module '@nhtio/adk/batteries/media/contracts' {\n * interface ConvertOptions {\n * watermark?: { text: string }\n * }\n * }\n * ```\n *\n * Typo'd keys become excess-property compile errors at literal call sites; the runtime stays\n * open — engines must ignore keys they don't understand (multi-hop conversion forwards one\n * bag to every hop). The namespace is flat and globally merged, so BYO keys should be named\n * to avoid collisions (prefix by engine where ambiguous).\n */\nexport interface ConvertOptions\n extends OcrConvertOptions, AsrConvertOptions, ImagesConvertOptions {}\n\n// ── the three capabilities ───────────────────────────────────────────────────\n\n/** A format-changing request handed to a {@link ConvertCapability}. */\nexport interface ConvertRequest {\n /** The input content bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The input filename (extension informs format sniffing). */\n filename: string\n /** The target format token (`pdf`, `docx`, `txt`, `pcm`, `images`, …). */\n to: string\n /** Capability-specific options — see {@link ConvertOptions}. */\n options?: ConvertOptions\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** One output of a convert — most converts yield exactly one; `images` yields many. */\nexport interface ConvertOutput {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type (honest — native encoding, no silent re-encode). */\n mimeType: string\n /** Output metadata (e.g. `{ sampleRate: 44100 }` on {@link PCM_MIME} outputs). */\n meta?: Record<string, unknown>\n}\n\n/** The settled result of a convert. */\nexport interface ConvertResult {\n /** The outputs, in source order. */\n outputs: readonly ConvertOutput[]\n}\n\n/**\n * One uniform block of an engine's conversion matrix: every format token in `to` is\n * producible from every input matching `from`.\n *\n * @remarks\n * Declarations are plain data — the registry reads them without calling engine code. An\n * input-dependent matrix (LibreOffice: docx→pdf yes, docx→xlsx no, ods→xlsx yes) is expressed\n * as several capability groups, each a uniform from×to block.\n */\nexport interface ConvertCapability {\n /** Input patterns this block accepts. */\n from: readonly MimePattern[]\n /** Format tokens producible from every `from` member. */\n to: readonly string[]\n /**\n * Perform the conversion.\n *\n * @param request - The input bytes, target token, and options.\n * @returns The conversion outputs.\n */\n convert(request: ConvertRequest): Promise<ConvertResult>\n}\n\n/**\n * A same-format content transform handed to a {@link MutateCapability} — the fused image\n * request: adjacent `image.*` steps fold into ONE request so a resize→rotate→format chain\n * costs a single decode/encode.\n */\nexport interface MutateRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** Resize, when requested. */\n resize?: {\n width?: number\n height?: number\n fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside'\n }\n /** Clockwise rotation in degrees. */\n rotate?: 90 | 180 | 270\n /** Flip axes. */\n flip?: { horizontal?: boolean; vertical?: boolean }\n /** Remove EXIF/ICC metadata. */\n stripMetadata?: boolean\n /** Vector annotation primitives, rendered over the image. */\n annotate?: readonly ImageAnnotation[]\n /** Re-encode target, when requested (rides the same fused call). */\n format?: { to: string; quality?: number }\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** A same-format content-transform capability group. */\n/** A primitive rendered by the image annotation operation. */\nexport type ImageAnnotation =\n | {\n type: 'rect'\n x: number\n y: number\n width: number\n height: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'line' | 'arrow'\n x1: number\n y1: number\n x2: number\n y2: number\n color?: string\n strokeWidth?: number\n }\n | {\n type: 'ellipse'\n cx: number\n cy: number\n rx: number\n ry: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'text'\n x: number\n y: number\n text: string\n color?: string\n size?: number\n font?: string\n }\n\n/** A same-format content-transform capability group. */\nexport interface MutateCapability {\n /** Input patterns this block mutates. */\n over: readonly MimePattern[]\n /** Content operations supported (`resize`, `rotate`, `flip`, `strip_metadata`, `annotate`). */\n ops: readonly string[]\n /** Format tokens reachable via `request.format` in the same fused call. */\n encodes: readonly string[]\n /**\n * Apply the fused transform.\n *\n * @param request - The folded operations and input bytes.\n * @returns The transformed bytes.\n */\n mutate(request: MutateRequest): Promise<EngineBytesResult>\n}\n\n/**\n * A structural document operation handed to an {@link EditCapability}: one named op with its\n * verb-table args, applied to in-memory bytes. Unlike the fused {@link MutateRequest} (which\n * folds adjacent image transforms into one decode/encode), edits run one op per request — a\n * worksheet splice is not a pixel pass and gains nothing from fusion.\n */\nexport interface EditRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The operation name, namespaced as in the verb table (`sheet.update_cells`, …). */\n op: string\n /** The op's arguments, in the verb table's declared shapes. */\n args: Record<string, unknown>\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** Counts an edit reports back for result summaries. */\nexport interface EditSummary {\n /** Items added (rows, columns, sheets…). */\n added?: number\n /** Items removed. */\n removed?: number\n /** Items modified. */\n modified?: number\n /** Non-fatal notes surfaced to the model. */\n warnings?: string[]\n}\n\n/** The settled result of an edit: the restructured bytes plus optional change counts. */\nexport interface EditResult extends EngineBytesResult {\n /** Change counts for result summaries. */\n summary?: EditSummary\n}\n\n/**\n * A structural document-editing capability group: every op in `ops` is applicable to every\n * input matching `over`.\n *\n * @remarks\n * Two engines may declare the same ops over the same patterns with different fidelity — e.g.\n * an ExcelJS-backed editor preserves styling while a SheetJS CE-backed one strips it. The\n * registry does not rank fidelity; supply order (or selection middleware) decides, which makes\n * the trade-off the consumer's visible composition decision.\n */\nexport interface EditCapability {\n /** Input patterns this block edits. */\n over: readonly MimePattern[]\n /** Operation names supported (`sheet.update_cells`, `sheet.add_rows`, …). */\n ops: readonly string[]\n /**\n * Apply one structural operation.\n *\n * @param request - The op, its args, and the input bytes.\n * @returns The restructured bytes plus optional change counts.\n */\n edit(request: EditRequest): Promise<EditResult>\n}\n\n/**\n * A self-declaring media engine: an id for error messages plus the capabilities it provides.\n * At least one capability entry is required.\n */\nexport interface MediaEngine {\n /** Stable identifier used in config and dispatch error messages (`jimp`, `soffice`, …). */\n readonly id: string\n /** Format-changing capability groups. */\n readonly converts?: readonly ConvertCapability[]\n /** Same-format content-transform capability groups. */\n readonly mutates?: readonly MutateCapability[]\n /** Structural document-editing capability groups. */\n readonly edits?: readonly EditCapability[]\n}\n\n// ── duck-typed guards ────────────────────────────────────────────────────────\n\nconst hasFns = (value: unknown, names: readonly string[]): boolean =>\n isObject(value) && names.every((n) => typeof (value as Record<string, unknown>)[n] === 'function')\n\nconst isStringArray = (value: unknown): boolean =>\n Array.isArray(value) && value.every((v) => typeof v === 'string')\n\n/** `true` when `value` structurally implements {@link BinaryExecutor}. */\nexport const implementsBinaryExecutor = (value: unknown): value is BinaryExecutor =>\n hasFns(value, ['exec'])\n\n/** `true` when `value` structurally implements {@link ScratchWorkspace}. */\nexport const implementsScratchWorkspace = (value: unknown): value is ScratchWorkspace =>\n hasFns(value, ['materialize', 'read', 'dir', 'list', 'dispose'])\n\n/** `true` when `value` structurally implements {@link ConvertCapability}. */\nexport const implementsConvertCapability = (value: unknown): value is ConvertCapability =>\n hasFns(value, ['convert']) &&\n isStringArray((value as ConvertCapability).from) &&\n isStringArray((value as ConvertCapability).to)\n\n/** `true` when `value` structurally implements {@link MutateCapability}. */\nexport const implementsMutateCapability = (value: unknown): value is MutateCapability =>\n hasFns(value, ['mutate']) &&\n isStringArray((value as MutateCapability).over) &&\n isStringArray((value as MutateCapability).ops) &&\n isStringArray((value as MutateCapability).encodes)\n\n/** `true` when `value` structurally implements {@link EditCapability}. */\nexport const implementsEditCapability = (value: unknown): value is EditCapability =>\n hasFns(value, ['edit']) &&\n isStringArray((value as EditCapability).over) &&\n isStringArray((value as EditCapability).ops)\n\n/**\n * `true` when `value` structurally implements {@link MediaEngine}: a string id plus at least\n * one well-formed capability entry. Every declared entry must pass its capability guard.\n */\nexport const implementsMediaEngine = (value: unknown): value is MediaEngine => {\n if (!isObject(value)) return false\n const engine = value as unknown as MediaEngine\n if (typeof engine.id !== 'string' || engine.id.length === 0) return false\n const converts = engine.converts\n const mutates = engine.mutates\n const edits = engine.edits\n if (converts !== undefined) {\n if (!Array.isArray(converts) || !converts.every(implementsConvertCapability)) return false\n }\n if (mutates !== undefined) {\n if (!Array.isArray(mutates) || !mutates.every(implementsMutateCapability)) return false\n }\n if (edits !== undefined) {\n if (!Array.isArray(edits) || !edits.every(implementsEditCapability)) return false\n }\n const convertCount = Array.isArray(converts) ? converts.length : 0\n const mutateCount = Array.isArray(mutates) ? mutates.length : 0\n const editCount = Array.isArray(edits) ? edits.length : 0\n return convertCount + mutateCount + editCount > 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmPA,IAAa,WAAW;;;;;;;;;;;;;;;;AAiBxB,IAAa,aAAa;;;;;;;;;;;;AAa1B,IAAa,cAAc,QAAkC;CAC3D,MAAM,OAAO,IAAI,aAAa,GAAG;CACjC,OAAO,IAAI,WAAW,KAAK,QAAQ,GAAG,KAAK,UAAU;AACvD;;;;;;;AAQA,IAAa,cAAc,UAAoC;CAC7D,MAAM,UAAU,IAAI,WAAW,MAAM,MAAM;CAC3C,QAAQ,IAAI,KAAK;CACjB,OAAO,IAAI,aAAa,QAAQ,QAAQ,GAAG,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;AACzE;AAkRA,IAAM,UAAU,OAAgB,UAC9B,eAAA,SAAS,KAAK,KAAK,MAAM,OAAO,MAAM,OAAQ,MAAkC,OAAO,UAAU;AAEnG,IAAM,iBAAiB,UACrB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;;AAGlE,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC;;AAGxB,IAAa,8BAA8B,UACzC,OAAO,OAAO;CAAC;CAAe;CAAQ;CAAO;CAAQ;AAAS,CAAC;;AAGjE,IAAa,+BAA+B,UAC1C,OAAO,OAAO,CAAC,SAAS,CAAC,KACzB,cAAe,MAA4B,IAAI,KAC/C,cAAe,MAA4B,EAAE;;AAG/C,IAAa,8BAA8B,UACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,KACxB,cAAe,MAA2B,IAAI,KAC9C,cAAe,MAA2B,GAAG,KAC7C,cAAe,MAA2B,OAAO;;AAGnD,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC,KACtB,cAAe,MAAyB,IAAI,KAC5C,cAAe,MAAyB,GAAG;;;;;AAM7C,IAAa,yBAAyB,UAAyC;CAC7E,IAAI,CAAC,eAAA,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,OAAO,YAAY,OAAO,GAAG,WAAW,GAAG,OAAO;CACpE,MAAM,WAAW,OAAO;CACxB,MAAM,UAAU,OAAO;CACvB,MAAM,QAAQ,OAAO;CACrB,IAAI,aAAa,KAAA;MACX,CAAC,MAAM,QAAQ,QAAQ,KAAK,CAAC,SAAS,MAAM,2BAA2B,GAAG,OAAO;CAAA;CAEvF,IAAI,YAAY,KAAA;MACV,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,MAAM,0BAA0B,GAAG,OAAO;CAAA;CAEpF,IAAI,UAAU,KAAA;MACR,CAAC,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,MAAM,wBAAwB,GAAG,OAAO;CAAA;CAE9E,MAAM,eAAe,MAAM,QAAQ,QAAQ,IAAI,SAAS,SAAS;CACjE,MAAM,cAAc,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS;CAC9D,MAAM,YAAY,MAAM,QAAQ,KAAK,IAAI,MAAM,SAAS;CACxD,OAAO,eAAe,cAAc,YAAY;AAClD"}
@@ -62,10 +62,85 @@ export interface BinaryInvocation {
62
62
  cmd: string;
63
63
  /** Arguments, exec-style (no shell interpolation). */
64
64
  args: string[];
65
- /** Wall-clock timeout in milliseconds. */
65
+ /**
66
+ * Working directory for the process. Omitted means the executor's own default.
67
+ *
68
+ * @remarks
69
+ * Exec-style, like `args`: the executor passes it to the process launcher and never interprets
70
+ * it as shell text. A sandbox wrapper that rewrites the invocation carries the caller's `cwd`
71
+ * through unchanged — the profile it generates is what decides whether that directory is
72
+ * reachable at all.
73
+ */
74
+ cwd?: string;
75
+ /**
76
+ * The caller's own EXPLICIT environment values, applied last.
77
+ *
78
+ * @remarks
79
+ * The same semantics as `SandboxPolicyEnforcer.run`'s `env`: these are the caller's own values —
80
+ * not a host-inheritance control — and a sandbox decides host inheritance separately through its
81
+ * allow-list. They are applied last, so they may add names or override inherited ones, and an
82
+ * adapter must not let them (or anything else) pull host variables beyond its allow-list into the
83
+ * child. They do not replace the executor's environment — unless the invocation clears
84
+ * {@link BinaryInvocation.extendEnv}, in which case this object IS the whole environment.
85
+ */
86
+ env?: Record<string, string>;
87
+ /**
88
+ * Whether {@link BinaryInvocation.env} extends the executor's own environment (`true`, the
89
+ * default) or replaces it entirely (`false`).
90
+ *
91
+ * @remarks
92
+ * This field exists for sandboxes. A sandbox decides what a child may inherit from the host
93
+ * (usually an allow-list, on the explicit grounds that anything inherited is readable back into
94
+ * the model's context by running `env`), so it must be able to say "this is the entire
95
+ * environment". An executor that always merged its own ambient environment back in would
96
+ * silently defeat that allow-list — execa's `extendEnv: true` default does exactly this — which
97
+ * is why the SRT wrapper sets it to `false` and the bundled executor maps it to
98
+ * `extendEnv: false`. Leave it unset for an ordinary, unsandboxed invocation.
99
+ */
100
+ extendEnv?: boolean;
101
+ /**
102
+ * Wall-clock timeout in milliseconds.
103
+ *
104
+ * @remarks
105
+ * `0`, `Infinity`, and finite values above 2,147,483,647 disable the deadline.
106
+ * Negative values and `NaN` reject the invocation before spawning.
107
+ */
66
108
  timeoutMs?: number;
67
109
  /** Abort signal to cancel the invocation. */
68
110
  signal?: AbortSignal;
111
+ /**
112
+ * The signal used to terminate the invocation when {@link BinaryInvocation.signal} aborts or
113
+ * {@link BinaryInvocation.timeoutMs} elapses. `'SIGTERM'` by default.
114
+ *
115
+ * @remarks
116
+ * Typed as `string` (not `NodeJS.Signals`) so that this contract stays browser-safe: it is a
117
+ * plain signal NAME, and an executor that runs somewhere without POSIX signals decides what to
118
+ * do with it. With the bundled executor's default `detached: true`, it signals the whole process
119
+ * group; with `detached: false`, it signals only the direct child.
120
+ */
121
+ killSignal?: string;
122
+ /**
123
+ * Milliseconds to wait after {@link BinaryInvocation.killSignal} before escalating to `SIGKILL`;
124
+ * `false` and `Infinity` disable escalation and never send `SIGKILL`.
125
+ *
126
+ * @remarks
127
+ * Settlement follows {@link BinaryInvocation.settleEscalation}: `'wait'` holds `exec()` until the
128
+ * escalation completes, `'cancel'` stops escalation when `exec()` returns, and `'poll'` may send
129
+ * `SIGKILL` after return. Omitted means the executor's default. Negative values and `NaN` reject
130
+ * before spawning.
131
+ */
132
+ forceKillAfterDelay?: number | false;
133
+ /**
134
+ * How escalation behaves when an abort or executor-owned timeout fires and the invocation settles
135
+ * while escalation is armed. Defaults to `'wait'`. `'wait'` delays settlement until the target is
136
+ * empty or SIGKILL is sent (nothing survives, at the cost of latency up to the escalation delay);
137
+ * `'cancel'` returns fastest but descendants may survive; `'poll'` returns fastest and may kill
138
+ * survivors later, with a narrow process-group reuse risk after return. A normal exit never waits
139
+ * or polls. Applies only with finite escalation and a known pid; `detached: false` cancels at
140
+ * settlement in every mode. Wait also has a narrow numeric PGID-reuse risk between probes,
141
+ * bounded to before return. The value is a browser-safe string union.
142
+ */
143
+ settleEscalation?: 'wait' | 'cancel' | 'poll';
69
144
  }
70
145
  /** The settled result of a {@link BinaryExecutor.exec} call. */
71
146
  export interface BinaryExecResult {
@@ -77,6 +152,14 @@ export interface BinaryExecResult {
77
152
  stderr: string;
78
153
  /** `true` when the invocation failed (non-zero exit, spawn failure, timeout, abort). */
79
154
  failed: boolean;
155
+ /**
156
+ * The signal that terminated the process, when one did.
157
+ *
158
+ * @remarks
159
+ * Omitted on a normal exit, so a consumer must treat absence as "exited on its own". An executor
160
+ * that cannot surface it simply leaves it off.
161
+ */
162
+ signalCode?: string;
80
163
  }
81
164
  /**
82
165
  * Runs a binary invocation to completion. How and where it runs — local child process, remote
@@ -87,7 +170,15 @@ export interface BinaryExecutor {
87
170
  * Run one invocation to completion and report the result. Implementations must not throw on
88
171
  * non-zero exits — report via `failed`/`exitCode` so callers map failures to readable errors.
89
172
  *
90
- * @param invocation - The command, args, and limits to run.
173
+ * @remarks
174
+ * When `invocation.signal` aborts or `invocation.timeoutMs` elapses, an implementation MUST
175
+ * terminate the process it started and settle, rather than leaving it running with this promise
176
+ * pending. A binary that spawns children of its own is the caller's hazard: the bundled executor
177
+ * spawns the child as its own process-group leader and signals the WHOLE group
178
+ * ({@link BinaryInvocation.killSignal}, escalating to `SIGKILL` per
179
+ * {@link BinaryInvocation.forceKillAfterDelay}) so a wrapper cannot outlive the invocation.
180
+ *
181
+ * @param invocation - The command, args, working directory, environment, and limits to run.
91
182
  * @returns The settled result.
92
183
  */
93
184
  exec(invocation: BinaryInvocation): Promise<BinaryExecResult>;
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.mjs","names":[],"sources":["../../../src/batteries/media/contracts.ts"],"sourcesContent":["/**\n * Generic engine contracts for the media pipeline battery — the seams every implementation\n * (bundled or BYO) plugs into.\n *\n * @module @nhtio/adk/batteries/media/contracts\n *\n * @remarks\n * Engines are seams, not policies. An engine is a self-declaring capability provider: it\n * states exactly which transforms it supports — {@link ConvertCapability} edges (input MIME\n * patterns to output format tokens), {@link MutateCapability} groups (same-format content\n * transforms), and {@link EditCapability} groups (structural document operations) — and the\n * pipeline dispatches against those declarations. There are only three capability shapes\n * because there are only three things a media engine ever does: change the format, change the\n * content, or restructure the document. OCR is a convert (image to text). Transcription is a\n * convert (PCM to text). Decoding audio is a convert (container to PCM). Generating a blank\n * file is a convert (from {@link EMPTY_MIME} — the source format happens to be nothing).\n * Resizing is a mutate. Inserting a worksheet row is an edit. A new capability is a new edge\n * in the data, never a new contract.\n *\n * Engines are supplied to `createMediaPipeline` as a flat ordered array and resolved eagerly\n * at construction (declarations drive verb narrowing, so they must be known up front).\n * Bundled engines stay cheap to resolve: their heavy peer dependencies load lazily inside\n * the capability methods, on first actual use.\n *\n * All contracts are duck-typed: validation guards check structure, not class identity, so a\n * consumer can implement an interface from scratch or adapt an existing client. Contracts are\n * enforced at runtime — construction validates every engine and every declared capability and\n * throws `E_INVALID_MEDIA_PIPELINE_CONFIG` naming the offending index when a value fails.\n *\n * Two further contracts exist so that even \"run a binary\" and \"give a binary a file\" are\n * movable seams rather than Node assumptions:\n *\n * - {@link BinaryExecutor} — how an invocation runs. The bundled `execa_executor` wraps execa;\n * a browser/remote/sandbox executor satisfies the same contract.\n * - {@link ScratchWorkspace} — bytes ⇄ executor-visible paths. A sibling of `ByteStore`, NOT a\n * `ByteStore`: byte stores promise in-process readers, while binaries are foreign processes\n * that need real paths. The bundled `fs_workspace` uses `node:fs/promises` via an async\n * resolver; any implementation whose paths the chosen executor can see is valid — that\n * compatibility is the consumer's composition decision.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\n\n// ── shared helper shapes ─────────────────────────────────────────────────────\n\n/**\n * A value-or-resolver: the canonical way to supply an engine. Resolvers may be sync or async\n * (dynamic import) and may resolve to the value directly or a `{ default: value }` module\n * namespace. Engine resolvers run eagerly at pipeline construction — the engine module itself\n * is cheap; heavy peer dependencies load lazily inside capability methods.\n */\nexport type EngineResolver<T = MediaEngine> =\n | T\n | (() => T | { default: T } | Promise<T | { default: T }>)\n\n/** Common result shape for engines that transform bytes to bytes. */\nexport interface EngineBytesResult {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type. */\n mimeType: string\n}\n\n// ── process execution + scratch filesystem ──────────────────────────────────\n\n/** A single binary invocation handed to a {@link BinaryExecutor}. */\nexport interface BinaryInvocation {\n /** The command to run (an absolute path or a name the executor can resolve). */\n cmd: string\n /** Arguments, exec-style (no shell interpolation). */\n args: string[]\n /** Wall-clock timeout in milliseconds. */\n timeoutMs?: number\n /** Abort signal to cancel the invocation. */\n signal?: AbortSignal\n}\n\n/** The settled result of a {@link BinaryExecutor.exec} call. */\nexport interface BinaryExecResult {\n /** The process exit code (or -1 when the process failed to start). */\n exitCode: number\n /** Captured standard output. */\n stdout: string\n /** Captured standard error. */\n stderr: string\n /** `true` when the invocation failed (non-zero exit, spawn failure, timeout, abort). */\n failed: boolean\n}\n\n/**\n * Runs a binary invocation to completion. How and where it runs — local child process, remote\n * runner, sandbox, container, a browser-side WASI shim — is the implementation's business.\n */\nexport interface BinaryExecutor {\n /**\n * Run one invocation to completion and report the result. Implementations must not throw on\n * non-zero exits — report via `failed`/`exitCode` so callers map failures to readable errors.\n *\n * @param invocation - The command, args, and limits to run.\n * @returns The settled result.\n */\n exec(invocation: BinaryInvocation): Promise<BinaryExecResult>\n}\n\n/**\n * Bytes ⇄ executor-visible paths. The seam that lets binary-backed engines exchange files\n * with the process (or remote runner) that executes them.\n */\nexport interface ScratchWorkspace {\n /**\n * Write `bytes` into the workspace under `filename` and return the absolute path the\n * paired executor can open.\n *\n * @param bytes - The content to materialize.\n * @param filename - The basename to use (extension matters to format-sniffing binaries).\n * @returns The absolute path.\n */\n materialize(bytes: Uint8Array, filename: string): Promise<string>\n /**\n * Read a file the executor produced inside the workspace.\n *\n * @param path - The absolute path to read.\n * @returns The file bytes.\n */\n read(path: string): Promise<Uint8Array>\n /** The workspace root directory, for `--outdir`-style binary arguments. */\n dir(): string\n /** List the files currently in the workspace root (basenames). */\n list(): Promise<string[]>\n /** Remove the workspace and everything in it. Engines call this in `finally`. */\n dispose(): Promise<void>\n}\n\n/**\n * A factory for per-execution scratch workspaces. Engines mint one workspace per invocation\n * so concurrent executions never share a directory.\n */\nexport type ScratchWorkspaceFactory = () => ScratchWorkspace | Promise<ScratchWorkspace>\n\n// ── the format vocabulary ────────────────────────────────────────────────────\n\n/**\n * An input-matching pattern: an exact MIME type (`application/pdf`), a family wildcard\n * (`image/*`), or a virtual MIME such as {@link PCM_MIME}.\n */\nexport type MimePattern = string\n\n/**\n * The virtual MIME type for decoded mono PCM audio — the intermediate between an audio\n * container and a transcription. Bytes are little-endian Float32 samples in `[-1, 1]`;\n * a {@link ConvertOutput} carrying PCM must set `meta.sampleRate` (Hz).\n */\nexport const PCM_MIME = 'audio/x-adk-pcm'\n\n/**\n * The virtual source MIME type for media generation — the single seam through which new media\n * comes into existence. An engine that can mint a blank/seed file declares\n * `converts: [{ from: [EMPTY_MIME], to: [...] }]` and receives a {@link ConvertRequest} with\n * zero bytes; the format token in `to` names what gets created.\n *\n * @remarks\n * Generating an .xlsx, a blank canvas, or a second of silence IS media generation — it is\n * *deterministic* generation (same inputs, same bytes). *Model-based semantic* generation\n * (diffusion, TTS) is the same edge with different machinery: a BYO engine declares\n * `from: [EMPTY_MIME]` and consumes a prompt from `request.options`. Both kinds ride one\n * declaration shape, which is exactly why this is a MIME and not a special API. `EMPTY_MIME`\n * can never become a conversion intermediate: no engine declares `to: 'empty'`, so the\n * pathfinder only ever sees it as a source.\n */\nexport const EMPTY_MIME = 'application/x-adk-empty'\n\n/**\n * Pack PCM samples into transport bytes for a {@link ConvertOutput}.\n *\n * @remarks\n * A `Float32Array` view over arbitrary `Uint8Array` bytes requires 4-byte alignment, which\n * sliced buffers do not guarantee — this helper (and {@link bytesToPcm}) copy-normalize so\n * neither side has to think about alignment.\n *\n * @param pcm - Mono PCM samples in `[-1, 1]`.\n * @returns The samples as little-endian Float32 bytes.\n */\nexport const pcmToBytes = (pcm: Float32Array): Uint8Array => {\n const copy = new Float32Array(pcm)\n return new Uint8Array(copy.buffer, 0, copy.byteLength)\n}\n\n/**\n * Read PCM samples back out of transport bytes.\n *\n * @param bytes - Little-endian Float32 bytes (as produced by {@link pcmToBytes}).\n * @returns The mono PCM samples.\n */\nexport const bytesToPcm = (bytes: Uint8Array): Float32Array => {\n const aligned = new Uint8Array(bytes.length)\n aligned.set(bytes)\n return new Float32Array(aligned.buffer, 0, Math.floor(bytes.length / 4))\n}\n\n// ── convert options (typed, augmentable) ─────────────────────────────────────\n\n/** Options understood by OCR-flavored converts (`image/*` → `txt`/`hocr`/`json`). */\nexport interface OcrConvertOptions {\n /** Recognition language hints (e.g. `['eng','deu']`). */\n languages?: readonly string[]\n}\n\n/** Options understood by transcription-flavored converts ({@link PCM_MIME} → `txt`/`srt`/`vtt`/`json`). */\nexport interface AsrConvertOptions {\n /** Source-language hint (BCP-47-ish). */\n lang?: string\n /** Translate the transcription to English. */\n translate?: boolean\n}\n\n/** Options understood by embedded-image extraction converts (`application/pdf` → `images`). */\nexport interface ImagesConvertOptions {\n /**\n * Preferred output encoding token (`jpg`, `png`, …). An extractor that can emit it natively\n * should; outputs in other encodings are re-encoded downstream by the requesting step.\n */\n format?: string\n}\n\n/**\n * The options bag carried by a {@link ConvertRequest} — one typed, augmentable interface\n * merging every documented convention.\n *\n * @remarks\n * Consumers add their own keys via declaration merging against this module:\n *\n * ```ts\n * declare module '@nhtio/adk/batteries/media/contracts' {\n * interface ConvertOptions {\n * watermark?: { text: string }\n * }\n * }\n * ```\n *\n * Typo'd keys become excess-property compile errors at literal call sites; the runtime stays\n * open — engines must ignore keys they don't understand (multi-hop conversion forwards one\n * bag to every hop). The namespace is flat and globally merged, so BYO keys should be named\n * to avoid collisions (prefix by engine where ambiguous).\n */\nexport interface ConvertOptions\n extends OcrConvertOptions, AsrConvertOptions, ImagesConvertOptions {}\n\n// ── the three capabilities ───────────────────────────────────────────────────\n\n/** A format-changing request handed to a {@link ConvertCapability}. */\nexport interface ConvertRequest {\n /** The input content bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The input filename (extension informs format sniffing). */\n filename: string\n /** The target format token (`pdf`, `docx`, `txt`, `pcm`, `images`, …). */\n to: string\n /** Capability-specific options — see {@link ConvertOptions}. */\n options?: ConvertOptions\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** One output of a convert — most converts yield exactly one; `images` yields many. */\nexport interface ConvertOutput {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type (honest — native encoding, no silent re-encode). */\n mimeType: string\n /** Output metadata (e.g. `{ sampleRate: 44100 }` on {@link PCM_MIME} outputs). */\n meta?: Record<string, unknown>\n}\n\n/** The settled result of a convert. */\nexport interface ConvertResult {\n /** The outputs, in source order. */\n outputs: readonly ConvertOutput[]\n}\n\n/**\n * One uniform block of an engine's conversion matrix: every format token in `to` is\n * producible from every input matching `from`.\n *\n * @remarks\n * Declarations are plain data — the registry reads them without calling engine code. An\n * input-dependent matrix (LibreOffice: docx→pdf yes, docx→xlsx no, ods→xlsx yes) is expressed\n * as several capability groups, each a uniform from×to block.\n */\nexport interface ConvertCapability {\n /** Input patterns this block accepts. */\n from: readonly MimePattern[]\n /** Format tokens producible from every `from` member. */\n to: readonly string[]\n /**\n * Perform the conversion.\n *\n * @param request - The input bytes, target token, and options.\n * @returns The conversion outputs.\n */\n convert(request: ConvertRequest): Promise<ConvertResult>\n}\n\n/**\n * A same-format content transform handed to a {@link MutateCapability} — the fused image\n * request: adjacent `image.*` steps fold into ONE request so a resize→rotate→format chain\n * costs a single decode/encode.\n */\nexport interface MutateRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** Resize, when requested. */\n resize?: {\n width?: number\n height?: number\n fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside'\n }\n /** Clockwise rotation in degrees. */\n rotate?: 90 | 180 | 270\n /** Flip axes. */\n flip?: { horizontal?: boolean; vertical?: boolean }\n /** Remove EXIF/ICC metadata. */\n stripMetadata?: boolean\n /** Vector annotation primitives, rendered over the image. */\n annotate?: readonly ImageAnnotation[]\n /** Re-encode target, when requested (rides the same fused call). */\n format?: { to: string; quality?: number }\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** A same-format content-transform capability group. */\n/** A primitive rendered by the image annotation operation. */\nexport type ImageAnnotation =\n | {\n type: 'rect'\n x: number\n y: number\n width: number\n height: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'line' | 'arrow'\n x1: number\n y1: number\n x2: number\n y2: number\n color?: string\n strokeWidth?: number\n }\n | {\n type: 'ellipse'\n cx: number\n cy: number\n rx: number\n ry: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'text'\n x: number\n y: number\n text: string\n color?: string\n size?: number\n font?: string\n }\n\n/** A same-format content-transform capability group. */\nexport interface MutateCapability {\n /** Input patterns this block mutates. */\n over: readonly MimePattern[]\n /** Content operations supported (`resize`, `rotate`, `flip`, `strip_metadata`, `annotate`). */\n ops: readonly string[]\n /** Format tokens reachable via `request.format` in the same fused call. */\n encodes: readonly string[]\n /**\n * Apply the fused transform.\n *\n * @param request - The folded operations and input bytes.\n * @returns The transformed bytes.\n */\n mutate(request: MutateRequest): Promise<EngineBytesResult>\n}\n\n/**\n * A structural document operation handed to an {@link EditCapability}: one named op with its\n * verb-table args, applied to in-memory bytes. Unlike the fused {@link MutateRequest} (which\n * folds adjacent image transforms into one decode/encode), edits run one op per request — a\n * worksheet splice is not a pixel pass and gains nothing from fusion.\n */\nexport interface EditRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The operation name, namespaced as in the verb table (`sheet.update_cells`, …). */\n op: string\n /** The op's arguments, in the verb table's declared shapes. */\n args: Record<string, unknown>\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** Counts an edit reports back for result summaries. */\nexport interface EditSummary {\n /** Items added (rows, columns, sheets…). */\n added?: number\n /** Items removed. */\n removed?: number\n /** Items modified. */\n modified?: number\n /** Non-fatal notes surfaced to the model. */\n warnings?: string[]\n}\n\n/** The settled result of an edit: the restructured bytes plus optional change counts. */\nexport interface EditResult extends EngineBytesResult {\n /** Change counts for result summaries. */\n summary?: EditSummary\n}\n\n/**\n * A structural document-editing capability group: every op in `ops` is applicable to every\n * input matching `over`.\n *\n * @remarks\n * Two engines may declare the same ops over the same patterns with different fidelity — e.g.\n * an ExcelJS-backed editor preserves styling while a SheetJS CE-backed one strips it. The\n * registry does not rank fidelity; supply order (or selection middleware) decides, which makes\n * the trade-off the consumer's visible composition decision.\n */\nexport interface EditCapability {\n /** Input patterns this block edits. */\n over: readonly MimePattern[]\n /** Operation names supported (`sheet.update_cells`, `sheet.add_rows`, …). */\n ops: readonly string[]\n /**\n * Apply one structural operation.\n *\n * @param request - The op, its args, and the input bytes.\n * @returns The restructured bytes plus optional change counts.\n */\n edit(request: EditRequest): Promise<EditResult>\n}\n\n/**\n * A self-declaring media engine: an id for error messages plus the capabilities it provides.\n * At least one capability entry is required.\n */\nexport interface MediaEngine {\n /** Stable identifier used in config and dispatch error messages (`jimp`, `soffice`, …). */\n readonly id: string\n /** Format-changing capability groups. */\n readonly converts?: readonly ConvertCapability[]\n /** Same-format content-transform capability groups. */\n readonly mutates?: readonly MutateCapability[]\n /** Structural document-editing capability groups. */\n readonly edits?: readonly EditCapability[]\n}\n\n// ── duck-typed guards ────────────────────────────────────────────────────────\n\nconst hasFns = (value: unknown, names: readonly string[]): boolean =>\n isObject(value) && names.every((n) => typeof (value as Record<string, unknown>)[n] === 'function')\n\nconst isStringArray = (value: unknown): boolean =>\n Array.isArray(value) && value.every((v) => typeof v === 'string')\n\n/** `true` when `value` structurally implements {@link BinaryExecutor}. */\nexport const implementsBinaryExecutor = (value: unknown): value is BinaryExecutor =>\n hasFns(value, ['exec'])\n\n/** `true` when `value` structurally implements {@link ScratchWorkspace}. */\nexport const implementsScratchWorkspace = (value: unknown): value is ScratchWorkspace =>\n hasFns(value, ['materialize', 'read', 'dir', 'list', 'dispose'])\n\n/** `true` when `value` structurally implements {@link ConvertCapability}. */\nexport const implementsConvertCapability = (value: unknown): value is ConvertCapability =>\n hasFns(value, ['convert']) &&\n isStringArray((value as ConvertCapability).from) &&\n isStringArray((value as ConvertCapability).to)\n\n/** `true` when `value` structurally implements {@link MutateCapability}. */\nexport const implementsMutateCapability = (value: unknown): value is MutateCapability =>\n hasFns(value, ['mutate']) &&\n isStringArray((value as MutateCapability).over) &&\n isStringArray((value as MutateCapability).ops) &&\n isStringArray((value as MutateCapability).encodes)\n\n/** `true` when `value` structurally implements {@link EditCapability}. */\nexport const implementsEditCapability = (value: unknown): value is EditCapability =>\n hasFns(value, ['edit']) &&\n isStringArray((value as EditCapability).over) &&\n isStringArray((value as EditCapability).ops)\n\n/**\n * `true` when `value` structurally implements {@link MediaEngine}: a string id plus at least\n * one well-formed capability entry. Every declared entry must pass its capability guard.\n */\nexport const implementsMediaEngine = (value: unknown): value is MediaEngine => {\n if (!isObject(value)) return false\n const engine = value as unknown as MediaEngine\n if (typeof engine.id !== 'string' || engine.id.length === 0) return false\n const converts = engine.converts\n const mutates = engine.mutates\n const edits = engine.edits\n if (converts !== undefined) {\n if (!Array.isArray(converts) || !converts.every(implementsConvertCapability)) return false\n }\n if (mutates !== undefined) {\n if (!Array.isArray(mutates) || !mutates.every(implementsMutateCapability)) return false\n }\n if (edits !== undefined) {\n if (!Array.isArray(edits) || !edits.every(implementsEditCapability)) return false\n }\n const convertCount = Array.isArray(converts) ? converts.length : 0\n const mutateCount = Array.isArray(mutates) ? mutates.length : 0\n const editCount = Array.isArray(edits) ? edits.length : 0\n return convertCount + mutateCount + editCount > 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,IAAa,WAAW;;;;;;;;;;;;;;;;AAiBxB,IAAa,aAAa;;;;;;;;;;;;AAa1B,IAAa,cAAc,QAAkC;CAC3D,MAAM,OAAO,IAAI,aAAa,GAAG;CACjC,OAAO,IAAI,WAAW,KAAK,QAAQ,GAAG,KAAK,UAAU;AACvD;;;;;;;AAQA,IAAa,cAAc,UAAoC;CAC7D,MAAM,UAAU,IAAI,WAAW,MAAM,MAAM;CAC3C,QAAQ,IAAI,KAAK;CACjB,OAAO,IAAI,aAAa,QAAQ,QAAQ,GAAG,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;AACzE;AAkRA,IAAM,UAAU,OAAgB,UAC9B,SAAS,KAAK,KAAK,MAAM,OAAO,MAAM,OAAQ,MAAkC,OAAO,UAAU;AAEnG,IAAM,iBAAiB,UACrB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;;AAGlE,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC;;AAGxB,IAAa,8BAA8B,UACzC,OAAO,OAAO;CAAC;CAAe;CAAQ;CAAO;CAAQ;AAAS,CAAC;;AAGjE,IAAa,+BAA+B,UAC1C,OAAO,OAAO,CAAC,SAAS,CAAC,KACzB,cAAe,MAA4B,IAAI,KAC/C,cAAe,MAA4B,EAAE;;AAG/C,IAAa,8BAA8B,UACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,KACxB,cAAe,MAA2B,IAAI,KAC9C,cAAe,MAA2B,GAAG,KAC7C,cAAe,MAA2B,OAAO;;AAGnD,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC,KACtB,cAAe,MAAyB,IAAI,KAC5C,cAAe,MAAyB,GAAG;;;;;AAM7C,IAAa,yBAAyB,UAAyC;CAC7E,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,OAAO,YAAY,OAAO,GAAG,WAAW,GAAG,OAAO;CACpE,MAAM,WAAW,OAAO;CACxB,MAAM,UAAU,OAAO;CACvB,MAAM,QAAQ,OAAO;CACrB,IAAI,aAAa,KAAA;MACX,CAAC,MAAM,QAAQ,QAAQ,KAAK,CAAC,SAAS,MAAM,2BAA2B,GAAG,OAAO;CAAA;CAEvF,IAAI,YAAY,KAAA;MACV,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,MAAM,0BAA0B,GAAG,OAAO;CAAA;CAEpF,IAAI,UAAU,KAAA;MACR,CAAC,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,MAAM,wBAAwB,GAAG,OAAO;CAAA;CAE9E,MAAM,eAAe,MAAM,QAAQ,QAAQ,IAAI,SAAS,SAAS;CACjE,MAAM,cAAc,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS;CAC9D,MAAM,YAAY,MAAM,QAAQ,KAAK,IAAI,MAAM,SAAS;CACxD,OAAO,eAAe,cAAc,YAAY;AAClD"}
1
+ {"version":3,"file":"contracts.mjs","names":[],"sources":["../../../src/batteries/media/contracts.ts"],"sourcesContent":["/**\n * Generic engine contracts for the media pipeline battery — the seams every implementation\n * (bundled or BYO) plugs into.\n *\n * @module @nhtio/adk/batteries/media/contracts\n *\n * @remarks\n * Engines are seams, not policies. An engine is a self-declaring capability provider: it\n * states exactly which transforms it supports — {@link ConvertCapability} edges (input MIME\n * patterns to output format tokens), {@link MutateCapability} groups (same-format content\n * transforms), and {@link EditCapability} groups (structural document operations) — and the\n * pipeline dispatches against those declarations. There are only three capability shapes\n * because there are only three things a media engine ever does: change the format, change the\n * content, or restructure the document. OCR is a convert (image to text). Transcription is a\n * convert (PCM to text). Decoding audio is a convert (container to PCM). Generating a blank\n * file is a convert (from {@link EMPTY_MIME} — the source format happens to be nothing).\n * Resizing is a mutate. Inserting a worksheet row is an edit. A new capability is a new edge\n * in the data, never a new contract.\n *\n * Engines are supplied to `createMediaPipeline` as a flat ordered array and resolved eagerly\n * at construction (declarations drive verb narrowing, so they must be known up front).\n * Bundled engines stay cheap to resolve: their heavy peer dependencies load lazily inside\n * the capability methods, on first actual use.\n *\n * All contracts are duck-typed: validation guards check structure, not class identity, so a\n * consumer can implement an interface from scratch or adapt an existing client. Contracts are\n * enforced at runtime — construction validates every engine and every declared capability and\n * throws `E_INVALID_MEDIA_PIPELINE_CONFIG` naming the offending index when a value fails.\n *\n * Two further contracts exist so that even \"run a binary\" and \"give a binary a file\" are\n * movable seams rather than Node assumptions:\n *\n * - {@link BinaryExecutor} — how an invocation runs. The bundled `execa_executor` wraps execa;\n * a browser/remote/sandbox executor satisfies the same contract.\n * - {@link ScratchWorkspace} — bytes ⇄ executor-visible paths. A sibling of `ByteStore`, NOT a\n * `ByteStore`: byte stores promise in-process readers, while binaries are foreign processes\n * that need real paths. The bundled `fs_workspace` uses `node:fs/promises` via an async\n * resolver; any implementation whose paths the chosen executor can see is valid — that\n * compatibility is the consumer's composition decision.\n */\n\nimport { isObject } from '@nhtio/adk/guards'\n\n// ── shared helper shapes ─────────────────────────────────────────────────────\n\n/**\n * A value-or-resolver: the canonical way to supply an engine. Resolvers may be sync or async\n * (dynamic import) and may resolve to the value directly or a `{ default: value }` module\n * namespace. Engine resolvers run eagerly at pipeline construction — the engine module itself\n * is cheap; heavy peer dependencies load lazily inside capability methods.\n */\nexport type EngineResolver<T = MediaEngine> =\n | T\n | (() => T | { default: T } | Promise<T | { default: T }>)\n\n/** Common result shape for engines that transform bytes to bytes. */\nexport interface EngineBytesResult {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type. */\n mimeType: string\n}\n\n// ── process execution + scratch filesystem ──────────────────────────────────\n\n/** A single binary invocation handed to a {@link BinaryExecutor}. */\nexport interface BinaryInvocation {\n /** The command to run (an absolute path or a name the executor can resolve). */\n cmd: string\n /** Arguments, exec-style (no shell interpolation). */\n args: string[]\n /**\n * Working directory for the process. Omitted means the executor's own default.\n *\n * @remarks\n * Exec-style, like `args`: the executor passes it to the process launcher and never interprets\n * it as shell text. A sandbox wrapper that rewrites the invocation carries the caller's `cwd`\n * through unchanged — the profile it generates is what decides whether that directory is\n * reachable at all.\n */\n cwd?: string\n /**\n * The caller's own EXPLICIT environment values, applied last.\n *\n * @remarks\n * The same semantics as `SandboxPolicyEnforcer.run`'s `env`: these are the caller's own values —\n * not a host-inheritance control — and a sandbox decides host inheritance separately through its\n * allow-list. They are applied last, so they may add names or override inherited ones, and an\n * adapter must not let them (or anything else) pull host variables beyond its allow-list into the\n * child. They do not replace the executor's environment — unless the invocation clears\n * {@link BinaryInvocation.extendEnv}, in which case this object IS the whole environment.\n */\n env?: Record<string, string>\n /**\n * Whether {@link BinaryInvocation.env} extends the executor's own environment (`true`, the\n * default) or replaces it entirely (`false`).\n *\n * @remarks\n * This field exists for sandboxes. A sandbox decides what a child may inherit from the host\n * (usually an allow-list, on the explicit grounds that anything inherited is readable back into\n * the model's context by running `env`), so it must be able to say \"this is the entire\n * environment\". An executor that always merged its own ambient environment back in would\n * silently defeat that allow-list — execa's `extendEnv: true` default does exactly this — which\n * is why the SRT wrapper sets it to `false` and the bundled executor maps it to\n * `extendEnv: false`. Leave it unset for an ordinary, unsandboxed invocation.\n */\n extendEnv?: boolean\n /**\n * Wall-clock timeout in milliseconds.\n *\n * @remarks\n * `0`, `Infinity`, and finite values above 2,147,483,647 disable the deadline.\n * Negative values and `NaN` reject the invocation before spawning.\n */\n timeoutMs?: number\n /** Abort signal to cancel the invocation. */\n signal?: AbortSignal\n /**\n * The signal used to terminate the invocation when {@link BinaryInvocation.signal} aborts or\n * {@link BinaryInvocation.timeoutMs} elapses. `'SIGTERM'` by default.\n *\n * @remarks\n * Typed as `string` (not `NodeJS.Signals`) so that this contract stays browser-safe: it is a\n * plain signal NAME, and an executor that runs somewhere without POSIX signals decides what to\n * do with it. With the bundled executor's default `detached: true`, it signals the whole process\n * group; with `detached: false`, it signals only the direct child.\n */\n killSignal?: string\n /**\n * Milliseconds to wait after {@link BinaryInvocation.killSignal} before escalating to `SIGKILL`;\n * `false` and `Infinity` disable escalation and never send `SIGKILL`.\n *\n * @remarks\n * Settlement follows {@link BinaryInvocation.settleEscalation}: `'wait'` holds `exec()` until the\n * escalation completes, `'cancel'` stops escalation when `exec()` returns, and `'poll'` may send\n * `SIGKILL` after return. Omitted means the executor's default. Negative values and `NaN` reject\n * before spawning.\n */\n forceKillAfterDelay?: number | false\n /**\n * How escalation behaves when an abort or executor-owned timeout fires and the invocation settles\n * while escalation is armed. Defaults to `'wait'`. `'wait'` delays settlement until the target is\n * empty or SIGKILL is sent (nothing survives, at the cost of latency up to the escalation delay);\n * `'cancel'` returns fastest but descendants may survive; `'poll'` returns fastest and may kill\n * survivors later, with a narrow process-group reuse risk after return. A normal exit never waits\n * or polls. Applies only with finite escalation and a known pid; `detached: false` cancels at\n * settlement in every mode. Wait also has a narrow numeric PGID-reuse risk between probes,\n * bounded to before return. The value is a browser-safe string union.\n */\n settleEscalation?: 'wait' | 'cancel' | 'poll'\n}\n\n/** The settled result of a {@link BinaryExecutor.exec} call. */\nexport interface BinaryExecResult {\n /** The process exit code (or -1 when the process failed to start). */\n exitCode: number\n /** Captured standard output. */\n stdout: string\n /** Captured standard error. */\n stderr: string\n /** `true` when the invocation failed (non-zero exit, spawn failure, timeout, abort). */\n failed: boolean\n /**\n * The signal that terminated the process, when one did.\n *\n * @remarks\n * Omitted on a normal exit, so a consumer must treat absence as \"exited on its own\". An executor\n * that cannot surface it simply leaves it off.\n */\n signalCode?: string\n}\n\n/**\n * Runs a binary invocation to completion. How and where it runs — local child process, remote\n * runner, sandbox, container, a browser-side WASI shim — is the implementation's business.\n */\nexport interface BinaryExecutor {\n /**\n * Run one invocation to completion and report the result. Implementations must not throw on\n * non-zero exits — report via `failed`/`exitCode` so callers map failures to readable errors.\n *\n * @remarks\n * When `invocation.signal` aborts or `invocation.timeoutMs` elapses, an implementation MUST\n * terminate the process it started and settle, rather than leaving it running with this promise\n * pending. A binary that spawns children of its own is the caller's hazard: the bundled executor\n * spawns the child as its own process-group leader and signals the WHOLE group\n * ({@link BinaryInvocation.killSignal}, escalating to `SIGKILL` per\n * {@link BinaryInvocation.forceKillAfterDelay}) so a wrapper cannot outlive the invocation.\n *\n * @param invocation - The command, args, working directory, environment, and limits to run.\n * @returns The settled result.\n */\n exec(invocation: BinaryInvocation): Promise<BinaryExecResult>\n}\n\n/**\n * Bytes ⇄ executor-visible paths. The seam that lets binary-backed engines exchange files\n * with the process (or remote runner) that executes them.\n */\nexport interface ScratchWorkspace {\n /**\n * Write `bytes` into the workspace under `filename` and return the absolute path the\n * paired executor can open.\n *\n * @param bytes - The content to materialize.\n * @param filename - The basename to use (extension matters to format-sniffing binaries).\n * @returns The absolute path.\n */\n materialize(bytes: Uint8Array, filename: string): Promise<string>\n /**\n * Read a file the executor produced inside the workspace.\n *\n * @param path - The absolute path to read.\n * @returns The file bytes.\n */\n read(path: string): Promise<Uint8Array>\n /** The workspace root directory, for `--outdir`-style binary arguments. */\n dir(): string\n /** List the files currently in the workspace root (basenames). */\n list(): Promise<string[]>\n /** Remove the workspace and everything in it. Engines call this in `finally`. */\n dispose(): Promise<void>\n}\n\n/**\n * A factory for per-execution scratch workspaces. Engines mint one workspace per invocation\n * so concurrent executions never share a directory.\n */\nexport type ScratchWorkspaceFactory = () => ScratchWorkspace | Promise<ScratchWorkspace>\n\n// ── the format vocabulary ────────────────────────────────────────────────────\n\n/**\n * An input-matching pattern: an exact MIME type (`application/pdf`), a family wildcard\n * (`image/*`), or a virtual MIME such as {@link PCM_MIME}.\n */\nexport type MimePattern = string\n\n/**\n * The virtual MIME type for decoded mono PCM audio — the intermediate between an audio\n * container and a transcription. Bytes are little-endian Float32 samples in `[-1, 1]`;\n * a {@link ConvertOutput} carrying PCM must set `meta.sampleRate` (Hz).\n */\nexport const PCM_MIME = 'audio/x-adk-pcm'\n\n/**\n * The virtual source MIME type for media generation — the single seam through which new media\n * comes into existence. An engine that can mint a blank/seed file declares\n * `converts: [{ from: [EMPTY_MIME], to: [...] }]` and receives a {@link ConvertRequest} with\n * zero bytes; the format token in `to` names what gets created.\n *\n * @remarks\n * Generating an .xlsx, a blank canvas, or a second of silence IS media generation — it is\n * *deterministic* generation (same inputs, same bytes). *Model-based semantic* generation\n * (diffusion, TTS) is the same edge with different machinery: a BYO engine declares\n * `from: [EMPTY_MIME]` and consumes a prompt from `request.options`. Both kinds ride one\n * declaration shape, which is exactly why this is a MIME and not a special API. `EMPTY_MIME`\n * can never become a conversion intermediate: no engine declares `to: 'empty'`, so the\n * pathfinder only ever sees it as a source.\n */\nexport const EMPTY_MIME = 'application/x-adk-empty'\n\n/**\n * Pack PCM samples into transport bytes for a {@link ConvertOutput}.\n *\n * @remarks\n * A `Float32Array` view over arbitrary `Uint8Array` bytes requires 4-byte alignment, which\n * sliced buffers do not guarantee — this helper (and {@link bytesToPcm}) copy-normalize so\n * neither side has to think about alignment.\n *\n * @param pcm - Mono PCM samples in `[-1, 1]`.\n * @returns The samples as little-endian Float32 bytes.\n */\nexport const pcmToBytes = (pcm: Float32Array): Uint8Array => {\n const copy = new Float32Array(pcm)\n return new Uint8Array(copy.buffer, 0, copy.byteLength)\n}\n\n/**\n * Read PCM samples back out of transport bytes.\n *\n * @param bytes - Little-endian Float32 bytes (as produced by {@link pcmToBytes}).\n * @returns The mono PCM samples.\n */\nexport const bytesToPcm = (bytes: Uint8Array): Float32Array => {\n const aligned = new Uint8Array(bytes.length)\n aligned.set(bytes)\n return new Float32Array(aligned.buffer, 0, Math.floor(bytes.length / 4))\n}\n\n// ── convert options (typed, augmentable) ─────────────────────────────────────\n\n/** Options understood by OCR-flavored converts (`image/*` → `txt`/`hocr`/`json`). */\nexport interface OcrConvertOptions {\n /** Recognition language hints (e.g. `['eng','deu']`). */\n languages?: readonly string[]\n}\n\n/** Options understood by transcription-flavored converts ({@link PCM_MIME} → `txt`/`srt`/`vtt`/`json`). */\nexport interface AsrConvertOptions {\n /** Source-language hint (BCP-47-ish). */\n lang?: string\n /** Translate the transcription to English. */\n translate?: boolean\n}\n\n/** Options understood by embedded-image extraction converts (`application/pdf` → `images`). */\nexport interface ImagesConvertOptions {\n /**\n * Preferred output encoding token (`jpg`, `png`, …). An extractor that can emit it natively\n * should; outputs in other encodings are re-encoded downstream by the requesting step.\n */\n format?: string\n}\n\n/**\n * The options bag carried by a {@link ConvertRequest} — one typed, augmentable interface\n * merging every documented convention.\n *\n * @remarks\n * Consumers add their own keys via declaration merging against this module:\n *\n * ```ts\n * declare module '@nhtio/adk/batteries/media/contracts' {\n * interface ConvertOptions {\n * watermark?: { text: string }\n * }\n * }\n * ```\n *\n * Typo'd keys become excess-property compile errors at literal call sites; the runtime stays\n * open — engines must ignore keys they don't understand (multi-hop conversion forwards one\n * bag to every hop). The namespace is flat and globally merged, so BYO keys should be named\n * to avoid collisions (prefix by engine where ambiguous).\n */\nexport interface ConvertOptions\n extends OcrConvertOptions, AsrConvertOptions, ImagesConvertOptions {}\n\n// ── the three capabilities ───────────────────────────────────────────────────\n\n/** A format-changing request handed to a {@link ConvertCapability}. */\nexport interface ConvertRequest {\n /** The input content bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The input filename (extension informs format sniffing). */\n filename: string\n /** The target format token (`pdf`, `docx`, `txt`, `pcm`, `images`, …). */\n to: string\n /** Capability-specific options — see {@link ConvertOptions}. */\n options?: ConvertOptions\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** One output of a convert — most converts yield exactly one; `images` yields many. */\nexport interface ConvertOutput {\n /** The output bytes. */\n bytes: Uint8Array\n /** The output MIME type (honest — native encoding, no silent re-encode). */\n mimeType: string\n /** Output metadata (e.g. `{ sampleRate: 44100 }` on {@link PCM_MIME} outputs). */\n meta?: Record<string, unknown>\n}\n\n/** The settled result of a convert. */\nexport interface ConvertResult {\n /** The outputs, in source order. */\n outputs: readonly ConvertOutput[]\n}\n\n/**\n * One uniform block of an engine's conversion matrix: every format token in `to` is\n * producible from every input matching `from`.\n *\n * @remarks\n * Declarations are plain data — the registry reads them without calling engine code. An\n * input-dependent matrix (LibreOffice: docx→pdf yes, docx→xlsx no, ods→xlsx yes) is expressed\n * as several capability groups, each a uniform from×to block.\n */\nexport interface ConvertCapability {\n /** Input patterns this block accepts. */\n from: readonly MimePattern[]\n /** Format tokens producible from every `from` member. */\n to: readonly string[]\n /**\n * Perform the conversion.\n *\n * @param request - The input bytes, target token, and options.\n * @returns The conversion outputs.\n */\n convert(request: ConvertRequest): Promise<ConvertResult>\n}\n\n/**\n * A same-format content transform handed to a {@link MutateCapability} — the fused image\n * request: adjacent `image.*` steps fold into ONE request so a resize→rotate→format chain\n * costs a single decode/encode.\n */\nexport interface MutateRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** Resize, when requested. */\n resize?: {\n width?: number\n height?: number\n fit?: 'cover' | 'contain' | 'fill' | 'inside' | 'outside'\n }\n /** Clockwise rotation in degrees. */\n rotate?: 90 | 180 | 270\n /** Flip axes. */\n flip?: { horizontal?: boolean; vertical?: boolean }\n /** Remove EXIF/ICC metadata. */\n stripMetadata?: boolean\n /** Vector annotation primitives, rendered over the image. */\n annotate?: readonly ImageAnnotation[]\n /** Re-encode target, when requested (rides the same fused call). */\n format?: { to: string; quality?: number }\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** A same-format content-transform capability group. */\n/** A primitive rendered by the image annotation operation. */\nexport type ImageAnnotation =\n | {\n type: 'rect'\n x: number\n y: number\n width: number\n height: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'line' | 'arrow'\n x1: number\n y1: number\n x2: number\n y2: number\n color?: string\n strokeWidth?: number\n }\n | {\n type: 'ellipse'\n cx: number\n cy: number\n rx: number\n ry: number\n color?: string\n fill?: string\n strokeWidth?: number\n }\n | {\n type: 'text'\n x: number\n y: number\n text: string\n color?: string\n size?: number\n font?: string\n }\n\n/** A same-format content-transform capability group. */\nexport interface MutateCapability {\n /** Input patterns this block mutates. */\n over: readonly MimePattern[]\n /** Content operations supported (`resize`, `rotate`, `flip`, `strip_metadata`, `annotate`). */\n ops: readonly string[]\n /** Format tokens reachable via `request.format` in the same fused call. */\n encodes: readonly string[]\n /**\n * Apply the fused transform.\n *\n * @param request - The folded operations and input bytes.\n * @returns The transformed bytes.\n */\n mutate(request: MutateRequest): Promise<EngineBytesResult>\n}\n\n/**\n * A structural document operation handed to an {@link EditCapability}: one named op with its\n * verb-table args, applied to in-memory bytes. Unlike the fused {@link MutateRequest} (which\n * folds adjacent image transforms into one decode/encode), edits run one op per request — a\n * worksheet splice is not a pixel pass and gains nothing from fusion.\n */\nexport interface EditRequest {\n /** The input bytes. */\n bytes: Uint8Array\n /** The input MIME type. */\n mimeType: string\n /** The operation name, namespaced as in the verb table (`sheet.update_cells`, …). */\n op: string\n /** The op's arguments, in the verb table's declared shapes. */\n args: Record<string, unknown>\n /** Abort signal threaded from the pipeline execution. */\n signal?: AbortSignal\n}\n\n/** Counts an edit reports back for result summaries. */\nexport interface EditSummary {\n /** Items added (rows, columns, sheets…). */\n added?: number\n /** Items removed. */\n removed?: number\n /** Items modified. */\n modified?: number\n /** Non-fatal notes surfaced to the model. */\n warnings?: string[]\n}\n\n/** The settled result of an edit: the restructured bytes plus optional change counts. */\nexport interface EditResult extends EngineBytesResult {\n /** Change counts for result summaries. */\n summary?: EditSummary\n}\n\n/**\n * A structural document-editing capability group: every op in `ops` is applicable to every\n * input matching `over`.\n *\n * @remarks\n * Two engines may declare the same ops over the same patterns with different fidelity — e.g.\n * an ExcelJS-backed editor preserves styling while a SheetJS CE-backed one strips it. The\n * registry does not rank fidelity; supply order (or selection middleware) decides, which makes\n * the trade-off the consumer's visible composition decision.\n */\nexport interface EditCapability {\n /** Input patterns this block edits. */\n over: readonly MimePattern[]\n /** Operation names supported (`sheet.update_cells`, `sheet.add_rows`, …). */\n ops: readonly string[]\n /**\n * Apply one structural operation.\n *\n * @param request - The op, its args, and the input bytes.\n * @returns The restructured bytes plus optional change counts.\n */\n edit(request: EditRequest): Promise<EditResult>\n}\n\n/**\n * A self-declaring media engine: an id for error messages plus the capabilities it provides.\n * At least one capability entry is required.\n */\nexport interface MediaEngine {\n /** Stable identifier used in config and dispatch error messages (`jimp`, `soffice`, …). */\n readonly id: string\n /** Format-changing capability groups. */\n readonly converts?: readonly ConvertCapability[]\n /** Same-format content-transform capability groups. */\n readonly mutates?: readonly MutateCapability[]\n /** Structural document-editing capability groups. */\n readonly edits?: readonly EditCapability[]\n}\n\n// ── duck-typed guards ────────────────────────────────────────────────────────\n\nconst hasFns = (value: unknown, names: readonly string[]): boolean =>\n isObject(value) && names.every((n) => typeof (value as Record<string, unknown>)[n] === 'function')\n\nconst isStringArray = (value: unknown): boolean =>\n Array.isArray(value) && value.every((v) => typeof v === 'string')\n\n/** `true` when `value` structurally implements {@link BinaryExecutor}. */\nexport const implementsBinaryExecutor = (value: unknown): value is BinaryExecutor =>\n hasFns(value, ['exec'])\n\n/** `true` when `value` structurally implements {@link ScratchWorkspace}. */\nexport const implementsScratchWorkspace = (value: unknown): value is ScratchWorkspace =>\n hasFns(value, ['materialize', 'read', 'dir', 'list', 'dispose'])\n\n/** `true` when `value` structurally implements {@link ConvertCapability}. */\nexport const implementsConvertCapability = (value: unknown): value is ConvertCapability =>\n hasFns(value, ['convert']) &&\n isStringArray((value as ConvertCapability).from) &&\n isStringArray((value as ConvertCapability).to)\n\n/** `true` when `value` structurally implements {@link MutateCapability}. */\nexport const implementsMutateCapability = (value: unknown): value is MutateCapability =>\n hasFns(value, ['mutate']) &&\n isStringArray((value as MutateCapability).over) &&\n isStringArray((value as MutateCapability).ops) &&\n isStringArray((value as MutateCapability).encodes)\n\n/** `true` when `value` structurally implements {@link EditCapability}. */\nexport const implementsEditCapability = (value: unknown): value is EditCapability =>\n hasFns(value, ['edit']) &&\n isStringArray((value as EditCapability).over) &&\n isStringArray((value as EditCapability).ops)\n\n/**\n * `true` when `value` structurally implements {@link MediaEngine}: a string id plus at least\n * one well-formed capability entry. Every declared entry must pass its capability guard.\n */\nexport const implementsMediaEngine = (value: unknown): value is MediaEngine => {\n if (!isObject(value)) return false\n const engine = value as unknown as MediaEngine\n if (typeof engine.id !== 'string' || engine.id.length === 0) return false\n const converts = engine.converts\n const mutates = engine.mutates\n const edits = engine.edits\n if (converts !== undefined) {\n if (!Array.isArray(converts) || !converts.every(implementsConvertCapability)) return false\n }\n if (mutates !== undefined) {\n if (!Array.isArray(mutates) || !mutates.every(implementsMutateCapability)) return false\n }\n if (edits !== undefined) {\n if (!Array.isArray(edits) || !edits.every(implementsEditCapability)) return false\n }\n const convertCount = Array.isArray(converts) ? converts.length : 0\n const mutateCount = Array.isArray(mutates) ? mutates.length : 0\n const editCount = Array.isArray(edits) ? edits.length : 0\n return convertCount + mutateCount + editCount > 0\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmPA,IAAa,WAAW;;;;;;;;;;;;;;;;AAiBxB,IAAa,aAAa;;;;;;;;;;;;AAa1B,IAAa,cAAc,QAAkC;CAC3D,MAAM,OAAO,IAAI,aAAa,GAAG;CACjC,OAAO,IAAI,WAAW,KAAK,QAAQ,GAAG,KAAK,UAAU;AACvD;;;;;;;AAQA,IAAa,cAAc,UAAoC;CAC7D,MAAM,UAAU,IAAI,WAAW,MAAM,MAAM;CAC3C,QAAQ,IAAI,KAAK;CACjB,OAAO,IAAI,aAAa,QAAQ,QAAQ,GAAG,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;AACzE;AAkRA,IAAM,UAAU,OAAgB,UAC9B,SAAS,KAAK,KAAK,MAAM,OAAO,MAAM,OAAQ,MAAkC,OAAO,UAAU;AAEnG,IAAM,iBAAiB,UACrB,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAO,MAAM,OAAO,MAAM,QAAQ;;AAGlE,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC;;AAGxB,IAAa,8BAA8B,UACzC,OAAO,OAAO;CAAC;CAAe;CAAQ;CAAO;CAAQ;AAAS,CAAC;;AAGjE,IAAa,+BAA+B,UAC1C,OAAO,OAAO,CAAC,SAAS,CAAC,KACzB,cAAe,MAA4B,IAAI,KAC/C,cAAe,MAA4B,EAAE;;AAG/C,IAAa,8BAA8B,UACzC,OAAO,OAAO,CAAC,QAAQ,CAAC,KACxB,cAAe,MAA2B,IAAI,KAC9C,cAAe,MAA2B,GAAG,KAC7C,cAAe,MAA2B,OAAO;;AAGnD,IAAa,4BAA4B,UACvC,OAAO,OAAO,CAAC,MAAM,CAAC,KACtB,cAAe,MAAyB,IAAI,KAC5C,cAAe,MAAyB,GAAG;;;;;AAM7C,IAAa,yBAAyB,UAAyC;CAC7E,IAAI,CAAC,SAAS,KAAK,GAAG,OAAO;CAC7B,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,OAAO,YAAY,OAAO,GAAG,WAAW,GAAG,OAAO;CACpE,MAAM,WAAW,OAAO;CACxB,MAAM,UAAU,OAAO;CACvB,MAAM,QAAQ,OAAO;CACrB,IAAI,aAAa,KAAA;MACX,CAAC,MAAM,QAAQ,QAAQ,KAAK,CAAC,SAAS,MAAM,2BAA2B,GAAG,OAAO;CAAA;CAEvF,IAAI,YAAY,KAAA;MACV,CAAC,MAAM,QAAQ,OAAO,KAAK,CAAC,QAAQ,MAAM,0BAA0B,GAAG,OAAO;CAAA;CAEpF,IAAI,UAAU,KAAA;MACR,CAAC,MAAM,QAAQ,KAAK,KAAK,CAAC,MAAM,MAAM,wBAAwB,GAAG,OAAO;CAAA;CAE9E,MAAM,eAAe,MAAM,QAAQ,QAAQ,IAAI,SAAS,SAAS;CACjE,MAAM,cAAc,MAAM,QAAQ,OAAO,IAAI,QAAQ,SAAS;CAC9D,MAAM,YAAY,MAAM,QAAQ,KAAK,IAAI,MAAM,SAAS;CACxD,OAAO,eAAe,cAAc,YAAY;AAClD"}