@zhin.js/service-typesafe 1.0.14 → 1.0.16
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/README.md +54 -79
- package/lib/decision-provider.d.ts +1 -1
- package/lib/decision-provider.d.ts.map +1 -1
- package/lib/decision-provider.js +29 -14
- package/lib/decision-provider.js.map +1 -1
- package/lib/index.d.ts +1 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/provider.d.ts +20 -0
- package/lib/provider.d.ts.map +1 -0
- package/lib/provider.js +102 -0
- package/lib/provider.js.map +1 -0
- package/lib/response-validator.d.ts +1 -1
- package/lib/response-validator.d.ts.map +1 -1
- package/package.json +5 -6
- package/plugin.js +3 -8
- package/schema.json +1 -73
- package/src/decision-provider.ts +25 -10
- package/src/index.ts +1 -1
- package/src/provider.ts +95 -0
- package/src/response-validator.ts +1 -1
package/README.md
CHANGED
|
@@ -1,30 +1,12 @@
|
|
|
1
|
-
# TypeSafe
|
|
1
|
+
# TypeSafe Decision Provider
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
## Install and configure
|
|
3
|
+
Publishes the real TypeSafe Choice, Score and Noul protocol for Zhin's operation-bound inference runtime. It does not turn chat JSON into a decision model.
|
|
6
4
|
|
|
7
5
|
```sh
|
|
8
6
|
pnpm add @zhin.js/service-typesafe
|
|
9
7
|
```
|
|
10
8
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
```dotenv
|
|
14
|
-
TYPESAFE_API_KEY=your-key
|
|
15
|
-
```
|
|
16
|
-
|
|
17
|
-
Run the optional wizard after configuring your chat Agent:
|
|
18
|
-
|
|
19
|
-
```sh
|
|
20
|
-
zhin setup --decisions
|
|
21
|
-
pnpm install
|
|
22
|
-
zhin doctor
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
The wizard keeps your chat model, writes the key to `.env`, installs the plugin manifest entry and starts Skill / Tool recommendations in `shadow` mode. On first setup, Agent selection, memory reranking and automatic approval start `off`. Reconfiguration preserves existing task settings and thresholds. Separate instances use separate key environment variables; an existing explicit key reference is preserved.
|
|
26
|
-
|
|
27
|
-
For manual configuration, declare the plugin in `zhin.config.yml`:
|
|
9
|
+
Register the plugin normally:
|
|
28
10
|
|
|
29
11
|
```yaml
|
|
30
12
|
configVersion: 2
|
|
@@ -32,79 +14,72 @@ plugins:
|
|
|
32
14
|
typesafe: '@zhin.js/service-typesafe'
|
|
33
15
|
```
|
|
34
16
|
|
|
35
|
-
Add its
|
|
17
|
+
The plugin has no account or model settings. Add its Service, Account and Profiles through Host inference management; keep the API key in the Account credential store or an `env://TYPESAFE_API_KEY` source reference. A reviewed plan can declare multiple models and select a Profile separately for each task:
|
|
36
18
|
|
|
37
19
|
```yaml
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
20
|
+
version: 1
|
|
21
|
+
services:
|
|
22
|
+
decision:
|
|
23
|
+
driver: typesafe
|
|
24
|
+
models:
|
|
25
|
+
jev-pinned:
|
|
26
|
+
id: jev-pinned
|
|
27
|
+
kinds: [decision]
|
|
28
|
+
protocol: typesafe-system-one
|
|
29
|
+
accounts:
|
|
30
|
+
deployment:
|
|
31
|
+
service: decision
|
|
32
|
+
auth:
|
|
33
|
+
method: api-key
|
|
34
|
+
source: env://TYPESAFE_API_KEY
|
|
35
|
+
profiles:
|
|
36
|
+
routing:
|
|
37
|
+
account: deployment
|
|
38
|
+
model: jev-pinned
|
|
39
|
+
parameters:
|
|
40
|
+
timeoutMs: 10000
|
|
41
|
+
maxRetries: 2
|
|
42
|
+
purposes:
|
|
43
43
|
decisions:
|
|
44
|
-
provider: root/typesafe
|
|
45
44
|
skills:
|
|
45
|
+
profile: routing
|
|
46
46
|
mode: shadow
|
|
47
47
|
tools:
|
|
48
|
+
profile: routing
|
|
48
49
|
mode: shadow
|
|
49
|
-
typesafe:
|
|
50
|
-
apiKey: ${TYPESAFE_API_KEY}
|
|
51
|
-
model: jev-latest
|
|
52
|
-
timeoutMs: 10000
|
|
53
|
-
maxRetries: 2
|
|
54
50
|
```
|
|
55
51
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
`schema.json` is the configuration contract. `timeoutMs` covers the whole call, including HTTP attempts and retry delays. A caller can supply its own total budget. `enabled: false` skips client creation and does not require a key. `baseUrl` defaults to `https://api.typesafe.ai`; custom roots cannot contain credentials, query strings or fragments.
|
|
59
|
-
|
|
60
|
-
Invalid configuration for an enabled instance stops plugin startup with a sanitized error instead of silently disabling the configured decision or approval provider. Resolve the environment reference or configuration error before restarting; use `enabled: false` to explicitly disable the instance.
|
|
61
|
-
|
|
62
|
-
## Use the decision interface
|
|
63
|
-
|
|
64
|
-
```ts
|
|
65
|
-
import { TypeSafeDecisionProvider } from '@zhin.js/service-typesafe';
|
|
66
|
-
|
|
67
|
-
const provider = new TypeSafeDecisionProvider({
|
|
68
|
-
apiKey: process.env.TYPESAFE_API_KEY!,
|
|
69
|
-
model: 'jev-latest',
|
|
70
|
-
});
|
|
71
|
-
try {
|
|
72
|
-
const result = await provider.evaluate({
|
|
73
|
-
state: { intent: 'Mute a group member' },
|
|
74
|
-
questions: {
|
|
75
|
-
skill: {
|
|
76
|
-
type: 'choice',
|
|
77
|
-
instructions: 'Choose the relevant permitted skill, or none.',
|
|
78
|
-
criteria: { moderation: 'Group moderation', none: 'No relevant skill' },
|
|
79
|
-
},
|
|
80
|
-
},
|
|
81
|
-
}, { signal: new AbortController().signal });
|
|
82
|
-
console.log(result.answers.skill.choice); // inferred: 'moderation' | 'none'
|
|
83
|
-
} finally {
|
|
84
|
-
provider.dispose();
|
|
85
|
-
}
|
|
86
|
-
```
|
|
52
|
+
Import previews resolve the Driver's exact Plugin owner and contract version. Applying a plan does not execute a model request. The former `typesafe.apiKey`, `model`, `enabled` and `ai.decisions.provider` configuration is removed; migrate it explicitly rather than running parallel clients. The old `zhin setup --decisions` format is not the target management path.
|
|
87
53
|
|
|
88
|
-
|
|
54
|
+
A normal plugin receives `aiInferenceClientToken` from its actual operation context and calls `evaluate` with an eligible Decision Profile reference. `evaluate` returns the supplier's typed answers, actual model and usage; task policies apply their own `off`, `shadow` or `active` behavior. Merely installing this plugin does not enable any decision policy.
|
|
89
55
|
|
|
90
|
-
|
|
56
|
+
- Choice retains the selected label, complete probability distribution and confidence.
|
|
57
|
+
- Score retains the rubric index, rubric legend, distribution and confidence. Its range follows the supplied rubric.
|
|
58
|
+
- Noul is a probability of true and has no separate confidence value.
|
|
59
|
+
- Deterministic identity, permission and approval checks remain authoritative.
|
|
91
60
|
|
|
92
|
-
|
|
93
|
-
- Score preserves the expected rubric index, rubric legend, probability distribution and confidence. A two-level rubric has a score in `[0, 1]`; a five-level rubric has a score in `[0, 4]`.
|
|
94
|
-
- Noul is the probability of true in `[0, 1]`. It has no separate confidence field.
|
|
95
|
-
- Every result includes the actual model name and token usage. Policy versioning and decision thresholds belong to the caller, not this transport.
|
|
96
|
-
|
|
97
|
-
The native API's top-level state, instructions and criterion descriptions accept strings, arrays, objects and null. Numeric and boolean data can appear inside objects or arrays. Non-finite numbers, cycles and unsupported entry types are rejected before dispatch. Responses are validated against the submitted question names, types, alternatives and score rubric. Missing answers, malformed distributions and invalid usage are rejected.
|
|
98
|
-
|
|
99
|
-
SDK logging is disabled, including when `TYPESAFE_LOG_LEVEL` is set. Errors expose only a local code and, when available, an HTTP status. Remote bodies, prompts, credentials and upstream causes are not attached to errors. Caller cancellation, total timeout and plugin disposal also cancel pending SDK retries.
|
|
100
|
-
|
|
101
|
-
Jev's decisions are advisory. Zhin's deterministic identity, permission and approval rules remain authoritative. Pin a model version before calibrating a production policy, and evaluate Chinese requests on representative scenarios; the SDK's `jev-latest` alias can change over time.
|
|
102
|
-
|
|
103
|
-
## Validation
|
|
61
|
+
`timeoutMs` bounds the whole SDK operation, including body consumption and configured retries. Every actual HTTP attempt obtains a current Account grant. Errors contain safe local codes and optional status, without provider bodies or credentials. Operation cancellation closes the ephemeral SDK client; retiring a Plugin generation does not itself cancel a retained operation.
|
|
104
62
|
|
|
105
63
|
```sh
|
|
106
64
|
pnpm --filter @zhin.js/service-typesafe test
|
|
107
65
|
pnpm --filter @zhin.js/service-typesafe build
|
|
108
66
|
```
|
|
109
67
|
|
|
110
|
-
Tests
|
|
68
|
+
Tests run the installed official SDK against synthetic HTTP fixtures. They do not establish real-account accuracy, latency, availability, provider permission or production cost.
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
The target interface requires the coordinated Provider release: `@zhin.js/ai >=1.1.51` and `@zhin.js/ai-provider >=1.0.0` (planned, not published by this change). Upgrade the Host and plugin together; the [migration guide](../../../docs/ai/provider-upgrade.md) lists the full version boundary. The root exports `typeSafeProvider` and safe decision errors; the old API-key constructor and its configuration type are no longer public author APIs.
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
## Migrating the former plugin configuration
|
|
75
|
+
|
|
76
|
+
The general headless importer does not execute plugin JavaScript to discover private configuration. A blocked TypeSafe entry requires this explicit migration, not a second legacy client:
|
|
77
|
+
|
|
78
|
+
1. Stop the old Host for the migration window. Keep a protected backup of its configuration, package versions, database and matching credential master key. Record the effective TypeSafe endpoint, exact native model ID, timeout/retry values and each decision task's existing policy; do not copy key material into a plan, log or issue. If the effective old model cannot be established, select an exact native ID before proceeding.
|
|
79
|
+
2. Replace the old configured plugin with the normal pure plugin declaration shown above. Remove the former plugin fields (`apiKey`, `model`, `enabled`, `baseUrl`, `timeoutMs`, `maxRetries`); even `enabled: false` is not the new plugin schema. Keep the old source in the protected backup. Keep an existing environment secret available privately if the new Account will refer to it.
|
|
80
|
+
3. Start the coordinated new Host and open its model management page in Console. Add a Service using the registered `typesafe` Driver and the old explicit endpoint. Declare the exact native model with `kinds: [decision]` and `protocol: typesafe-system-one`. This is a manual declaration, not a claim that a catalogue probe verified the model.
|
|
81
|
+
4. Add its Host Account with authentication `api-key`: either use the existing Host source reference, such as `env://TYPESAFE_API_KEY`, or submit the key through the authenticated private Account form. Create a Profile selecting that Account and native model; copy the old `timeoutMs` and `maxRetries` into Profile parameters. The plugin itself stores neither credentials nor a selected model.
|
|
82
|
+
5. Bind the Profile separately to the six decision purposes: `skills`, `tools`, `memory`, `agents`, `approval`, and `ambient`. Copy each task's original `mode`, `timeoutMs`, `minConfidence`, `topK`, `maxCandidates` and `maxSelections` where configured. Do not enable previously disabled tasks, invent new thresholds, or copy one task's policy over the others. Remove the obsolete `ai.decisions.provider` and old startup task routes only as part of this explicit cutover; the new runtime does not dual-read them.
|
|
83
|
+
6. Save through the normal management transaction and inspect the selected Service, Account, Profile and purpose bindings. Saving does not perform model inference. Real model acceptance and billing require a separately authorized test; offline validation is not that evidence. If a save outcome is unknown, query its original mutation receipt before retrying.
|
|
84
|
+
|
|
85
|
+
To restore the old release, stop the new Host and restore the old package/configuration set together with its matching database and credential-key backup. Do not point the old client at the new Provider graph or re-enable a legacy client alongside the new one.
|
|
@@ -9,7 +9,7 @@ export interface TypeSafeDecisionConfig {
|
|
|
9
9
|
readonly timeoutMs?: number;
|
|
10
10
|
readonly maxRetries?: number;
|
|
11
11
|
}
|
|
12
|
-
/** Generation-owned
|
|
12
|
+
/** Generation-owned configuration; each call owns SDK cancellation and its private rejection reason. */
|
|
13
13
|
export declare class TypeSafeDecisionProvider implements DecisionProvider {
|
|
14
14
|
#private;
|
|
15
15
|
constructor(config: TypeSafeDecisionConfig, transport?: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decision-provider.d.ts","sourceRoot":"","sources":["../src/decision-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"decision-provider.d.ts","sourceRoot":"","sources":["../src/decision-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,KAAK,EAAoE,MAAM,kBAAkB,CAAC;AAC1I,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,eAAe,EAAE,cAAc,EAAa,MAAM,aAAa,CAAC;AAIpI,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B,mDAAmD;IACnD,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;CAC9B;AA8CD,wGAAwG;AACxG,qBAAa,wBAAyB,YAAW,gBAAgB;;gBAMnD,MAAM,EAAE,sBAAsB,EAAE,SAAS,GAAE;QAAE,KAAK,CAAC,EAAE,KAAK,CAAA;KAAO;IAmBvE,QAAQ,CAAC,KAAK,CAAC,CAAC,SAAS,iBAAiB,EAAE,OAAO,EAAE,eAAe,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC;IAoDpI,OAAO,IAAI,IAAI;CAChB"}
|
package/lib/decision-provider.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { TypeSafeClient, APIError } from '@typesafe-ai/sdk';
|
|
2
|
+
import { ProviderAdmissionError } from '@zhin.js/ai/provider';
|
|
2
3
|
import { TypeSafeDecisionError, validateDecisionResult } from './response-validator.js';
|
|
3
4
|
function positiveBudget(value) {
|
|
4
5
|
if (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647)
|
|
@@ -64,9 +65,10 @@ function validateRequest(request) {
|
|
|
64
65
|
throw new TypeSafeDecisionError('invalid-request');
|
|
65
66
|
}
|
|
66
67
|
}
|
|
67
|
-
/** Generation-owned
|
|
68
|
+
/** Generation-owned configuration; each call owns SDK cancellation and its private rejection reason. */
|
|
68
69
|
export class TypeSafeDecisionProvider {
|
|
69
|
-
#
|
|
70
|
+
#configuration;
|
|
71
|
+
#fetch;
|
|
70
72
|
#timeoutMs;
|
|
71
73
|
#disposed = new AbortController();
|
|
72
74
|
constructor(config, transport = {}) {
|
|
@@ -90,12 +92,10 @@ export class TypeSafeDecisionProvider {
|
|
|
90
92
|
throw new TypeSafeDecisionError('invalid-config');
|
|
91
93
|
}
|
|
92
94
|
}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
throw new TypeSafeDecisionError('invalid-config');
|
|
98
|
-
}
|
|
95
|
+
// All SDK environment-backed fields are explicit, especially the real account key.
|
|
96
|
+
this.#configuration = Object.freeze({ apiKey: config.apiKey, defaultModel: config.model ?? 'jev-latest', baseURL: config.baseUrl ?? 'https://api.typesafe.ai',
|
|
97
|
+
timeout: this.#timeoutMs, retry: Object.freeze({ maxRetries }), logLevel: 'off' });
|
|
98
|
+
this.#fetch = transport.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
99
99
|
}
|
|
100
100
|
async evaluate(request, options) {
|
|
101
101
|
if (this.#disposed.signal.aborted)
|
|
@@ -116,7 +116,8 @@ export class TypeSafeDecisionProvider {
|
|
|
116
116
|
const controller = new AbortController();
|
|
117
117
|
const signal = AbortSignal.any([options.signal, this.#disposed.signal, controller.signal]);
|
|
118
118
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
119
|
-
const abortError = () =>
|
|
119
|
+
const abortError = () => controller.signal.reason instanceof ProviderAdmissionError ? controller.signal.reason
|
|
120
|
+
: new TypeSafeDecisionError(this.#disposed.signal.aborted ? 'disposed' : options.signal.aborted ? 'cancelled' : 'timeout');
|
|
120
121
|
let onAbort;
|
|
121
122
|
try {
|
|
122
123
|
const aborted = new Promise((_, reject) => {
|
|
@@ -126,17 +127,31 @@ export class TypeSafeDecisionProvider {
|
|
|
126
127
|
onAbort();
|
|
127
128
|
});
|
|
128
129
|
// Readonly JSON types differ only in mutability from the SDK's wire contract.
|
|
129
|
-
const
|
|
130
|
+
const client = new TypeSafeClient({ ...this.#configuration, fetch: async (input, init) => {
|
|
131
|
+
try {
|
|
132
|
+
return await this.#fetch(input, init);
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
// The SDK wraps every fetch rejection as a retryable connection error. Its
|
|
136
|
+
// caller-abort contract stops retries without changing actual network policy.
|
|
137
|
+
if (error instanceof ProviderAdmissionError)
|
|
138
|
+
controller.abort(error);
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
} });
|
|
142
|
+
const pending = client.systemOne(snapshot, { signal, timeout: timeoutMs });
|
|
130
143
|
const raw = await Promise.race([pending, aborted]);
|
|
131
|
-
if (signal.aborted)
|
|
132
|
-
throw abortError();
|
|
133
144
|
return validateDecisionResult(raw, snapshot.questions);
|
|
134
145
|
}
|
|
135
146
|
catch (error) {
|
|
136
|
-
|
|
137
|
-
|
|
147
|
+
// Once the result branch wins, later cancellation cannot replace its known
|
|
148
|
+
// response/validation outcome. Pending calls still resolve via abortError.
|
|
149
|
+
if (error instanceof ProviderAdmissionError)
|
|
150
|
+
throw error;
|
|
138
151
|
if (error instanceof TypeSafeDecisionError)
|
|
139
152
|
throw error;
|
|
153
|
+
if (signal.aborted)
|
|
154
|
+
throw abortError();
|
|
140
155
|
throw new TypeSafeDecisionError('request-failed', error instanceof APIError ? error.status : undefined);
|
|
141
156
|
}
|
|
142
157
|
finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decision-provider.js","sourceRoot":"","sources":["../src/decision-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,QAAQ,
|
|
1
|
+
{"version":3,"file":"decision-provider.js","sourceRoot":"","sources":["../src/decision-provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAgF,MAAM,kBAAkB,CAAC;AAE1I,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,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sB;gBAAE,MAAM,KAAK,CAAC;YACzD,IAAI,KAAK,YAAY,qBAAqB;gBAAE,MAAM,KAAK,CAAC;YACxD,IAAI,MAAM,CAAC,OAAO;gBAAE,MAAM,UAAU,EAAE,CAAC;YACvC,MAAM,IAAI,qBAAqB,CAAC,gBAAgB,EAAE,KAAK,YAAY,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QAC1G,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,IAAI,OAAO;gBAAE,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5D,CAAC;IACH,CAAC;IAED,OAAO,KAAW,IAAI,CAAC,SAAS,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;CAC5C"}
|
package/lib/index.d.ts
CHANGED
package/lib/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC"}
|
package/lib/index.js
CHANGED
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
interface TypeSafeServiceOptions {
|
|
2
|
+
readonly baseUrl: string;
|
|
3
|
+
}
|
|
4
|
+
interface TypeSafeParameters {
|
|
5
|
+
readonly timeoutMs?: number;
|
|
6
|
+
readonly maxRetries?: number;
|
|
7
|
+
}
|
|
8
|
+
export declare const typeSafeProvider: import("@zhin.js/ai/provider").ProviderDefinition<TypeSafeServiceOptions, TypeSafeParameters> & Readonly<{
|
|
9
|
+
id: "typesafe";
|
|
10
|
+
authentication: import("@zhin.js/ai/provider").ProviderAuthentication<TypeSafeServiceOptions> & Readonly<{
|
|
11
|
+
methods: readonly ["api-key"];
|
|
12
|
+
}>;
|
|
13
|
+
}>;
|
|
14
|
+
declare module '@zhin.js/ai/provider' {
|
|
15
|
+
interface AIProviderRegistry {
|
|
16
|
+
typesafe: typeof typeSafeProvider;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
export {};
|
|
20
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAGA,UAAU,sBAAsB;IAAG,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE;AAC7D,UAAU,kBAAkB;IAAG,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE;AAwC1F,eAAO,MAAM,gBAAgB;;;;;EA8C3B,CAAC;AAEH,OAAO,QAAQ,sBAAsB,CAAC;IACpC,UAAU,kBAAkB;QAAG,QAAQ,EAAE,OAAO,gBAAgB,CAAA;KAAE;CACnE"}
|
package/lib/provider.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { defineProvider } from '@zhin.js/ai/provider';
|
|
2
|
+
import { TypeSafeDecisionProvider } from './decision-provider.js';
|
|
3
|
+
const serviceInput = { type: 'object', additionalProperties: false, properties: {
|
|
4
|
+
baseUrl: { type: 'string', format: 'uri', default: 'https://api.typesafe.ai' },
|
|
5
|
+
} };
|
|
6
|
+
const budgets = {
|
|
7
|
+
timeoutMs: { type: 'integer', minimum: 1, maximum: 2_147_483_647 },
|
|
8
|
+
maxRetries: { type: 'integer', minimum: 0, maximum: 10 },
|
|
9
|
+
};
|
|
10
|
+
const modelContracts = [{ protocol: 'typesafe-system-one', kinds: ['decision'] }];
|
|
11
|
+
function fields(input, allowed) {
|
|
12
|
+
if (input === undefined)
|
|
13
|
+
return {};
|
|
14
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
15
|
+
throw new Error('Invalid TypeSafe configuration');
|
|
16
|
+
const value = input;
|
|
17
|
+
if (Object.keys(value).some(name => !allowed.includes(name)))
|
|
18
|
+
throw new Error('Unknown TypeSafe configuration field');
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
const serviceSchema = { inputSchema: serviceInput, parse(input) {
|
|
22
|
+
const value = fields(input, ['baseUrl']);
|
|
23
|
+
if (value.baseUrl !== undefined && typeof value.baseUrl !== 'string')
|
|
24
|
+
throw new Error('Invalid TypeSafe endpoint');
|
|
25
|
+
const url = new URL(typeof value.baseUrl === 'string' ? value.baseUrl : serviceInput.properties.baseUrl.default);
|
|
26
|
+
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.hash || url.search)
|
|
27
|
+
throw new Error('Invalid TypeSafe endpoint');
|
|
28
|
+
return { baseUrl: url.href.replace(/\/$/, '') };
|
|
29
|
+
} };
|
|
30
|
+
const decisionProfileSchema = { inputSchema: { type: 'object', additionalProperties: false, properties: budgets }, parse(input) {
|
|
31
|
+
const value = fields(input, Object.keys(budgets));
|
|
32
|
+
for (const [key, limits] of Object.entries(budgets)) {
|
|
33
|
+
const number = value[key];
|
|
34
|
+
if (number !== undefined && (typeof number !== 'number' || !Number.isSafeInteger(number) || number < limits.minimum || number > limits.maximum))
|
|
35
|
+
throw new Error('Invalid TypeSafe request budget');
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
} };
|
|
39
|
+
/** Actual Choice/Score/Noul service. A chat JSON generator cannot publish this contract. */
|
|
40
|
+
function profileSchema({ model }) {
|
|
41
|
+
if (model.protocol !== modelContracts[0].protocol || model.kinds.length !== 1 || model.kinds[0] !== 'decision')
|
|
42
|
+
throw new Error('Invalid TypeSafe Profile protocol');
|
|
43
|
+
return decisionProfileSchema;
|
|
44
|
+
}
|
|
45
|
+
export const typeSafeProvider = defineProvider({
|
|
46
|
+
id: 'typesafe', label: 'TypeSafe AI', contractVersion: '1', serviceSchema,
|
|
47
|
+
profileSchema, modelContracts,
|
|
48
|
+
identity: service => ({ product: 'typesafe', baseUrl: service.options.baseUrl }),
|
|
49
|
+
authentication: { methods: ['api-key'] },
|
|
50
|
+
targets: service => ({ authentication: [], inference: [service.options.baseUrl] }),
|
|
51
|
+
models(service) {
|
|
52
|
+
for (const [id, model] of Object.entries(service.models)) {
|
|
53
|
+
if (model.id !== id || model.protocol !== modelContracts[0].protocol || model.kinds.length !== 1 || model.kinds[0] !== modelContracts[0].kinds[0])
|
|
54
|
+
throw new Error('Invalid TypeSafe model contract');
|
|
55
|
+
}
|
|
56
|
+
return service.models;
|
|
57
|
+
},
|
|
58
|
+
createExecution(options) {
|
|
59
|
+
return { decision: {
|
|
60
|
+
async evaluate(request) {
|
|
61
|
+
const signal = AbortSignal.any([options.signal, request.signal]);
|
|
62
|
+
const baseUrl = options.binding.service.options.baseUrl;
|
|
63
|
+
const first = await options.credentials.authorize({ target: new URL(baseUrl), signal });
|
|
64
|
+
if (!first.token)
|
|
65
|
+
throw new Error('TypeSafe account is not authorized');
|
|
66
|
+
const callRequests = new Set();
|
|
67
|
+
const fetch = async (url, init) => {
|
|
68
|
+
const input = new Request(url, init);
|
|
69
|
+
if (url instanceof Request)
|
|
70
|
+
callRequests.add(url);
|
|
71
|
+
const currentSignal = init?.signal ?? (url instanceof Request ? url.signal : signal);
|
|
72
|
+
const grant = await options.credentials.authorize({ target: new URL(input.url), signal: currentSignal });
|
|
73
|
+
if (!grant.token)
|
|
74
|
+
throw new Error('TypeSafe account is not authorized');
|
|
75
|
+
const headers = new Headers(input.headers);
|
|
76
|
+
for (const [name, value] of Object.entries(grant.headers))
|
|
77
|
+
headers.set(name, value);
|
|
78
|
+
headers.set('authorization', `Bearer ${grant.token}`);
|
|
79
|
+
const request = new Request(input, { headers, signal: currentSignal });
|
|
80
|
+
const bound = options.credentials.bindRequest({ grant, request });
|
|
81
|
+
callRequests.add(request);
|
|
82
|
+
callRequests.add(bound);
|
|
83
|
+
return options.fetch(bound);
|
|
84
|
+
};
|
|
85
|
+
const provider = new TypeSafeDecisionProvider({
|
|
86
|
+
apiKey: first.token, baseUrl, model: options.binding.model.id,
|
|
87
|
+
...options.binding.profile.parameters,
|
|
88
|
+
}, { fetch });
|
|
89
|
+
try {
|
|
90
|
+
return await provider.evaluate({ state: request.state, questions: request.questions, model: options.binding.model.id }, {
|
|
91
|
+
signal, timeoutMs: request.timeoutMs,
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
finally {
|
|
95
|
+
provider.dispose();
|
|
96
|
+
callRequests.clear();
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
} };
|
|
100
|
+
},
|
|
101
|
+
});
|
|
102
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAmE,MAAM,sBAAsB,CAAC;AACvH,OAAO,EAAE,wBAAwB,EAAE,MAAM,wBAAwB,CAAC;AAIlE,MAAM,YAAY,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,oBAAoB,EAAE,KAAK,EAAE,UAAU,EAAE;QAC9E,OAAO,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,yBAAyB,EAAE;KAC/E,EAAW,CA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CAAC,SAAS;yBACrC,CAAC,CAAC;oBACL,CAAC;4BAAS,CAAC;wBAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;wBAAC,YAAY,CAAC,KAAK,EAAE,CAAC;oBAAC,CAAC;gBACzD,CAAC;aACF,EAAE,CAAC;IACN,CAAC;CACF,CAAC,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DecisionQuestions, DecisionResult } from '@zhin.js/ai';
|
|
1
|
+
import type { DecisionQuestions, DecisionResult } from '@zhin.js/ai/provider';
|
|
2
2
|
/** Never includes a remote body, credential, prompt or candidate label. */
|
|
3
3
|
export declare class TypeSafeDecisionError extends Error {
|
|
4
4
|
readonly code: 'invalid-request' | 'invalid-response' | 'invalid-config' | 'disposed' | 'cancelled' | 'timeout' | 'request-failed';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"response-validator.d.ts","sourceRoot":"","sources":["../src/response-validator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAa,MAAM,
|
|
1
|
+
{"version":3,"file":"response-validator.d.ts","sourceRoot":"","sources":["../src/response-validator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAa,MAAM,sBAAsB,CAAC;AAEzF,2EAA2E;AAC3E,qBAAa,qBAAsB,SAAQ,KAAK;IAClC,QAAQ,CAAC,IAAI,EAAE,iBAAiB,GAAG,kBAAkB,GAAG,gBAAgB,GAAG,UAAU,GAAG,WAAW,GAAG,SAAS,GAAG,gBAAgB;IAAE,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM;gBAAnJ,IAAI,EAAE,iBAAiB,GAAG,kBAAkB,GAAG,gBAAgB,GAAG,UAAU,GAAG,WAAW,GAAG,SAAS,GAAG,gBAAgB,EAAW,MAAM,CAAC,EAAE,MAAM,YAAA;CAIzK;AAkCD,8FAA8F;AAC9F,wBAAgB,sBAAsB,CAAC,CAAC,SAAS,iBAAiB,EAAE,GAAG,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,GAAG,cAAc,CAAC,CAAC,CAAC,CAkCjH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhin.js/service-typesafe",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.16",
|
|
4
4
|
"description": "Optional TypeSafe AI Jev decision provider for Zhin",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -21,18 +21,17 @@
|
|
|
21
21
|
],
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"@typesafe-ai/sdk": "^0.6.0",
|
|
24
|
-
"@zhin.js/ai": "1.1.
|
|
24
|
+
"@zhin.js/ai": "1.1.51",
|
|
25
|
+
"@zhin.js/ai-provider": "1.0.1"
|
|
25
26
|
},
|
|
26
27
|
"peerDependencies": {
|
|
27
|
-
"
|
|
28
|
-
"zhin.js": "^1.1.19"
|
|
28
|
+
"zhin.js": "^1.1.21"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "^26.1.2",
|
|
32
32
|
"typescript": "^6.0.3",
|
|
33
33
|
"vitest": "^4.1.10",
|
|
34
|
-
"
|
|
35
|
-
"zhin.js": "1.1.19"
|
|
34
|
+
"zhin.js": "1.1.21"
|
|
36
35
|
},
|
|
37
36
|
"engines": {
|
|
38
37
|
"node": ">=22.19.0"
|
package/plugin.js
CHANGED
|
@@ -1,16 +1,11 @@
|
|
|
1
1
|
// Generated by build-plugin-runtime-entries.mjs. Do not edit.
|
|
2
2
|
import { definePlugin } from 'zhin.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { provideAiProviders } from '@zhin.js/ai-provider';
|
|
4
|
+
import { typeSafeProvider } from "./lib/provider.js";
|
|
5
5
|
export default definePlugin({
|
|
6
6
|
name: 'typesafe',
|
|
7
7
|
metadata: { displayName: 'TypeSafe AI' },
|
|
8
8
|
setup(context) {
|
|
9
|
-
|
|
10
|
-
if (config.enabled === false)
|
|
11
|
-
return;
|
|
12
|
-
const provider = new TypeSafeDecisionProvider(config);
|
|
13
|
-
provideAgentDecisionProvider(context.resources, provider);
|
|
14
|
-
context.lifecycle.add(() => provider.dispose());
|
|
9
|
+
provideAiProviders(context.resources, [typeSafeProvider]);
|
|
15
10
|
},
|
|
16
11
|
});
|
package/schema.json
CHANGED
|
@@ -2,77 +2,5 @@
|
|
|
2
2
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
3
3
|
"type": "object",
|
|
4
4
|
"additionalProperties": false,
|
|
5
|
-
"
|
|
6
|
-
"patchPaths": ["ai.decisions"]
|
|
7
|
-
},
|
|
8
|
-
"properties": {
|
|
9
|
-
"enabled": {
|
|
10
|
-
"type": "boolean",
|
|
11
|
-
"default": true,
|
|
12
|
-
"description": "Enable this decision provider.",
|
|
13
|
-
"x-descriptionZh": "启用该决策服务。"
|
|
14
|
-
},
|
|
15
|
-
"apiKey": {
|
|
16
|
-
"type": "string",
|
|
17
|
-
"minLength": 1,
|
|
18
|
-
"pattern": "\\S",
|
|
19
|
-
"writeOnly": true,
|
|
20
|
-
"description": "TypeSafe API key; reference TYPESAFE_API_KEY from the environment.",
|
|
21
|
-
"x-descriptionZh": "通过环境变量 TYPESAFE_API_KEY 引用密钥。"
|
|
22
|
-
},
|
|
23
|
-
"model": {
|
|
24
|
-
"type": "string",
|
|
25
|
-
"minLength": 1,
|
|
26
|
-
"pattern": "\\S",
|
|
27
|
-
"default": "jev-latest",
|
|
28
|
-
"description": "Model name; pin a model version for calibrated policies.",
|
|
29
|
-
"x-descriptionZh": "模型名称;校准后的策略应固定模型版本。"
|
|
30
|
-
},
|
|
31
|
-
"baseUrl": {
|
|
32
|
-
"type": "string",
|
|
33
|
-
"default": "https://api.typesafe.ai",
|
|
34
|
-
"description": "API root URL without query, credentials or fragment.",
|
|
35
|
-
"x-descriptionZh": "API 根地址,不包含凭据、查询或片段。",
|
|
36
|
-
"pattern": "^https?://[^/?#@\\s]+(?:/[^?#\\s]*)?$"
|
|
37
|
-
},
|
|
38
|
-
"timeoutMs": {
|
|
39
|
-
"type": "integer",
|
|
40
|
-
"minimum": 1,
|
|
41
|
-
"maximum": 2147483647,
|
|
42
|
-
"default": 10000,
|
|
43
|
-
"description": "Total budget including all requests and retry delays.",
|
|
44
|
-
"x-descriptionZh": "包含全部请求与重试等待的总超时。"
|
|
45
|
-
},
|
|
46
|
-
"maxRetries": {
|
|
47
|
-
"type": "integer",
|
|
48
|
-
"minimum": 0,
|
|
49
|
-
"maximum": 10,
|
|
50
|
-
"default": 2,
|
|
51
|
-
"description": "Maximum SDK retries after the first attempt.",
|
|
52
|
-
"x-descriptionZh": "首次请求后的最大重试次数。"
|
|
53
|
-
}
|
|
54
|
-
},
|
|
55
|
-
"allOf": [
|
|
56
|
-
{
|
|
57
|
-
"if": {
|
|
58
|
-
"properties": {
|
|
59
|
-
"enabled": {
|
|
60
|
-
"const": false
|
|
61
|
-
}
|
|
62
|
-
},
|
|
63
|
-
"required": [
|
|
64
|
-
"enabled"
|
|
65
|
-
]
|
|
66
|
-
},
|
|
67
|
-
"then": {},
|
|
68
|
-
"else": {
|
|
69
|
-
"required": [
|
|
70
|
-
"apiKey"
|
|
71
|
-
],
|
|
72
|
-
"properties": {
|
|
73
|
-
"apiKey": {}
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
]
|
|
5
|
+
"properties": {}
|
|
78
6
|
}
|
package/src/decision-provider.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { TypeSafeClient, APIError, type Fetch, type Questions, type SystemOneRequest } from '@typesafe-ai/sdk';
|
|
1
|
+
import { TypeSafeClient, APIError, type Fetch, type Questions, type SystemOneRequest, type TypeSafeClientConfig } from '@typesafe-ai/sdk';
|
|
2
2
|
import type { DecisionOptions, DecisionProvider, DecisionQuestions, DecisionRequest, DecisionResult, JsonValue } from '@zhin.js/ai';
|
|
3
|
+
import { ProviderAdmissionError } from '@zhin.js/ai/provider';
|
|
3
4
|
import { TypeSafeDecisionError, validateDecisionResult } from './response-validator.js';
|
|
4
5
|
|
|
5
6
|
export interface TypeSafeDecisionConfig {
|
|
@@ -56,9 +57,10 @@ function validateRequest(request: DecisionRequest): void {
|
|
|
56
57
|
}
|
|
57
58
|
}
|
|
58
59
|
|
|
59
|
-
/** Generation-owned
|
|
60
|
+
/** Generation-owned configuration; each call owns SDK cancellation and its private rejection reason. */
|
|
60
61
|
export class TypeSafeDecisionProvider implements DecisionProvider {
|
|
61
|
-
readonly #
|
|
62
|
+
readonly #configuration: Readonly<TypeSafeClientConfig>;
|
|
63
|
+
readonly #fetch: Fetch;
|
|
62
64
|
readonly #timeoutMs: number;
|
|
63
65
|
readonly #disposed = new AbortController();
|
|
64
66
|
|
|
@@ -75,9 +77,10 @@ export class TypeSafeDecisionProvider implements DecisionProvider {
|
|
|
75
77
|
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error();
|
|
76
78
|
} catch { throw new TypeSafeDecisionError('invalid-config'); }
|
|
77
79
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
80
|
+
// All SDK environment-backed fields are explicit, especially the real account key.
|
|
81
|
+
this.#configuration = Object.freeze({ apiKey: config.apiKey, defaultModel: config.model ?? 'jev-latest', baseURL: config.baseUrl ?? 'https://api.typesafe.ai',
|
|
82
|
+
timeout: this.#timeoutMs, retry: Object.freeze({ maxRetries }), logLevel: 'off' });
|
|
83
|
+
this.#fetch = transport.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
81
84
|
}
|
|
82
85
|
|
|
83
86
|
async evaluate<const Q extends DecisionQuestions>(request: DecisionRequest<Q>, options: DecisionOptions): Promise<DecisionResult<Q>> {
|
|
@@ -97,7 +100,8 @@ export class TypeSafeDecisionProvider implements DecisionProvider {
|
|
|
97
100
|
const controller = new AbortController();
|
|
98
101
|
const signal = AbortSignal.any([options.signal, this.#disposed.signal, controller.signal]);
|
|
99
102
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
100
|
-
const abortError = ():
|
|
103
|
+
const abortError = (): Error => controller.signal.reason instanceof ProviderAdmissionError ? controller.signal.reason
|
|
104
|
+
: new TypeSafeDecisionError(this.#disposed.signal.aborted ? 'disposed' : options.signal.aborted ? 'cancelled' : 'timeout');
|
|
101
105
|
let onAbort: (() => void) | undefined;
|
|
102
106
|
try {
|
|
103
107
|
const aborted = new Promise<never>((_, reject) => {
|
|
@@ -106,13 +110,24 @@ export class TypeSafeDecisionProvider implements DecisionProvider {
|
|
|
106
110
|
if (signal.aborted) onAbort();
|
|
107
111
|
});
|
|
108
112
|
// Readonly JSON types differ only in mutability from the SDK's wire contract.
|
|
109
|
-
const
|
|
113
|
+
const client = new TypeSafeClient({ ...this.#configuration, fetch: async (input, init) => {
|
|
114
|
+
try { return await this.#fetch(input, init); }
|
|
115
|
+
catch (error) {
|
|
116
|
+
// The SDK wraps every fetch rejection as a retryable connection error. Its
|
|
117
|
+
// caller-abort contract stops retries without changing actual network policy.
|
|
118
|
+
if (error instanceof ProviderAdmissionError) controller.abort(error);
|
|
119
|
+
throw error;
|
|
120
|
+
}
|
|
121
|
+
} });
|
|
122
|
+
const pending = client.systemOne(snapshot as unknown as SystemOneRequest<Questions>, { signal, timeout: timeoutMs });
|
|
110
123
|
const raw = await Promise.race([pending, aborted]);
|
|
111
|
-
if (signal.aborted) throw abortError();
|
|
112
124
|
return validateDecisionResult(raw, snapshot.questions);
|
|
113
125
|
} catch (error) {
|
|
114
|
-
|
|
126
|
+
// Once the result branch wins, later cancellation cannot replace its known
|
|
127
|
+
// response/validation outcome. Pending calls still resolve via abortError.
|
|
128
|
+
if (error instanceof ProviderAdmissionError) throw error;
|
|
115
129
|
if (error instanceof TypeSafeDecisionError) throw error;
|
|
130
|
+
if (signal.aborted) throw abortError();
|
|
116
131
|
throw new TypeSafeDecisionError('request-failed', error instanceof APIError ? error.status : undefined);
|
|
117
132
|
} finally {
|
|
118
133
|
clearTimeout(timer);
|
package/src/index.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export {
|
|
1
|
+
export { typeSafeProvider } from './provider.js';
|
|
2
2
|
export { TypeSafeDecisionError } from './response-validator.js';
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { defineProvider, type ModelDefinition, type ProviderSchema, type ProviderService } from '@zhin.js/ai/provider';
|
|
2
|
+
import { TypeSafeDecisionProvider } from './decision-provider.js';
|
|
3
|
+
|
|
4
|
+
interface TypeSafeServiceOptions { readonly baseUrl: string }
|
|
5
|
+
interface TypeSafeParameters { readonly timeoutMs?: number; readonly maxRetries?: number }
|
|
6
|
+
const serviceInput = { type: 'object', additionalProperties: false, properties: {
|
|
7
|
+
baseUrl: { type: 'string', format: 'uri', default: 'https://api.typesafe.ai' },
|
|
8
|
+
} } as const;
|
|
9
|
+
const budgets = {
|
|
10
|
+
timeoutMs: { type: 'integer', minimum: 1, maximum: 2_147_483_647 },
|
|
11
|
+
maxRetries: { type: 'integer', minimum: 0, maximum: 10 },
|
|
12
|
+
} as const;
|
|
13
|
+
const modelContracts = [{ protocol: 'typesafe-system-one', kinds: ['decision'] }] as const;
|
|
14
|
+
|
|
15
|
+
function fields(input: unknown, allowed: readonly string[]): Record<string, unknown> {
|
|
16
|
+
if (input === undefined) return {};
|
|
17
|
+
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Invalid TypeSafe configuration');
|
|
18
|
+
const value = input as Record<string, unknown>;
|
|
19
|
+
if (Object.keys(value).some(name => !allowed.includes(name))) throw new Error('Unknown TypeSafe configuration field');
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const serviceSchema: ProviderSchema<TypeSafeServiceOptions> = { inputSchema: serviceInput, parse(input) {
|
|
24
|
+
const value = fields(input, ['baseUrl']);
|
|
25
|
+
if (value.baseUrl !== undefined && typeof value.baseUrl !== 'string') throw new Error('Invalid TypeSafe endpoint');
|
|
26
|
+
const url = new URL(typeof value.baseUrl === 'string' ? value.baseUrl : serviceInput.properties.baseUrl.default);
|
|
27
|
+
if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.hash || url.search) throw new Error('Invalid TypeSafe endpoint');
|
|
28
|
+
return { baseUrl: url.href.replace(/\/$/, '') };
|
|
29
|
+
} };
|
|
30
|
+
|
|
31
|
+
const decisionProfileSchema: ProviderSchema<TypeSafeParameters> = { inputSchema: { type: 'object', additionalProperties: false, properties: budgets }, parse(input) {
|
|
32
|
+
const value = fields(input, Object.keys(budgets));
|
|
33
|
+
for (const [key, limits] of Object.entries(budgets)) {
|
|
34
|
+
const number = value[key];
|
|
35
|
+
if (number !== undefined && (typeof number !== 'number' || !Number.isSafeInteger(number) || number < limits.minimum || number > limits.maximum)) throw new Error('Invalid TypeSafe request budget');
|
|
36
|
+
}
|
|
37
|
+
return value as TypeSafeParameters;
|
|
38
|
+
} };
|
|
39
|
+
|
|
40
|
+
/** Actual Choice/Score/Noul service. A chat JSON generator cannot publish this contract. */
|
|
41
|
+
function profileSchema({ model }: Readonly<{ service: ProviderService<TypeSafeServiceOptions>; model: ModelDefinition }>): ProviderSchema<TypeSafeParameters> {
|
|
42
|
+
if (model.protocol !== modelContracts[0].protocol || model.kinds.length !== 1 || model.kinds[0] !== 'decision') throw new Error('Invalid TypeSafe Profile protocol');
|
|
43
|
+
return decisionProfileSchema;
|
|
44
|
+
}
|
|
45
|
+
export const typeSafeProvider = defineProvider({
|
|
46
|
+
id: 'typesafe', label: 'TypeSafe AI', contractVersion: '1', serviceSchema,
|
|
47
|
+
profileSchema, modelContracts,
|
|
48
|
+
identity: service => ({ product: 'typesafe', baseUrl: service.options.baseUrl }),
|
|
49
|
+
authentication: { methods: ['api-key'] },
|
|
50
|
+
targets: service => ({ authentication: [], inference: [service.options.baseUrl] }),
|
|
51
|
+
models(service): Readonly<Record<string, ModelDefinition>> {
|
|
52
|
+
for (const [id, model] of Object.entries(service.models)) {
|
|
53
|
+
if (model.id !== id || model.protocol !== modelContracts[0].protocol || model.kinds.length !== 1 || model.kinds[0] !== modelContracts[0].kinds[0]) throw new Error('Invalid TypeSafe model contract');
|
|
54
|
+
}
|
|
55
|
+
return service.models;
|
|
56
|
+
},
|
|
57
|
+
createExecution(options) {
|
|
58
|
+
return { decision: {
|
|
59
|
+
async evaluate(request) {
|
|
60
|
+
const signal = AbortSignal.any([options.signal, request.signal]);
|
|
61
|
+
const baseUrl = options.binding.service.options.baseUrl;
|
|
62
|
+
const first = await options.credentials.authorize({ target: new URL(baseUrl), signal });
|
|
63
|
+
if (!first.token) throw new Error('TypeSafe account is not authorized');
|
|
64
|
+
const callRequests = new Set<Request>();
|
|
65
|
+
const fetch: typeof globalThis.fetch = async (url, init) => {
|
|
66
|
+
const input = new Request(url, init);
|
|
67
|
+
if (url instanceof Request) callRequests.add(url);
|
|
68
|
+
const currentSignal = init?.signal ?? (url instanceof Request ? url.signal : signal);
|
|
69
|
+
const grant = await options.credentials.authorize({ target: new URL(input.url), signal: currentSignal });
|
|
70
|
+
if (!grant.token) throw new Error('TypeSafe account is not authorized');
|
|
71
|
+
const headers = new Headers(input.headers);
|
|
72
|
+
for (const [name, value] of Object.entries(grant.headers)) headers.set(name, value);
|
|
73
|
+
headers.set('authorization', `Bearer ${grant.token}`);
|
|
74
|
+
const request = new Request(input, { headers, signal: currentSignal });
|
|
75
|
+
const bound = options.credentials.bindRequest({ grant, request });
|
|
76
|
+
callRequests.add(request); callRequests.add(bound);
|
|
77
|
+
return options.fetch(bound);
|
|
78
|
+
};
|
|
79
|
+
const provider = new TypeSafeDecisionProvider({
|
|
80
|
+
apiKey: first.token, baseUrl, model: options.binding.model.id,
|
|
81
|
+
...options.binding.profile.parameters,
|
|
82
|
+
}, { fetch });
|
|
83
|
+
try {
|
|
84
|
+
return await provider.evaluate({ state: request.state, questions: request.questions, model: options.binding.model.id }, {
|
|
85
|
+
signal, timeoutMs: request.timeoutMs,
|
|
86
|
+
});
|
|
87
|
+
} finally { provider.dispose(); callRequests.clear(); }
|
|
88
|
+
},
|
|
89
|
+
} };
|
|
90
|
+
},
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
declare module '@zhin.js/ai/provider' {
|
|
94
|
+
interface AIProviderRegistry { typesafe: typeof typeSafeProvider }
|
|
95
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DecisionQuestions, DecisionResult, JsonValue } from '@zhin.js/ai';
|
|
1
|
+
import type { DecisionQuestions, DecisionResult, JsonValue } from '@zhin.js/ai/provider';
|
|
2
2
|
|
|
3
3
|
/** Never includes a remote body, credential, prompt or candidate label. */
|
|
4
4
|
export class TypeSafeDecisionError extends Error {
|