@parcha/agentrun-decisions 0.0.0-stage → 0.1.0-beta.30

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/CHANGELOG.md ADDED
@@ -0,0 +1,38 @@
1
+ # Changelog
2
+
3
+ ## [Unreleased]
4
+
5
+ ## 0.1.0-beta.29 (2026-11-04)
6
+
7
+ - **Decision nodes name their provider, pin their model, ask for evidence and bound their own time**
8
+ - `judge`, `pick`, `sift`, a judged `route` and an `ask` predicate take optional `provider`, `model`, `evidence` (`"off"`, `"if_supported"` or `"required"`) and `timeoutMs` (1 to 120000). A route by value takes none of them.
9
+ - `judgeFromProviders({ providers, default, deadlineMs })` is the interpreter's `runJudge` over several providers: each request goes to its node's provider, or the default, with its pinned model, within the shorter of the node's `timeoutMs` and the provider's deadline. A node only ever shortens it. A call its node's bound cuts is `outcome_unknown`: never asked again, and the run escalates as `decision_interrupted`.
10
+ - With `decisionProviders: { providers, default }` in its deps, a run checks every decision node before any node runs: a provider the host lacks, `"required"` evidence from a provider that gives none, a model it does not serve, or a question type it does not answer stops the run naming the node. A provider is looked up by own property only, so a name such as `"constructor"` is a provider the host lacks, in the check and in `judgeFromProviders`.
11
+ - Without `decisionProviders`, a run refuses before any node runs a node that names a provider or sets `timeoutMs`: the host's judge could honour neither. `dryRunWorkflow` holds a node to no host's providers.
12
+ - `DecisionCapabilities` takes an optional `models`, the names a node may pin (absent or null: any). A pin outside them is refused before any node runs, and `checkCapabilities` refuses it as `invalid_request` before a provider sends anything. `parallelProvider()` declares `parallel-fast`, the one mode it asks.
13
+ - Pi's Jev judge is `judgeFromProviders` over a Jev-only registry, which the run's checks get too: a node naming another provider is refused before the run, with nothing sent to Jev, and a node's `timeoutMs` bounds its request. A Jev failure behind it keeps pi's fixed report (`jev_http` with its status, `jev_invalid_response` with its reason): `jevProvider` keeps the `JevError` as the `cause` of the `DecisionProviderError` it throws.
14
+ - The provider's evidence (`{ url, title, excerpts, scope }`) travels with the answer to the `<as>$answers` sidecar, the decision receipt and the node's answered event; `"off"` drops it, and `"required"` with none fails the decision. Receipts name the provider that answered. A `sift` gives each item's sidecar the evidence of the request that answered it, and its answered event names the provider and every request's evidence.
15
+ - A pinned `provider` or `model` is part of the decision id, so changing it asks the decision again. A node that pins neither keeps the id it had.
16
+ - A decision whose outcome was lost (`outcome_unknown`) is booked with the provider's `cost_basis` beside its cost: the exchange `recordDecision` gets carries both.
17
+ - `dryRunWorkflow` passes a node whose `evidence` is `"required"`: its synthetic answer carries a placeholder source.
18
+ - **Decision models plug in through one seam, and Parallel Decisions is the second one after Jev**
19
+ - `@parcha/agentrun-dsl` has `DecisionProvider`: a fast, non-agentic decision model that answers typed questions and declares what it can (question types, inputs, evidence, where its probabilities come from, web grounding, replay, limits) and the keys it reads by name. `judgeFromProvider(provider)` is a `runJudge`, so every decision node runs on it unchanged. A request beyond what the provider declares is refused before it is sent; a choice or score with probabilities but no confidence gets one derived with the formulas TypeSafe documents for Jev, and the decision receipt's new `confidence_source` names each one's source. The result also carries the provider's evidence, its request id and `cost_basis` (`reported`, `estimate` or `unknown`, which goes with a null cost).
20
+ - A provider may refuse a question: `{ "type": "refusal" }` is a valid answer. It never decodes to a value (not false, not an option, not a score). The run ends `escalated` for a person, with kind `DECISION_REFUSED` (`"decision_refused"`) at stage `"decision"` and the workflow state at the node, so the case is kept instead of lost to a failed run. A route with an `unsure` branch takes that branch instead, as it would an answer of no confidence. The receipt lists the refused questions in `refused`.
21
+ - `@parcha/agentrun-dsl/testing` has `registerDecisionProviderConformance`, the suite a provider's tests register with a fake transport: exact answers, a null cost never read as 0, typed errors (`auth`, `invalid_request`, `rate_limited`, `invalid_response`, `aborted`, and `outcome_unknown` for a 5xx or a deadline after sending from a provider that cannot replay; `http` and `timeout` for one that dedupes), no retry after sending for a provider that cannot replay, no key in what it returns or throws, declared limits refused before sending, and a refusal kept as one.
22
+ - `@parcha/agentrun-jev` has `jevProvider(options)`, Jev as a `DecisionProvider` that passes the suite. It sends each decision once (`maxAttempts: 1`), and a 408, a 5xx or a connection error is `outcome_unknown` at an unknown cost.
23
+ - Behaviour change under recovery (`withRecovery`): a decision whose provider throws `outcome_unknown` now ends `interrupted`, not `failed`. A failed decision is asked again by the next process; for a request sent whose outcome was lost, that would be a second paid ask. Now the next process escalates it as `decision_interrupted` without asking. Its estimate (`error.costUsd`), or an unknown cost that makes the run's spend read incomplete, is booked once, in the same commit as the outcome.
24
+ - An answer rejected after it was paid for is booked. When `judgeFromProvider` rejects a provider's answer (`invalid_response`, for example a distribution that does not sum to 1), the error now carries the provider's cost and basis, and a provider's own `invalid_response` for a response it could not read carries its charge too: Parallel at list price, Jev at an unknown cost. The decision ends `failed` and is asked again, and its cost is booked, in the receipt and under recovery in the run's spend, with the outcome. An unknown cost counts as an unpriced request, never $0. A request refused before it was sent books nothing.
25
+ - A provider's `outcome_unknown` error (a request sent whose outcome was lost, which may have been answered and billed) ends the run `escalated` as an interrupted decision: kind `"decision_interrupted"`, stage `"decision"`, booked at the cost the error carries. It is never asked again. The suite checks that a provider declaring `replay: "never"` never retries a failure after sending.
26
+ - New package `@parcha/agentrun-decisions`, held (not on npm yet), with `parallelProvider()`: Parallel Decisions (`POST /v1/decisions`) with probabilities and web citations as call-level evidence. The answered request is booked at list price as an estimate. The API takes no idempotency key, so a paid request is never re-sent unasked: it is sent again only when it provably never reached Parallel, or on a 429 with `Retry-After`. A 408, a 5xx or a connection lost after sending fails `outcome_unknown`, booked at list price, and the run escalates the decision as interrupted (`decision_interrupted`, stage `decision`) for a person. Its key is `PARALLEL_API_KEY`. Its tests run on a fake fetch over 28 recorded responses; the paid REST path is tested only by `test/parallel.live.test.mjs` with a key, and is skipped without one.
27
+ - **OpenRouter's Decisions models answer decision nodes, and four-place probabilities are accepted**
28
+ - `openrouterProvider()` in `@parcha/agentrun-decisions` sends a decision to any OpenRouter Decisions model (`POST https://openrouter.ai/api/v1/systemone`) named by the node's `model`, such as `liquid/d1`, `perplexity/pplx-decider-v1.2`, `cloudflare/clef` or `typesafe/jev-1.14`. A node that names no model is refused before sending. The response's `usage.cost` is booked as reported, else the cost is unknown. A request is sent again only when it never reached OpenRouter or on a 429 with `Retry-After`; one lost after sending is `outcome_unknown`. Its key is `OPENROUTER_API_KEY`.
29
+ - Images to OpenRouter (experimental) go in the JSON body as base64 `assets`, only to a model the public catalog lists with image input. Jev takes an image token anywhere in the state or a question, at most 1568 px on a side; every other model only as a whole top-level state value, sent as an item of an array state. A token placed anywhere else is refused before sending.
30
+ - `@parcha/agentrun-decisions/testing/faux-system-one` is a fake System One endpoint for a host's tests and rehearsals.
31
+ - `parallelProvider({ modes })` lists the Parallel modes a node may pin as `parallel-<mode>` (default `PARALLEL_MODES`, `["fast"]`); a node that pins none asks the first.
32
+ - `validateAnswers` accepts probabilities rounded to two, three or four places: a value may be off by half its grid's step. Cloudflare's `clef` reports four places (a distribution summing to 0.9999), which was refused as `probability_mass`.
33
+ - `jevProvider`'s refusal of images on its OpenRouter route names the way that works: the `openrouter` provider with `typesafe/jev-1.14`.
34
+ - AgentRun Server is published to npm, and `@parcha/agentrun-decisions` with it, which the server uses: `npx @parcha/agentrun-serve` starts the server with nothing else installed, its console included. pi runs; the Claude Agent SDK and Codex stay optional peers a person installs beside it, and capabilities say for each that it is not installed and the line that installs it. The archive carries the console with `dist/console/THIRD-PARTY-NOTICES.txt`, which the console's build writes from the bundle's own module list (each bundled package, its version, license and license text), and the server's `NOTICE` points to it. The release builds the console and stops when the server's archive lacks the console or its notices.
35
+ - A request to `openrouterProvider` now waits for its image check only within its deadline and cancel. Before, the first image request to a model other than Jev waited for `takesImages` before its deadline started and without looking at the run's signal. The catalog read behind it has its own 10 s bound, so a cancelled or shorter request waited up to 10 s, and a host's `takesImages` that never returned held the request forever. A wait the run's cancel cuts fails `aborted`, and one the deadline cuts fails `timeout`, including a node's `timeoutMs`. Nothing was sent in either case, and the error says so (`unsent`), so through `judgeFromProviders` neither becomes `outcome_unknown`. The catalog read itself is shared and is not cut: it goes on under its own 10 s timeout for the requests after it.
36
+ - A model other than Jev that `openrouterProvider` sends images to now knows which image is which. An object state's image fields go as top-level items after the other fields, and the first item now names them in order in `image_fields`. So `{ invoice: "<i1>", receipt: "<i2>", vendor: "Acme" }` goes as `[{ vendor: "Acme", image_fields: ["invoice", "receipt"] }, "<i1>", "<i2>"]`. Before, the field names were dropped, and a question comparing the receipt with the invoice reached the model with no word on which image was which. A state with a field of its own named `image_fields` keeps it, and the names go under `_image_fields`. Images to these models remain an OpenRouter alpha.
37
+ - The Parallel decision provider's README says that Parallel answers from live web evidence as well as the state it is given, so a judgment that must rest on the state alone should use Jev.
38
+ - Install and `npx` commands in the READMEs and docs name `@latest` instead of `@beta`. Releases publish under npm's `latest` tag, and `beta` was not moved with them: it still pointed at 0.1.0-beta.21 while `latest` was 0.1.0-beta.28, and `@parcha/pi-durable-agent`, `@parcha/pi-git-remote` and `@parcha/pi-agent-learn` had no `beta` tag at all, so their install lines failed. The harness demo's hint for a missing `@parcha/pi-transport` names `@latest` too. `@parcha/agentrun-harness` is not on npm yet (its `latest` is a placeholder), so its README says it is held and installs it from a packed tarball. The README's Render option gives measured memory: a Starter's 512 MB runs about 3 pi agents at once, and Claude Code or Codex runs want a 2 GB instance. The stranger check reads the install line as `@latest`, installs `@latest` with `--registry`, and walks the keyless examples against the registry's `latest`. The release guide drops the step that moved `beta` after a release; `beta` is kept only for older links, with the one-time command to bring it up to a release.
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
@@ -0,0 +1,2 @@
1
+ AgentRun
2
+ Copyright 2026 Parcha Labs, Inc.
package/README.md CHANGED
@@ -1,3 +1,66 @@
1
- # Temporary Holding Version
1
+ # @parcha/agentrun-decisions
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Published to npm from the next release (`@latest`), with AgentRun Server, which uses it. Until then it installs from this repository.
4
+
5
+ Third-party decision models for the AgentRun DSL's decision nodes (`judge`, `pick`, `sift`, a judged `route`, `ask` and a `verify` clause). Each is a `DecisionProvider`, the seam in `@parcha/agentrun-dsl`, and runs through `judgeFromProvider`, with no agent harness. Jev's provider is `jevProvider` in `@parcha/agentrun-jev`.
6
+
7
+ ## Parallel Decisions
8
+
9
+ `parallelProvider()` asks [Parallel Decisions](https://docs.parallel.ai) (`POST https://api.parallel.ai/v1/decisions`): yes/no (noul), choice and score questions about a JSON state, answered with probabilities and grounded in live web evidence.
10
+
11
+ ```ts
12
+ import { judgeFromProvider, runWorkflow } from '@parcha/agentrun-dsl';
13
+ import { parallelProvider } from '@parcha/agentrun-decisions';
14
+
15
+ const result = await runWorkflow(workflow, input, { runJudge: judgeFromProvider(parallelProvider()) });
16
+ ```
17
+
18
+ The key is `PARALLEL_API_KEY`, read by name when a request is made, or `apiKey`. With neither, the request fails with a `DecisionProviderError` of code `configuration` that names the variable, and nothing is sent.
19
+
20
+ What it does with Parallel's answers:
21
+
22
+ - **Types and limits.** It answers `noul`, `choice` and `score`. Before sending, it refuses as `invalid_request` anything over Parallel's documented limits: more than 100 questions, a choice outside 2 to 255 options, a score outside 2 to 10 levels, a question that renders past 5,000 characters, or a state over 96,000 bytes. A choice option with no description is described by its own name.
23
+ - **Model.** It asks Parallel's `fast` mode and declares the one model it serves, `parallel-fast`. A node that pins another model is refused before the run starts when the host passes its providers to the run's checks, and as `invalid_request` before anything is sent otherwise. `modes` (default `PARALLEL_MODES`, `["fast"]`) lists the modes a node may pin as `parallel-<mode>`, for one Parallel adds before this package does; a node that pins none asks the first.
24
+ - **Refusals.** Parallel may decline a question (`{ "type": "refusal" }`). It stays a refusal: the DSL never decodes it to a value. The run escalates for a person (`decision_refused`), or a route takes its `unsure` branch.
25
+ - **Confidence.** A choice or score that comes back without a confidence gets one derived from its probabilities, and the decision receipt's `confidence_source` says so.
26
+ - **Evidence.** Parallel's citations apply to the whole request, not to one answer, so each is evidence with `scope: "call"`.
27
+ - **Grounding.** Parallel answers from live web evidence as well as the state it is given. A claim the web knows nothing about (a private or fictional fact) can score lower than the state alone supports, with citations to unrelated pages. For a judgment that must rest on the state alone, use Jev (`jevProvider`), which judges only what it is given.
28
+ - **Cost.** The response carries no cost, so the answered request is booked at Parallel's list price, `PARALLEL_LIST_PRICE_USD` ($0.001 per request), with `cost_basis: "estimate"`. So is one sent whose outcome was lost (below). Its `decision_id` is the `provider_request_id`.
29
+ - **Replay.** The API takes no idempotency key, so the provider declares `replay: "never"`: a paid request is never re-sent unasked. It is sent again only when it provably never reached Parallel (no DNS answer, no connection, no TLS handshake), or on a 429 that says when to retry (`Retry-After`). A 408, a 5xx or a connection lost after sending is sent once and fails `outcome_unknown`, booked at list price as an estimate. The run then escalates the decision for a person as interrupted (`decision_interrupted`), and it is never asked again.
30
+ - **Errors.** Each one is a `DecisionProviderError`:
31
+ - 401 and 403 are `auth`;
32
+ - 400 and 422 are `invalid_request`, with Parallel's `ref_id` as `refId` and the body dropped;
33
+ - a 429 is retried after its `Retry-After`, and is `rate_limited` without one or once the attempts are spent;
34
+ - a 408, a 5xx or a connection lost after sending is `outcome_unknown`, with `costUsd` and `costBasis` on the error;
35
+ - a request that never reached Parallel is retried with backoff, then `connection`;
36
+ - a body that is not JSON, or answers that do not match the questions, is `invalid_response`;
37
+ - the host's own cancel is `aborted`. The deadline (`timeoutMs`, 30 s by default, or the host's shorter one) ending a request in flight is `outcome_unknown`, booked at list price, since Parallel may have answered it. One that ends a wait between attempts, with nothing in flight, is `timeout`.
38
+
39
+ No message carries the key, a header or a body.
40
+
41
+ ## OpenRouter Decisions
42
+
43
+ `openrouterProvider()` asks any of [OpenRouter's](https://openrouter.ai) Decisions models (`POST https://openrouter.ai/api/v1/systemone`), the System One request Jev takes (`{ state, model, questions }`), sent to the model the node's `model` names, such as `perplexity/pplx-decider-v1.2`, `liquid/d1`, `cloudflare/clef` or `typesafe/jev-1.14`. A node that names none is refused before anything is sent, unless the provider was given a default `model`.
44
+
45
+ ```ts
46
+ import { judgeFromProviders } from '@parcha/agentrun-dsl';
47
+ import { openrouterProvider, parallelProvider } from '@parcha/agentrun-decisions';
48
+
49
+ const runJudge = judgeFromProviders({ providers: { openrouter: openrouterProvider(), parallel: parallelProvider() }, default: 'openrouter' });
50
+ ```
51
+
52
+ The key is `OPENROUTER_API_KEY`, read by name when a request is made, or `apiKey`.
53
+
54
+ - **Cost.** The response's `usage.cost` is booked as `reported`; a response without one is an unknown cost (null, never 0).
55
+ - **Replay.** As Parallel: `replay: "never"`. A request is sent again only when it never reached OpenRouter, or on a 429 with `Retry-After` (up to `maxAttempts`, default 3). A 408, a 5xx, a connection lost after sending or a deadline in flight is `outcome_unknown` at an unknown cost.
56
+ - **Images (experimental).** OpenRouter takes JSON only, so a request's images go in the body as `assets` (`{ type: "image", format, data_base64 }`) with the `TypeSafe-Danger-Zone-Images` header, and only to a model the public catalog (`/v1/models?output_modalities=decisions`) lists with image input (`takesImages` overrides the catalog). Jev reads an image token anywhere in the state or a question, and refuses an image over 1568 px on a side, which the provider refuses before sending. Every other model reads an image only as a top-level item of an array state: an object state whose tokens are whole top-level values goes as `[{ the other fields, image_fields }, "<token>", ...]`, where `image_fields` names, in order, the field each image stood in (`{ invoice: "<i1>", receipt: "<i2>" }` goes as `[{ image_fields: ["invoice", "receipt"] }, "<i1>", "<i2>"]`), and a token anywhere else is refused before sending. A request waits for that image check only within its own deadline and cancel. The catalog read behind the check is shared by every request and is not cut with one: it goes on under its own 10 s timeout, and its answer serves the requests after it (a read that fails is tried again by the next one). OpenRouter documents image assets as alpha, so the provider lists `image` under `experimental.inputs`.
57
+
58
+ `@parcha/agentrun-decisions/testing/faux-system-one` is a fake System One endpoint for a host's tests: its answers are made up but stable (drawn from a hash of the model, the question and the state), it lists a small Decisions catalog, and it reads images as OpenRouter does. No request leaves the process.
59
+
60
+ ## Tests
61
+
62
+ `npm test -w @parcha/agentrun-decisions` runs on a fake fetch. It registers the DSL's provider conformance suite, replays 28 responses recorded from Parallel's decision tool and the live Parallel and OpenRouter responses of 2026-10-30 (five OpenRouter models) through the seam, and checks the request as sent, the limits and the errors. `test/parallel.live.test.mjs` makes three decisions on the paid REST path (about $0.003) and runs only with `PARALLEL_API_KEY` set; without it, it is skipped and says so.
63
+
64
+ ## License
65
+
66
+ Apache-2.0
@@ -0,0 +1,2 @@
1
+ export { parallelProvider, PARALLEL_LIST_PRICE_USD, PARALLEL_MODES, type ParallelOptions } from "./parallel.js";
2
+ export { openrouterProvider, type OpenRouterOptions, type ExperimentalInputs } from "./openrouter.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { parallelProvider, PARALLEL_LIST_PRICE_USD, PARALLEL_MODES } from "./parallel.js";
2
+ export { openrouterProvider } from "./openrouter.js";
@@ -0,0 +1,34 @@
1
+ import type { DecisionCapabilities, DecisionProvider } from "@parcha/agentrun-dsl";
2
+ export interface OpenRouterOptions {
3
+ /** The key; otherwise OPENROUTER_API_KEY, read when a request is made. */
4
+ apiKey?: string;
5
+ /** API root, without /v1/systemone (default https://openrouter.ai/api). */
6
+ baseURL?: string;
7
+ /** The transport: a host's faux fetch replaces OpenRouter here (see `@parcha/agentrun-decisions/testing/faux-system-one`). */
8
+ fetch?: typeof fetch;
9
+ /** The model for a node that names none. Absent, such a node is refused: every OpenRouter decision names its model. */
10
+ model?: string;
11
+ /** The longest one request may take, every attempt included (default 30 s); a shorter deadline from the host wins. */
12
+ timeoutMs?: number;
13
+ /** Attempts for a request that never reached OpenRouter, or a 429 that says when to retry (default 3). */
14
+ maxAttempts?: number;
15
+ retryBaseMs?: number;
16
+ retryMaxMs?: number;
17
+ /** Whether `model` takes image input. Absent, the public model catalog (`/v1/models?output_modalities=decisions`) is read
18
+ * once, through `fetch`, the first time a request carries an image; a model it does not list with image input is refused
19
+ * before sending. A catalog that cannot be read refuses nothing. */
20
+ takesImages?: (model: string) => boolean | Promise<boolean>;
21
+ /** Sent as OpenRouter's app attribution headers (HTTP-Referer, X-Title) when set. */
22
+ app?: {
23
+ url?: string;
24
+ title?: string;
25
+ };
26
+ }
27
+ /** What a provider adds beside the seam's capabilities: the inputs not verified against the live API. */
28
+ export interface ExperimentalInputs {
29
+ experimental: {
30
+ inputs: readonly DecisionCapabilities["inputs"][number][];
31
+ note: string;
32
+ };
33
+ }
34
+ export declare function openrouterProvider(options?: OpenRouterOptions): DecisionProvider & ExperimentalInputs;
@@ -0,0 +1,282 @@
1
+ // OpenRouter's Decisions models (POST https://openrouter.ai/api/v1/systemone) as a DecisionProvider: the System One request
2
+ // Jev takes ({ state, model, questions }), sent to whichever Decisions model the node's `model` names, such as
3
+ // `perplexity/pplx-decider-v1.2`, `liquid/d1` or `cloudflare/clef`. A request is paid once sent, so it is sent again only
4
+ // when it provably never reached OpenRouter (a connect error before sending) or was refused with a time to retry (a 429
5
+ // with Retry-After); a 408, a 5xx, a connection lost after sending or a deadline in flight is outcome_unknown at an unknown
6
+ // cost. The cost is the response's `usage.cost`, else unknown (null, never 0). Images go in the JSON body as base64
7
+ // `assets` (OpenRouter refuses TypeSafe's multipart form), only to a model whose catalog entry lists image input; OpenRouter
8
+ // documents them as alpha, so the provider marks them experimental.
9
+ import { setTimeout as sleep } from "node:timers/promises";
10
+ import { checkCapabilities, DecisionProviderError, imageDimensions } from "@parcha/agentrun-dsl";
11
+ const KEY_VARIABLE = "OPENROUTER_API_KEY";
12
+ const BASE_URL = "https://openrouter.ai/api";
13
+ const IMAGE_HEADER = "TypeSafe-Danger-Zone-Images";
14
+ /** Jev's longest image side in pixels: past it TypeSafe answers HTTP 400 "Invalid image dimensions.", through OpenRouter
15
+ * too (live, 2026-10-30). The same cap as @parcha/agentrun-jev's JEV_MAX_IMAGE_SIDE_PX. */
16
+ const JEV_MAX_IMAGE_SIDE_PX = 1568;
17
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
18
+ const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0;
19
+ /** Failures a request meets before it is sent: no DNS answer, no connection, no TLS handshake. Any other is after. */
20
+ const BEFORE_SENDING = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "UND_ERR_CONNECT_TIMEOUT",
21
+ "CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "ERR_TLS_CERT_ALTNAME_INVALID"]);
22
+ const neverSent = (error) => {
23
+ for (let cause = error, depth = 0; isRecord(cause) || cause instanceof Error; cause = cause.cause, depth++) {
24
+ const code = cause.code;
25
+ if (typeof code === "string" && BEFORE_SENDING.has(code))
26
+ return true;
27
+ if (depth >= 4)
28
+ break;
29
+ }
30
+ return false;
31
+ };
32
+ /** The wait a Retry-After header asks for, in milliseconds: a number of seconds, or an HTTP date (a past one is 0). */
33
+ function retryAfterMs(response) {
34
+ const value = response.headers.get("retry-after")?.trim();
35
+ if (!value)
36
+ return undefined;
37
+ if (/^\d+(?:\.\d+)?$/.test(value))
38
+ return Math.round(Number(value) * 1000);
39
+ const at = Date.parse(value);
40
+ return Number.isFinite(at) ? Math.max(0, at - Date.now()) : undefined;
41
+ }
42
+ /** The request body. OpenRouter takes JSON only (a multipart body is refused, "invalid content-type"): each image goes in
43
+ * `assets` under its token as `{ type: "image", format, data_base64 }`, the file in standard base64 with no `data:` prefix. */
44
+ function bodyOf(payload, images) {
45
+ const entries = Object.entries(images ?? {});
46
+ const headers = { "content-type": "application/json" };
47
+ if (!entries.length)
48
+ return { body: JSON.stringify(payload), headers };
49
+ const assets = Object.fromEntries(entries.map(([token, image]) => [token, { type: "image", format: image.mime === "image/jpeg" ? "jpeg" : "png", data_base64: Buffer.from(image.bytes).toString("base64") }]));
50
+ return { body: JSON.stringify({ ...payload, assets }), headers: { ...headers, [IMAGE_HEADER]: "true" } };
51
+ }
52
+ /** Whether `model` is Jev, which reads an image token anywhere in the state or a question, inside longer text too.
53
+ * OpenRouter's other Decisions models read an image only as a top-level item of an array state; anywhere else OpenRouter
54
+ * refuses it (live, 2026-10-30: "reads images only as top-level state items"). */
55
+ const readsTokenAnywhere = (model) => /^~?(typesafe\/)?jev-/.test(model);
56
+ /** The state a non-Jev model reads its images in: an array state with each token a top-level item goes as it is; an object
57
+ * state (a workflow node's) whose tokens are top-level values goes as `[{ the other fields, image_fields }, "<token>",
58
+ * ...]`, where `image_fields` names, in order, the field each image item after it stood in (`["invoice", "receipt"]`), so
59
+ * a question that compares them can tell which is which. Names, not tokens: OpenRouter refuses a token anywhere but as a
60
+ * top-level item. A state that has its own `image_fields` keeps it, and the names go under `_image_fields`. Null when a
61
+ * token stands anywhere else. */
62
+ function itemizedState(state, tokens) {
63
+ if (Array.isArray(state))
64
+ return tokens.every((token) => state.includes(token)) ? state : null;
65
+ if (!isRecord(state))
66
+ return null;
67
+ const isToken = (value) => typeof value === "string" && tokens.includes(value);
68
+ const placed = Object.values(state).filter(isToken);
69
+ if (!tokens.every((token) => placed.includes(token)))
70
+ return null;
71
+ const rest = Object.fromEntries(Object.entries(state).filter(([, value]) => !isToken(value)));
72
+ let key = "image_fields";
73
+ while (Object.hasOwn(rest, key))
74
+ key = `_${key}`;
75
+ rest[key] = Object.entries(state).filter(([, value]) => isToken(value)).map(([name]) => name);
76
+ return [rest, ...placed];
77
+ }
78
+ /** Every string value in the state, an instruction or a criterion: the places Jev reads an image token. */
79
+ function* tokenPlaces(state, questions) {
80
+ const walk = function* (value) {
81
+ if (typeof value === "string")
82
+ yield value;
83
+ else if (Array.isArray(value))
84
+ for (const each of value)
85
+ yield* walk(each);
86
+ else if (isRecord(value))
87
+ for (const each of Object.values(value))
88
+ yield* walk(each);
89
+ };
90
+ yield* walk(state);
91
+ for (const question of Object.values(questions))
92
+ if (isRecord(question)) {
93
+ yield* walk(question.instructions);
94
+ yield* walk(question.criteria);
95
+ }
96
+ }
97
+ /** The answers, metering and id of a 200 response, checked for shape and against the questions asked; the seam checks
98
+ * each answer against its question. */
99
+ function readResponse(body, questions, attempts) {
100
+ // OpenRouter answered, so the request was billed: a response this rejects is booked at an unknown cost.
101
+ const invalid = (why) => new DecisionProviderError("invalid_response", `OpenRouter returned ${why}.`, { attempts, costUsd: null, costBasis: "unknown" });
102
+ if (!isRecord(body) || !isRecord(body.answers))
103
+ throw invalid("no answers");
104
+ const given = Object.keys(body.answers);
105
+ if (given.length !== Object.keys(questions).length || given.some((id) => !Object.hasOwn(questions, id)))
106
+ throw invalid("answers that do not match the questions asked");
107
+ const answers = Object.create(null);
108
+ for (const [id, answer] of Object.entries(body.answers)) {
109
+ if (!isRecord(answer) || typeof answer.type !== "string")
110
+ throw invalid(`an answer with no type for "${id}"`);
111
+ answers[id] = answer;
112
+ }
113
+ const usage = isRecord(body.usage) ? body.usage : undefined;
114
+ const counted = usage && isCount(usage.input_tokens) ? { input_tokens: usage.input_tokens, output_tokens: isCount(usage.output_tokens) ? usage.output_tokens : 0 } : null;
115
+ const cost = usage && typeof usage.cost === "number" && Number.isFinite(usage.cost) && usage.cost >= 0 ? usage.cost : null;
116
+ return {
117
+ answers: { ...answers }, evidence: [], model: typeof body.model === "string" && body.model.trim() ? body.model : null, usage: counted,
118
+ cost_usd: cost, cost_basis: cost === null ? "unknown" : "reported", provider_request_id: typeof body.id === "string" ? body.id : null,
119
+ };
120
+ }
121
+ /** `promise`, or `signal`'s reason once it aborts first. The promise itself runs on: the catalog read is shared by every
122
+ * request, so one request's cut does not end it for the others. */
123
+ function raced(promise, signal) {
124
+ if (signal.aborted) {
125
+ promise.catch(() => { });
126
+ return Promise.reject(signal.reason);
127
+ }
128
+ return new Promise((resolve, reject) => {
129
+ const stop = () => reject(signal.reason);
130
+ signal.addEventListener("abort", stop, { once: true });
131
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
132
+ });
133
+ }
134
+ /** The image-capable Decisions models the public catalog lists, read once; null when it cannot be read. */
135
+ function catalogReader(fetcher, root) {
136
+ let read;
137
+ return () => (read ??= (async () => {
138
+ try {
139
+ const response = await fetcher(`${root}/v1/models?output_modalities=decisions`, { signal: AbortSignal.timeout(10_000) });
140
+ if (!response.ok)
141
+ return null;
142
+ const body = await response.json();
143
+ const models = isRecord(body) && Array.isArray(body.data) ? body.data : [];
144
+ return new Set(models.filter(isRecord).filter((m) => isRecord(m.architecture) && Array.isArray(m.architecture.input_modalities) && m.architecture.input_modalities.includes("image")).map((m) => String(m.id)));
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ })().then((set) => { if (set === null)
150
+ read = undefined; return set; }));
151
+ }
152
+ export function openrouterProvider(options = {}) {
153
+ const capabilities = {
154
+ types: ["noul", "choice", "score"], inputs: ["text", "json", "image"], evidence: "none", probability: "model", grounding: false,
155
+ replay: "never", maxQuestions: null, maxStateBytes: null,
156
+ };
157
+ const timeoutMs = options.timeoutMs ?? 30_000;
158
+ const maxAttempts = options.maxAttempts ?? 3;
159
+ const retryBaseMs = options.retryBaseMs ?? 500;
160
+ const retryMaxMs = options.retryMaxMs ?? 5_000;
161
+ const root = (options.baseURL ?? BASE_URL).replace(/\/+$/, "");
162
+ const url = `${root}/v1/systemone`;
163
+ const fetcher = options.fetch ?? fetch;
164
+ const catalog = catalogReader(fetcher, root);
165
+ const takesImages = options.takesImages ?? (async (model) => (await catalog())?.has(model) ?? true);
166
+ return {
167
+ id: "openrouter", needs: [KEY_VARIABLE], capabilities,
168
+ experimental: { inputs: ["image"], note: "Images to OpenRouter's Decisions models go as base64 JSON assets, an alpha OpenRouter feature; for other models each token is a whole top-level state value, sent as an item of an array state." },
169
+ async decide(request, ctx) {
170
+ checkCapabilities(capabilities, request);
171
+ const model = request.model ?? options.model;
172
+ if (typeof model !== "string" || !model.trim())
173
+ throw new DecisionProviderError("invalid_request", "An OpenRouter decision names its model (the node's model, such as liquid/d1); this one names none.");
174
+ const images = request.images && Object.keys(request.images).length ? request.images : undefined;
175
+ // The deadline starts here, before the image check, and the check ends on a cancel or the deadline like the request.
176
+ const budgetMs = Math.min(timeoutMs, ctx.deadlineMs ?? Infinity);
177
+ const deadlineAt = Date.now() + budgetMs;
178
+ const signal = AbortSignal.any([ctx.signal, AbortSignal.timeout(budgetMs)]);
179
+ const stopped = (attempts) => new DecisionProviderError("aborted", "The OpenRouter request was cancelled.", { attempts });
180
+ let state = request.state ?? null;
181
+ if (images) {
182
+ let takes;
183
+ try {
184
+ takes = await raced(Promise.resolve().then(() => takesImages(model)), signal);
185
+ }
186
+ catch (error) {
187
+ if (!signal.aborted)
188
+ throw error;
189
+ // Nothing was sent, and the error says so (unsent), so a host's node timeout never takes it for a billed request.
190
+ // A cancel is aborted; a deadline is timeout, the node's own timeoutMs (its cut's TimeoutError) included.
191
+ const cancelled = ctx.signal.aborted && ctx.signal.reason?.name !== "TimeoutError";
192
+ throw cancelled
193
+ ? new DecisionProviderError("aborted", "The OpenRouter request was cancelled before it was sent.", { attempts: 0, unsent: true })
194
+ : new DecisionProviderError("timeout", `Whether the OpenRouter model ${model} takes images was not known before the deadline; nothing was sent.`, { attempts: 0, unsent: true });
195
+ }
196
+ if (!takes)
197
+ throw new DecisionProviderError("invalid_request", `The OpenRouter model ${model} takes no image input.`);
198
+ if (readsTokenAnywhere(model)) {
199
+ const places = [...tokenPlaces(request.state, request.questions)];
200
+ const unplaced = Object.keys(images).filter((token) => !places.some((text) => text.includes(token)));
201
+ if (unplaced.length)
202
+ throw new DecisionProviderError("invalid_request", `Every image token must appear in the state or a question: ${unplaced.join(", ")} does not.`);
203
+ for (const [token, image] of Object.entries(images)) {
204
+ const size = imageDimensions(image.bytes);
205
+ if (size === null)
206
+ throw new DecisionProviderError("invalid_request", `The image ${token} (${image.ref}) has no width and height its header can be read from; nothing was sent.`);
207
+ if (size.width > JEV_MAX_IMAGE_SIDE_PX || size.height > JEV_MAX_IMAGE_SIDE_PX)
208
+ throw new DecisionProviderError("invalid_request", `The image ${token} (${image.ref}) is ${size.width}x${size.height} px; Jev takes at most ${JEV_MAX_IMAGE_SIDE_PX} px on each side. Render it smaller (a letter page at 140 dpi is 1190x1540); nothing was sent.`);
209
+ }
210
+ }
211
+ else {
212
+ state = itemizedState(request.state, Object.keys(images));
213
+ if (state === null)
214
+ throw new DecisionProviderError("invalid_request", `The OpenRouter model ${model} reads an image only where the state holds its token as a whole top-level value, such as state: { "page": "${Object.keys(images)[0]}" }; not inside text or a question.`);
215
+ }
216
+ }
217
+ const key = options.apiKey ?? process.env[KEY_VARIABLE];
218
+ if (typeof key !== "string" || !key.trim())
219
+ throw new DecisionProviderError("configuration", `${KEY_VARIABLE} is not set.`);
220
+ const payload = { state, model, questions: request.questions };
221
+ // Sent and lost: it may have been answered and billed, so it is never sent again, at an unknown cost.
222
+ const lost = (attempts, what, status) => new DecisionProviderError("outcome_unknown", `OpenRouter ${what} after the request was sent; it may have been answered, and is not sent again.`, { attempts, ...(status !== undefined ? { status } : {}), costUsd: null, costBasis: "unknown" });
223
+ const app = { ...(options.app?.url ? { "HTTP-Referer": options.app.url } : {}), ...(options.app?.title ? { "X-Title": options.app.title } : {}) };
224
+ for (let attempt = 1;; attempt++) {
225
+ // A form body is read as it is sent, so each attempt builds its own.
226
+ const { body, headers } = bodyOf(payload, images);
227
+ let response;
228
+ try {
229
+ response = await fetcher(url, { method: "POST", headers: { ...headers, ...app, authorization: `Bearer ${key}` }, body, signal });
230
+ }
231
+ catch (error) {
232
+ if (signal.aborted)
233
+ throw ctx.signal.aborted ? stopped(attempt) : lost(attempt, "passed its deadline");
234
+ if (!neverSent(error))
235
+ throw lost(attempt, "lost the connection");
236
+ if (attempt >= maxAttempts)
237
+ throw new DecisionProviderError("connection", "OpenRouter could not be reached.", { attempts: attempt });
238
+ await sleep(Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1)), undefined, { signal }).catch(() => { throw ctx.signal.aborted ? stopped(attempt) : new DecisionProviderError("timeout", "OpenRouter could not be reached before the deadline.", { attempts: attempt }); });
239
+ continue;
240
+ }
241
+ if (response.ok) {
242
+ let text;
243
+ try {
244
+ text = await response.text();
245
+ }
246
+ catch {
247
+ throw ctx.signal.aborted ? stopped(attempt) : lost(attempt, signal.aborted ? "passed its deadline" : "lost the connection while the answer was read");
248
+ }
249
+ let parsed;
250
+ try {
251
+ parsed = JSON.parse(text);
252
+ }
253
+ catch {
254
+ throw new DecisionProviderError("invalid_response", "OpenRouter returned a body that is not JSON.", { attempts: attempt, costUsd: null, costBasis: "unknown" });
255
+ }
256
+ return readResponse(parsed, request.questions, attempt);
257
+ }
258
+ const status = response.status;
259
+ if (status === 408 || (status >= 500 && status <= 599)) {
260
+ void response.body?.cancel().catch(() => { });
261
+ throw lost(attempt, `answered HTTP ${status}`, status);
262
+ }
263
+ // A 429 was refused unanswered; it is sent again only when OpenRouter says when, and only if that is before the deadline.
264
+ const wait = status === 429 ? retryAfterMs(response) : undefined;
265
+ if (wait !== undefined && attempt < maxAttempts && wait < deadlineAt - Date.now()) {
266
+ void response.body?.cancel().catch(() => { });
267
+ await sleep(wait, undefined, { signal }).catch(() => { throw ctx.signal.aborted ? stopped(attempt) : new DecisionProviderError("rate_limited", `OpenRouter rate-limited the request after ${attempt} attempts.`, { status, attempts: attempt }); });
268
+ continue;
269
+ }
270
+ void response.body?.cancel().catch(() => { });
271
+ const details = { status, attempts: attempt };
272
+ if (status === 401 || status === 403)
273
+ throw new DecisionProviderError("auth", `OpenRouter refused the key (HTTP ${status}).`, details);
274
+ if (status === 400 || status === 404 || status === 422)
275
+ throw new DecisionProviderError("invalid_request", `OpenRouter refused the request (HTTP ${status}).`, details);
276
+ if (status === 429)
277
+ throw new DecisionProviderError("rate_limited", `OpenRouter rate-limited the request after ${attempt} attempts.`, details);
278
+ throw new DecisionProviderError("http", `OpenRouter answered HTTP ${status}.`, details);
279
+ }
280
+ },
281
+ };
282
+ }
@@ -0,0 +1,25 @@
1
+ import type { DecisionProvider } from "@parcha/agentrun-dsl";
2
+ /** Parallel's list price for one `fast` decision request, up to 100 questions (docs.parallel.ai pricing, 2026-10-28). */
3
+ export declare const PARALLEL_LIST_PRICE_USD = 0.001;
4
+ /** The modes Parallel Decisions takes, as its API reference lists them (2026-10-30: `fast` only, a const). A node pins
5
+ * one as `parallel-<mode>`, the name an answer's model reads; a node that pins none asks the first. */
6
+ export declare const PARALLEL_MODES: readonly string[];
7
+ export interface ParallelOptions {
8
+ /** The modes a node may pin (default PARALLEL_MODES), for when Parallel adds one before this package does. */
9
+ modes?: readonly string[];
10
+ /** The key; otherwise PARALLEL_API_KEY, read when a request is made. */
11
+ apiKey?: string;
12
+ /** API root, without /v1/decisions. */
13
+ baseURL?: string;
14
+ fetch?: typeof fetch;
15
+ /** The longest one request may take, every attempt included (default 30 s); a shorter deadline from the host wins. */
16
+ timeoutMs?: number;
17
+ /** Attempts for a request that never reached Parallel, or a 429 that says when to retry (default 3). A failure after
18
+ * sending is never retried. */
19
+ maxAttempts?: number;
20
+ retryBaseMs?: number;
21
+ retryMaxMs?: number;
22
+ /** Whether citations carry their passages (default true). */
23
+ includeExcerpts?: boolean;
24
+ }
25
+ export declare function parallelProvider(options?: ParallelOptions): DecisionProvider;
@@ -0,0 +1,192 @@
1
+ // Parallel Decisions (POST https://api.parallel.ai/v1/decisions) as a DecisionProvider: typed questions about a JSON
2
+ // state, answered with probabilities and grounded in live web evidence. The response carries no cost and the API takes no
3
+ // idempotency key, so the answered request is booked at list price as an estimate, and a paid request is never re-sent
4
+ // unasked: only one that provably never reached Parallel (a connect error before sending) or a 429 that says when to
5
+ // retry is sent again. A 408, a 5xx or a connection lost after sending is outcome_unknown, booked at list price, and a 200
6
+ // whose body does not parse or match the questions is invalid_response, booked at list price too.
7
+ import { setTimeout as sleep } from "node:timers/promises";
8
+ import { checkCapabilities, DecisionProviderError } from "@parcha/agentrun-dsl";
9
+ /** Parallel's list price for one `fast` decision request, up to 100 questions (docs.parallel.ai pricing, 2026-10-28). */
10
+ export const PARALLEL_LIST_PRICE_USD = 0.001;
11
+ const KEY_VARIABLE = "PARALLEL_API_KEY";
12
+ const BASE_URL = "https://api.parallel.ai";
13
+ /** Parallel's documented limits: options per choice, levels per score, and characters per rendered question. */
14
+ const LIMITS = { minOptions: 2, maxOptions: 255, minLevels: 2, maxLevels: 10, renderedChars: 5_000 };
15
+ /** The modes Parallel Decisions takes, as its API reference lists them (2026-10-30: `fast` only, a const). A node pins
16
+ * one as `parallel-<mode>`, the name an answer's model reads; a node that pins none asks the first. */
17
+ export const PARALLEL_MODES = ["fast"];
18
+ const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
19
+ const unit = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 && v <= 1;
20
+ /** Failures a request meets before it is sent: no DNS answer, no connection, no TLS handshake. Any other is after. */
21
+ const BEFORE_SENDING = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "UND_ERR_CONNECT_TIMEOUT",
22
+ "CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "ERR_TLS_CERT_ALTNAME_INVALID"]);
23
+ const neverSent = (error) => {
24
+ const cause = isRecord(error) ? error.cause : undefined;
25
+ return isRecord(cause) && typeof cause.code === "string" && BEFORE_SENDING.has(cause.code);
26
+ };
27
+ /** A question as Parallel takes it: a choice option with no description is described by its own name, and a noul's
28
+ * criteria name both outcomes. */
29
+ function wireQuestion(question) {
30
+ if (question.type === "choice")
31
+ return { type: "choice", instructions: question.instructions, criteria: Object.fromEntries(Object.entries(question.criteria).map(([option, text]) => [option, text ?? option])) };
32
+ if (question.type === "noul")
33
+ return { type: "noul", instructions: question.instructions, ...(question.criteria ? { criteria: { true: question.criteria.true ?? "otherwise", false: question.criteria.false ?? "otherwise" } } : {}) };
34
+ return { ...question };
35
+ }
36
+ function checkLimits(questions) {
37
+ for (const [id, question] of Object.entries(questions)) {
38
+ const refuse = (why) => { throw new DecisionProviderError("invalid_request", `Question "${id}" ${why}.`); };
39
+ if (question.type === "choice") {
40
+ const options = Object.keys(question.criteria).length;
41
+ if (options < LIMITS.minOptions || options > LIMITS.maxOptions)
42
+ refuse(`has ${options} options; Parallel takes ${LIMITS.minOptions} to ${LIMITS.maxOptions}`);
43
+ }
44
+ if (question.type === "score" && (question.criteria.length < LIMITS.minLevels || question.criteria.length > LIMITS.maxLevels))
45
+ refuse(`has ${question.criteria.length} levels; Parallel takes ${LIMITS.minLevels} to ${LIMITS.maxLevels}`);
46
+ const rendered = id.length + JSON.stringify(wireQuestion(question)).length;
47
+ if (rendered > LIMITS.renderedChars)
48
+ refuse(`renders to ${rendered} characters; Parallel takes ${LIMITS.renderedChars}`);
49
+ }
50
+ }
51
+ /** The answers, sources and metering of a 200 response, checked against the questions asked. */
52
+ function readResponse(body, questions, attempts) {
53
+ // Parallel answered, so the request was billed: a response it rejects is booked at list price too.
54
+ const invalid = (why) => new DecisionProviderError("invalid_response", `Parallel returned ${why}.`, { attempts, costUsd: PARALLEL_LIST_PRICE_USD, costBasis: "estimate" });
55
+ if (!isRecord(body) || !isRecord(body.answers))
56
+ throw invalid("no answers");
57
+ const asked = Object.keys(questions);
58
+ const given = Object.keys(body.answers);
59
+ if (given.length !== asked.length || given.some((id) => !Object.hasOwn(questions, id)))
60
+ throw invalid("answers that do not match the questions asked");
61
+ // A null-prototype record: a question may be named __proto__, which on a plain object would set its prototype.
62
+ const answers = Object.create(null);
63
+ for (const id of asked) {
64
+ const a = body.answers[id];
65
+ if (!isRecord(a))
66
+ throw invalid(`no answer for "${id}"`);
67
+ if (a.type === "refusal")
68
+ answers[id] = { type: "refusal" };
69
+ else if (a.type === "noul")
70
+ answers[id] = { type: "noul", noul: a.noul };
71
+ else if (a.type === "choice")
72
+ answers[id] = { type: "choice", choice: a.choice, probabilities: a.probabilities, ...(unit(a.confidence) ? { confidence: a.confidence } : {}) };
73
+ else if (a.type === "score")
74
+ answers[id] = { type: "score", score: a.score, legend: a.legend, probabilities: a.probabilities, ...(unit(a.confidence) ? { confidence: a.confidence } : {}) };
75
+ else
76
+ throw invalid(`an answer of unknown type for "${id}"`);
77
+ }
78
+ if (body.citations !== undefined && !Array.isArray(body.citations))
79
+ throw invalid("citations that are not a list");
80
+ const evidence = (body.citations ?? []).filter(isRecord).filter((c) => typeof c.url === "string").map((c) => ({
81
+ url: c.url, title: typeof c.title === "string" ? c.title : null,
82
+ excerpts: Array.isArray(c.excerpts) ? c.excerpts.filter((e) => typeof e === "string") : [], scope: "call",
83
+ }));
84
+ const usage = isRecord(body.usage) && Number.isSafeInteger(body.usage.input_tokens) && body.usage.input_tokens >= 0 ? { input_tokens: body.usage.input_tokens, output_tokens: 0 } : null;
85
+ return {
86
+ answers: { ...answers }, evidence, model: typeof body.mode === "string" ? `parallel-${body.mode}` : null, usage,
87
+ cost_usd: PARALLEL_LIST_PRICE_USD, cost_basis: "estimate", provider_request_id: typeof body.decision_id === "string" ? body.decision_id : null,
88
+ };
89
+ }
90
+ /** The wait a Retry-After header asks for, in milliseconds: a number of seconds, or an HTTP date (a past one is 0). */
91
+ function retryAfterMs(response) {
92
+ const value = response.headers.get("retry-after")?.trim();
93
+ if (!value)
94
+ return undefined;
95
+ if (/^\d+(?:\.\d+)?$/.test(value))
96
+ return Math.round(Number(value) * 1000);
97
+ const at = Date.parse(value);
98
+ return Number.isFinite(at) ? Math.max(0, at - Date.now()) : undefined;
99
+ }
100
+ export function parallelProvider(options = {}) {
101
+ const modes = options.modes ?? PARALLEL_MODES;
102
+ const capabilities = {
103
+ types: ["noul", "choice", "score"], inputs: ["text", "json", "url"], evidence: "citations", probability: "model", grounding: true,
104
+ replay: "never", maxQuestions: 100, maxStateBytes: 96_000, models: modes.map((mode) => `parallel-${mode}`),
105
+ };
106
+ const timeoutMs = options.timeoutMs ?? 30_000;
107
+ const maxAttempts = options.maxAttempts ?? 3;
108
+ const retryBaseMs = options.retryBaseMs ?? 500;
109
+ const retryMaxMs = options.retryMaxMs ?? 5_000;
110
+ const url = `${(options.baseURL ?? BASE_URL).replace(/\/+$/, "")}/v1/decisions`;
111
+ return {
112
+ id: "parallel", needs: [KEY_VARIABLE], capabilities,
113
+ async decide(request, ctx) {
114
+ checkCapabilities(capabilities, request);
115
+ checkLimits(request.questions);
116
+ // checkCapabilities refused any pin outside the declared modes.
117
+ const mode = request.model ? request.model.slice("parallel-".length) : modes[0];
118
+ const key = options.apiKey ?? process.env[KEY_VARIABLE];
119
+ if (typeof key !== "string" || !key.trim())
120
+ throw new DecisionProviderError("configuration", `${KEY_VARIABLE} is not set.`);
121
+ const body = JSON.stringify({ mode, state: request.state ?? null, questions: Object.fromEntries(Object.entries(request.questions).map(([id, q]) => [id, wireQuestion(q)])), include_excerpts: options.includeExcerpts ?? true });
122
+ const budgetMs = Math.min(timeoutMs, ctx.deadlineMs ?? Infinity);
123
+ const deadlineAt = Date.now() + budgetMs;
124
+ const deadline = AbortSignal.timeout(budgetMs);
125
+ const signal = AbortSignal.any([ctx.signal, deadline]);
126
+ const stopped = (attempts) => ctx.signal.aborted
127
+ ? new DecisionProviderError("aborted", "The Parallel request was cancelled.", { attempts })
128
+ : new DecisionProviderError("timeout", "The Parallel request passed its deadline.", { attempts });
129
+ const fetcher = options.fetch ?? fetch;
130
+ // Sent and lost: it may have been answered and billed, so it is booked and never sent again.
131
+ const lost = (attempts, what, status) => new DecisionProviderError("outcome_unknown", `Parallel ${what} after the request was sent; it may have been answered, and is not sent again.`, { attempts, ...(status !== undefined ? { status } : {}), costUsd: PARALLEL_LIST_PRICE_USD, costBasis: "estimate" });
132
+ for (let attempt = 1;; attempt++) {
133
+ let response;
134
+ try {
135
+ response = await fetcher(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": key }, body, signal });
136
+ }
137
+ catch (error) {
138
+ // A deadline that ends a request in flight may have ended it after Parallel answered: only the host's cancel is not a lost outcome.
139
+ if (signal.aborted)
140
+ throw ctx.signal.aborted ? stopped(attempt) : lost(attempt, "passed its deadline");
141
+ if (!neverSent(error))
142
+ throw lost(attempt, "lost the connection");
143
+ if (attempt >= maxAttempts)
144
+ throw new DecisionProviderError("connection", "Parallel could not be reached.", { attempts: attempt });
145
+ await sleep(Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1)), undefined, { signal }).catch(() => { throw stopped(attempt); });
146
+ continue;
147
+ }
148
+ if (response.ok) {
149
+ // The headers say Parallel answered: a body cut off while it is read is a lost outcome; one that arrived whole and
150
+ // does not parse is an invalid response.
151
+ let text;
152
+ try {
153
+ text = await response.text();
154
+ }
155
+ catch {
156
+ throw ctx.signal.aborted ? stopped(attempt) : lost(attempt, signal.aborted ? "passed its deadline" : "lost the connection while the answer was read");
157
+ }
158
+ let parsed;
159
+ try {
160
+ parsed = JSON.parse(text);
161
+ }
162
+ catch {
163
+ throw new DecisionProviderError("invalid_response", "Parallel returned a body that is not JSON.", { attempts: attempt, costUsd: PARALLEL_LIST_PRICE_USD, costBasis: "estimate" });
164
+ }
165
+ return readResponse(parsed, request.questions, attempt);
166
+ }
167
+ const status = response.status;
168
+ if (status === 408 || (status >= 500 && status <= 599)) {
169
+ await response.body?.cancel().catch(() => { });
170
+ throw lost(attempt, `answered HTTP ${status}`, status);
171
+ }
172
+ // A 429 was refused unanswered; it is sent again only when Parallel says when.
173
+ const wait = status === 429 ? retryAfterMs(response) : undefined;
174
+ // A wait that would not end before the deadline is never started: the retry after it would have no time to answer.
175
+ if (wait !== undefined && attempt < maxAttempts && wait < deadlineAt - Date.now()) {
176
+ await response.body?.cancel().catch(() => { });
177
+ await sleep(wait, undefined, { signal }).catch(() => { throw stopped(attempt); });
178
+ continue;
179
+ }
180
+ const refId = await response.json().then((b) => (isRecord(b) && isRecord(b.error) && typeof b.error.ref_id === "string" ? b.error.ref_id : undefined), () => undefined);
181
+ const details = { status, attempts: attempt, ...(refId !== undefined ? { refId } : {}) };
182
+ if (status === 401 || status === 403)
183
+ throw new DecisionProviderError("auth", `Parallel refused the key (HTTP ${status}).`, details);
184
+ if (status === 400 || status === 422)
185
+ throw new DecisionProviderError("invalid_request", `Parallel refused the request (HTTP ${status}).`, details);
186
+ if (status === 429)
187
+ throw new DecisionProviderError("rate_limited", `Parallel rate-limited the request after ${attempt} attempts.`, details);
188
+ throw new DecisionProviderError("http", `Parallel answered HTTP ${status}.`, details);
189
+ }
190
+ },
191
+ };
192
+ }
@@ -0,0 +1 @@
1
+ export default function fauxSystemOne(input: string | URL | Request, init?: RequestInit): Promise<Response>;
@@ -0,0 +1,109 @@
1
+ // A faux System One service for rehearsals and tests: its default export is a fetch that answers `POST .../v1/systemone`
2
+ // as TypeSafe's Jev and OpenRouter's Decisions models do (JSON, or the multipart form a request with images is), and
3
+ // `GET .../v1/models` with a small Decisions catalog. A host points a provider's `fetch` option at it, as serve does under
4
+ // --faux with AGENTRUN_SERVE_FAUX_JEV or AGENTRUN_SERVE_FAUX_OPENROUTER. No request leaves the process.
5
+ //
6
+ // Answers are made up but stable: each is drawn from a hash of the model, the question and the state, so the same request
7
+ // answers the same, two models answer one question differently, and a map over 20 documents shows a spread. A noul
8
+ // question whose instructions or state hold "FAUX_NO" answers no, one holding "FAUX_YES" answers yes. Each call reports
9
+ // 120 input tokens per KB of state (at least 120), plus 800 per image, and a cost at OpenRouter's listed $0.02 per million
10
+ // input tokens for liquid/d1. Every faux answer's model ends in "(faux)".
11
+ //
12
+ // Environment, read per call:
13
+ // AGENTRUN_FAUX_SYSTEM_ONE_DELAY_MS base latency per call (default 150); each call adds up to as much again
14
+ // AGENTRUN_FAUX_SYSTEM_ONE_STATUS every call fails with this HTTP status, after it was received
15
+ // AGENTRUN_FAUX_SYSTEM_ONE_FAIL a substring: a call whose state holds it fails with HTTP 503 (an outcome_unknown)
16
+ // AGENTRUN_FAUX_SYSTEM_ONE_CALLS a file each call appends one JSON line to: path, model, question ids, image count
17
+ import { createHash } from "node:crypto";
18
+ import { appendFileSync } from "node:fs";
19
+ import { setTimeout as sleep } from "node:timers/promises";
20
+ const PRICE_PER_TOKEN = 0.00000002;
21
+ /** The Decisions catalog the faux lists: a few models, with what each takes. */
22
+ const CATALOG = [
23
+ { id: "~typesafe/jev-latest", input: ["text", "image"] },
24
+ { id: "liquid/d1", input: ["text", "image"] },
25
+ { id: "perplexity/pplx-decider-v1.2", input: ["text", "image"] },
26
+ { id: "cloudflare/clef", input: ["text", "image"] },
27
+ { id: "microsoft/microsoft-decision-1", input: ["text"] },
28
+ ];
29
+ const json = (body, status = 200, headers = {}) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } });
30
+ /** A number in [0, 1) drawn from `parts`. */
31
+ const draw = (...parts) => createHash("sha256").update(JSON.stringify(parts)).digest().readUInt32BE(0) / 2 ** 32;
32
+ const round = (n) => Math.round(n * 1000) / 1000;
33
+ /** A distribution over `n` options that puts most of its mass on `top`. */
34
+ function distribution(n, top, sharpness) {
35
+ const rest = n > 1 ? (1 - sharpness) / (n - 1) : 0;
36
+ const values = Array.from({ length: n }, (_, i) => round(i === top ? sharpness : rest));
37
+ values[top] = round(1 - values.reduce((sum, v, i) => (i === top ? sum : sum + v), 0));
38
+ return values;
39
+ }
40
+ function answer(question, seed, stateText) {
41
+ const p = draw(...seed);
42
+ if (question.type === "choice") {
43
+ const options = Object.keys((question.criteria ?? {}));
44
+ const top = Math.floor(p * options.length);
45
+ const sharpness = 0.55 + 0.4 * draw(...seed, "sharp");
46
+ const probabilities = distribution(options.length, top, sharpness);
47
+ return { type: "choice", choice: options[top], probabilities: Object.fromEntries(options.map((o, i) => [o, probabilities[i]])), confidence: round(sharpness) };
48
+ }
49
+ if (question.type === "score") {
50
+ const levels = Array.isArray(question.criteria) ? question.criteria : [];
51
+ const top = Math.floor(p * levels.length);
52
+ const sharpness = 0.6 + 0.35 * draw(...seed, "sharp");
53
+ const probabilities = distribution(levels.length, top, sharpness);
54
+ const score = round(probabilities.reduce((sum, v, i) => sum + v * i, 0));
55
+ return { type: "score", score, legend: Object.fromEntries(levels.map((l, i) => [i, String(l)])), probabilities: Object.fromEntries(probabilities.map((v, i) => [i, v])), confidence: round(sharpness) };
56
+ }
57
+ const text = `${question.instructions ?? ""} ${stateText}`;
58
+ if (text.includes("FAUX_NO"))
59
+ return { type: "noul", noul: round(0.04 + 0.1 * p) };
60
+ if (text.includes("FAUX_YES"))
61
+ return { type: "noul", noul: round(0.86 + 0.1 * p) };
62
+ return { type: "noul", noul: round(0.03 + 0.94 * p) };
63
+ }
64
+ /** The request's JSON and its image count, from a JSON body (OpenRouter's: base64 `assets`) or the multipart form TypeSafe's SDK sends images in. */
65
+ async function readRequest(init) {
66
+ const headers = new Headers(init.headers);
67
+ const body = init.body;
68
+ if (body instanceof FormData || (headers.get("content-type") ?? "").startsWith("multipart/form-data") || body instanceof Blob) {
69
+ const form = body instanceof FormData ? body : await new Response(body, { headers: { "content-type": headers.get("content-type") ?? "" } }).formData();
70
+ const part = form.get("request");
71
+ const request = JSON.parse(typeof part === "string" ? part : await part.text());
72
+ return { request, images: [...form.keys()].filter((name) => name !== "request").length };
73
+ }
74
+ const text = typeof body === "string" ? body : body instanceof Uint8Array ? new TextDecoder().decode(body) : await new Response(body).text();
75
+ const request = JSON.parse(text);
76
+ return { request, images: request.assets !== null && typeof request.assets === "object" ? Object.keys(request.assets).length : 0 };
77
+ }
78
+ export default async function fauxSystemOne(input, init = {}) {
79
+ const url = new URL(typeof input === "string" || input instanceof URL ? String(input) : input.url);
80
+ if ((init.method ?? "GET").toUpperCase() === "GET" && url.pathname.endsWith("/v1/models")) {
81
+ return json({ data: CATALOG.map((m) => ({ id: m.id, name: `${m.id} (faux)`, architecture: { input_modalities: m.input, output_modalities: ["decisions"] }, pricing: { prompt: String(PRICE_PER_TOKEN), completion: "0" } })) });
82
+ }
83
+ if (!url.pathname.endsWith("/v1/systemone"))
84
+ return json({ error: { message: "not found" } }, 404);
85
+ const { request, images } = await readRequest(init);
86
+ const model = typeof request.model === "string" ? request.model : "jev-latest";
87
+ const questions = (request.questions ?? {});
88
+ const stateText = JSON.stringify(request.state ?? null);
89
+ // As OpenRouter does live: a model other than Jev reads an image only as a top-level item of an array state.
90
+ const assets = request.assets !== null && typeof request.assets === "object" ? Object.keys(request.assets) : [];
91
+ if (assets.length && !/^~?(typesafe\/)?jev-/.test(model) && !(Array.isArray(request.state) && assets.every((token) => request.state.includes(token)))) {
92
+ return json({ error: { message: `${model} reads images only as top-level state items; an image part nested in state or placed in a question's instructions or criteria would be sent as text`, code: 400 } }, 400);
93
+ }
94
+ if (process.env.AGENTRUN_FAUX_SYSTEM_ONE_CALLS)
95
+ appendFileSync(process.env.AGENTRUN_FAUX_SYSTEM_ONE_CALLS, `${JSON.stringify({ pid: process.pid, path: url.pathname, model, questions: Object.keys(questions), images })}\n`);
96
+ const base = Number(process.env.AGENTRUN_FAUX_SYSTEM_ONE_DELAY_MS ?? 150);
97
+ if (base > 0)
98
+ await sleep(Math.round(base * (1 + draw(model, stateText, "latency"))), undefined, init.signal ? { signal: init.signal } : undefined);
99
+ const failWith = Number(process.env.AGENTRUN_FAUX_SYSTEM_ONE_STATUS);
100
+ if (failWith)
101
+ return json({ error: { message: "faux failure" } }, failWith);
102
+ const failOn = process.env.AGENTRUN_FAUX_SYSTEM_ONE_FAIL;
103
+ if (failOn && stateText.includes(failOn))
104
+ return json({ error: { message: "faux unavailable" } }, 503);
105
+ const answers = Object.fromEntries(Object.entries(questions).map(([id, q]) => [id, answer(q, [model, id, q.instructions, stateText], stateText)]));
106
+ const inputTokens = Math.max(120, Math.round(120 * Buffer.byteLength(stateText) / 1024)) + 800 * images;
107
+ return json({ id: `faux-${createHash("sha256").update(model + stateText).digest("hex").slice(0, 16)}`, model: `${model} (faux)`, answers,
108
+ usage: { input_tokens: inputTokens, output_tokens: 0, cost: inputTokens * PRICE_PER_TOKEN } });
109
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-decisions",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.30",
4
+ "description": "Third-party decision models as DecisionProviders for the AgentRun DSL: Parallel Decisions (typed questions grounded in live web evidence) and OpenRouter's Decisions models (any of them by name), behind the DSL's runJudge seam.",
5
+ "keywords": [
6
+ "agentrun",
7
+ "decisions",
8
+ "parallel",
9
+ "workflow",
10
+ "judge",
11
+ "openrouter"
12
+ ],
13
+ "type": "module",
14
+ "license": "Apache-2.0",
15
+ "author": "Parcha Labs, Inc.",
16
+ "engines": {
17
+ "node": ">=22.19.0"
18
+ },
19
+ "main": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./testing/faux-system-one": {
27
+ "types": "./dist/testing/faux-system-one.d.ts",
28
+ "default": "./dist/testing/faux-system-one.js"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist",
34
+ "README.md",
35
+ "CHANGELOG.md",
36
+ "LICENSE",
37
+ "NOTICE"
38
+ ],
39
+ "sideEffects": false,
40
+ "scripts": {
41
+ "build": "rm -rf dist && (test -f ../dsl/dist/index.d.ts || npm --prefix ../dsl run build) && tsc -p tsconfig.json",
42
+ "prepack": "npm run build",
43
+ "typecheck": "tsc -p tsconfig.json --noEmit",
44
+ "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
45
+ },
46
+ "dependencies": {
47
+ "@parcha/agentrun-dsl": "0.1.0-beta.30"
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/Parcha-ai/agentrun.git",
52
+ "directory": "packages/decisions"
53
+ },
54
+ "bugs": {
55
+ "url": "https://github.com/Parcha-ai/agentrun/issues"
56
+ },
57
+ "homepage": "https://agentrun.ai",
58
+ "publishConfig": {
59
+ "access": "public",
60
+ "tag": "beta"
61
+ }
62
+ }