@gobing-ai/ts-decision-fm 0.5.3
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 +176 -0
- package/NOTICE +5 -0
- package/README.md +149 -0
- package/dist/driver.d.ts +48 -0
- package/dist/driver.d.ts.map +1 -0
- package/dist/driver.js +105 -0
- package/dist/estimate.d.ts +26 -0
- package/dist/estimate.d.ts.map +1 -0
- package/dist/estimate.js +90 -0
- package/dist/fm-process.d.ts +52 -0
- package/dist/fm-process.d.ts.map +1 -0
- package/dist/fm-process.js +137 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/schema.d.ts +43 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +104 -0
- package/package.json +63 -0
- package/src/driver.ts +206 -0
- package/src/estimate.ts +97 -0
- package/src/fm-process.ts +187 -0
- package/src/index.ts +21 -0
- package/src/schema.ts +120 -0
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
package/README.md
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
# @gobing-ai/ts-decision-fm
|
|
2
|
+
|
|
3
|
+
Apple on-device Foundation Model decision backend for the neutral decision
|
|
4
|
+
surface owned by `@gobing-ai/ts-ai-runner`: answers `choice` / `score` / `noul`
|
|
5
|
+
questions on-device by driving the macOS 27 `fm` command-line tool as one-shot
|
|
6
|
+
processes over `ts-runtime`'s `ProcessExecutor`
|
|
7
|
+
([ADR-029](../../docs/00_ADR.md)). Probabilities are empirical sample
|
|
8
|
+
frequencies — the model is never asked for a confidence
|
|
9
|
+
([ADR-030](../../docs/00_ADR.md)).
|
|
10
|
+
|
|
11
|
+
Part of the `@gobing-ai/ts-libs` monorepo and lockstep-versioned with it.
|
|
12
|
+
|
|
13
|
+
- **License:** Apache-2.0 (see [LICENSE](./LICENSE)).
|
|
14
|
+
- **No model weights or third-party code are bundled.** The engine is the `fm`
|
|
15
|
+
system binary on the host.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Host prerequisites
|
|
20
|
+
|
|
21
|
+
1. **Platform:** macOS on Apple Silicon (`darwin arm64`). Unsupported hosts fail
|
|
22
|
+
at construction with a `DecisionConfigError`, before any process is spawned.
|
|
23
|
+
2. **`fm` CLI:** macOS 27+ ships `/usr/bin/fm` (validated against build
|
|
24
|
+
`FoundationModels-2.0.68.1.402`). A custom path can be injected via
|
|
25
|
+
`fmPath`. A missing binary is reported as `DecisionConfigError` "fm not
|
|
26
|
+
found" on the first ask.
|
|
27
|
+
3. **System model availability:** probed once per driver with
|
|
28
|
+
`fm available --model system` before the first sample and cached for the
|
|
29
|
+
driver's lifetime. A model that is present but not ready raises
|
|
30
|
+
`DecisionConfigError` carrying fm's reason (e.g. `modelNotReady`).
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { createFmDriver } from '@gobing-ai/ts-decision-fm';
|
|
38
|
+
|
|
39
|
+
const driver = createFmDriver(); // defaults; or createFmDriver({ samples: 7 })
|
|
40
|
+
const answers = await driver.ask({
|
|
41
|
+
state: 'Customer was billed twice for invoice INV-42.',
|
|
42
|
+
questions: {
|
|
43
|
+
sentiment: {
|
|
44
|
+
kind: 'choice',
|
|
45
|
+
prompt: 'Sentiment of the message',
|
|
46
|
+
labels: { positive: 'Praise', negative: 'Complaint' },
|
|
47
|
+
},
|
|
48
|
+
priority: {
|
|
49
|
+
kind: 'score',
|
|
50
|
+
prompt: 'Queue priority',
|
|
51
|
+
rubric: ['Routine — normal SLA', 'Critical — customer blocked'],
|
|
52
|
+
},
|
|
53
|
+
refund: { kind: 'noul', prompt: 'Refund the duplicate charge?' },
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
// answers.sentiment: { kind: 'choice', label, confidence, probabilities }
|
|
57
|
+
// answers.priority: { kind: 'score', score, confidence, legend, probabilities }
|
|
58
|
+
// answers.refund: { kind: 'noul', probability }
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The `model` argument of `ask` accepts only `undefined` or `'system'` — the
|
|
62
|
+
on-device system model is the only one fm offers; anything else raises
|
|
63
|
+
`DecisionRequestError`.
|
|
64
|
+
|
|
65
|
+
### Options
|
|
66
|
+
|
|
67
|
+
| Option | Default | Meaning |
|
|
68
|
+
|--------|---------|---------|
|
|
69
|
+
| `samples` | `5` | Sequential `fm respond` samples per ask. Ignored when `deterministic`. |
|
|
70
|
+
| `deterministic` | `false` | One greedy sample (`fm respond -g`); probabilities are one-hot, confidence 1. |
|
|
71
|
+
| `maxPromptTokens` | `6000` | Pre-flight budget. The rendered prompt is counted with `fm count-tokens -q` before sampling; over budget raises `DecisionRequestError` and no model call runs. |
|
|
72
|
+
| `requestTimeoutMs` | `30000` | Budget for one `fm respond` process; expiry raises `DecisionTimeoutError`. |
|
|
73
|
+
| `guardrails` | omitted | `--guardrails` level (`'default'` \| `'permissive-content-transformations'`). |
|
|
74
|
+
| `fmPath` | `'fm'` | Executable to spawn. |
|
|
75
|
+
| `executor` | ts-runtime `ProcessExecutor` | Injected process seam (tests stub this). |
|
|
76
|
+
| `platform`, `arch` | `process.platform`, `process.arch` | Injectable host facts so tests can pin the host. |
|
|
77
|
+
|
|
78
|
+
### Backend selection (`ts-ai-runner`)
|
|
79
|
+
|
|
80
|
+
The `fm-local` backend name joins `createDecisionMaker` via `ts-ai-runner`
|
|
81
|
+
(task 0085); `ts-ai-runner` resolves `@gobing-ai/ts-decision-fm` through a
|
|
82
|
+
dynamic import, the same way `laya-local` resolves `ts-laya-mlx`. Callers who
|
|
83
|
+
need non-default options pass the driver explicitly:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
import { createDecisionMaker } from '@gobing-ai/ts-ai-runner';
|
|
87
|
+
import { createFmDriver } from '@gobing-ai/ts-decision-fm';
|
|
88
|
+
|
|
89
|
+
const dm = createDecisionMaker({ driver: createFmDriver({ deterministic: true }) });
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Estimator semantics (read before trusting `confidence`)
|
|
95
|
+
|
|
96
|
+
Every probability this driver returns is a **frequency over k parsed samples**
|
|
97
|
+
(`estimator: { kind: 'sample-frequency' }`):
|
|
98
|
+
|
|
99
|
+
- `choice` — `probabilities[label] = count(label) / k` for every supplied label
|
|
100
|
+
(unsampled labels get 0). `label` is the most frequent with ties broken by
|
|
101
|
+
label declaration order.
|
|
102
|
+
- `score` — the same over level indices; ties go to the lower level.
|
|
103
|
+
- `noul` — a bare yes-probability, no `confidence` key, by contract.
|
|
104
|
+
|
|
105
|
+
`confidence` is `1 − H(p) / ln(n)` over the declared options — the Laya
|
|
106
|
+
reference's `confidence_from_probs` on the empirical distribution. It measures
|
|
107
|
+
**how much the samples agreed, not calibration**. The model is never asked for a
|
|
108
|
+
confidence; a self-reported one would be fabricated calibration.
|
|
109
|
+
|
|
110
|
+
Resolution limit: with k samples every probability is a multiple of 1/k, and
|
|
111
|
+
`confidence` has at most k+1 distinct values. k = 5 detects a 60/40 split, not a
|
|
112
|
+
64/36 one. In deterministic mode k = 1, so every answer is one-hot with
|
|
113
|
+
confidence 1.
|
|
114
|
+
|
|
115
|
+
### Latency
|
|
116
|
+
|
|
117
|
+
fm one-shot calls cost ~0.3 s warm each, so an ask costs **~0.3 s × k** (plus
|
|
118
|
+
one `count-tokens` call). Calls are sequential by design: parallel sampling is
|
|
119
|
+
out of scope and fm exposes no logprobs that would make batching worthwhile
|
|
120
|
+
(ADR-029).
|
|
121
|
+
|
|
122
|
+
---
|
|
123
|
+
|
|
124
|
+
## Errors
|
|
125
|
+
|
|
126
|
+
All failures surface through the `@gobing-ai/ts-ai-runner` decision error
|
|
127
|
+
taxonomy — never as an answer:
|
|
128
|
+
|
|
129
|
+
| Condition | Class |
|
|
130
|
+
|-----------|-------|
|
|
131
|
+
| Not darwin/arm64; `fm` not found; system model unavailable | `DecisionConfigError` |
|
|
132
|
+
| `model` other than `system`; prompt over `maxPromptTokens`; fewer than two options | `DecisionRequestError` |
|
|
133
|
+
| fm reports the context size was exceeded | `DecisionRequestError` |
|
|
134
|
+
| fm reports the safety guardrails were triggered | `DecisionBackendError` (not retried) |
|
|
135
|
+
| Other non-zero exit; non-JSON stdout; schema violation | `DecisionBackendError` |
|
|
136
|
+
| A sample exceeded `requestTimeoutMs` | `DecisionTimeoutError` |
|
|
137
|
+
|
|
138
|
+
Failure is all-or-nothing: one failed sample rejects the whole ask. Partial
|
|
139
|
+
frequencies are never returned as probabilities.
|
|
140
|
+
|
|
141
|
+
---
|
|
142
|
+
|
|
143
|
+
## Testing
|
|
144
|
+
|
|
145
|
+
The default suite is stubbed (injected `ProcessExecutor`, pinned
|
|
146
|
+
`darwin`/`arm64`) and runs on every platform including Linux CI. The live suite
|
|
147
|
+
(`tests/live.test.ts`) runs only where the system model is actually available
|
|
148
|
+
(darwin/arm64 and `fm available --model system` exits 0) and skips with a stated
|
|
149
|
+
reason everywhere else.
|
package/dist/driver.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Apple `fm` decision driver (task 0084 R2, R8, R9; design § Main export).
|
|
3
|
+
* Satisfies the same {@link DecisionDriver} contract as the other backends over
|
|
4
|
+
* one-shot `fm` processes: one schema per ask answers the whole question map,
|
|
5
|
+
* probabilities come from k sample frequencies (ADR-030), and every failure
|
|
6
|
+
* surfaces through the decision error taxonomy — never as an answer.
|
|
7
|
+
*/
|
|
8
|
+
import { type DecisionDriver } from '@gobing-ai/ts-ai-runner';
|
|
9
|
+
import { type ProcessExecutor } from '@gobing-ai/ts-runtime';
|
|
10
|
+
import { type FmGuardrails } from './fm-process';
|
|
11
|
+
/** Configuration options for {@link createFmDriver}. */
|
|
12
|
+
export interface FmDriverOptions {
|
|
13
|
+
/** Samples per ask. Default: 5. Ignored when `deterministic` is true. */
|
|
14
|
+
samples?: number;
|
|
15
|
+
/** One greedy sample (`fm respond -g`); probabilities are one-hot. Default: false. */
|
|
16
|
+
deterministic?: boolean;
|
|
17
|
+
/** Prompt-token budget checked with `fm count-tokens` before sampling. Default: 6_000. */
|
|
18
|
+
maxPromptTokens?: number;
|
|
19
|
+
/** Budget for one `fm respond` process. Default: 30_000. */
|
|
20
|
+
requestTimeoutMs?: number;
|
|
21
|
+
/** `--guardrails` level. Default: omitted (fm's `default`). */
|
|
22
|
+
guardrails?: FmGuardrails;
|
|
23
|
+
/** Executable. Default: 'fm'. */
|
|
24
|
+
fmPath?: string;
|
|
25
|
+
/** Injected process seam. Default: ts-runtime's ProcessExecutor. */
|
|
26
|
+
executor?: ProcessExecutor;
|
|
27
|
+
/** Host platform, injectable so tests pin the host. Default: `process.platform` (as laya-mlx). */
|
|
28
|
+
platform?: string;
|
|
29
|
+
/** Host architecture. Default: `process.arch`. */
|
|
30
|
+
arch?: string;
|
|
31
|
+
}
|
|
32
|
+
/** The fm driver: a {@link DecisionDriver} with a declared estimator (ADR-030). */
|
|
33
|
+
export interface FmDecisionDriver extends DecisionDriver {
|
|
34
|
+
readonly name: 'fm-local';
|
|
35
|
+
/** Declared estimator — how every probability this driver returns was produced. */
|
|
36
|
+
readonly estimator: {
|
|
37
|
+
readonly kind: 'sample-frequency';
|
|
38
|
+
readonly samples: number;
|
|
39
|
+
readonly greedy: boolean;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Build the `fm-local` decision driver. Host platform/architecture is checked
|
|
44
|
+
* here, at construction, without spawning (R8); the `fm` availability probe
|
|
45
|
+
* runs once, on the first `ask`, and is cached for the driver's lifetime.
|
|
46
|
+
*/
|
|
47
|
+
export declare function createFmDriver(options?: FmDriverOptions): FmDecisionDriver;
|
|
48
|
+
//# sourceMappingURL=driver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"driver.d.ts","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAGH,KAAK,cAAc,EAItB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAKH,KAAK,eAAe,EACvB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAEH,KAAK,YAAY,EAMpB,MAAM,cAAc,CAAC;AAGtB,wDAAwD;AACxD,MAAM,WAAW,eAAe;IAC5B,yEAAyE;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,sFAAsF;IACtF,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,0FAA0F;IAC1F,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,4DAA4D;IAC5D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,+DAA+D;IAC/D,UAAU,CAAC,EAAE,YAAY,CAAC;IAC1B,iCAAiC;IACjC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oEAAoE;IACpE,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,kGAAkG;IAClG,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,kDAAkD;IAClD,IAAI,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,mFAAmF;AACnF,MAAM,WAAW,gBAAiB,SAAQ,cAAc;IACpD,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,mFAAmF;IACnF,QAAQ,CAAC,SAAS,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;QAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAA;KAAE,CAAC;CACjH;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,GAAE,eAAoB,GAAG,gBAAgB,CAwI9E"}
|
package/dist/driver.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Apple `fm` decision driver (task 0084 R2, R8, R9; design § Main export).
|
|
3
|
+
* Satisfies the same {@link DecisionDriver} contract as the other backends over
|
|
4
|
+
* one-shot `fm` processes: one schema per ask answers the whole question map,
|
|
5
|
+
* probabilities come from k sample frequencies (ADR-030), and every failure
|
|
6
|
+
* surfaces through the decision error taxonomy — never as an answer.
|
|
7
|
+
*/
|
|
8
|
+
import { DecisionConfigError, DecisionRequestError, } from '@gobing-ai/ts-ai-runner';
|
|
9
|
+
import { createNodeFileSystem, getProcessEnv, joinPath, nodeBunFactory, } from '@gobing-ai/ts-runtime';
|
|
10
|
+
import { estimateChoice, estimateNoul, estimateScore } from './estimate.js';
|
|
11
|
+
import { countPromptTokens, parseFmRespond, probeFmAvailability, requireEnumValue, respondArgv, runFmRespond, } from './fm-process.js';
|
|
12
|
+
import { buildFmSchema, buildPrompt, declaredOptions, FM_INSTRUCTIONS } from './schema.js';
|
|
13
|
+
/**
|
|
14
|
+
* Build the `fm-local` decision driver. Host platform/architecture is checked
|
|
15
|
+
* here, at construction, without spawning (R8); the `fm` availability probe
|
|
16
|
+
* runs once, on the first `ask`, and is cached for the driver's lifetime.
|
|
17
|
+
*/
|
|
18
|
+
export function createFmDriver(options = {}) {
|
|
19
|
+
const { samples = 5, deterministic = false, maxPromptTokens = 6_000, requestTimeoutMs = 30_000, guardrails, fmPath = 'fm', executor = nodeBunFactory.createProcessExecutor(), platform = process.platform, arch = process.arch, } = options;
|
|
20
|
+
if (!Number.isInteger(samples) || samples < 1) {
|
|
21
|
+
throw new DecisionRequestError(`samples must be a positive integer; got ${samples}`, undefined, undefined);
|
|
22
|
+
}
|
|
23
|
+
const k = deterministic ? 1 : samples;
|
|
24
|
+
if (platform !== 'darwin' || arch !== 'arm64') {
|
|
25
|
+
throw new DecisionConfigError(`decision-fm requires macOS on Apple Silicon (darwin arm64); current platform is '${platform} ${arch}'`, 'PLATFORM');
|
|
26
|
+
}
|
|
27
|
+
const fs = createNodeFileSystem();
|
|
28
|
+
let availabilityVerified = false;
|
|
29
|
+
async function ensureFmAvailable() {
|
|
30
|
+
if (availabilityVerified)
|
|
31
|
+
return;
|
|
32
|
+
await probeFmAvailability(executor, fmPath);
|
|
33
|
+
availabilityVerified = true;
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
name: 'fm-local',
|
|
37
|
+
estimator: { kind: 'sample-frequency', samples: k, greedy: deterministic },
|
|
38
|
+
async ask({ state, questions, model, }) {
|
|
39
|
+
// R9: only the on-device system model exists (design: fm CLI facts).
|
|
40
|
+
if (model !== undefined && model !== 'system') {
|
|
41
|
+
throw new DecisionRequestError(`fm-local supports only the 'system' model (or undefined); got '${model}'`, undefined, undefined);
|
|
42
|
+
}
|
|
43
|
+
const entries = Object.entries(questions);
|
|
44
|
+
if (entries.length === 0) {
|
|
45
|
+
throw new DecisionRequestError('expected a nonempty question map', undefined, undefined);
|
|
46
|
+
}
|
|
47
|
+
for (const [key, question] of entries) {
|
|
48
|
+
const optionCount = question.kind === 'choice'
|
|
49
|
+
? Object.keys(question.labels).length
|
|
50
|
+
: question.kind === 'score'
|
|
51
|
+
? question.rubric.length
|
|
52
|
+
: 2; // noul is binary by type
|
|
53
|
+
if (optionCount < 2) {
|
|
54
|
+
throw new DecisionRequestError(`question '${key}' has fewer than two options (${optionCount})`, undefined, undefined);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// R8: prerequisite probe before the first sample; cached per driver.
|
|
58
|
+
await ensureFmAvailable();
|
|
59
|
+
const instructions = FM_INSTRUCTIONS;
|
|
60
|
+
const prompt = buildPrompt(state, questions);
|
|
61
|
+
// R4: pre-flight budget — over budget rejects before any `fm respond`.
|
|
62
|
+
const tokens = await countPromptTokens(executor, fmPath, instructions, prompt);
|
|
63
|
+
if (tokens > maxPromptTokens) {
|
|
64
|
+
throw new DecisionRequestError(`prompt is ${tokens} tokens, above the maxPromptTokens budget of ${maxPromptTokens}`, undefined, undefined);
|
|
65
|
+
}
|
|
66
|
+
// R3: one schema per ask over the whole question map, in a uniquely
|
|
67
|
+
// named temp file, deleted in `finally` on success and failure.
|
|
68
|
+
const schemaPath = joinPath(getProcessEnv().TMPDIR ?? '/tmp', `fm-schema-${crypto.randomUUID()}.json`);
|
|
69
|
+
try {
|
|
70
|
+
fs.writeFile(schemaPath, JSON.stringify(buildFmSchema(questions)));
|
|
71
|
+
// R5: k sequential samples; each stdout parsed as JSON, read by key.
|
|
72
|
+
const allowed = new Map(entries.map(([key, question]) => [key, declaredOptions(question)]));
|
|
73
|
+
const samplesByKey = new Map(entries.map(([key]) => [key, []]));
|
|
74
|
+
for (let i = 0; i < k; i++) {
|
|
75
|
+
const stdout = await runFmRespond(executor, fmPath, respondArgv({ schemaPath, instructions, prompt, greedy: deterministic, guardrails }), requestTimeoutMs);
|
|
76
|
+
const parsed = parseFmRespond(stdout);
|
|
77
|
+
for (const [key, values] of samplesByKey) {
|
|
78
|
+
values.push(requireEnumValue(parsed, key, allowed.get(key) ?? []));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// R6: frequencies over the declared labels/levels, argmax with
|
|
82
|
+
// declaration-order / lower-level tie-break, entropy confidence.
|
|
83
|
+
const answers = {};
|
|
84
|
+
for (const [key, question] of entries) {
|
|
85
|
+
const values = samplesByKey.get(key) ?? [];
|
|
86
|
+
switch (question.kind) {
|
|
87
|
+
case 'choice':
|
|
88
|
+
answers[key] = estimateChoice(Object.keys(question.labels), values);
|
|
89
|
+
break;
|
|
90
|
+
case 'score':
|
|
91
|
+
answers[key] = estimateScore(question.rubric, values);
|
|
92
|
+
break;
|
|
93
|
+
case 'noul':
|
|
94
|
+
answers[key] = estimateNoul(values);
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return answers;
|
|
99
|
+
}
|
|
100
|
+
finally {
|
|
101
|
+
fs.deleteFile(schemaPath);
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Probability estimation from repeated samples (task 0084 R6, ADR-030,
|
|
3
|
+
* design § Probability estimation). Every probability is an empirical sample
|
|
4
|
+
* frequency — never a self-reported confidence — so the resolution limit is
|
|
5
|
+
* 1/k and `confidence` measures how much the k samples agreed, not calibration.
|
|
6
|
+
*/
|
|
7
|
+
import type { ChoiceAnswer, Desc, NoulAnswer, ScoreAnswer } from '@gobing-ai/ts-ai-runner';
|
|
8
|
+
/**
|
|
9
|
+
* Laya reference `confidence_from_probs` on the empirical distribution:
|
|
10
|
+
* `1 − H(p) / ln(n)` over the n declared options. One-hot ⇒ 1, uniform ⇒ 0.
|
|
11
|
+
*/
|
|
12
|
+
export declare function entropyConfidence(probabilities: number[]): number;
|
|
13
|
+
/**
|
|
14
|
+
* Choice frequencies over every supplied label (unsampled ⇒ 0). The answer
|
|
15
|
+
* label is the most frequent with ties broken by label declaration order.
|
|
16
|
+
*/
|
|
17
|
+
export declare function estimateChoice(labels: readonly string[], samples: readonly string[]): ChoiceAnswer<string>;
|
|
18
|
+
/**
|
|
19
|
+
* Score frequencies over the level indices `0…n-1`. The answer score is the
|
|
20
|
+
* most frequent level with ties going to the lower level; the legend maps each
|
|
21
|
+
* index back to its rubric description.
|
|
22
|
+
*/
|
|
23
|
+
export declare function estimateScore(rubric: readonly Desc[], samples: readonly string[]): ScoreAnswer;
|
|
24
|
+
/** Noul is a bare yes-probability — no `confidence` key, by contract. */
|
|
25
|
+
export declare function estimateNoul(samples: readonly string[]): NoulAnswer;
|
|
26
|
+
//# sourceMappingURL=estimate.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"estimate.d.ts","sourceRoot":"","sources":["../src/estimate.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EAAE,YAAY,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAC;AAC3F;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,aAAa,EAAE,MAAM,EAAE,GAAG,MAAM,CAQjE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,CAyB1G;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,WAAW,CAiC9F;AAED,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,CAGnE"}
|
package/dist/estimate.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Laya reference `confidence_from_probs` on the empirical distribution:
|
|
3
|
+
* `1 − H(p) / ln(n)` over the n declared options. One-hot ⇒ 1, uniform ⇒ 0.
|
|
4
|
+
*/
|
|
5
|
+
export function entropyConfidence(probabilities) {
|
|
6
|
+
const n = probabilities.length;
|
|
7
|
+
if (n <= 1)
|
|
8
|
+
return 1;
|
|
9
|
+
let entropy = 0;
|
|
10
|
+
for (const p of probabilities) {
|
|
11
|
+
if (p > 0)
|
|
12
|
+
entropy -= p * Math.log(p);
|
|
13
|
+
}
|
|
14
|
+
return 1 - entropy / Math.log(n);
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Choice frequencies over every supplied label (unsampled ⇒ 0). The answer
|
|
18
|
+
* label is the most frequent with ties broken by label declaration order.
|
|
19
|
+
*/
|
|
20
|
+
export function estimateChoice(labels, samples) {
|
|
21
|
+
const counts = new Map(labels.map((label) => [label, 0]));
|
|
22
|
+
for (const sample of samples)
|
|
23
|
+
counts.set(sample, (counts.get(sample) ?? 0) + 1);
|
|
24
|
+
const k = samples.length;
|
|
25
|
+
const probabilities = {};
|
|
26
|
+
const distribution = [];
|
|
27
|
+
let bestLabel = labels[0] ?? '';
|
|
28
|
+
let bestCount = -1;
|
|
29
|
+
for (const label of labels) {
|
|
30
|
+
const count = counts.get(label) ?? 0;
|
|
31
|
+
const probability = count / k;
|
|
32
|
+
distribution.push(probability);
|
|
33
|
+
probabilities[label] = probability;
|
|
34
|
+
// Declaration order wins ties: strict `>` keeps the earlier label.
|
|
35
|
+
if (count > bestCount) {
|
|
36
|
+
bestCount = count;
|
|
37
|
+
bestLabel = label;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
kind: 'choice',
|
|
42
|
+
label: bestLabel,
|
|
43
|
+
confidence: entropyConfidence(distribution),
|
|
44
|
+
probabilities,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Score frequencies over the level indices `0…n-1`. The answer score is the
|
|
49
|
+
* most frequent level with ties going to the lower level; the legend maps each
|
|
50
|
+
* index back to its rubric description.
|
|
51
|
+
*/
|
|
52
|
+
export function estimateScore(rubric, samples) {
|
|
53
|
+
const k = samples.length;
|
|
54
|
+
const counts = [];
|
|
55
|
+
for (const sample of samples) {
|
|
56
|
+
const level = Number.parseInt(sample, 10);
|
|
57
|
+
counts[level] = (counts[level] ?? 0) + 1;
|
|
58
|
+
}
|
|
59
|
+
const probabilities = {};
|
|
60
|
+
const distribution = [];
|
|
61
|
+
let bestLevel = 0;
|
|
62
|
+
let bestCount = -1;
|
|
63
|
+
for (let level = 0; level < rubric.length; level++) {
|
|
64
|
+
const count = counts[level] ?? 0;
|
|
65
|
+
const probability = count / k;
|
|
66
|
+
distribution.push(probability);
|
|
67
|
+
probabilities[level] = probability;
|
|
68
|
+
// Lower level wins ties: strict `>` keeps the smaller index.
|
|
69
|
+
if (count > bestCount) {
|
|
70
|
+
bestCount = count;
|
|
71
|
+
bestLevel = level;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const legend = {};
|
|
75
|
+
rubric.forEach((desc, level) => {
|
|
76
|
+
legend[level] = desc;
|
|
77
|
+
});
|
|
78
|
+
return {
|
|
79
|
+
kind: 'score',
|
|
80
|
+
score: bestLevel,
|
|
81
|
+
confidence: entropyConfidence(distribution),
|
|
82
|
+
legend,
|
|
83
|
+
probabilities,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
/** Noul is a bare yes-probability — no `confidence` key, by contract. */
|
|
87
|
+
export function estimateNoul(samples) {
|
|
88
|
+
const yes = samples.filter((sample) => sample === 'yes').length;
|
|
89
|
+
return { kind: 'noul', probability: yes / samples.length };
|
|
90
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one-shot `fm` process bridge (task 0084 R4, R5, R7, R8; design § Errors).
|
|
3
|
+
* Argv builders plus run/error mapping. Spawned exclusively through the
|
|
4
|
+
* injected ts-runtime {@link ProcessExecutor} — never `node:child_process`.
|
|
5
|
+
* Prompt and instructions travel as positional arguments because
|
|
6
|
+
* `ProcessExecutor.run` has no stdin input; fm's argv limit is far above the
|
|
7
|
+
* token budget, and the pre-flight `count-tokens` check keeps it bounded.
|
|
8
|
+
*/
|
|
9
|
+
import type { ProcessExecutor } from '@gobing-ai/ts-runtime';
|
|
10
|
+
/** `--guardrails` levels accepted by `fm respond` (design: fm CLI facts). */
|
|
11
|
+
export type FmGuardrails = 'default' | 'permissive-content-transformations';
|
|
12
|
+
/** Subcommand + flag order verified against the design's live observations. */
|
|
13
|
+
export declare function countTokensArgv(instructions: string, prompt: string): string[];
|
|
14
|
+
/** Builds the `fm respond` argv: schema flag, `-i` instructions, positional prompt, optional `-g`/`--guardrails`. */
|
|
15
|
+
export declare function respondArgv(options: {
|
|
16
|
+
schemaPath: string;
|
|
17
|
+
instructions: string;
|
|
18
|
+
prompt: string;
|
|
19
|
+
/** Deterministic mode: single greedy sample. */
|
|
20
|
+
greedy?: boolean;
|
|
21
|
+
/** Omitted ⇒ the flag is omitted (fm's `default`). */
|
|
22
|
+
guardrails?: FmGuardrails;
|
|
23
|
+
}): string[];
|
|
24
|
+
/** Bare `fm available` always exits 0 — only `--model system` is a real probe. */
|
|
25
|
+
export declare function availableArgv(): string[];
|
|
26
|
+
/**
|
|
27
|
+
* R8 prerequisite probe: `fm available --model system`. A spawn failure maps to
|
|
28
|
+
* `DecisionConfigError` "fm not found"; a non-zero exit carries fm's printed
|
|
29
|
+
* reason (e.g. `modelNotReady`). An exit 0 caches availability in the driver.
|
|
30
|
+
*/
|
|
31
|
+
export declare function probeFmAvailability(executor: ProcessExecutor, fmPath: string): Promise<void>;
|
|
32
|
+
/**
|
|
33
|
+
* R4 pre-flight: `fm count-tokens -q -i <instructions> <prompt>` prints a bare
|
|
34
|
+
* integer. Non-zero exit or unparseable output is a `DecisionBackendError` —
|
|
35
|
+
* the budget comparison itself happens in the driver.
|
|
36
|
+
*/
|
|
37
|
+
export declare function countPromptTokens(executor: ProcessExecutor, fmPath: string, instructions: string, prompt: string): Promise<number>;
|
|
38
|
+
/**
|
|
39
|
+
* One `fm respond` sample: run with the per-sample timeout, map every failure
|
|
40
|
+
* row of the error table, return stdout on success (parsing happens in
|
|
41
|
+
* {@link parseFmRespond}).
|
|
42
|
+
*/
|
|
43
|
+
export declare function runFmRespond(executor: ProcessExecutor, fmPath: string, args: string[], requestTimeoutMs: number): Promise<string>;
|
|
44
|
+
/**
|
|
45
|
+
* Parse one sample's stdout as the schema-conformant JSON object. fm prints one
|
|
46
|
+
* JSON object per call, but the key order varies — callers read by key, never
|
|
47
|
+
* by position. Non-JSON or non-object output is a `DecisionBackendError`.
|
|
48
|
+
*/
|
|
49
|
+
export declare function parseFmRespond(stdout: string): Record<string, string>;
|
|
50
|
+
/** A parsed value outside the declared enum is a schema violation, never an answer (R7). */
|
|
51
|
+
export declare function requireEnumValue(parsed: Record<string, string>, key: string, allowed: readonly string[]): string;
|
|
52
|
+
//# sourceMappingURL=fm-process.d.ts.map
|