@gobing-ai/ts-laya-mlx 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/NOTICE ADDED
@@ -0,0 +1,31 @@
1
+ @gobing-ai/ts-laya-mlx
2
+ Copyright 2026 Robin Min and ts-libs contributors
3
+
4
+ This package derives from the laya-mlx project:
5
+ https://github.com/mizorewww/laya-mlx
6
+ Upstream source revision: fc1df62828a3fedf4d8229fdac1cbd85f1cdf337
7
+ Licensed under Apache-2.0; its NOTICE is carried forward below as required by
8
+ the Apache License 2.0, section 4(d).
9
+
10
+ Model weights for the Laya multilingual checkpoint are downloaded separately
11
+ from Convai Innovations on Hugging Face at run time; they are not included in
12
+ this package.
13
+
14
+ --- Begin upstream NOTICE (laya-mlx @ fc1df62828a3fedf4d8229fdac1cbd85f1cdf337) ---
15
+
16
+ laya-mlx
17
+ Copyright 2026 laya-mlx contributors
18
+
19
+ This product includes software derived from Laya:
20
+ https://github.com/NandhaKishorM/laya
21
+ Copyright Convai Innovations and Laya contributors. Licensed under Apache-2.0.
22
+ Upstream source revision: 6a5819129eb220570792e417e49723d697efd76f
23
+
24
+ The token sequence construction, question rendering, confidence calculation,
25
+ presets, email utilities and language router are adapted from Laya.
26
+ The neural network is reimplemented using Apple's MLX, following Laya's
27
+ DecisionModel and the ModernBERT architecture in Hugging Face Transformers.
28
+ Model weights are downloaded separately from Convai Innovations on Hugging Face;
29
+ they are not included in this repository.
30
+
31
+ --- End upstream NOTICE ---
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # @gobing-ai/ts-laya-mlx
2
+
3
+ Local Laya decision backend for the neutral decision surface owned by
4
+ `@gobing-ai/ts-ai-runner`: answers `choice` / `score` / `noul` questions
5
+ on-device by driving the vendored [`laya-mlx`](https://github.com/mizorewww/laya-mlx)
6
+ Python runtime as a long-lived JSON-lines worker over `ts-runtime`'s
7
+ `ProcessExecutor` ([ADR-027](../../docs/00_ADR.md)).
8
+
9
+ Part of the `@gobing-ai/ts-libs` monorepo and lockstep-versioned with it.
10
+
11
+ - **License:** Apache-2.0 (see [LICENSE](./LICENSE)).
12
+ - **Attribution:** derived from `laya-mlx` by mizorewww, upstream revision
13
+ `fc1df62828a3fedf4d8229fdac1cbd85f1cdf337` (see [NOTICE](./NOTICE)).
14
+ - **No model weights are redistributed.** Model weights are resolved and cached by
15
+ the worker at run time from Hugging Face and never enter the published tarball.
16
+
17
+ ---
18
+
19
+ ## Host prerequisites
20
+
21
+ > **Notice:** This is the only package in the workspace with specific host architecture constraints.
22
+
23
+ 1. **Platform:** macOS on Apple Silicon (`darwin arm64`). Unsupported platforms fail fast at construction time before any process is spawned.
24
+ 2. **Python:** Python 3.10+ carrying the `laya-mlx` runtime (resolvable via `pythonPath`, injected `env.LAYA_PYTHON`, or `python3` on `PATH`).
25
+ 3. **Supported runtime range:** `laya-mlx 0.1.x` (validated against upstream `0.1.0` @ `fc1df62828a3fedf4d8229fdac1cbd85f1cdf337`).
26
+ 4. **Install command:**
27
+ ```sh
28
+ pip install laya-mlx
29
+ # or with uv:
30
+ uv pip install laya-mlx
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Backend selection (`ts-ai-runner`)
36
+
37
+ Downstream applications using `createDecisionMaker` from `@gobing-ai/ts-ai-runner`
38
+ can select the local backend without editing decision call sites:
39
+
40
+ ```ts
41
+ import { createDecisionMaker, q } from '@gobing-ai/ts-ai-runner';
42
+
43
+ // 1. Hosted TypeSafe backend (default):
44
+ const hosted = createDecisionMaker({
45
+ backend: 'typesafe', // or omitted
46
+ apiKey: process.env.TYPESAFE_API_KEY,
47
+ });
48
+
49
+ // 2. Local Laya on-device backend:
50
+ const local = createDecisionMaker({
51
+ backend: 'laya-local',
52
+ });
53
+
54
+ // All call sites are 100% identical and substitutable:
55
+ const result = await local.choice('customer inquiry', 'Select team', {
56
+ billing: 'Invoices, payments, refunds',
57
+ tech: 'Technical issues, system bugs',
58
+ sales: 'Pricing, new contracts',
59
+ });
60
+ console.log(result.label); // "billing" | "tech" | "sales"
61
+ ```
62
+
63
+ Resolution order: `options.driver` (custom driver double) → `options.backend` (`'typesafe' | 'laya-local'`) → `'typesafe'` (default).
64
+ `ts-ai-runner` resolves `@gobing-ai/ts-laya-mlx` via dynamic import on first `ask`; missing installations reject with a descriptive `DecisionConfigError`.
65
+
66
+ ---
67
+
68
+ ## Hosted SDK vs Local Driver substitution reference
69
+
70
+ | Dimension | Hosted TypeSafe (`ts-ai-runner`) | Local Laya (`ts-laya-mlx`) | Notes |
71
+ |-----------|----------------------------------|---------------------------|-------|
72
+ | **Factory** | `createTypesafeDriver(config)` | `createLayaDriver(options)` | Both return `DecisionDriver` with single `ask()` method. |
73
+ | **Driver name** | `'typesafe'` | `'laya-local'` | Available on `driver.name`. |
74
+ | **Credentials** | `apiKey: string` (`TYPESAFE_API_KEY`) | `env.HF_TOKEN` (optional) | Local inference needs no key; token only for gated HF repos. |
75
+ | **Model selector** | `model?: string` | `modelId?: string` | Default: `'convaiinnovations/laya-multilingual'`. |
76
+ | **Offline path** | `baseURL?: string` (custom proxy) | `modelPath?: string` (local weights) | Explicit local path suppresses all network fetches. |
77
+ | **Cache root** | N/A (stateless HTTP) | `cacheDir?: string` (`LAYA_CACHE_DIR`) | Reuses cached weights across driver instances. |
78
+ | **Timeouts** | `timeoutMs?: number` (per request) | `requestTimeoutMs`, `startupTimeoutMs` | Independent budgets for inference vs weight loading. |
79
+ | **Choice answer** | `{ kind: 'choice', label, confidence, probabilities }` | `{ kind: 'choice', label, confidence, probabilities }` | Identical shape and probability distributions. |
80
+ | **Score answer** | `{ kind: 'score', score, confidence, legend, probabilities }` | `{ kind: 'score', score, confidence, legend, probabilities }` | Identical shape with 0-indexed rubric scores. |
81
+ | **Noul answer** | `{ kind: 'noul', probability }` | `{ kind: 'noul', probability }` | Binary yes/no probability. |
82
+
83
+ ### Intentional divergences
84
+
85
+ 1. **Noul confidence dropped:**
86
+ The reference Python implementation computes a `confidence` field for binary `noul` decisions (`max(p, 1-p)`). This field is deliberately dropped by `mapWorkerAnswer`.
87
+ *Reason:* For binary decisions, the probability already expresses confidence. Synthesizing or passing this field would make local answers type-incompatible with the hosted SDK and violate substitutability.
88
+ 2. **Action probability dropped:**
89
+ The reference Python model returns an `action: { act_probability }` channel. This field is stripped from all neutral answers.
90
+ *Reason:* The provider-neutral decision contract has no action channel; exposing it would bind callers to model-internal details.
91
+ 3. **Hardware lock:**
92
+ The local driver requires Apple Silicon macOS due to MLX dependency, whereas the hosted driver runs on any Node/Bun runtime.
93
+ 4. **Environment isolation:**
94
+ All configuration is passed via explicit `options.env` records rather than ambient `process.env` access ([ADR-011](../../docs/00_ADR.md)).
95
+
96
+ ---
97
+
98
+ ## Worker protocol (terminal debugging)
99
+
100
+ The driver communicates with `worker/laya_worker.py` over stdin/stdout using UTF-8 LF-delimited JSON Lines. You can test and debug the bridge directly in a shell:
101
+
102
+ ```sh
103
+ # 1. Start worker with model checkpoint
104
+ python3 worker/laya_worker.py --model convaiinnovations/laya-multilingual
105
+
106
+ # Output: worker emits readiness handshake:
107
+ {"ready": true, "model": "convaiinnovations/laya-multilingual", "revision": null, "maxLen": 512}
108
+
109
+ # 2. Send a request line on stdin:
110
+ {"id": "req-1", "state": "Invoice was double billed", "questions": {"dept": {"type": "choice", "instructions": "Pick team", "criteria": {"billing": "Refunds", "support": "Other"}}}}
111
+
112
+ # Output: worker prints response line:
113
+ {"id": "req-1", "ok": true, "result": {"model": "laya", "answers": {"dept": {"type": "choice", "choice": "billing", "confidence": 0.9942, "probabilities": {"billing": 0.9942, "support": 0.0058}}}}}
114
+ ```
115
+
116
+ ### Error categorization
117
+
118
+ The worker classifies errors into three kinds:
119
+ - `config` → Configuration or startup failures (missing parameters, unsupported dtype). Maps to `DecisionConfigError`.
120
+ - `request` → Malformed request syntax or invalid question specifications. Maps to `DecisionRequestError`.
121
+ - `backend` → Model numeric failures (e.g. non-finite logits). Maps to `DecisionBackendError`.
122
+
123
+ ---
124
+
125
+ ## Parity verification (two-layer check)
126
+
127
+ To keep CI fast and runnable on arbitrary platforms without downloading model weights or requiring Python, correctness is validated in two layers:
128
+
129
+ 1. **Protocol fixture layer (`bun test`):**
130
+ Runs automatically in the default test suite. Exercises request construction, line framing, correlation, answer mapping, and error translation against committed recorded lines in `tests/fixtures/protocol-lines.json` with zero skipped tests.
131
+
132
+ 2. **Full parity layer (`bun run parity`):**
133
+ Selected explicitly via `bun run parity` (or `bun scripts/full-parity.ts`) on a provisioned Apple Silicon host with `laya-mlx` and weights installed. Runs the 16 parity cases (63 questions) and reports agreement against recorded validation expectations.
134
+
135
+ ### Numerical tolerance (0.0001)
136
+
137
+ The full parity runner checks probability outputs with a tolerance of **0.0001** (`1e-4`), not exact floating-point equality.
138
+ **Reason:** The Python worker rounds output probabilities to 4 decimal places, and differences in floating-point representations across precision modes (e.g. `float16` vs `float32`) and hardware backends affect least-significant digits. A 0.0001 tolerance accommodates these representation differences while guaranteeing identical categorical decisions (argmax label and score agreement).
139
+
140
+ ---
141
+
142
+ ## Attribution
143
+
144
+ Derived from [`laya-mlx`](https://github.com/mizorewww/laya-mlx) by mizorewww, upstream source revision `fc1df62828a3fedf4d8229fdac1cbd85f1cdf337`, licensed under Apache 2.0.
145
+ Upstream NOTICE is carried forward in [NOTICE](./NOTICE) in compliance with Section 4(d) of the Apache License 2.0.
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The local Laya decision driver satisfying {@link DecisionDriver} from `@gobing-ai/ts-ai-runner`.
3
+ * Translates provider-neutral decision requests into the JSON-lines worker format
4
+ * and maps worker answers back onto neutral {@link Answer} types (task 0078).
5
+ */
6
+ import { type Answer, type DecisionDriver, type Question } from '@gobing-ai/ts-ai-runner';
7
+ import { LayaWorkerClient, type LayaWorkerClientOptions, type WorkerQuestion } from './worker-client';
8
+ /** Configuration options for {@link createLayaDriver}. */
9
+ export interface LayaDriverOptions extends LayaWorkerClientOptions {
10
+ /** Pre-constructed worker client (useful for dependency injection in tests). */
11
+ client?: LayaWorkerClient;
12
+ }
13
+ /** Convert a neutral {@link Question} into the wire shape consumed by the worker. */
14
+ export declare function toWorkerQuestion(question: Question): WorkerQuestion;
15
+ /**
16
+ * Map a raw worker answer onto the neutral {@link Answer} union (R2, R3, R4, R5).
17
+ * Drops `action.act_probability` and `noul.confidence` deliberately per contract.
18
+ */
19
+ export declare function mapWorkerAnswer(question: Question, rawAnswer: unknown): Answer;
20
+ /**
21
+ * Build the local Laya decision driver satisfying {@link DecisionDriver} (R1).
22
+ * Exposes a readonly `name: 'laya-local'` and a single `ask` method with no sugar.
23
+ */
24
+ export declare function createLayaDriver(options?: LayaDriverOptions): DecisionDriver;
25
+ //# sourceMappingURL=driver.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EACH,KAAK,MAAM,EAEX,KAAK,cAAc,EAInB,KAAK,QAAQ,EAChB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,gBAAgB,EAAE,KAAK,uBAAuB,EAAE,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEtG,0DAA0D;AAC1D,MAAM,WAAW,iBAAkB,SAAQ,uBAAuB;IAC9D,gFAAgF;IAChF,MAAM,CAAC,EAAE,gBAAgB,CAAC;CAC7B;AASD,qFAAqF;AACrF,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,GAAG,cAAc,CA8BnE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,GAAG,MAAM,CA0E9E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,iBAAsB,GAAG,cAAc,CAoChF"}
package/dist/driver.js ADDED
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The local Laya decision driver satisfying {@link DecisionDriver} from `@gobing-ai/ts-ai-runner`.
3
+ * Translates provider-neutral decision requests into the JSON-lines worker format
4
+ * and maps worker answers back onto neutral {@link Answer} types (task 0078).
5
+ */
6
+ import { DecisionBackendError, DecisionRequestError, } from '@gobing-ai/ts-ai-runner';
7
+ import { LayaWorkerClient } from './worker-client.js';
8
+ /** Format a {@link Desc} field into a string instructions value for the worker. */
9
+ function formatDesc(desc) {
10
+ if (typeof desc === 'string')
11
+ return desc;
12
+ if (desc === null || desc === undefined)
13
+ return '';
14
+ return JSON.stringify(desc);
15
+ }
16
+ /** Convert a neutral {@link Question} into the wire shape consumed by the worker. */
17
+ export function toWorkerQuestion(question) {
18
+ switch (question.kind) {
19
+ case 'choice':
20
+ return {
21
+ type: 'choice',
22
+ instructions: formatDesc(question.prompt),
23
+ labels: question.labels,
24
+ criteria: question.labels,
25
+ };
26
+ case 'score':
27
+ return {
28
+ type: 'score',
29
+ instructions: formatDesc(question.prompt),
30
+ rubric: question.rubric,
31
+ // The runtime rejects a map here: score criteria is the rubric as a
32
+ // nonempty list of descriptions (laya_mlx agent.py `_to_internal`).
33
+ criteria: question.rubric.map(formatDesc),
34
+ };
35
+ case 'noul': {
36
+ const outcomes = question.yes === undefined && question.no === undefined
37
+ ? undefined
38
+ : { true: question.yes ?? null, false: question.no ?? null };
39
+ return {
40
+ type: 'noul',
41
+ instructions: formatDesc(question.prompt),
42
+ ...(outcomes !== undefined ? { criteria: outcomes } : {}),
43
+ };
44
+ }
45
+ }
46
+ }
47
+ /**
48
+ * Map a raw worker answer onto the neutral {@link Answer} union (R2, R3, R4, R5).
49
+ * Drops `action.act_probability` and `noul.confidence` deliberately per contract.
50
+ */
51
+ export function mapWorkerAnswer(question, rawAnswer) {
52
+ if (!rawAnswer || typeof rawAnswer !== 'object' || Array.isArray(rawAnswer)) {
53
+ throw new DecisionBackendError('laya worker returned invalid answer: expected object', undefined);
54
+ }
55
+ const raw = rawAnswer;
56
+ switch (question.kind) {
57
+ case 'choice': {
58
+ const label = raw.choice ?? raw.label;
59
+ if (typeof label !== 'string' || label.length === 0) {
60
+ throw new DecisionBackendError('laya worker returned invalid choice answer: missing label', undefined);
61
+ }
62
+ const confidence = typeof raw.confidence === 'number' ? raw.confidence : 0;
63
+ const probabilities = (raw.probabilities ?? {});
64
+ return {
65
+ kind: 'choice',
66
+ label,
67
+ confidence,
68
+ probabilities,
69
+ };
70
+ }
71
+ case 'score': {
72
+ const confidence = typeof raw.confidence === 'number' ? raw.confidence : 0;
73
+ const legend = Object.fromEntries(question.rubric.map((desc, idx) => [idx, desc]));
74
+ const rawLegend = raw.legend;
75
+ const normalizedLegend = {};
76
+ if (rawLegend) {
77
+ for (const [k, v] of Object.entries(rawLegend)) {
78
+ normalizedLegend[Number(k)] = v;
79
+ }
80
+ }
81
+ const rawProbs = (raw.probabilities ?? {});
82
+ const normalizedProbs = {};
83
+ for (const [k, v] of Object.entries(rawProbs)) {
84
+ normalizedProbs[Number(k)] = v;
85
+ }
86
+ // The runtime reports score as the probability-weighted expectation
87
+ // (e.g. 1.8451); the neutral contract is the categorical rubric index —
88
+ // argmax over the per-level probabilities (validation.json semantics).
89
+ const probEntries = Object.entries(normalizedProbs);
90
+ let score;
91
+ if (probEntries.length > 0) {
92
+ score = Number(probEntries.reduce((best, cur) => (cur[1] > best[1] ? cur : best))[0]);
93
+ }
94
+ else if (typeof raw.score === 'number' && Number.isFinite(raw.score)) {
95
+ score = Math.round(raw.score);
96
+ }
97
+ else {
98
+ throw new DecisionBackendError('laya worker returned invalid score answer: no score or probabilities', undefined);
99
+ }
100
+ return {
101
+ kind: 'score',
102
+ score,
103
+ confidence,
104
+ legend: rawLegend ? normalizedLegend : legend,
105
+ probabilities: normalizedProbs,
106
+ };
107
+ }
108
+ case 'noul': {
109
+ // R4: NoulAnswer carries a bare probability by contract; confidence is dropped.
110
+ // R5: action.act_probability is dropped.
111
+ const probability = typeof raw.noul === 'number' ? raw.noul : raw.probability;
112
+ if (typeof probability !== 'number' || !Number.isFinite(probability)) {
113
+ throw new DecisionBackendError('laya worker returned invalid noul answer: missing probability', undefined);
114
+ }
115
+ return {
116
+ kind: 'noul',
117
+ probability,
118
+ };
119
+ }
120
+ }
121
+ }
122
+ /**
123
+ * Build the local Laya decision driver satisfying {@link DecisionDriver} (R1).
124
+ * Exposes a readonly `name: 'laya-local'` and a single `ask` method with no sugar.
125
+ */
126
+ export function createLayaDriver(options = {}) {
127
+ const client = options.client ?? new LayaWorkerClient(options);
128
+ return {
129
+ name: 'laya-local',
130
+ async ask({ state, questions, }) {
131
+ if (!questions || typeof questions !== 'object' || Object.keys(questions).length === 0) {
132
+ throw new DecisionRequestError('expected a nonempty question map', undefined, undefined);
133
+ }
134
+ const stateStr = typeof state === 'string' ? state : state === null || state === undefined ? '' : JSON.stringify(state);
135
+ const workerQuestions = Object.fromEntries(Object.entries(questions).map(([name, q]) => [name, toWorkerQuestion(q)]));
136
+ const result = await client.ask(stateStr, workerQuestions);
137
+ if (!result?.answers || typeof result.answers !== 'object' || Array.isArray(result.answers)) {
138
+ throw new DecisionBackendError('laya worker returned invalid result: expected answers map', undefined);
139
+ }
140
+ const answers = Object.fromEntries(Object.entries(questions).map(([name, q]) => {
141
+ const raw = result.answers[name];
142
+ if (raw === undefined) {
143
+ throw new DecisionBackendError(`laya worker missing answer for question '${name}'`, undefined);
144
+ }
145
+ return [name, mapWorkerAnswer(q, raw)];
146
+ }));
147
+ return answers;
148
+ },
149
+ };
150
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @gobing-ai/ts-laya-mlx — Local Laya decision backend driving the vendored MLX runtime.
3
+ * Implements the {@link DecisionDriver} interface for `@gobing-ai/ts-ai-runner` over a JSON-lines process bridge.
4
+ */
5
+ export { createLayaDriver, type LayaDriverOptions } from './driver';
6
+ export { LayaWorkerClient, type LayaWorkerClientOptions, type LayaWorkerResult, translateWorkerError, validateHostPrerequisites, type WorkerQuestion, } from './worker-client';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,gBAAgB,EAAE,KAAK,iBAAiB,EAAE,MAAM,UAAU,CAAC;AACpE,OAAO,EACH,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,gBAAgB,EACrB,oBAAoB,EACpB,yBAAyB,EACzB,KAAK,cAAc,GACtB,MAAM,iBAAiB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * @gobing-ai/ts-laya-mlx — Local Laya decision backend driving the vendored MLX runtime.
3
+ * Implements the {@link DecisionDriver} interface for `@gobing-ai/ts-ai-runner` over a JSON-lines process bridge.
4
+ */
5
+ export { createLayaDriver } from './driver.js';
6
+ export { LayaWorkerClient, translateWorkerError, validateHostPrerequisites, } from './worker-client.js';
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Process-lifecycle client for the laya JSON-lines worker (task 0076).
3
+ *
4
+ * Spawns `worker/laya_worker.py` through ts-runtime's `ProcessExecutor.runStreaming`
5
+ * (ADR-011/ADR-014 — the only sanctioned spawn seam), awaits the startup handshake
6
+ * before the first request, correlates responses by id, and enforces two independent
7
+ * budgets: `startupTimeoutMs` for the one-time weight load, `requestTimeoutMs` for a
8
+ * single forward pass. The worker is started lazily on the first ask and held for the
9
+ * client's lifetime; a worker that dies rejects every in-flight call and the next ask
10
+ * starts a fresh process — never a silent mid-ask restart. Only documented env keys
11
+ * reach the child, so the injected-env contract (ADR-011) holds across the process
12
+ * boundary. Protocol reference: docs/design/laya-local-decision-backend.md.
13
+ */
14
+ import { type DecisionError } from '@gobing-ai/ts-ai-runner';
15
+ import { type ProcessExecutor } from '@gobing-ai/ts-runtime';
16
+ /** Configuration options for {@link LayaWorkerClient}. */
17
+ export interface LayaWorkerClientOptions {
18
+ /** Interpreter that carries `laya-mlx`. Default: `'python3'`. */
19
+ pythonPath?: string;
20
+ /** Runtime module the worker imports. Default: `'laya_mlx'`. */
21
+ module?: string;
22
+ /** Worker script path. Default: `worker/laya_worker.py` in this package. */
23
+ workerScript?: string;
24
+ /** Working directory for the spawn. Default: this package root. */
25
+ cwd?: string;
26
+ /** Hugging Face model id. Default: worker-side (the runtime's own default). */
27
+ modelId?: string;
28
+ /** Local checkpoint directory; wins over `modelId`. */
29
+ modelPath?: string;
30
+ /** Checkpoint revision pinned for resolution. */
31
+ revision?: string;
32
+ /** Artifact cache root, exported as `HF_HUB_CACHE` inside the worker. */
33
+ cacheDir?: string;
34
+ /** Weight precision. Default: `'float16'`. */
35
+ dtype?: 'float32' | 'float16' | 'bfloat16';
36
+ /** Questions per forward pass. Default: `16`. */
37
+ batchSize?: number;
38
+ /** Budget for the startup handshake, which covers the one-time weight load. Default: `120_000`. */
39
+ startupTimeoutMs?: number;
40
+ /** Budget for one request once the worker is ready. Default: `30_000`. */
41
+ requestTimeoutMs?: number;
42
+ /** Injected environment record — this package never reads the ambient environment (ADR-011). */
43
+ env?: Record<string, string | undefined>;
44
+ /** Platform name for prerequisite validation. Default: `process.platform`. */
45
+ platform?: string;
46
+ /** Architecture name for prerequisite validation. Default: `process.arch`. */
47
+ arch?: string;
48
+ }
49
+ /**
50
+ * Project the injected environment onto the child allowlist. Everything absent from
51
+ * `FORWARDED_ENV_KEYS` is dropped, so the parent environment is never inherited
52
+ * wholesale and the child gets exactly the documented keys that are set.
53
+ */
54
+ export declare function resolveForwardedEnv(env: Record<string, string | undefined> | undefined): Record<string, string>;
55
+ /** Worker-level question — the reference format `predict` consumes. Neutral-shape mapping lands with the driver facade. */
56
+ export interface WorkerQuestion {
57
+ type: 'choice' | 'score' | 'noul';
58
+ instructions: string;
59
+ [key: string]: unknown;
60
+ }
61
+ /** The runtime's own `predict` payload, passed through unaltered. */
62
+ export interface LayaWorkerResult {
63
+ model: string;
64
+ answers: Record<string, unknown>;
65
+ usage?: Record<string, unknown>;
66
+ }
67
+ /**
68
+ * Validate host platform prerequisites for `@gobing-ai/ts-laya-mlx`.
69
+ * Throws {@link DecisionConfigError} if the platform is not Apple Silicon macOS.
70
+ */
71
+ export declare function validateHostPrerequisites(platform?: string, arch?: string): void;
72
+ /**
73
+ * Map worker-reported error kinds and messages onto the decision taxonomy (design: Errors table, task 0077).
74
+ */
75
+ export declare function translateWorkerError(kind: string | undefined, message: string): DecisionError;
76
+ /**
77
+ * TypeScript half of the laya process bridge: start the Python worker lazily,
78
+ * hold it warm for the client's lifetime, and serve serialized asks with
79
+ * id-correlated, timeout-bounded responses.
80
+ */
81
+ export declare class LayaWorkerClient {
82
+ private readonly pythonPath;
83
+ private readonly args;
84
+ private readonly cwd;
85
+ private readonly startupTimeoutMs;
86
+ private readonly requestTimeoutMs;
87
+ private readonly forwardedEnv;
88
+ private readonly executor;
89
+ private worker;
90
+ private chain;
91
+ private disposed;
92
+ constructor(options?: LayaWorkerClientOptions, executor?: ProcessExecutor);
93
+ /**
94
+ * Ask one batch of worker-format questions. Requests are serialized — the
95
+ * worker serves one request at a time and batching happens inside a single
96
+ * request — and the worker spawns lazily on the first call, so the weight
97
+ * load is paid once per client.
98
+ */
99
+ ask(state: string, questions: Record<string, WorkerQuestion>): Promise<LayaWorkerResult>;
100
+ /** Close the worker; safe to call repeatedly. In-flight calls reject through the exit watcher. */
101
+ dispose(): void;
102
+ private dispatch;
103
+ private ensureWorker;
104
+ private spawn;
105
+ }
106
+ //# sourceMappingURL=worker-client.d.ts.map