@parcha/agentrun-jev 0.1.0-beta.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 +202 -0
- package/NOTICE +2 -0
- package/README.md +122 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +183 -0
- package/package.json +46 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# @parcha/agentrun-jev
|
|
2
|
+
|
|
3
|
+
Optional [TypeSafe Jev](https://docs.typesafe.ai/) support for AgentRun DSL. Jev answers focused questions with typed values and probability distributions. The workflow decides how to use them.
|
|
4
|
+
|
|
5
|
+
Requires Node.js 22.19 or later. This is a public-beta release candidate; package publication is pending.
|
|
6
|
+
|
|
7
|
+
After publication to npm:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @parcha/agentrun-dsl @parcha/agentrun-jev
|
|
11
|
+
export TYPESAFE_API_KEY="your-key"
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { createJevRunner } from '@parcha/agentrun-jev';
|
|
16
|
+
|
|
17
|
+
const runJudge = createJevRunner();
|
|
18
|
+
// Supply runJudge alongside your other runWorkflow dependencies.
|
|
19
|
+
const result = await runJudge({
|
|
20
|
+
label: 'triage',
|
|
21
|
+
kind: 'judge',
|
|
22
|
+
state: { ticket: 'I was charged twice.' },
|
|
23
|
+
questions: {
|
|
24
|
+
team: {
|
|
25
|
+
type: 'choice',
|
|
26
|
+
instructions: 'Which team should handle this ticket?',
|
|
27
|
+
criteria: { billing: 'Invoices, payments, or refunds', other: 'Everything else' },
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
console.log(result.answers.team);
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`judge`, `pick`, `sift`, `route`, semantic predicates, and judgment verification use the same `runJudge` adapter. Choice, Noul, and Score answers retain their raw probabilities. The core validates answer IDs, probability keys and normalization, score rubrics, and value ranges before consuming a result. A typed answer records the model's decision. It does not prove that a real-world claim is true.
|
|
35
|
+
|
|
36
|
+
`System One` is TypeSafe's typed-question interface, exposed by the SDK as `systemOne`. A Noul answer is a truth probability from 0 to 1; the DSL converts probabilities of at least 0.5 to `true` and retains the probability beside that value. Choice and Score confidence comes from the response. Jev does not return a separate confidence for Noul; the DSL derives its own gate-strength value from the distance from 0.5, scaled to the range 0 to 1. These numbers are useful gate inputs, not calibrated guarantees.
|
|
37
|
+
|
|
38
|
+
The public adapter API includes `createJevRunner`, `JevError`, `isJevResponseReason`, and the types `JevOptions`, `JevClient`, `JevErrorCode`, `JevResponseReason`, and `JevResponseDiagnostic`. The shared question, answer and distribution helpers live in `@parcha/agentrun-dsl`.
|
|
39
|
+
|
|
40
|
+
## Configuration
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
const controller = new AbortController();
|
|
44
|
+
const runJudge = createJevRunner({
|
|
45
|
+
timeoutMs: 30_000, // Total budget, including retry waits.
|
|
46
|
+
maxAttempts: 3, // Includes the first attempt; maximum 10.
|
|
47
|
+
retryBaseMs: 500,
|
|
48
|
+
retryMaxMs: 5_000,
|
|
49
|
+
signal: controller.signal,
|
|
50
|
+
});
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The official `@typesafe-ai/sdk` resolves `TYPESAFE_API_KEY` and `TYPESAFE_BASE_URL`. Explicit `apiKey` and `baseURL` options take precedence. An API root ends before `/v1/systemone`. Set `fetch` for a custom transport, or supply a `client` with a `systemOne(request, options)` method. A custom client must honor the request signal and disable its own retries; it owns its credentials and cannot be combined with transport options.
|
|
54
|
+
|
|
55
|
+
The adapter retries transient HTTP 408, 429, 5xx responses and connection failures with bounded exponential delays. SDK retries are disabled. Validation failures and other HTTP errors do not retry. The deadline and either the runner or per-call signal interrupt both requests and backoff. Cancellation bounds when the adapter returns; an uncooperative custom client can still continue its own work.
|
|
56
|
+
|
|
57
|
+
Request state has no local byte cap by default. Set `maxStateBytes` to a positive safe integer to reject serialized UTF-8 JSON state exceeding that host-owned limit before transport; omission or `null` disables this guard. This is a byte guard, not a token estimate. [Provider model context limits](https://docs.typesafe.ai/models.md) still apply. The adapter never truncates or splits state or questions.
|
|
58
|
+
|
|
59
|
+
The core allows up to 240 options per choice and 2–10 levels per score rubric. Adapter timeouts are positive integer milliseconds up to 2,147,483,647; retry delays may also be zero. `maxAttempts` is 1–10, with a default of 3.
|
|
60
|
+
|
|
61
|
+
`JevError` provides a stable `code`, `attempts`, and optional HTTP `status`. Errors deliberately omit raw service bodies, headers, input state, and causes. SDK logging is disabled. Custom clients and transports own their own logging. Do not expose credentials in browser code.
|
|
62
|
+
|
|
63
|
+
Optional `responseDiagnostic.reason` identifies a fixed response invariant, such
|
|
64
|
+
as `answer_keys`, `probability_mass`, or `token_usage`. An explicitly structured
|
|
65
|
+
capacity rejection can report `max_tokens_exceeded`; arbitrary provider messages
|
|
66
|
+
are never parsed for a reason. These details do not change validation, retry
|
|
67
|
+
policy, or the submitted evidence. Unknown causes remain unspecified.
|
|
68
|
+
|
|
69
|
+
Successful results retain `answers`, reported `model`, reported token `usage`, and a SHA-256 of the submitted request. `cost_usd` is `null` unless both usage and explicit `pricing: { inputUsdPerMillionTokens, outputUsdPerMillionTokens }` are available. Configured prices produce an estimate for the successful response; costs from unsuccessful or interrupted attempts are unknown.
|
|
70
|
+
|
|
71
|
+
## Offline tests
|
|
72
|
+
|
|
73
|
+
Inject a client to exercise the real adapter without a key or network request. After installing the DSL and Jev packages, save this as `offline-jev.mjs` and run `node offline-jev.mjs`:
|
|
74
|
+
|
|
75
|
+
```js
|
|
76
|
+
import assert from 'node:assert/strict';
|
|
77
|
+
import { createJevRunner } from '@parcha/agentrun-jev';
|
|
78
|
+
|
|
79
|
+
const runJudge = createJevRunner({
|
|
80
|
+
maxAttempts: 1,
|
|
81
|
+
client: {
|
|
82
|
+
async systemOne(request, options) {
|
|
83
|
+
options.signal?.throwIfAborted();
|
|
84
|
+
assert.deepEqual(Object.keys(request.questions), ['answersQuestion']);
|
|
85
|
+
return {
|
|
86
|
+
answers: { answersQuestion: { type: 'noul', noul: 0.95 } },
|
|
87
|
+
};
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
const result = await runJudge({
|
|
93
|
+
label: 'screen-evidence',
|
|
94
|
+
kind: 'judge',
|
|
95
|
+
state: {
|
|
96
|
+
question: 'Can emergency documentation fixes bypass prior approval?',
|
|
97
|
+
passage: 'During an incident, the on-call engineer may merge a fix immediately; a second person reviews it the next working day.',
|
|
98
|
+
},
|
|
99
|
+
questions: {
|
|
100
|
+
answersQuestion: {
|
|
101
|
+
type: 'noul',
|
|
102
|
+
instructions: 'Does the passage contain a specific rule or exception answering the question? Retain conditional and contrary evidence; reject topic mentions and promotional claims.',
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
assert.equal(result.answers.answersQuestion.noul, 0.95);
|
|
107
|
+
console.log(result.answers.answersQuestion);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
This prints `{ type: 'noul', noul: 0.95 }`. The answer is **scripted**; it does not evaluate the passage or adapt to prompt changes. Answer IDs must match the requested question IDs. Noul returns a probability, not a boolean. Reported model and token usage may be omitted; the adapter preserves missing usage/cost as unknown instead of inventing measurements.
|
|
111
|
+
|
|
112
|
+
The [standalone TypeScript starter](../../examples/starter/README.md) includes unpublished local-tarball installation, a complete search-and-screen workflow, and tests for missing evidence and the screening step alone. Its injected client answers every named question generated by `sift`.
|
|
113
|
+
|
|
114
|
+
For adapter boundary tests from the repository root, run `npm run build` and `npm test -w @parcha/agentrun-jev`. Those tests inject fake HTTP responses and do not load provider credentials or call a model.
|
|
115
|
+
|
|
116
|
+
## Use a workflow as an agent tool
|
|
117
|
+
|
|
118
|
+
The [support integration example](../../docs/support-quickstart.md) returns a validated answer or escalation from a callable function. Register it as a tool in your application. Your host controls the surrounding agent loop, tool permissions and delivery.
|
|
119
|
+
|
|
120
|
+
## License
|
|
121
|
+
|
|
122
|
+
Apache-2.0. See the included LICENSE and NOTICE files.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { Fetch, RequestOptions, SystemOneRequest } from "@typesafe-ai/sdk";
|
|
2
|
+
import type { WorkflowDeps, SystemOneResponseReason } from "@parcha/agentrun-dsl";
|
|
3
|
+
/** Injectable client boundary. Custom clients must honor signal and disable their own retries. */
|
|
4
|
+
export interface JevClient {
|
|
5
|
+
systemOne(request: SystemOneRequest, options: RequestOptions): PromiseLike<unknown>;
|
|
6
|
+
}
|
|
7
|
+
export interface JevOptions {
|
|
8
|
+
apiKey?: string;
|
|
9
|
+
/** API root, without /v1/systemone; useful for an explicitly configured gateway. */
|
|
10
|
+
baseURL?: string;
|
|
11
|
+
fetch?: Fetch;
|
|
12
|
+
/** When supplied, owns credentials and transport; cannot be combined with apiKey/baseURL/fetch. */
|
|
13
|
+
client?: JevClient;
|
|
14
|
+
model?: string;
|
|
15
|
+
signal?: AbortSignal;
|
|
16
|
+
/** null disables the adapter deadline; requires a cancellation-only host client. */
|
|
17
|
+
timeoutMs?: number | null;
|
|
18
|
+
/** Optional host guard on serialized UTF-8 JSON state; null or omission disables it. */
|
|
19
|
+
maxStateBytes?: number | null;
|
|
20
|
+
maxAttempts?: number;
|
|
21
|
+
retryBaseMs?: number;
|
|
22
|
+
retryMaxMs?: number;
|
|
23
|
+
/** Explicit estimate; unknown prices are never silently treated as free. */
|
|
24
|
+
pricing?: {
|
|
25
|
+
inputUsdPerMillionTokens: number;
|
|
26
|
+
outputUsdPerMillionTokens: number;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
export type JevErrorCode = "configuration" | "invalid_request" | "invalid_response" | "http" | "connection" | "aborted" | "timeout";
|
|
30
|
+
declare const adapterResponseReasons: readonly ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
31
|
+
export type JevResponseReason = SystemOneResponseReason | typeof adapterResponseReasons[number];
|
|
32
|
+
export declare function isJevResponseReason(value: unknown): value is JevResponseReason;
|
|
33
|
+
export type JevResponseDiagnostic = {
|
|
34
|
+
reason: JevResponseReason;
|
|
35
|
+
};
|
|
36
|
+
export type JevRequestDiagnostic = {
|
|
37
|
+
reason: "invalid_state" | "state_too_large" | "invalid_questions";
|
|
38
|
+
label?: string;
|
|
39
|
+
stateBytes?: number;
|
|
40
|
+
maxStateBytes?: number;
|
|
41
|
+
};
|
|
42
|
+
/** Deliberately excludes provider bodies, headers, input state, and underlying causes. */
|
|
43
|
+
export declare class JevError extends Error {
|
|
44
|
+
readonly code: JevErrorCode;
|
|
45
|
+
readonly attempts: number;
|
|
46
|
+
readonly status?: number | undefined;
|
|
47
|
+
readonly requestDiagnostic?: JevRequestDiagnostic | undefined;
|
|
48
|
+
readonly responseDiagnostic?: JevResponseDiagnostic;
|
|
49
|
+
constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic);
|
|
50
|
+
}
|
|
51
|
+
export declare function createJevRunner(options?: JevOptions): NonNullable<WorkflowDeps["runJudge"]>;
|
|
52
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { APIConnectionError, APIError, TypeSafeClient } from "@typesafe-ai/sdk";
|
|
3
|
+
import { validateAnswers, SystemOneError, isSystemOneResponseReason } from "@parcha/agentrun-dsl";
|
|
4
|
+
const adapterResponseReasons = ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
5
|
+
export function isJevResponseReason(value) {
|
|
6
|
+
return isSystemOneResponseReason(value) || typeof value === "string" && adapterResponseReasons.includes(value);
|
|
7
|
+
}
|
|
8
|
+
/** Deliberately excludes provider bodies, headers, input state, and underlying causes. */
|
|
9
|
+
export class JevError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
attempts;
|
|
12
|
+
status;
|
|
13
|
+
requestDiagnostic;
|
|
14
|
+
responseDiagnostic;
|
|
15
|
+
constructor(code, message, attempts = 0, status, requestDiagnostic, responseDiagnostic) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.attempts = attempts;
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.requestDiagnostic = requestDiagnostic;
|
|
21
|
+
this.name = "JevError";
|
|
22
|
+
if (isJevResponseReason(responseDiagnostic?.reason))
|
|
23
|
+
this.responseDiagnostic = { reason: responseDiagnostic.reason };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const configuration = (condition, message) => {
|
|
27
|
+
if (!condition)
|
|
28
|
+
throw new JevError("configuration", message);
|
|
29
|
+
};
|
|
30
|
+
const milliseconds = (n, allowZero = false) => Number.isSafeInteger(n) && n >= (allowZero ? 0 : 1) && n <= 2_147_483_647;
|
|
31
|
+
const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
32
|
+
const tokens = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
33
|
+
function abortable(promise, signal, error) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
const abort = () => { signal.removeEventListener("abort", abort); reject(error()); };
|
|
36
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
37
|
+
Promise.resolve(promise).then(value => { signal.removeEventListener("abort", abort); if (signal.aborted)
|
|
38
|
+
reject(error());
|
|
39
|
+
else
|
|
40
|
+
resolve(value); }, failure => { signal.removeEventListener("abort", abort); reject(signal.aborted ? error() : failure); });
|
|
41
|
+
if (signal.aborted)
|
|
42
|
+
abort();
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
function wait(ms, signal, error) {
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
const abort = () => { clearTimeout(timer); signal.removeEventListener("abort", abort); reject(error()); };
|
|
48
|
+
const timer = setTimeout(() => { signal.removeEventListener("abort", abort); resolve(); }, ms);
|
|
49
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
50
|
+
if (signal.aborted)
|
|
51
|
+
abort();
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export function createJevRunner(options = {}) {
|
|
55
|
+
const timeoutMs = options.timeoutMs === null ? null : (options.timeoutMs ?? 30_000);
|
|
56
|
+
const maxStateBytes = options.maxStateBytes ?? null;
|
|
57
|
+
const maxAttempts = options.maxAttempts ?? 3;
|
|
58
|
+
const retryBaseMs = options.retryBaseMs ?? 500;
|
|
59
|
+
const retryMaxMs = options.retryMaxMs ?? 5_000;
|
|
60
|
+
configuration(timeoutMs === null || milliseconds(timeoutMs), "timeoutMs must be null or a positive integer of at most 2147483647.");
|
|
61
|
+
configuration(maxStateBytes === null || (Number.isSafeInteger(maxStateBytes) && maxStateBytes > 0), "maxStateBytes must be null or a positive safe integer.");
|
|
62
|
+
configuration(timeoutMs !== null || options.client !== undefined, "The TypeSafe SDK requires a finite timeout. For timeoutMs: null, supply a cancellation-only host client.");
|
|
63
|
+
configuration(Number.isInteger(maxAttempts) && maxAttempts >= 1 && maxAttempts <= 10, "maxAttempts must be an integer from 1 to 10.");
|
|
64
|
+
configuration(milliseconds(retryBaseMs, true) && milliseconds(retryMaxMs, true) && retryBaseMs <= retryMaxMs, "Retry delays must be nonnegative integers; retryBaseMs cannot exceed retryMaxMs.");
|
|
65
|
+
configuration(!options.client || (options.apiKey === undefined && options.baseURL === undefined && options.fetch === undefined), "Supply either client or transport options, not both.");
|
|
66
|
+
const pricing = options.pricing ? { ...options.pricing } : undefined;
|
|
67
|
+
if (pricing)
|
|
68
|
+
configuration([pricing.inputUsdPerMillionTokens, pricing.outputUsdPerMillionTokens].every(n => Number.isFinite(n) && n >= 0), "Configured token prices must be finite nonnegative numbers.");
|
|
69
|
+
const model = options.model ?? "jev-latest";
|
|
70
|
+
configuration(typeof model === "string" && model.trim().length > 0, "model must be a nonempty string.");
|
|
71
|
+
let client;
|
|
72
|
+
try {
|
|
73
|
+
client = options.client ?? new TypeSafeClient({
|
|
74
|
+
apiKey: options.apiKey, baseURL: options.baseURL, fetch: options.fetch,
|
|
75
|
+
defaultModel: model, retry: { maxRetries: 0 }, timeout: timeoutMs ?? undefined, logLevel: "off",
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
throw new JevError("configuration", "Could not configure Jev. Supply apiKey or set TYPESAFE_API_KEY, and check transport options.");
|
|
80
|
+
}
|
|
81
|
+
const runnerSignal = options.signal;
|
|
82
|
+
return async (params) => {
|
|
83
|
+
const deadline = new AbortController();
|
|
84
|
+
const signals = [deadline.signal, runnerSignal, params.signal].filter((s) => !!s);
|
|
85
|
+
const signal = AbortSignal.any(signals);
|
|
86
|
+
let attempt = 0;
|
|
87
|
+
const abortError = () => (runnerSignal?.aborted || params.signal?.aborted)
|
|
88
|
+
? new JevError("aborted", "Jev request was cancelled.", attempt)
|
|
89
|
+
: new JevError("timeout", "Jev request exceeded its total deadline.", attempt);
|
|
90
|
+
if (signal.aborted)
|
|
91
|
+
throw abortError();
|
|
92
|
+
const timer = timeoutMs === null ? undefined : setTimeout(() => deadline.abort(), timeoutMs);
|
|
93
|
+
const started = Date.now();
|
|
94
|
+
try {
|
|
95
|
+
let body;
|
|
96
|
+
let request;
|
|
97
|
+
const invalid = (reason, message, stateBytes) => new JevError("invalid_request", message, 0, undefined, { reason,
|
|
98
|
+
...(typeof params.label === "string" ? { label: params.label.slice(0, 200) } : {}),
|
|
99
|
+
...(stateBytes === undefined || maxStateBytes === null ? {} : { stateBytes, maxStateBytes }) });
|
|
100
|
+
const state = params.state ?? null;
|
|
101
|
+
let serializedState;
|
|
102
|
+
try {
|
|
103
|
+
if (typeof state !== "string" && state !== null && typeof state !== "object")
|
|
104
|
+
throw new Error();
|
|
105
|
+
serializedState = JSON.stringify(state);
|
|
106
|
+
if (typeof serializedState !== "string")
|
|
107
|
+
throw new Error();
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
throw invalid("invalid_state", "Jev state must be JSON-serializable text, an object, an array or null.");
|
|
111
|
+
}
|
|
112
|
+
const stateBytes = Buffer.byteLength(serializedState, "utf8");
|
|
113
|
+
if (maxStateBytes !== null && stateBytes > maxStateBytes)
|
|
114
|
+
throw invalid("state_too_large", `Jev assembled state is ${stateBytes} UTF-8 bytes; configured host limit is ${maxStateBytes} bytes. No request was sent.`, stateBytes);
|
|
115
|
+
try {
|
|
116
|
+
body = JSON.stringify({ state: JSON.parse(serializedState), model, questions: params.questions });
|
|
117
|
+
request = JSON.parse(body);
|
|
118
|
+
if (!record(request.questions) || Object.keys(request.questions).length === 0)
|
|
119
|
+
throw new Error();
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw invalid("invalid_questions", "Jev requires a nonempty JSON question map; no request was sent.");
|
|
123
|
+
}
|
|
124
|
+
for (attempt = 1;; attempt++) {
|
|
125
|
+
if (signal.aborted)
|
|
126
|
+
throw abortError();
|
|
127
|
+
let result;
|
|
128
|
+
try {
|
|
129
|
+
result = await abortable(client.systemOne(request, {
|
|
130
|
+
signal, ...(timeoutMs === null ? {} : { timeout: Math.max(1, timeoutMs - (Date.now() - started)) }), retry: { maxRetries: 0 },
|
|
131
|
+
}), signal, abortError);
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
if (signal.aborted)
|
|
135
|
+
throw abortError();
|
|
136
|
+
const status = error instanceof APIError ? error.status : undefined;
|
|
137
|
+
const retryable = status === 408 || status === 429 || (status !== undefined && status >= 500 && status <= 599) || error instanceof APIConnectionError;
|
|
138
|
+
if (retryable && attempt < maxAttempts) {
|
|
139
|
+
await wait(Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1)), signal, abortError);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (status !== undefined) {
|
|
143
|
+
const safeStatus = Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
|
|
144
|
+
const capacity = error instanceof APIError && record(error.body) && record(error.body.detail)
|
|
145
|
+
&& error.body.detail.error_type === "max_tokens_exceeded";
|
|
146
|
+
throw new JevError("http", safeStatus === undefined ? "Jev returned an HTTP failure." : `Jev returned HTTP ${safeStatus}.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined);
|
|
147
|
+
}
|
|
148
|
+
if (error instanceof APIConnectionError)
|
|
149
|
+
throw new JevError("connection", "Jev transport failed.", attempt);
|
|
150
|
+
throw new JevError("invalid_request", "Jev could not process the request. Check question and transport configuration.", attempt);
|
|
151
|
+
}
|
|
152
|
+
if (!record(result))
|
|
153
|
+
throw new JevError("invalid_response", "Jev returned an invalid response.", attempt, undefined, undefined, { reason: "response_shape" });
|
|
154
|
+
const answers = result.answers;
|
|
155
|
+
try {
|
|
156
|
+
validateAnswers(params.questions, answers);
|
|
157
|
+
}
|
|
158
|
+
catch (error) {
|
|
159
|
+
throw new JevError("invalid_response", "Jev returned invalid answers or probability distributions.", attempt, undefined, undefined, { reason: error instanceof SystemOneError && isSystemOneResponseReason(error.responseReason) ? error.responseReason : "answer_validation" });
|
|
160
|
+
}
|
|
161
|
+
const usage = result.usage;
|
|
162
|
+
if (usage != null && (!record(usage) || !tokens(usage.input_tokens) || !tokens(usage.output_tokens))) {
|
|
163
|
+
throw new JevError("invalid_response", "Jev returned invalid token usage.", attempt, undefined, undefined, { reason: "token_usage" });
|
|
164
|
+
}
|
|
165
|
+
if (result.model != null && (typeof result.model !== "string" || !result.model.trim())) {
|
|
166
|
+
throw new JevError("invalid_response", "Jev returned an invalid model identifier.", attempt, undefined, undefined, { reason: "model_identifier" });
|
|
167
|
+
}
|
|
168
|
+
const metering = record(usage) ? { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens } : null;
|
|
169
|
+
const cost = pricing && metering ? (metering.input_tokens * pricing.inputUsdPerMillionTokens + metering.output_tokens * pricing.outputUsdPerMillionTokens) / 1_000_000 : null;
|
|
170
|
+
if (cost !== null && !Number.isFinite(cost))
|
|
171
|
+
throw new JevError("invalid_response", "Jev cost estimate exceeded the numeric range.", attempt, undefined, undefined, { reason: "cost_range" });
|
|
172
|
+
return {
|
|
173
|
+
answers, model: typeof result.model === "string" ? result.model : null,
|
|
174
|
+
usage: metering, cost_usd: cost,
|
|
175
|
+
request_sha256: createHash("sha256").update(body).digest("hex"),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
clearTimeout(timer);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@parcha/agentrun-jev",
|
|
3
|
+
"version": "0.1.0-beta.1",
|
|
4
|
+
"description": "Optional Jev system one decisions for AgentRun workflows",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.19.0"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE",
|
|
22
|
+
"NOTICE"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc -p tsconfig.json",
|
|
26
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
+
"test": "node --test test/*.test.mjs"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.1",
|
|
31
|
+
"@typesafe-ai/sdk": "0.6.0"
|
|
32
|
+
},
|
|
33
|
+
"repository": {
|
|
34
|
+
"type": "git",
|
|
35
|
+
"url": "git+https://github.com/Parcha-ai/agentrun.git",
|
|
36
|
+
"directory": "packages/jev"
|
|
37
|
+
},
|
|
38
|
+
"bugs": {
|
|
39
|
+
"url": "https://github.com/Parcha-ai/agentrun/issues"
|
|
40
|
+
},
|
|
41
|
+
"homepage": "https://agentrun.ai",
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"tag": "beta"
|
|
45
|
+
}
|
|
46
|
+
}
|