@alma-harness/batch 0.6.0
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/README.md +65 -0
- package/dist/index.d.ts +71 -0
- package/dist/index.js +416 -0
- package/dist/index.js.map +1 -0
- package/package.json +50 -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/README.md
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# @alma-harness/batch
|
|
2
|
+
|
|
3
|
+
Governed single-dispatch batch execution. Node >=22 and matching Alma
|
|
4
|
+
packages are required. `createGovernedBatchRunner` composes BatchSubmissionStore,
|
|
5
|
+
BatchUsageStore, BatchAccountingStore, ExecutionResultStore, governed settlement,
|
|
6
|
+
same-counter spend.peek, audit and SingleDispatchBatchClient capabilities.
|
|
7
|
+
|
|
8
|
+
Supply immutable configRevision (including provider account selection), bounded
|
|
9
|
+
request/output/aggregate sizes, runTimeoutMs <=5 minutes and onBackgroundError.
|
|
10
|
+
The host creates authorized complete manifests: scope/session, item identities,
|
|
11
|
+
original prices/policy/controls, content/config revisions and result retention.
|
|
12
|
+
The host derives allowed tools/media/schema; this primitive does not route policy
|
|
13
|
+
or execute handlers. Never accept manifests/scopes/handles from model output or
|
|
14
|
+
unverified browser input. Changing config requires a new revision; old batches
|
|
15
|
+
must still resolve their original configuration, prices and provider account.
|
|
16
|
+
|
|
17
|
+
`submit({input,rationale,loadItems,signal?})` reserves every result and awaits audit
|
|
18
|
+
before loading content. Requests must match ordered IDs, model, batch tier and
|
|
19
|
+
controls. Only the first durable dispatch:true response permits a provider attempt.
|
|
20
|
+
Equal replay never loads input or submits again. The optional awaited onInputFile
|
|
21
|
+
hook can retain upload references before create; without it no durable orphan-file
|
|
22
|
+
inventory is claimed. Any ambiguous submission stays unresolved, even after expiry.
|
|
23
|
+
No fallback, automatic resubmission, provider cancellation or lease takeover exists.
|
|
24
|
+
|
|
25
|
+
`collect({scope,key},{signal?})` resolves the stored handle and collects every
|
|
26
|
+
terminal status, including failed/expired/cancelled. Every observation is journaled
|
|
27
|
+
before governed settlement and inclusive accounting. Those are the only financial
|
|
28
|
+
writers: neither SpendStore.add nor AuditLog.cost runs. Hashes deduplicate metadata
|
|
29
|
+
observations only; original manifest settlement identities own charges. Unknown,
|
|
30
|
+
unpriced and contradictory evidence stays pending for explicit reconciliation.
|
|
31
|
+
|
|
32
|
+
New output is retained only after complete, independently validated EOF. Corrupt
|
|
33
|
+
or missing tails cannot authorize partial new output. Content bounds/failures do
|
|
34
|
+
not stop known-usage drainage. `eof` describes this invocation, not a durable
|
|
35
|
+
completion certificate. `reconciliationRequired` reports this collection's pending
|
|
36
|
+
financial/content work. Existing output remains readable after a later failed GET.
|
|
37
|
+
A crash between puts can require another GET, but never another model submission.
|
|
38
|
+
|
|
39
|
+
`read({scope,key})` returns persisted metadata, inclusive financial evidence and
|
|
40
|
+
current retained item results; it makes no claim of EOF or delivery. Successful
|
|
41
|
+
`output` is a backstage `governed-batch-v1` envelope with ordered neutral blocks and
|
|
42
|
+
stop. Reasoning is not a public reply; the host validates its business schema and
|
|
43
|
+
authorizes any effects. Refusal/truncation/invalid/blocked/unavailable stay distinct.
|
|
44
|
+
Original block decisions suppress successful outputs; missing aggregate receipts
|
|
45
|
+
keep block-mode success pending until those decisions can be evaluated; warn preserves them. Monetary
|
|
46
|
+
warnings are durable evidence, not calls to an external notification service.
|
|
47
|
+
|
|
48
|
+
`reconcile({scope,key},query?)` repairs journaled finance without provider/content
|
|
49
|
+
access. It returns scanned/repaired/pending counts and afterId. Pages default50,
|
|
50
|
+
maximum100; restart future passes at the beginning. Already adopted observations
|
|
51
|
+
must still repair missing aggregate receipts, so default queries include them.
|
|
52
|
+
|
|
53
|
+
Result retention begins at submission reservation. Collection never prepares a
|
|
54
|
+
new reservation, renews retention or resurrects erasure. Read/put respect the
|
|
55
|
+
original binding; register result erasure/purge with the host. Successful public
|
|
56
|
+
submit/collect promises are bounded by timeout/abort (submission also by its
|
|
57
|
+
original deadline); cancellation does not prove dependency termination. Late
|
|
58
|
+
acceptance/financial work is observed, and background failures report only scoped
|
|
59
|
+
stage metadata. Permanent process loss cannot guarantee missing provider evidence.
|
|
60
|
+
|
|
61
|
+
Migrate batch accounting (which composes submission, usage and governed costs),
|
|
62
|
+
results and audit before enabling this runner. PostgreSQL store deadlines still
|
|
63
|
+
apply to read/reconcile. Routines and channel/business delivery require their own
|
|
64
|
+
persistent claims; this runner never sends real messages or certifies delivery.
|
|
65
|
+
See [spec](../../docs/specs/099-governed-batch-runner.md).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { BatchSubmissionRecord, BatchFinancialSummary, BatchFinancialReceipt, BatchSubmissionStore, BatchUsageStore, BatchAccountingStore, GovernedCostSettlementStore, SingleDispatchBatchClient, BatchSubmissionInput, BatchUsageQuery } from '@alma-harness/execution';
|
|
2
|
+
import { Scope, ExecutionResultRecord, ExecutionResult, JobOutput, ExecutionResultStore, SpendStore, AuditLog, ProviderId, JobItem } from '@alma-harness/core';
|
|
3
|
+
|
|
4
|
+
interface BatchKey {
|
|
5
|
+
scope: Scope;
|
|
6
|
+
key: string;
|
|
7
|
+
}
|
|
8
|
+
interface GovernedBatchConfig {
|
|
9
|
+
batches: BatchSubmissionStore;
|
|
10
|
+
usage: BatchUsageStore;
|
|
11
|
+
accounting: BatchAccountingStore;
|
|
12
|
+
results: ExecutionResultStore;
|
|
13
|
+
settlements: GovernedCostSettlementStore;
|
|
14
|
+
spend: Pick<SpendStore, 'peek'>;
|
|
15
|
+
audit: AuditLog;
|
|
16
|
+
clients: Partial<Record<ProviderId, SingleDispatchBatchClient>>;
|
|
17
|
+
configRevision: string;
|
|
18
|
+
runTimeoutMs: number;
|
|
19
|
+
maxRequestChars: number;
|
|
20
|
+
maxOutputChars: number;
|
|
21
|
+
maxBatchOutputChars: number;
|
|
22
|
+
onBackgroundError(event: BatchKey & {
|
|
23
|
+
stage: string;
|
|
24
|
+
}): void;
|
|
25
|
+
/** Metadata observation only. Failure stops submission before advancing past the uploaded file. */
|
|
26
|
+
onInputFile?(event: BatchKey & {
|
|
27
|
+
fileId: string;
|
|
28
|
+
}): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
interface GovernedBatchSubmit {
|
|
31
|
+
input: BatchSubmissionInput;
|
|
32
|
+
rationale: string;
|
|
33
|
+
loadItems(): Promise<JobItem[]>;
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
}
|
|
36
|
+
interface GovernedBatchOutput extends Omit<JobOutput, 'usage'> {
|
|
37
|
+
version: 'governed-batch-v1';
|
|
38
|
+
}
|
|
39
|
+
interface GovernedBatchItemView {
|
|
40
|
+
id: string;
|
|
41
|
+
state: ExecutionResultRecord['state'] | 'unavailable';
|
|
42
|
+
result: ExecutionResult;
|
|
43
|
+
receipt?: BatchFinancialReceipt;
|
|
44
|
+
output?: GovernedBatchOutput;
|
|
45
|
+
}
|
|
46
|
+
interface GovernedBatchView {
|
|
47
|
+
record: BatchSubmissionRecord;
|
|
48
|
+
financial: BatchFinancialSummary | null;
|
|
49
|
+
items: GovernedBatchItemView[];
|
|
50
|
+
}
|
|
51
|
+
interface GovernedBatchCollection {
|
|
52
|
+
eof: boolean;
|
|
53
|
+
reconciliationRequired: boolean;
|
|
54
|
+
view: GovernedBatchView;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
declare function createGovernedBatchRunner(value: GovernedBatchConfig): {
|
|
58
|
+
submit: (value: GovernedBatchSubmit) => Promise<GovernedBatchView>;
|
|
59
|
+
collect: (value: BatchKey, opts?: {
|
|
60
|
+
signal?: AbortSignal;
|
|
61
|
+
}) => Promise<GovernedBatchCollection>;
|
|
62
|
+
read: (value: BatchKey) => Promise<GovernedBatchView | null>;
|
|
63
|
+
reconcile: (value: BatchKey, query?: BatchUsageQuery) => Promise<{
|
|
64
|
+
afterId?: string;
|
|
65
|
+
scanned: number;
|
|
66
|
+
repaired: number;
|
|
67
|
+
pending: number;
|
|
68
|
+
} | null>;
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export { type BatchKey, type GovernedBatchCollection, type GovernedBatchConfig, type GovernedBatchItemView, type GovernedBatchOutput, type GovernedBatchSubmit, type GovernedBatchView, createGovernedBatchRunner };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,416 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
import { AuditSinkError, BudgetExceededError, equalExecution, ExecutionConflictError, ExecutionResultPolicyError, ExecutionStateError, normalizeSpendTotals, normalizeBudgetCaps, settlementIdentifier, settlementScope } from "@alma-harness/core";
|
|
4
|
+
import { batchUsageQuery, batchUsageSettlement, normalizeBatchRecord, normalizeBatchSubmission, normalizeBatchUsage } from "@alma-harness/execution";
|
|
5
|
+
|
|
6
|
+
// src/output.ts
|
|
7
|
+
var unavailable = () => ({ outcome: "unavailable", stopReason: null });
|
|
8
|
+
var binding = (e) => ({ scope: e.scope, callId: e.callId, sessionId: e.sessionId, sensitivity: e.intent.sensitivity, retentionMs: e.governance.resultRetentionMs });
|
|
9
|
+
function json(value, depth = 0) {
|
|
10
|
+
if (depth > 100) throw new TypeError("Invalid batch output");
|
|
11
|
+
if (value === null || typeof value === "boolean") return;
|
|
12
|
+
if (typeof value === "string") {
|
|
13
|
+
if (!value.isWellFormed() || value.includes("\0")) throw new TypeError("Invalid batch output");
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (typeof value === "number" && Number.isFinite(value)) return;
|
|
17
|
+
if (!value || typeof value !== "object" || !Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype) throw new TypeError("Invalid batch output");
|
|
18
|
+
if (Array.isArray(value) && Object.keys(value).length !== value.length) throw new TypeError("Sparse batch output");
|
|
19
|
+
for (const k of Reflect.ownKeys(value)) {
|
|
20
|
+
if (k === "length" && Array.isArray(value)) continue;
|
|
21
|
+
if (typeof k !== "string") throw new TypeError("Invalid batch output");
|
|
22
|
+
json(k, depth + 1);
|
|
23
|
+
json(value[k], depth + 1);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
function decode(text, max) {
|
|
27
|
+
if (text.length > max) throw new TypeError("Oversized batch output");
|
|
28
|
+
const v = JSON.parse(text);
|
|
29
|
+
json(v);
|
|
30
|
+
if (!v || Object.keys(v).sort().join() !== "blocks,stop,version" || v.version !== "governed-batch-v1" || !Array.isArray(v.blocks) || !["end_turn", "tool_use", "pause"].includes(v.stop)) throw new TypeError("Invalid batch output");
|
|
31
|
+
const ids = /* @__PURE__ */ new Map(), results = /* @__PURE__ */ new Set();
|
|
32
|
+
const bad = () => {
|
|
33
|
+
throw new TypeError("Invalid batch block");
|
|
34
|
+
};
|
|
35
|
+
const string = (v2) => typeof v2 === "string" && v2.length > 0 && v2.length <= 200;
|
|
36
|
+
const provider = (v2) => ["anthropic", "openai", "openrouter"].includes(v2);
|
|
37
|
+
const closed = (b, keys) => {
|
|
38
|
+
if (Object.keys(b).some((k) => !keys.includes(k))) bad();
|
|
39
|
+
};
|
|
40
|
+
for (const b of v.blocks) {
|
|
41
|
+
if (!b || typeof b !== "object" || Array.isArray(b)) bad();
|
|
42
|
+
switch (b.type) {
|
|
43
|
+
case "text":
|
|
44
|
+
closed(b, ["type", "text", "origin"]);
|
|
45
|
+
if (typeof b.text !== "string" || b.origin !== void 0 && b.origin !== "harness") bad();
|
|
46
|
+
break;
|
|
47
|
+
case "reasoning":
|
|
48
|
+
closed(b, ["type", "provider", "text", "opaque"]);
|
|
49
|
+
if (!provider(b.provider) || b.text !== void 0 && typeof b.text !== "string") bad();
|
|
50
|
+
break;
|
|
51
|
+
case "tool_call":
|
|
52
|
+
case "provider_tool_call": {
|
|
53
|
+
const remote = b.type === "provider_tool_call";
|
|
54
|
+
closed(b, remote ? ["type", "id", "name", "provider", "input"] : ["type", "id", "name", "input"]);
|
|
55
|
+
if (!string(b.id) || !string(b.name) || !Object.hasOwn(b, "input") || ids.has(b.id) || remote && (!provider(b.provider) || b.name !== "web_search")) bad();
|
|
56
|
+
ids.set(b.id, remote ? `provider:${b.provider}:${b.name}` : "local");
|
|
57
|
+
break;
|
|
58
|
+
}
|
|
59
|
+
case "tool_result":
|
|
60
|
+
case "provider_tool_result": {
|
|
61
|
+
const remote = b.type === "provider_tool_result";
|
|
62
|
+
closed(b, remote ? ["type", "callId", "name", "provider", "results", "error", "opaque"] : ["type", "callId", "output", "isError"]);
|
|
63
|
+
if (!string(b.callId) || results.has(b.callId) || ids.get(b.callId) !== (remote ? `provider:${b.provider}:${b.name}` : "local")) bad();
|
|
64
|
+
results.add(b.callId);
|
|
65
|
+
if (remote) {
|
|
66
|
+
if (!provider(b.provider) || b.name !== "web_search" || !Array.isArray(b.results) || b.error !== void 0 && typeof b.error !== "string") bad();
|
|
67
|
+
for (const r of b.results) {
|
|
68
|
+
if (!r || typeof r !== "object" || Array.isArray(r)) bad();
|
|
69
|
+
closed(r, ["url", "title", "pageAge"]);
|
|
70
|
+
if (typeof r.url !== "string" || r.title !== void 0 && typeof r.title !== "string" || r.pageAge !== void 0 && typeof r.pageAge !== "string") bad();
|
|
71
|
+
}
|
|
72
|
+
} else if (!Object.hasOwn(b, "output") || b.isError !== void 0 && typeof b.isError !== "boolean") bad();
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
default:
|
|
76
|
+
bad();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return v;
|
|
80
|
+
}
|
|
81
|
+
function encode(content, max) {
|
|
82
|
+
if (content.outcome !== "succeeded") return { outcome: content.outcome === "unusable" ? "invalid" : content.outcome === "cancelled" ? "cancelled" : "unavailable", stopReason: null };
|
|
83
|
+
const { stop, blocks } = content.output;
|
|
84
|
+
if (stop === "refusal") return { outcome: "refusal", stopReason: stop };
|
|
85
|
+
if (stop === "max_tokens" || stop === "context_window_exceeded") return { outcome: "truncated", stopReason: stop };
|
|
86
|
+
try {
|
|
87
|
+
const value = { version: "governed-batch-v1", blocks, stop };
|
|
88
|
+
json(value);
|
|
89
|
+
const text = JSON.stringify(value);
|
|
90
|
+
decode(text, max);
|
|
91
|
+
return { outcome: "success", stopReason: stop, output: { format: "json", text } };
|
|
92
|
+
} catch {
|
|
93
|
+
return { outcome: "invalid", stopReason: ["end_turn", "tool_use", "pause"].includes(stop) ? stop : null };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/index.ts
|
|
98
|
+
var abortError = () => new DOMException("Batch operation interrupted", "AbortError");
|
|
99
|
+
function canonical(v) {
|
|
100
|
+
if (v === null || typeof v !== "object") return JSON.stringify(v);
|
|
101
|
+
if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
|
|
102
|
+
return `{${Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + canonical(v[k])).join(",")}}`;
|
|
103
|
+
}
|
|
104
|
+
function createGovernedBatchRunner(value) {
|
|
105
|
+
for (const [key2, max] of [["runTimeoutMs", 3e5], ["maxRequestChars", 64e6], ["maxOutputChars", 1e6], ["maxBatchOutputChars", 64e6]])
|
|
106
|
+
if (!Number.isSafeInteger(value[key2]) || value[key2] < 1 || value[key2] > max) throw new TypeError("Invalid batch limits");
|
|
107
|
+
if (typeof value.onBackgroundError !== "function") throw new TypeError("Missing background observer");
|
|
108
|
+
const c = { ...value, configRevision: settlementIdentifier(value.configRevision), clients: { ...value.clients } };
|
|
109
|
+
const key = (v) => ({ scope: settlementScope(v.scope), key: settlementIdentifier(v.key) });
|
|
110
|
+
function config(r) {
|
|
111
|
+
if (r.input.configRevision !== c.configRevision) throw new ExecutionConflictError();
|
|
112
|
+
}
|
|
113
|
+
function client(r) {
|
|
114
|
+
config(r);
|
|
115
|
+
const v = c.clients[r.input.items[0].execution.model.provider];
|
|
116
|
+
if (!v || v.dispatchPolicy !== "single" || typeof v.validate !== "function") throw new TypeError("Single-dispatch batch client required");
|
|
117
|
+
return v;
|
|
118
|
+
}
|
|
119
|
+
async function lookup(k) {
|
|
120
|
+
const raw = await c.batches.get(k.scope, k.key);
|
|
121
|
+
if (!raw) return null;
|
|
122
|
+
const r = normalizeBatchRecord(raw);
|
|
123
|
+
if (!equalExecution(r.input.scope, k.scope) || r.input.key !== k.key) throw new ExecutionConflictError();
|
|
124
|
+
config(r);
|
|
125
|
+
return r;
|
|
126
|
+
}
|
|
127
|
+
async function receipts(k) {
|
|
128
|
+
const all = [];
|
|
129
|
+
for (let afterOrdinal = 0; afterOrdinal < 512; ) {
|
|
130
|
+
const page = await c.accounting.list(k.scope, k.key, { afterOrdinal, limit: 100 });
|
|
131
|
+
all.push(...page);
|
|
132
|
+
if (page.length < 100) break;
|
|
133
|
+
afterOrdinal = page.at(-1).accountingOrdinal;
|
|
134
|
+
}
|
|
135
|
+
return all;
|
|
136
|
+
}
|
|
137
|
+
async function read(value2) {
|
|
138
|
+
const k = key(value2), record = await lookup(k);
|
|
139
|
+
if (!record) return null;
|
|
140
|
+
const financial = await c.accounting.get(k.scope, k.key), rows = await receipts(k), items = [];
|
|
141
|
+
const incompleteBlock = Object.values(normalizeBudgetCaps(record.input.items[0].execution.governance.caps)).some((cap) => cap.onExceeded === "block") && rows.length !== record.input.items.length;
|
|
142
|
+
const block = rows.some((r) => r.decisions.some((d) => d.exceeded && d.onExceeded === "block"));
|
|
143
|
+
let chars = 0;
|
|
144
|
+
for (const member of record.input.items) {
|
|
145
|
+
const e = member.execution, receipt = rows.find((r) => r.itemId === member.id);
|
|
146
|
+
if (receipt && (receipt.batchId !== record.input.id || receipt.callId !== e.callId || receipt.settlementId !== e.settlementId)) throw new ExecutionConflictError();
|
|
147
|
+
let saved;
|
|
148
|
+
try {
|
|
149
|
+
saved = await c.results.get(k.scope, e.callId);
|
|
150
|
+
} catch (err) {
|
|
151
|
+
if (!(err instanceof ExecutionResultPolicyError)) throw err;
|
|
152
|
+
}
|
|
153
|
+
if (saved && !equalExecution(saved.binding, binding(e))) throw new ExecutionConflictError();
|
|
154
|
+
let result = saved?.state === "available" && receipt && saved.result ? saved.result : unavailable(), output;
|
|
155
|
+
if (result.outcome === "success") {
|
|
156
|
+
try {
|
|
157
|
+
if (result.output.format !== "json") throw new TypeError();
|
|
158
|
+
output = decode(result.output.text, c.maxOutputChars);
|
|
159
|
+
if (output.stop !== result.stopReason) throw new TypeError();
|
|
160
|
+
chars += result.output.text.length;
|
|
161
|
+
if (chars > c.maxBatchOutputChars) throw new TypeError();
|
|
162
|
+
} catch {
|
|
163
|
+
result = unavailable();
|
|
164
|
+
output = void 0;
|
|
165
|
+
}
|
|
166
|
+
if (incompleteBlock) {
|
|
167
|
+
result = unavailable();
|
|
168
|
+
output = void 0;
|
|
169
|
+
} else if (block) {
|
|
170
|
+
result = { outcome: "blocked", stopReason: result.stopReason };
|
|
171
|
+
output = void 0;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
items.push({ id: member.id, state: saved?.state ?? "unavailable", result, ...receipt ? { receipt } : {}, ...output ? { output } : {} });
|
|
175
|
+
}
|
|
176
|
+
return { record, financial, items };
|
|
177
|
+
}
|
|
178
|
+
async function required(k) {
|
|
179
|
+
const view = await read(k);
|
|
180
|
+
if (!view) throw new ExecutionStateError();
|
|
181
|
+
return view;
|
|
182
|
+
}
|
|
183
|
+
async function repair(k, row) {
|
|
184
|
+
const request = batchUsageSettlement(row);
|
|
185
|
+
if (!request) return false;
|
|
186
|
+
await c.settlements.settleGoverned(request);
|
|
187
|
+
const adopted = await c.usage.recordSettlement(k.scope, k.key, row.input.id);
|
|
188
|
+
if (adopted.status === "pending") return false;
|
|
189
|
+
return (await c.accounting.record(k.scope, k.key, row.input.id)).status !== "pending";
|
|
190
|
+
}
|
|
191
|
+
async function reconcile(value2, query) {
|
|
192
|
+
const k = key(value2), record = await lookup(k);
|
|
193
|
+
if (!record) return null;
|
|
194
|
+
const rows = await c.usage.list(k.scope, k.key, batchUsageQuery(query));
|
|
195
|
+
let repaired = 0, pending = 0;
|
|
196
|
+
for (const row of rows) {
|
|
197
|
+
try {
|
|
198
|
+
if (await repair(k, row)) repaired++;
|
|
199
|
+
else pending++;
|
|
200
|
+
} catch {
|
|
201
|
+
pending++;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return { scanned: rows.length, repaired, pending, ...rows.length ? { afterId: rows.at(-1).input.id } : {} };
|
|
205
|
+
}
|
|
206
|
+
function bounded(k, external, work) {
|
|
207
|
+
const controller = new AbortController();
|
|
208
|
+
let stage = "lookup", interrupted = false;
|
|
209
|
+
let deadlineTimer;
|
|
210
|
+
const abort = () => controller.abort();
|
|
211
|
+
const timer = setTimeout(abort, c.runTimeoutMs);
|
|
212
|
+
const rejected = new Promise((_, reject) => controller.signal.addEventListener("abort", () => {
|
|
213
|
+
interrupted = true;
|
|
214
|
+
reject(abortError());
|
|
215
|
+
}, { once: true }));
|
|
216
|
+
external?.addEventListener("abort", abort, { once: true });
|
|
217
|
+
if (external?.aborted) abort();
|
|
218
|
+
const check = () => {
|
|
219
|
+
if (controller.signal.aborted) throw abortError();
|
|
220
|
+
};
|
|
221
|
+
const active = work(controller.signal, check, (v) => {
|
|
222
|
+
stage = v;
|
|
223
|
+
}, (at) => {
|
|
224
|
+
deadlineTimer = setTimeout(abort, Math.max(1, Date.parse(at) - Date.now()));
|
|
225
|
+
});
|
|
226
|
+
void active.catch(() => {
|
|
227
|
+
if (interrupted) try {
|
|
228
|
+
void Promise.resolve(c.onBackgroundError({ ...structuredClone(k), stage })).catch(() => {
|
|
229
|
+
});
|
|
230
|
+
} catch {
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
return Promise.race([active, rejected]).finally(() => {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
clearTimeout(deadlineTimer);
|
|
236
|
+
external?.removeEventListener("abort", abort);
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
function submit(value2) {
|
|
240
|
+
const input = normalizeBatchSubmission(value2.input), k = key(input), load = value2.loadItems, rationale = value2.rationale;
|
|
241
|
+
if (input.configRevision !== c.configRevision || typeof load !== "function" || typeof rationale !== "string" || rationale.length > 1e3 || input.items.some((i) => !/^[A-Za-z0-9_-]{1,64}$/.test(i.id))) throw new TypeError("Invalid batch submission");
|
|
242
|
+
return bounded(k, value2.signal, async (signal, check, stage, armDeadline) => {
|
|
243
|
+
check();
|
|
244
|
+
const old = await lookup(k);
|
|
245
|
+
check();
|
|
246
|
+
if (old) {
|
|
247
|
+
if (!equalExecution(old.input, input)) throw new ExecutionConflictError();
|
|
248
|
+
return required(k);
|
|
249
|
+
}
|
|
250
|
+
const active = () => {
|
|
251
|
+
check();
|
|
252
|
+
if (Date.now() >= Date.parse(input.submitDeadlineAt)) throw abortError();
|
|
253
|
+
};
|
|
254
|
+
active();
|
|
255
|
+
armDeadline(input.submitDeadlineAt);
|
|
256
|
+
const transport = c.clients[input.items[0].execution.model.provider];
|
|
257
|
+
if (!transport || transport.dispatchPolicy !== "single") throw new TypeError("Single-dispatch batch client required");
|
|
258
|
+
for (const { execution: e } of input.items) {
|
|
259
|
+
const blocked = Object.entries(e.governance.caps).filter(([, cap]) => cap.onExceeded === "block");
|
|
260
|
+
const totals = blocked.some(([name]) => name !== "perTurnUsd") ? normalizeSpendTotals(await c.spend.peek({ scope: k.scope, sessionId: e.sessionId, at: e.occurredAt })) : { sessionUsd: 0, tenantDayUsd: 0 };
|
|
261
|
+
active();
|
|
262
|
+
for (const [name, cap] of blocked) {
|
|
263
|
+
const spent = name === "perTurnUsd" ? 0 : name === "perSessionUsd" ? totals.sessionUsd : totals.tenantDayUsd;
|
|
264
|
+
if (spent > cap.usd) throw new BudgetExceededError(name, cap.usd, spent);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
stage("claim");
|
|
268
|
+
const claim = await c.batches.claim(input);
|
|
269
|
+
active();
|
|
270
|
+
if (claim.status !== "claimed") return required(k);
|
|
271
|
+
try {
|
|
272
|
+
stage("reservation");
|
|
273
|
+
for (const { execution: e } of input.items) {
|
|
274
|
+
const p = await c.results.prepare(binding(e));
|
|
275
|
+
active();
|
|
276
|
+
if (p.state !== "pending" || !equalExecution(p.binding, binding(e))) throw new ExecutionStateError();
|
|
277
|
+
}
|
|
278
|
+
stage("audit");
|
|
279
|
+
for (const { execution: e } of input.items) {
|
|
280
|
+
const correlation = { scope: k.scope, at: e.occurredAt, sessionId: e.sessionId, operationId: e.operationId, attemptId: e.attemptId, callId: e.callId };
|
|
281
|
+
try {
|
|
282
|
+
await c.audit.routing({ ...correlation, ...e.intent, model: e.model, rationale, serviceTier: "batch", ...e.controls.reasoning ? { reasoning: e.controls.reasoning.effort } : {}, ...e.controls.cache ? { cacheTtl: e.controls.cache.ttl } : {} });
|
|
283
|
+
} catch (err) {
|
|
284
|
+
throw new AuditSinkError("routing", err);
|
|
285
|
+
}
|
|
286
|
+
active();
|
|
287
|
+
try {
|
|
288
|
+
await c.audit.access({ ...correlation, tool: "governed_batch_input", action: "read", resource: e.inputRevision });
|
|
289
|
+
} catch (err) {
|
|
290
|
+
throw new AuditSinkError("access", err);
|
|
291
|
+
}
|
|
292
|
+
active();
|
|
293
|
+
}
|
|
294
|
+
stage("input");
|
|
295
|
+
const items = structuredClone(await load());
|
|
296
|
+
active();
|
|
297
|
+
if (!Array.isArray(items) || items.length !== input.items.length || JSON.stringify(items).length > c.maxRequestChars) throw new ExecutionConflictError();
|
|
298
|
+
for (let n = 0; n < items.length; n++) {
|
|
299
|
+
const item = items[n], member = input.items[n], r = item.request, e = member.execution;
|
|
300
|
+
const controls = { maxTokens: r.maxTokens, ...r.temperature !== void 0 ? { temperature: r.temperature } : {}, ...r.reasoning !== void 0 ? { reasoning: r.reasoning } : {}, ...r.cache !== void 0 ? { cache: r.cache } : {} };
|
|
301
|
+
if (item.id !== member.id || !equalExecution(r.model, e.model) || r.serviceTier !== "batch" || !equalExecution(controls, e.controls)) throw new ExecutionConflictError();
|
|
302
|
+
}
|
|
303
|
+
transport.validate(structuredClone(items));
|
|
304
|
+
active();
|
|
305
|
+
for (const { execution: e } of input.items) {
|
|
306
|
+
const p = await c.results.get(k.scope, e.callId);
|
|
307
|
+
active();
|
|
308
|
+
if (p?.state !== "pending" || !equalExecution(p.binding, binding(e))) throw new ExecutionStateError();
|
|
309
|
+
}
|
|
310
|
+
stage("dispatch");
|
|
311
|
+
const dispatched = await c.batches.beginDispatch(claim.fence);
|
|
312
|
+
active();
|
|
313
|
+
if (!dispatched.dispatch) return required(k);
|
|
314
|
+
let accepted = false;
|
|
315
|
+
stage("submission");
|
|
316
|
+
for await (const event of transport.submitEvidence(items, { signal })) {
|
|
317
|
+
if (event.type === "accepted") {
|
|
318
|
+
await c.batches.accept(claim.fence, event.handle);
|
|
319
|
+
accepted = true;
|
|
320
|
+
} else if (event.type === "input_file") {
|
|
321
|
+
active();
|
|
322
|
+
await c.onInputFile?.({ ...structuredClone(k), fileId: settlementIdentifier(event.fileId) });
|
|
323
|
+
active();
|
|
324
|
+
} else throw new ExecutionStateError();
|
|
325
|
+
}
|
|
326
|
+
if (!accepted) throw new ExecutionStateError();
|
|
327
|
+
return required(k);
|
|
328
|
+
} catch (err) {
|
|
329
|
+
try {
|
|
330
|
+
await c.batches.markUncertain(claim.fence);
|
|
331
|
+
} catch {
|
|
332
|
+
}
|
|
333
|
+
throw err;
|
|
334
|
+
}
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
function collect(value2, opts = {}) {
|
|
338
|
+
const k = key(value2);
|
|
339
|
+
return bounded(k, opts.signal, async (signal, check, stage) => {
|
|
340
|
+
check();
|
|
341
|
+
const record = await lookup(k);
|
|
342
|
+
check();
|
|
343
|
+
if (!record) throw new ExecutionStateError();
|
|
344
|
+
if (!record.handle) return { eof: false, reconciliationRequired: true, view: await required(k) };
|
|
345
|
+
const transport = client(record);
|
|
346
|
+
stage("status");
|
|
347
|
+
const progress = await transport.status(record.handle, { signal });
|
|
348
|
+
check();
|
|
349
|
+
if (!["done", "failed", "expired", "cancelled"].includes(progress.status)) return { eof: false, reconciliationRequired: false, view: await required(k) };
|
|
350
|
+
const expected = record.input.items.map((i) => i.id), seen = /* @__PURE__ */ new Set(), outputs = /* @__PURE__ */ new Map();
|
|
351
|
+
let failed = false, eof = false, chars = 0;
|
|
352
|
+
stage("evidence");
|
|
353
|
+
try {
|
|
354
|
+
for await (const raw of transport.resultsEvidence(record.handle, expected, { signal })) {
|
|
355
|
+
if (!expected.includes(raw.id) || seen.has(raw.id)) throw new ExecutionConflictError();
|
|
356
|
+
seen.add(raw.id);
|
|
357
|
+
const normalized = normalizeBatchUsage({ id: "observation", itemId: raw.id, handle: record.handle, evidence: raw.evidence, outcome: raw.content.outcome, ...raw.providerRequestId === void 0 ? {} : { providerRequestId: raw.providerRequestId } });
|
|
358
|
+
normalized.id = createHash("sha256").update(canonical(normalized)).digest("hex");
|
|
359
|
+
const itemId = normalized.itemId;
|
|
360
|
+
let result;
|
|
361
|
+
try {
|
|
362
|
+
result = encode(structuredClone(raw.content), c.maxOutputChars);
|
|
363
|
+
} catch {
|
|
364
|
+
result = { outcome: "invalid", stopReason: null };
|
|
365
|
+
}
|
|
366
|
+
let accounted = false;
|
|
367
|
+
try {
|
|
368
|
+
const row = await c.usage.append(k.scope, k.key, normalized);
|
|
369
|
+
accounted = await repair(k, row);
|
|
370
|
+
if (!accounted) failed = true;
|
|
371
|
+
} catch {
|
|
372
|
+
failed = true;
|
|
373
|
+
}
|
|
374
|
+
try {
|
|
375
|
+
const size = result.outcome === "success" ? result.output.text.length : 0;
|
|
376
|
+
chars += size;
|
|
377
|
+
if (chars > c.maxBatchOutputChars) {
|
|
378
|
+
failed = true;
|
|
379
|
+
} else if (accounted) outputs.set(itemId, result);
|
|
380
|
+
} catch {
|
|
381
|
+
failed = true;
|
|
382
|
+
}
|
|
383
|
+
check();
|
|
384
|
+
}
|
|
385
|
+
check();
|
|
386
|
+
eof = seen.size === expected.length;
|
|
387
|
+
if (!eof) failed = true;
|
|
388
|
+
} catch {
|
|
389
|
+
failed = true;
|
|
390
|
+
}
|
|
391
|
+
if (eof) {
|
|
392
|
+
stage("results");
|
|
393
|
+
for (const member of record.input.items) {
|
|
394
|
+
check();
|
|
395
|
+
const result = outputs.get(member.id);
|
|
396
|
+
if (!result) continue;
|
|
397
|
+
try {
|
|
398
|
+
const p = await c.results.get(k.scope, member.execution.callId);
|
|
399
|
+
check();
|
|
400
|
+
if (!p || !equalExecution(p.binding, binding(member.execution))) throw new ExecutionConflictError();
|
|
401
|
+
if (p.state === "pending" || p.state === "available") await c.results.put(k.scope, member.execution.callId, result);
|
|
402
|
+
} catch {
|
|
403
|
+
failed = true;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
check();
|
|
408
|
+
return { eof, reconciliationRequired: failed, view: await required(k) };
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
return { submit, collect, read, reconcile };
|
|
412
|
+
}
|
|
413
|
+
export {
|
|
414
|
+
createGovernedBatchRunner
|
|
415
|
+
};
|
|
416
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/output.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { AuditSinkError, BudgetExceededError, equalExecution, ExecutionConflictError, ExecutionResultPolicyError, ExecutionStateError, normalizeSpendTotals, normalizeBudgetCaps, settlementIdentifier, settlementScope, type ExecutionResult, type Scope } from '@alma-harness/core';\nimport { batchUsageQuery, batchUsageSettlement, normalizeBatchRecord, normalizeBatchSubmission, normalizeBatchUsage, type BatchFinancialReceipt, type BatchSubmissionRecord, type BatchUsageQuery, type BatchUsageRecord } from '@alma-harness/execution';\nimport { binding, decode, encode, unavailable } from './output';\nimport type { BatchKey, GovernedBatchCollection, GovernedBatchConfig, GovernedBatchItemView, GovernedBatchSubmit, GovernedBatchView } from './types';\nexport type * from './types';\nconst abortError=()=>new DOMException('Batch operation interrupted','AbortError');\nfunction canonical(v:unknown):string {if(v===null||typeof v!=='object')return JSON.stringify(v);if(Array.isArray(v))return `[${v.map(canonical).join(',')}]`;return `{${Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical((v as Record<string,unknown>)[k])).join(',')}}`;}\nexport function createGovernedBatchRunner(value:GovernedBatchConfig) {\n for(const [key,max] of [['runTimeoutMs',300_000],['maxRequestChars',64_000_000],['maxOutputChars',1_000_000],['maxBatchOutputChars',64_000_000]] as const)\n if(!Number.isSafeInteger(value[key])||value[key]<1||value[key]>max)throw new TypeError('Invalid batch limits');\n if(typeof value.onBackgroundError!=='function')throw new TypeError('Missing background observer');\n const c={...value,configRevision:settlementIdentifier(value.configRevision),clients:{...value.clients}};\n const key=(v:BatchKey):BatchKey=>({scope:settlementScope(v.scope),key:settlementIdentifier(v.key)});\n function config(r:BatchSubmissionRecord):void {if(r.input.configRevision!==c.configRevision)throw new ExecutionConflictError();}\n function client(r:BatchSubmissionRecord){config(r);const v=c.clients[r.input.items[0]!.execution.model.provider];if(!v||v.dispatchPolicy!=='single'||typeof v.validate!=='function')throw new TypeError('Single-dispatch batch client required');return v;}\n async function lookup(k:BatchKey){const raw=await c.batches.get(k.scope,k.key);if(!raw)return null;const r=normalizeBatchRecord(raw);if(!equalExecution(r.input.scope,k.scope)||r.input.key!==k.key)throw new ExecutionConflictError();config(r);return r;}\n async function receipts(k:BatchKey){const all:BatchFinancialReceipt[]=[];for(let afterOrdinal=0;afterOrdinal<512;){const page=await c.accounting.list(k.scope,k.key,{afterOrdinal,limit:100});all.push(...page);if(page.length<100)break;afterOrdinal=page.at(-1)!.accountingOrdinal;}return all;}\n async function read(value:BatchKey):Promise<GovernedBatchView|null> {\n const k=key(value),record=await lookup(k);if(!record)return null;\n const financial=await c.accounting.get(k.scope,k.key),rows=await receipts(k),items:GovernedBatchItemView[]=[];\n const incompleteBlock=Object.values(normalizeBudgetCaps(record.input.items[0]!.execution.governance!.caps)).some(cap=>cap.onExceeded==='block')&&rows.length!==record.input.items.length;\n const block=rows.some(r=>r.decisions.some(d=>d.exceeded&&d.onExceeded==='block'));let chars=0;\n for(const member of record.input.items){const e=member.execution,receipt=rows.find(r=>r.itemId===member.id);\n if(receipt&&(receipt.batchId!==record.input.id||receipt.callId!==e.callId||receipt.settlementId!==e.settlementId))throw new ExecutionConflictError();\n let saved;try{saved=await c.results.get(k.scope,e.callId);}catch(err){if(!(err instanceof ExecutionResultPolicyError))throw err;}\n if(saved&&!equalExecution(saved.binding,binding(e)))throw new ExecutionConflictError();\n let result=saved?.state==='available'&&receipt&&saved.result?saved.result:unavailable(),output;\n if(result.outcome==='success'){\n try{if(result.output.format!=='json')throw new TypeError();output=decode(result.output.text,c.maxOutputChars);if(output.stop!==result.stopReason)throw new TypeError();chars+=result.output.text.length;if(chars>c.maxBatchOutputChars)throw new TypeError();}\n catch{result=unavailable();output=undefined;}\n if(incompleteBlock){result=unavailable();output=undefined;}else if(block){result={outcome:'blocked',stopReason:result.stopReason};output=undefined;}\n }\n items.push({id:member.id,state:saved?.state??'unavailable',result,...(receipt?{receipt}:{}),...(output?{output}:{})});\n }\n return {record,financial,items};\n }\n async function required(k:BatchKey){const view=await read(k);if(!view)throw new ExecutionStateError();return view;}\n async function repair(k:BatchKey,row:BatchUsageRecord):Promise<boolean>{\n const request=batchUsageSettlement(row);if(!request)return false;\n await c.settlements.settleGoverned(request);\n const adopted=await c.usage.recordSettlement(k.scope,k.key,row.input.id);if(adopted.status==='pending')return false;\n return (await c.accounting.record(k.scope,k.key,row.input.id)).status!=='pending';\n }\n async function reconcile(value:BatchKey,query?:BatchUsageQuery){const k=key(value),record=await lookup(k);if(!record)return null;\n const rows=await c.usage.list(k.scope,k.key,batchUsageQuery(query));let repaired=0,pending=0;\n for(const row of rows){try{if(await repair(k,row))repaired++;else pending++;}catch{pending++;}}\n return {scanned:rows.length,repaired,pending,...(rows.length?{afterId:rows.at(-1)!.input.id}:{})};\n }\n function bounded<T>(k:BatchKey,external:AbortSignal|undefined,work:(signal:AbortSignal,check:()=>void,stage:(v:string)=>void,deadline:(at:string)=>void)=>Promise<T>):Promise<T>{\n const controller=new AbortController();let stage='lookup',interrupted=false;let deadlineTimer:ReturnType<typeof setTimeout>|undefined;\n const abort=()=>controller.abort();const timer=setTimeout(abort,c.runTimeoutMs);\n const rejected=new Promise<never>((_,reject)=>controller.signal.addEventListener('abort',()=>{interrupted=true;reject(abortError());},{once:true}));\n external?.addEventListener('abort',abort,{once:true});if(external?.aborted)abort();\n const check=()=>{if(controller.signal.aborted)throw abortError();};\n const active=work(controller.signal,check,v=>{stage=v;},at=>{deadlineTimer=setTimeout(abort,Math.max(1,Date.parse(at)-Date.now()));});\n void active.catch(()=>{if(interrupted)try{void Promise.resolve(c.onBackgroundError({...structuredClone(k),stage})).catch(()=>{});}catch{/* Monitoring cannot create an unhandled rejection. */}});\n return Promise.race([active,rejected]).finally(()=>{clearTimeout(timer);clearTimeout(deadlineTimer);external?.removeEventListener('abort',abort);});\n }\n function submit(value:GovernedBatchSubmit):Promise<GovernedBatchView>{\n const input=normalizeBatchSubmission(value.input),k=key(input),load=value.loadItems,rationale=value.rationale;\n if(input.configRevision!==c.configRevision||typeof load!=='function'||typeof rationale!=='string'||rationale.length>1000||input.items.some(i=>! /^[A-Za-z0-9_-]{1,64}$/.test(i.id)))throw new TypeError('Invalid batch submission');\n return bounded(k,value.signal,async(signal,check,stage,armDeadline)=>{\n check();const old=await lookup(k);check();if(old){if(!equalExecution(old.input,input))throw new ExecutionConflictError();return required(k);}\n const active=()=>{check();if(Date.now()>=Date.parse(input.submitDeadlineAt))throw abortError();};active();armDeadline(input.submitDeadlineAt);\n const transport=c.clients[input.items[0]!.execution.model.provider];if(!transport||transport.dispatchPolicy!=='single')throw new TypeError('Single-dispatch batch client required');\n // Each item's original UTC day may differ, so check each relevant projection.\n for(const {execution:e} of input.items){const blocked=Object.entries(e.governance!.caps).filter(([,cap])=>cap.onExceeded==='block');\n const totals=blocked.some(([name])=>name!=='perTurnUsd')?normalizeSpendTotals(await c.spend.peek({scope:k.scope,sessionId:e.sessionId,at:e.occurredAt})):{sessionUsd:0,tenantDayUsd:0};active();\n for(const [name,cap] of blocked){const spent=name==='perTurnUsd'?0:name==='perSessionUsd'?totals.sessionUsd:totals.tenantDayUsd;if(spent>cap.usd)throw new BudgetExceededError(name as 'perTurnUsd',cap.usd,spent);}}\n stage('claim');const claim=await c.batches.claim(input);active();if(claim.status!=='claimed')return required(k);\n try{\n stage('reservation');for(const {execution:e} of input.items){const p=await c.results.prepare(binding(e));active();if(p.state!=='pending'||!equalExecution(p.binding,binding(e)))throw new ExecutionStateError();}\n stage('audit');for(const {execution:e} of input.items){const correlation={scope:k.scope,at:e.occurredAt,sessionId:e.sessionId,operationId:e.operationId,attemptId:e.attemptId,callId:e.callId};\n try{await c.audit.routing({...correlation,...e.intent,model:e.model,rationale,serviceTier:'batch',...(e.controls.reasoning?{reasoning:e.controls.reasoning.effort}:{}),...(e.controls.cache?{cacheTtl:e.controls.cache.ttl}:{})});}catch(err){throw new AuditSinkError('routing',err);}active();\n try{await c.audit.access({...correlation,tool:'governed_batch_input',action:'read',resource:e.inputRevision});}catch(err){throw new AuditSinkError('access',err);}active();}\n stage('input');const items=structuredClone(await load());active();\n if(!Array.isArray(items)||items.length!==input.items.length||JSON.stringify(items).length>c.maxRequestChars)throw new ExecutionConflictError();\n for(let n=0;n<items.length;n++){const item=items[n]!,member=input.items[n]!,r=item.request,e=member.execution;\n const controls={maxTokens:r.maxTokens,...(r.temperature!==undefined?{temperature:r.temperature}:{}),...(r.reasoning!==undefined?{reasoning:r.reasoning}:{}),...(r.cache!==undefined?{cache:r.cache}:{})};\n if(item.id!==member.id||!equalExecution(r.model,e.model)||r.serviceTier!=='batch'||!equalExecution(controls,e.controls))throw new ExecutionConflictError();}\n transport.validate(structuredClone(items));active();\n for(const {execution:e} of input.items){const p=await c.results.get(k.scope,e.callId);active();if(p?.state!=='pending'||!equalExecution(p.binding,binding(e)))throw new ExecutionStateError();}\n stage('dispatch');const dispatched=await c.batches.beginDispatch(claim.fence);active();if(!dispatched.dispatch)return required(k);\n let accepted=false;stage('submission');\n for await(const event of transport.submitEvidence(items,{signal})){\n if(event.type==='accepted'){await c.batches.accept(claim.fence,event.handle);accepted=true;}\n else if(event.type==='input_file'){active();await c.onInputFile?.({...structuredClone(k),fileId:settlementIdentifier(event.fileId)});active();}\n else throw new ExecutionStateError();\n }\n if(!accepted)throw new ExecutionStateError();return required(k);\n }catch(err){try{await c.batches.markUncertain(claim.fence);}catch{/* Original record never grants dispatch again. */}throw err;}\n });\n }\n function collect(value:BatchKey,opts:{signal?:AbortSignal}={}):Promise<GovernedBatchCollection>{\n const k=key(value);\n return bounded(k,opts.signal,async(signal,check,stage)=>{\n check();const record=await lookup(k);check();if(!record)throw new ExecutionStateError();\n if(!record.handle)return {eof:false,reconciliationRequired:true,view:await required(k)};\n const transport=client(record);stage('status');const progress=await transport.status(record.handle,{signal});check();\n if(!['done','failed','expired','cancelled'].includes(progress.status))return {eof:false,reconciliationRequired:false,view:await required(k)};\n const expected=record.input.items.map(i=>i.id),seen=new Set<string>(),outputs=new Map<string,ExecutionResult>();let failed=false,eof=false,chars=0;\n stage('evidence');try{\n for await(const raw of transport.resultsEvidence(record.handle,expected,{signal})){\n // Persist a yielded observation even when cancellation races its arrival.\n if(!expected.includes(raw.id)||seen.has(raw.id))throw new ExecutionConflictError();seen.add(raw.id);\n const normalized=normalizeBatchUsage({id:'observation',itemId:raw.id,handle:record.handle,evidence:raw.evidence,outcome:raw.content.outcome,...(raw.providerRequestId===undefined?{}:{providerRequestId:raw.providerRequestId})});\n normalized.id=createHash('sha256').update(canonical(normalized)).digest('hex');\n const itemId=normalized.itemId;let result:ExecutionResult;try{result=encode(structuredClone(raw.content),c.maxOutputChars);}catch{result={outcome:'invalid',stopReason:null};}\n let accounted=false;try{const row=await c.usage.append(k.scope,k.key,normalized);accounted=await repair(k,row);if(!accounted)failed=true;}catch{failed=true;}\n // Content failure cannot terminate the financial drain.\n try{const size=result.outcome==='success'?result.output.text.length:0;chars+=size;\n if(chars>c.maxBatchOutputChars){failed=true;}else if(accounted)outputs.set(itemId,result);\n }catch{failed=true;}\n check();\n }\n check();eof=seen.size===expected.length;if(!eof)failed=true;\n }catch{failed=true;}\n if(eof){stage('results');for(const member of record.input.items){check();const result=outputs.get(member.id);if(!result)continue;\n try{const p=await c.results.get(k.scope,member.execution.callId);check();if(!p||!equalExecution(p.binding,binding(member.execution)))throw new ExecutionConflictError();\n if(p.state==='pending'||p.state==='available')await c.results.put(k.scope,member.execution.callId,result);\n }catch{failed=true;}\n }}\n check();return {eof,reconciliationRequired:failed,view:await required(k)};\n });\n }\n return {submit,collect,read,reconcile};\n}\n","import type { ExecutionInput, ExecutionResult, ExecutionResultBinding } from '@alma-harness/core';\nimport type { BatchContent } from '@alma-harness/execution';\nimport type { GovernedBatchOutput } from './types';\nexport const unavailable = ():ExecutionResult => ({outcome:'unavailable',stopReason:null});\nexport const binding = (e:ExecutionInput):ExecutionResultBinding => ({scope:e.scope,callId:e.callId,sessionId:e.sessionId,sensitivity:e.intent.sensitivity,retentionMs:e.governance!.resultRetentionMs});\nfunction json(value:unknown,depth=0):void {\n if(depth>100)throw new TypeError('Invalid batch output');\n if(value===null||typeof value==='boolean')return;\n if(typeof value==='string'){if(!value.isWellFormed()||value.includes('\\0'))throw new TypeError('Invalid batch output');return;}\n if(typeof value==='number'&&Number.isFinite(value))return;\n if(!value||typeof value!=='object'||(!Array.isArray(value)&&Object.getPrototypeOf(value)!==Object.prototype))throw new TypeError('Invalid batch output');\n if(Array.isArray(value)&&Object.keys(value).length!==value.length)throw new TypeError('Sparse batch output');\n for(const k of Reflect.ownKeys(value)){if(k==='length'&&Array.isArray(value))continue;if(typeof k!=='string')throw new TypeError('Invalid batch output');json(k,depth+1);json((value as Record<string,unknown>)[k],depth+1);}\n}\nexport function decode(text:string,max:number):GovernedBatchOutput {\n if(text.length>max)throw new TypeError('Oversized batch output');const v=JSON.parse(text);json(v);\n if(!v||Object.keys(v).sort().join()!=='blocks,stop,version'||v.version!=='governed-batch-v1'||!Array.isArray(v.blocks)||!['end_turn','tool_use','pause'].includes(v.stop))throw new TypeError('Invalid batch output');\n const ids=new Map<string,string>(),results=new Set<string>();\n const bad=():never=>{throw new TypeError('Invalid batch block');};\n const string=(v:unknown):v is string=>typeof v==='string'&&v.length>0&&v.length<=200;\n const provider=(v:unknown)=>['anthropic','openai','openrouter'].includes(v as string);\n const closed=(b:Record<string,unknown>,keys:string[])=>{if(Object.keys(b).some(k=>!keys.includes(k)))bad();};\n for(const b of v.blocks){\n if(!b||typeof b!=='object'||Array.isArray(b))bad();\n switch(b.type){\n case 'text':closed(b,['type','text','origin']);if(typeof b.text!=='string'||(b.origin!==undefined&&b.origin!=='harness'))bad();break;\n case 'reasoning':closed(b,['type','provider','text','opaque']);if(!provider(b.provider)||(b.text!==undefined&&typeof b.text!=='string'))bad();break;\n case 'tool_call':case 'provider_tool_call':{\n const remote=b.type==='provider_tool_call';closed(b,remote?['type','id','name','provider','input']:['type','id','name','input']);\n if(!string(b.id)||!string(b.name)||!Object.hasOwn(b,'input')||ids.has(b.id)||(remote&&(!provider(b.provider)||b.name!=='web_search')))bad();\n ids.set(b.id,remote?`provider:${b.provider}:${b.name}`:'local');break;\n }\n case 'tool_result':case 'provider_tool_result':{\n const remote=b.type==='provider_tool_result';closed(b,remote?['type','callId','name','provider','results','error','opaque']:['type','callId','output','isError']);\n if(!string(b.callId)||results.has(b.callId)||ids.get(b.callId)!==(remote?`provider:${b.provider}:${b.name}`:'local'))bad();\n results.add(b.callId);\n if(remote){if(!provider(b.provider)||b.name!=='web_search'||!Array.isArray(b.results)||(b.error!==undefined&&typeof b.error!=='string'))bad();\n for(const r of b.results){if(!r||typeof r!=='object'||Array.isArray(r))bad();closed(r,['url','title','pageAge']);if(typeof r.url!=='string'||(r.title!==undefined&&typeof r.title!=='string')||(r.pageAge!==undefined&&typeof r.pageAge!=='string'))bad();}\n }else if(!Object.hasOwn(b,'output')||(b.isError!==undefined&&typeof b.isError!=='boolean'))bad();break;\n }\n default:bad();\n }\n }\n return v;\n}\nexport function encode(content:BatchContent,max:number):ExecutionResult {\n if(content.outcome!=='succeeded')return {outcome:content.outcome==='unusable'?'invalid':content.outcome==='cancelled'?'cancelled':'unavailable',stopReason:null};\n const {stop,blocks}=content.output;\n if(stop==='refusal')return {outcome:'refusal',stopReason:stop};\n if(stop==='max_tokens'||stop==='context_window_exceeded')return {outcome:'truncated',stopReason:stop};\n try{const value={version:'governed-batch-v1',blocks,stop};json(value);const text=JSON.stringify(value);decode(text,max);return {outcome:'success',stopReason:stop,output:{format:'json',text}};}\n catch{return {outcome:'invalid',stopReason:['end_turn','tool_use','pause'].includes(stop)?stop:null};}\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB,qBAAqB,gBAAgB,wBAAwB,4BAA4B,qBAAqB,sBAAsB,qBAAqB,sBAAsB,uBAAyD;AACjQ,SAAS,iBAAiB,sBAAsB,sBAAsB,0BAA0B,2BAAgI;;;ACCzN,IAAM,cAAc,OAAuB,EAAC,SAAQ,eAAc,YAAW,KAAI;AACjF,IAAM,UAAU,CAAC,OAA6C,EAAC,OAAM,EAAE,OAAM,QAAO,EAAE,QAAO,WAAU,EAAE,WAAU,aAAY,EAAE,OAAO,aAAY,aAAY,EAAE,WAAY,kBAAiB;AACtM,SAAS,KAAK,OAAc,QAAM,GAAQ;AACxC,MAAG,QAAM,IAAI,OAAM,IAAI,UAAU,sBAAsB;AACvD,MAAG,UAAQ,QAAM,OAAO,UAAQ,UAAU;AAC1C,MAAG,OAAO,UAAQ,UAAS;A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AAAA,IAC1E,CAAC;AAAA,EACH;AACA,SAAO,EAAC,QAAO,SAAQ,MAAK,UAAS;AACvC;","names":["v","key","value"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@alma-harness/batch",
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Governed single-dispatch batch execution for Alma.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "https://github.com/FabioFernandesCarneiro/alma.git",
|
|
19
|
+
"directory": "packages/batch"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"@alma-harness/execution": "^0.6.0",
|
|
23
|
+
"@alma-harness/core": "^0.6.0"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^24.1.0",
|
|
27
|
+
"typescript": "^5.9.2",
|
|
28
|
+
"vitest": "^3.2.4",
|
|
29
|
+
"pg": "^8.16.3",
|
|
30
|
+
"@types/pg": "^8.15.4",
|
|
31
|
+
"@alma-harness/core": "^0.6.0",
|
|
32
|
+
"@alma-harness/execution": "^0.6.0",
|
|
33
|
+
"@alma-harness/memory": "^0.6.0",
|
|
34
|
+
"@alma-harness/postgres": "^0.6.0",
|
|
35
|
+
"@alma-harness/postgres-execution": "^0.6.0"
|
|
36
|
+
},
|
|
37
|
+
"files": [
|
|
38
|
+
"dist"
|
|
39
|
+
],
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"build": "tsup"
|
|
47
|
+
},
|
|
48
|
+
"main": "./dist/index.js",
|
|
49
|
+
"types": "./dist/index.d.ts"
|
|
50
|
+
}
|