contextos-client 0.0.0-stage → 0.1.0-alpha.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +20 -0
- package/README.md +52 -2
- package/client.d.ts +286 -0
- package/client.mjs +552 -0
- package/package.json +30 -4
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,20 @@
|
|
|
1
|
+
ContextOS
|
|
2
|
+
Copyright 2026 The ContextOS Authors
|
|
3
|
+
|
|
4
|
+
This product includes software developed as part of the ContextOS project
|
|
5
|
+
(https://github.com/contextosai/ContextOS), licensed under the Apache License,
|
|
6
|
+
Version 2.0 (see LICENSE).
|
|
7
|
+
|
|
8
|
+
Third-party dependency licenses and attribution are in THIRD_PARTY_NOTICES.txt.
|
|
9
|
+
|
|
10
|
+
conformance/reference/ includes the unmodified deterministic TypeScript reference
|
|
11
|
+
and synthetic fixtures from contextosai/contextosai, revision
|
|
12
|
+
7e2462fd931a79e3777ede81fb382e0cbf2ff46c.
|
|
13
|
+
Copyright (c) 2025-2026 ContextOS; licensed under Apache-2.0.
|
|
14
|
+
|
|
15
|
+
Documentation prose in docs/ and the Markdown guides is licensed under the
|
|
16
|
+
Creative Commons Attribution 4.0 International license (see LICENSE-docs);
|
|
17
|
+
code examples within it are licensed under Apache-2.0.
|
|
18
|
+
|
|
19
|
+
"ContextOS" and its logo are trademarks of the ContextOS project; neither
|
|
20
|
+
license grants rights to use them (see TRADEMARKS.md).
|
package/README.md
CHANGED
|
@@ -1,3 +1,53 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ContextOS for Node.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Two parts, published differently:
|
|
4
|
+
|
|
5
|
+
- `contextos-client` on npm is the HTTP client for `contextosd` (`client.mjs`, with
|
|
6
|
+
TypeScript types in `client.d.ts`). It has no dependencies and runs anywhere `fetch`
|
|
7
|
+
does: Node.js 18 or newer, edge and serverless runtimes.
|
|
8
|
+
- The in-process kernel (`index.mjs`, an N-API addon) is not published. Build it from
|
|
9
|
+
this repository only if you embed the kernel without a server.
|
|
10
|
+
|
|
11
|
+
## The HTTP client
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npm install contextos-client
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { Client, ToolPaused, ToolBlocked, governedTool } from "contextos-client";
|
|
19
|
+
|
|
20
|
+
const client = new Client("https://contextos.internal", { token: process.env.CONTEXTOS_TOKEN! });
|
|
21
|
+
const run = await client.admit(admissionBody); // holds the executor generation
|
|
22
|
+
const output = await run.callTool("adp_payments.issue_refund", args,
|
|
23
|
+
{ approvalMode: "destructive", idempotencyKey: "refund:ord_881", evidenceRefs });
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Results that are not plain success throw: `ToolPaused` (approval, input, or an unknown
|
|
27
|
+
outcome to reconcile: never retry blindly), `ToolBlocked`, `ToolRejected`,
|
|
28
|
+
`ToolFailed`. Only requests the server did not process (429, 503) are retried.
|
|
29
|
+
|
|
30
|
+
Try it against a local server from a checkout: `./examples/dev-server.sh` prints
|
|
31
|
+
`CONTEXTOS_URL` and `CONTEXTOS_TOKEN`. The
|
|
32
|
+
[integration guides](https://github.com/contextosai/ContextOS/tree/main/docs/integrations)
|
|
33
|
+
show the client inside Mastra, the Vercel AI SDK and the OpenAI Agents SDK.
|
|
34
|
+
|
|
35
|
+
The client's version matches the `contextosd` release it was published with. Use the
|
|
36
|
+
same release on both sides while ContextOS is in alpha: before its first admission the
|
|
37
|
+
client emits a `VersionMismatchWarning` when the server is another release, and throws
|
|
38
|
+
`IncompatibleServer` for a server with another API generation. `checkServer: false`
|
|
39
|
+
skips the check.
|
|
40
|
+
|
|
41
|
+
## The embedded kernel
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
cargo build --release -p contextos-node
|
|
45
|
+
cp target/release/libcontextos_node.so bindings/node/contextos.node # .dylib on macOS
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { kernel } from "./bindings/node/index.mjs";
|
|
50
|
+
const compiled = await kernel.call("compile", { pack, request, run_context });
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`CONTEXTOS_NATIVE` overrides the addon's path.
|
package/client.d.ts
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
export declare const GENERATION_HEADER: "ContextOS-Executor-Generation";
|
|
2
|
+
|
|
3
|
+
export type ApprovalMode = "read_only" | "local_write" | "network" | "delegated" | "destructive";
|
|
4
|
+
export type DecisionStatus = "DECIDED" | "DEFERRED" | "REJECTED" | "ESCALATED" | "IN_FLIGHT" | "CLOSED";
|
|
5
|
+
export type Json = null | boolean | number | string | Json[] | { [key: string]: Json };
|
|
6
|
+
|
|
7
|
+
export type RevocationKind = "tenant" | "pack" | "agent" | "adapter" | "capability";
|
|
8
|
+
export interface Revocations {
|
|
9
|
+
revoked: { kind: RevocationKind; target: string; reason: string; by: string; at: string }[];
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface DispatchReport {
|
|
13
|
+
status: string;
|
|
14
|
+
action_digest: string | null;
|
|
15
|
+
operation_id: string | null;
|
|
16
|
+
attempt_id: string | null;
|
|
17
|
+
reason_codes: string[];
|
|
18
|
+
obligations: string[];
|
|
19
|
+
approval_request_id: string | null;
|
|
20
|
+
audit_sequences: number[];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export declare const RUN_HEADER: string;
|
|
24
|
+
export declare const CLIENT_VERSION: string;
|
|
25
|
+
export declare const API_VERSION: "v1";
|
|
26
|
+
|
|
27
|
+
export interface ServerVersions {
|
|
28
|
+
apiVersion: string | null;
|
|
29
|
+
runtimeVersion: string | null;
|
|
30
|
+
clientVersion: string;
|
|
31
|
+
}
|
|
32
|
+
/** The server speaks a different HTTP API generation than this client. */
|
|
33
|
+
export declare class IncompatibleServer extends Error {}
|
|
34
|
+
export declare function checkVersions(deployment: unknown, clientVersion?: string): ServerVersions;
|
|
35
|
+
export declare const RESERVATION_HEADER: string;
|
|
36
|
+
|
|
37
|
+
export declare class ContextOSHTTPError extends Error {
|
|
38
|
+
readonly status: number;
|
|
39
|
+
readonly code: string;
|
|
40
|
+
readonly detail: unknown;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A model-call or replan reservation the run's budget cannot fit; stop the loop. */
|
|
44
|
+
export declare class BudgetExhausted extends ContextOSHTTPError {
|
|
45
|
+
readonly reasons: string[];
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export declare class ToolOutcome extends Error {
|
|
49
|
+
readonly result: Record<string, Json>;
|
|
50
|
+
readonly report: DispatchReport;
|
|
51
|
+
readonly status: string;
|
|
52
|
+
readonly reasonCodes: string[];
|
|
53
|
+
readonly obligations: string[];
|
|
54
|
+
readonly operationId: string | null;
|
|
55
|
+
}
|
|
56
|
+
/** A team finding: a claim, or an observation bound to a recorded tool call. */
|
|
57
|
+
export interface Finding {
|
|
58
|
+
finding_id: string;
|
|
59
|
+
kind: "claim" | "observed";
|
|
60
|
+
statement: string;
|
|
61
|
+
depends_on: string[];
|
|
62
|
+
urgent: boolean;
|
|
63
|
+
basis: { run_id: string; operation_id: string; action_digest: string; capability_ref: Json; outcome: "confirmed"; observation_ref: Json; observed_at: string } | null;
|
|
64
|
+
refutes: string | null;
|
|
65
|
+
author_run_id: string;
|
|
66
|
+
created_at: string;
|
|
67
|
+
status: "active" | "suspect" | "invalidated";
|
|
68
|
+
suspect_because: string[];
|
|
69
|
+
invalidation: { by_run_id: string; at: string; reason: string; refuted_by: string | null } | null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface Notice {
|
|
73
|
+
seq: number;
|
|
74
|
+
kind: "finding_invalidated" | "finding_published";
|
|
75
|
+
finding_id: string;
|
|
76
|
+
by_run_id: string;
|
|
77
|
+
at: string;
|
|
78
|
+
excerpt: string;
|
|
79
|
+
suspect: string[];
|
|
80
|
+
suspect_count: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface NoticeView {
|
|
84
|
+
notices: Notice[];
|
|
85
|
+
pending: number;
|
|
86
|
+
missed: boolean;
|
|
87
|
+
acknowledged_seq: number;
|
|
88
|
+
latest_seq: number;
|
|
89
|
+
data_only: true;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** An effect whose capability declares compensation, and where it stands. */
|
|
93
|
+
export interface CompensableEffect {
|
|
94
|
+
operation_id: string;
|
|
95
|
+
capability_id: string;
|
|
96
|
+
compensator: string;
|
|
97
|
+
outcome: string;
|
|
98
|
+
compensation_operation_id: string;
|
|
99
|
+
compensation_outcome: string;
|
|
100
|
+
state: "compensable" | "compensated" | "partially_compensated" | "compensating" | "compensation_exhausted" | "unresolved" | "not_applied";
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Approval pending, input required, or an unknown outcome to reconcile. Never retry blindly. */
|
|
104
|
+
export declare class ToolPaused extends ToolOutcome {
|
|
105
|
+
/**
|
|
106
|
+
* What the pause waits on: `approval` (re-send the same call once approved), `input`
|
|
107
|
+
* (answer with provideInput), `unknown_outcome` (the effect may have happened:
|
|
108
|
+
* reconcile), `duplicate` (already requested; not repeated) or `other`.
|
|
109
|
+
*/
|
|
110
|
+
readonly kind: "approval" | "input" | "unknown_outcome" | "duplicate" | "other";
|
|
111
|
+
readonly inputRequests: Record<string, Json> | null;
|
|
112
|
+
}
|
|
113
|
+
/** Authority, policy, constraints or budget refused the call. */
|
|
114
|
+
export declare class ToolBlocked extends ToolOutcome {}
|
|
115
|
+
/** Malformed, not surfaced to this run, or incompatible reuse of an operation key. */
|
|
116
|
+
export declare class ToolRejected extends ToolOutcome {}
|
|
117
|
+
/** The provider definitively did not apply the effect. */
|
|
118
|
+
export declare class ToolFailed extends ToolOutcome {}
|
|
119
|
+
|
|
120
|
+
export interface CallOptions {
|
|
121
|
+
approvalMode?: ApprovalMode;
|
|
122
|
+
idempotencyKey?: string | null;
|
|
123
|
+
evidenceRefs?: string[];
|
|
124
|
+
toolCallId?: string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export declare class Client {
|
|
128
|
+
constructor(baseUrl: string, options: { token: string; timeoutMs?: number; maxRetries?: number; fetch?: typeof fetch; checkServer?: boolean });
|
|
129
|
+
/** Reads GET /v1/deployment: throws IncompatibleServer on another API generation, warns on another release. Runs once before the first admit. */
|
|
130
|
+
checkServer(): Promise<ServerVersions>;
|
|
131
|
+
readonly baseUrl: string;
|
|
132
|
+
request<T = any>(method: string, path: string, options?: { body?: unknown; generation?: number; query?: Record<string, string | number> }): Promise<T>;
|
|
133
|
+
admit(body: Record<string, any>, options?: { principalChain?: { kind: string; id: string }[] }): Promise<Run>;
|
|
134
|
+
attach(runId: string, traceId: string, principalChain: { kind: string; id: string }[]): Promise<Run>;
|
|
135
|
+
/** Scores a recorded decision as an independent evaluator (token with only `evaluate`). */
|
|
136
|
+
amendTaskAuthorization(runId: string, expectedRevision: number, task: Json): Promise<{ run_id: string; revision: number; change: "narrowed" | "widened"; task_authorization_ref: Json; policy_refs: Json[] }>;
|
|
137
|
+
score(runId: string, recordId: string, scores: { evaluatorRef: string; policy: number; utility: number; safety: number }): Promise<{ score: Record<string, any>; audit_sequence: number }>;
|
|
138
|
+
/** Files an operator correction or override against a run (token with `evaluate`, independent of the run). */
|
|
139
|
+
fileFeedback(runId: string, feedback: { kind: "correction" | "override" | "approval_verdict"; targetSurface: FeedbackSurface; summary: string; decisionRecordId?: string; expectedOutcome?: string }): Promise<Feedback>;
|
|
140
|
+
/** The tenant's open policy escalations, oldest first. */
|
|
141
|
+
openEscalations(options?: { limit?: number }): Promise<{ open: number; escalations: Record<string, Json>[] }>;
|
|
142
|
+
/** Records how a human resolved an escalation (token with `control`); grants nothing. */
|
|
143
|
+
resolveEscalation(escalationId: string, resolution: "handled" | "dismissed", reason: string): Promise<Record<string, Json>>;
|
|
144
|
+
/** The tenant's open feedback, oldest first. */
|
|
145
|
+
openFeedback(options?: { limit?: number }): Promise<{ open: number; feedback: Feedback[] }>;
|
|
146
|
+
/** Closes feedback with a reference to the evidence (token with `control`). */
|
|
147
|
+
closeFeedback(feedbackId: string, status: "fixed" | "still_failing" | "invalid" | "superseded", evidence: { artifactType: string; artifactId: string; sha256: string }): Promise<Feedback>;
|
|
148
|
+
/** Kill switch (token with the `control` scope). */
|
|
149
|
+
revoke(kind: RevocationKind, target: string, reason: string): Promise<Revocations>;
|
|
150
|
+
restore(kind: RevocationKind, target: string, reason: string): Promise<Revocations>;
|
|
151
|
+
revocations(): Promise<Revocations>;
|
|
152
|
+
auditEntries(options?: { from?: number; page?: number }): AsyncGenerator<Record<string, Json>>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export type FeedbackSurface = "run_context" | "pack" | "policy" | "tool" | "memory" | "skill" | "evaluator" | "unknown";
|
|
156
|
+
|
|
157
|
+
export interface Feedback {
|
|
158
|
+
feedback_id: string;
|
|
159
|
+
run_id: string;
|
|
160
|
+
trace_id: string;
|
|
161
|
+
decision_record_id: string | null;
|
|
162
|
+
kind: string;
|
|
163
|
+
target_surface: FeedbackSurface;
|
|
164
|
+
summary: string;
|
|
165
|
+
expected_outcome: string | null;
|
|
166
|
+
reporter: string;
|
|
167
|
+
filed_at: string;
|
|
168
|
+
status: "open" | "fixed" | "still_failing" | "invalid" | "superseded";
|
|
169
|
+
replay_obligation: { case: string; replay_case: string };
|
|
170
|
+
closed_at?: string;
|
|
171
|
+
closed_by?: string;
|
|
172
|
+
evidence_ref?: { artifact_type: string; artifact_id: string; sha256: string };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export interface WorkEvidence { artifact_type: string; artifact_id: string; sha256: string }
|
|
176
|
+
export interface WorkClaim { run_id: string; executor_generation: number; lease_epoch: number; expires_at: string }
|
|
177
|
+
export interface WorkTask {
|
|
178
|
+
task_id: string; title: string; acceptance_criteria: string; dependencies: string[];
|
|
179
|
+
created_by_run_id: string; created_at: string; revision: number; lease_epoch: number;
|
|
180
|
+
status: "pending" | "claimed" | "completed"; claim: WorkClaim | null; previous_claim: WorkClaim | null;
|
|
181
|
+
evidence_refs: WorkEvidence[]; dependencies_ready: boolean; available: boolean; lease_expired: boolean;
|
|
182
|
+
}
|
|
183
|
+
export type WorkCommand =
|
|
184
|
+
| { action: "claim"; expected_revision: number; lease_seconds: number }
|
|
185
|
+
| { action: "renew"; expected_revision: number; lease_epoch: number; lease_seconds: number }
|
|
186
|
+
| { action: "release"; expected_revision: number; lease_epoch: number }
|
|
187
|
+
| { action: "complete"; expected_revision: number; lease_epoch: number; evidence_refs: WorkEvidence[] };
|
|
188
|
+
/** Advisory worker metadata; evidence refs are not independently verified. */
|
|
189
|
+
export interface WorkResult { root_run_id: string; task: WorkTask; data_only: true; evidence_verified: false }
|
|
190
|
+
export interface WorkPage { root_run_id: string; tasks: WorkTask[]; next_cursor: string | null; data_only: true; evidence_verified: false }
|
|
191
|
+
|
|
192
|
+
export declare class Run {
|
|
193
|
+
readonly client: Client;
|
|
194
|
+
readonly runId: string;
|
|
195
|
+
readonly traceId: string;
|
|
196
|
+
executorGeneration: number;
|
|
197
|
+
readonly principalChain: { kind: string; id: string }[];
|
|
198
|
+
envelope(capabilityId: string, args: Record<string, Json>, options?: CallOptions): Record<string, Json>;
|
|
199
|
+
callTool(capabilityId: string, args: Record<string, Json>, options?: CallOptions): Promise<Record<string, Json>>;
|
|
200
|
+
provideInput(paused: ToolPaused, envelope: Record<string, Json>, responses: Record<string, Json>): Promise<Record<string, Json>>;
|
|
201
|
+
reconcile(operationId: string, options?: { outcome?: "confirmed" | "not_applied" | "partial"; evidenceRef?: Record<string, string> }): Promise<any>;
|
|
202
|
+
/** Relays an outcome witness's signed reading (compact JWS); needs `outcome:report`. */
|
|
203
|
+
reportOutcome(operationId: string, attestation: string): Promise<{ run_id: string; operation_id: string; state: "witnessed"; postcondition: string; late: boolean; observation: Record<string, Json> }>;
|
|
204
|
+
compensations(): Promise<{ run_id: string; effects: CompensableEffect[] }>;
|
|
205
|
+
compensate(operationId: string, options?: { toolCallId?: string }): Promise<Record<string, Json>>;
|
|
206
|
+
compensateAll(): Promise<{ run_id: string; status: "compensated" | "stopped"; steps: { operation_id: string; result: any; report: any }[]; stopped_at: { operation_id: string; reason: string } | null }>;
|
|
207
|
+
recordDecision(decisionKey: string, status: DecisionStatus, options?: { decisionVersion?: string; outcome?: string; toolCalls?: { tool_call_id: string; operation_id: string }[]; [field: string]: unknown }): Promise<{ record: any; replay_packet: any }>;
|
|
208
|
+
delegate(childAdmission: Record<string, any>, envelope: Record<string, any>): Promise<Run>;
|
|
209
|
+
closeChild(child: Run, decision?: "accept" | "reject"): Promise<{ status: string; usage: Record<string, number> | null; reason_codes: string[] }>;
|
|
210
|
+
checkpoint(state: Json, expectedRevision: number): Promise<{ run_id: string; revision: number; digest: string; executor_generation: number; saved_at: string }>;
|
|
211
|
+
latestCheckpoint(): Promise<{ revision: number; digest: string; state: Json; executor_generation: number; saved_at: string }>;
|
|
212
|
+
publishWork(taskId: string, title: string, acceptanceCriteria: string, options?: { dependencies?: string[] }): Promise<WorkResult>;
|
|
213
|
+
workTasks(options?: { after?: string; limit?: number }): Promise<WorkPage>;
|
|
214
|
+
workTask(taskId: string): Promise<WorkResult>;
|
|
215
|
+
updateWork(taskId: string, command: WorkCommand): Promise<WorkResult>;
|
|
216
|
+
/** Peer notices that came with the latest tool result (peer data, never instructions). */
|
|
217
|
+
lastNotices: NoticeView | null;
|
|
218
|
+
publishFinding(findingId: string, statement: string, options?: { kind?: "claim" | "observed"; dependsOn?: string[]; basisOperationId?: string; basisRunId?: string; refutes?: string; urgent?: boolean }): Promise<{ root_run_id: string; finding: Finding; data_only: true }>;
|
|
219
|
+
findings(options?: { after?: string; limit?: number }): Promise<{ root_run_id: string; findings: Finding[]; next_cursor: string | null; data_only: true }>;
|
|
220
|
+
invalidateFinding(findingId: string, reason: string, options?: { refutedBy?: string }): Promise<{ root_run_id: string; finding: Finding; suspect: string[]; data_only: true }>;
|
|
221
|
+
notices(options?: { limit?: number }): Promise<NoticeView & { root_run_id: string }>;
|
|
222
|
+
ackNotices(through: number): Promise<NoticeView>;
|
|
223
|
+
reserveUsage(kind: "model_call" | "replan", options?: { tokens?: number; costCents?: number }): Promise<string>;
|
|
224
|
+
settleUsage(reservationId: string): Promise<{ reservation_id: string; charged: Record<string, number>; verified: boolean }>;
|
|
225
|
+
/** Headers for a model request that a metering LLM gateway settles with the usage it measures. */
|
|
226
|
+
meteringHeaders(reservationId: string): Record<string, string>;
|
|
227
|
+
/**
|
|
228
|
+
* Reserves budget around one model call and settles it afterwards; throws BudgetExhausted first if it
|
|
229
|
+
* cannot fit. `metered` leaves settlement to a metering LLM gateway unless the call throws.
|
|
230
|
+
*/
|
|
231
|
+
budgetedModelCall<T>(
|
|
232
|
+
fn: (reservationId: string) => Promise<T>,
|
|
233
|
+
options: { tokens: number; costCents?: number; metered?: boolean },
|
|
234
|
+
): Promise<T>;
|
|
235
|
+
status(): Promise<{ run_id: string; status: string; executor_generation: number }>;
|
|
236
|
+
takeOver(): Promise<Run>;
|
|
237
|
+
complete(): Promise<any>;
|
|
238
|
+
fail(): Promise<any>;
|
|
239
|
+
cancel(): Promise<any>;
|
|
240
|
+
evidence(): Promise<any>;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export declare function governedTool<A extends Record<string, Json>>(
|
|
244
|
+
run: Run,
|
|
245
|
+
capabilityId: string,
|
|
246
|
+
options?: {
|
|
247
|
+
approvalMode?: ApprovalMode;
|
|
248
|
+
idempotencyKey?: (args: A) => string;
|
|
249
|
+
evidenceRefs?: string[];
|
|
250
|
+
toolCallId?: (args: A) => string;
|
|
251
|
+
},
|
|
252
|
+
): (args: A) => Promise<Record<string, Json>>;
|
|
253
|
+
|
|
254
|
+
export interface PrincipalRef {
|
|
255
|
+
principal_id: string;
|
|
256
|
+
principal_type: "person" | "workload" | "agent";
|
|
257
|
+
trust_domain: string;
|
|
258
|
+
tenant_id: string;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export declare function taskScope(
|
|
262
|
+
rootRunId: string,
|
|
263
|
+
purposeId: string,
|
|
264
|
+
capabilityId: string,
|
|
265
|
+
options?: {
|
|
266
|
+
resources?: string[];
|
|
267
|
+
destinations?: string[];
|
|
268
|
+
classification?: string;
|
|
269
|
+
amount?: [number, string];
|
|
270
|
+
argumentConstraints?: Json[];
|
|
271
|
+
},
|
|
272
|
+
): Json;
|
|
273
|
+
|
|
274
|
+
export declare function taskAuthorization(
|
|
275
|
+
issuedBy: PrincipalRef,
|
|
276
|
+
scopes: Json[],
|
|
277
|
+
options?: {
|
|
278
|
+
outOfScope?: "deny" | "ask";
|
|
279
|
+
readOnly?: "allow" | "scoped";
|
|
280
|
+
confirmationRef?: Json;
|
|
281
|
+
/** Most effects the whole task may make. */
|
|
282
|
+
maxEffects?: number;
|
|
283
|
+
/** Most the task's effects may move in total. */
|
|
284
|
+
amountTotal?: { minorUnits: number; currency: string };
|
|
285
|
+
},
|
|
286
|
+
): Json;
|
package/client.mjs
ADDED
|
@@ -0,0 +1,552 @@
|
|
|
1
|
+
// HTTP client for contextosd: govern an agent's tool calls from Node.js or any
|
|
2
|
+
// runtime with fetch. No dependencies and no native addon.
|
|
3
|
+
//
|
|
4
|
+
// import { Client, ToolPaused, ToolBlocked, governedTool } from "contextos-client";
|
|
5
|
+
// const client = new Client("https://contextos.internal", { token: process.env.CONTEXTOS_TOKEN });
|
|
6
|
+
// const run = await client.admit(admissionBody); // holds the executor generation
|
|
7
|
+
// const output = await run.callTool("adp_payments.issue_refund", args,
|
|
8
|
+
// { approvalMode: "destructive", idempotencyKey: "refund:ord_881", evidenceRefs });
|
|
9
|
+
//
|
|
10
|
+
// Results that are not plain success throw: ToolPaused (approval, input, or an
|
|
11
|
+
// unknown outcome to reconcile — never retry blindly), ToolBlocked, ToolRejected,
|
|
12
|
+
// ToolFailed. Only requests the server did not process (429, 503) are retried.
|
|
13
|
+
|
|
14
|
+
export const GENERATION_HEADER = "ContextOS-Executor-Generation";
|
|
15
|
+
// On a model request, these tell a metering LLM gateway which reservation to settle with
|
|
16
|
+
// the usage it measures (see examples/metering-proxy).
|
|
17
|
+
export const RUN_HEADER = "ContextOS-Run-Id";
|
|
18
|
+
export const RESERVATION_HEADER = "ContextOS-Usage-Reservation";
|
|
19
|
+
// This client's release (scripts/package_clients.py checks it against Cargo.toml) and
|
|
20
|
+
// the HTTP API generation it speaks; a server reports both in GET /v1/deployment.
|
|
21
|
+
export const CLIENT_VERSION = "0.1.0-alpha.12";
|
|
22
|
+
export const API_VERSION = "v1";
|
|
23
|
+
|
|
24
|
+
/** The server speaks a different HTTP API generation than this client. */
|
|
25
|
+
export class IncompatibleServer extends Error {}
|
|
26
|
+
|
|
27
|
+
function warnVersion(message) {
|
|
28
|
+
if (typeof globalThis.process?.emitWarning === "function") {
|
|
29
|
+
globalThis.process.emitWarning(message, "VersionMismatchWarning");
|
|
30
|
+
} else {
|
|
31
|
+
console.warn(`VersionMismatchWarning: ${message}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Throws on a different API generation; warns on a different or unreported release.
|
|
36
|
+
export function checkVersions(deployment, clientVersion = CLIENT_VERSION) {
|
|
37
|
+
const api = deployment?.api_version ?? null;
|
|
38
|
+
const runtime = deployment?.runtime_version ?? null;
|
|
39
|
+
if (api !== null && api !== API_VERSION) {
|
|
40
|
+
throw new IncompatibleServer(`contextosd speaks API ${api}; this client speaks ${API_VERSION}`);
|
|
41
|
+
}
|
|
42
|
+
if (runtime === null) {
|
|
43
|
+
warnVersion(`contextosd does not report its release (older than this client, ${clientVersion}); use the same release on both sides`);
|
|
44
|
+
} else if (runtime !== clientVersion) {
|
|
45
|
+
warnVersion(`contextosd is release ${runtime}; this client is ${clientVersion}. Use the same release on both sides`);
|
|
46
|
+
}
|
|
47
|
+
return { apiVersion: api, runtimeVersion: runtime, clientVersion };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export class ContextOSHTTPError extends Error {
|
|
51
|
+
constructor(status, code, message, detail) {
|
|
52
|
+
super(`${status} ${code}: ${message}`);
|
|
53
|
+
this.status = status;
|
|
54
|
+
this.code = code;
|
|
55
|
+
this.detail = detail;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The run's budget cannot fit a model-call or replan reservation; `reasons` says which
|
|
60
|
+
* limit. Stop the loop: retrying the same reservation cannot succeed. */
|
|
61
|
+
export class BudgetExhausted extends ContextOSHTTPError {
|
|
62
|
+
get reasons() {
|
|
63
|
+
return Array.isArray(this.detail) ? this.detail : [];
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
const HTTP_ERRORS = { budget_exhausted: BudgetExhausted };
|
|
67
|
+
|
|
68
|
+
export class ToolOutcome extends Error {
|
|
69
|
+
constructor(result, report) {
|
|
70
|
+
const reasons = report.reason_codes ?? [];
|
|
71
|
+
super(`${result.status}: ${reasons.join(", ") || result.error || ""}`);
|
|
72
|
+
this.result = result;
|
|
73
|
+
this.report = report;
|
|
74
|
+
this.status = result.status;
|
|
75
|
+
this.reasonCodes = reasons;
|
|
76
|
+
this.obligations = report.obligations ?? [];
|
|
77
|
+
this.operationId = report.operation_id ?? null;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export class ToolPaused extends ToolOutcome {
|
|
81
|
+
/** What the pause waits on; see client.d.ts. */
|
|
82
|
+
get kind() {
|
|
83
|
+
const { obligations: o, reasonCodes: r } = this;
|
|
84
|
+
if (o.includes("await_approval")) return "approval";
|
|
85
|
+
if (o.includes("provide_requested_input")) return "input";
|
|
86
|
+
if (o.includes("reconcile_effect_before_retry")) return "unknown_outcome";
|
|
87
|
+
if (r.includes("retry_unsafe") || o.includes("reconcile_existing_operation")) return "duplicate";
|
|
88
|
+
return "other";
|
|
89
|
+
}
|
|
90
|
+
get inputRequests() {
|
|
91
|
+
return this.result.output?.result?.inputRequests ?? null;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export class ToolBlocked extends ToolOutcome {}
|
|
95
|
+
export class ToolRejected extends ToolOutcome {}
|
|
96
|
+
export class ToolFailed extends ToolOutcome {}
|
|
97
|
+
|
|
98
|
+
const OUTCOMES = { paused: ToolPaused, blocked: ToolBlocked, rejected: ToolRejected, failed: ToolFailed };
|
|
99
|
+
|
|
100
|
+
function outcome(response) {
|
|
101
|
+
const { result, report } = response;
|
|
102
|
+
if (result.status === "ok" || result.status === "completed") return result.output ?? {};
|
|
103
|
+
throw new (OUTCOMES[result.status] ?? ToolOutcome)(result, report);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
107
|
+
const segment = (value) => {
|
|
108
|
+
if (value === "" || value === "." || value === "..") throw new TypeError(`invalid path segment ${JSON.stringify(value)}`);
|
|
109
|
+
return encodeURIComponent(value);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
// Before its first admission the client reads GET /v1/deployment once: a server with
|
|
113
|
+
// another API generation throws IncompatibleServer, another release warns
|
|
114
|
+
// (VersionMismatchWarning). `checkServer: false` skips it.
|
|
115
|
+
export class Client {
|
|
116
|
+
#token;
|
|
117
|
+
#serverChecked;
|
|
118
|
+
|
|
119
|
+
constructor(baseUrl, { token, timeoutMs = 30_000, maxRetries = 3, fetch: fetchImpl = globalThis.fetch, checkServer = true } = {}) {
|
|
120
|
+
if (!token) throw new TypeError("a token is required");
|
|
121
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
122
|
+
this.#token = token;
|
|
123
|
+
this.timeoutMs = timeoutMs;
|
|
124
|
+
this.maxRetries = maxRetries;
|
|
125
|
+
this.fetch = fetchImpl;
|
|
126
|
+
this.#serverChecked = checkServer ? null : Promise.resolve();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Compares the server's API generation and release with this client's. */
|
|
130
|
+
async checkServer() {
|
|
131
|
+
const versions = checkVersions(await this.request("GET", "/v1/deployment"));
|
|
132
|
+
this.#serverChecked = Promise.resolve();
|
|
133
|
+
return versions;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
toJSON() {
|
|
137
|
+
return { baseUrl: this.baseUrl }; // never serialize the token
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async request(method, path, { body, generation, query } = {}) {
|
|
141
|
+
let url = this.baseUrl + path;
|
|
142
|
+
if (query) url += "?" + new URLSearchParams(Object.entries(query).map(([k, v]) => [k, String(v)]));
|
|
143
|
+
const headers = { Authorization: `Bearer ${this.#token}`, Accept: "application/json" };
|
|
144
|
+
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
145
|
+
if (generation !== undefined) headers[GENERATION_HEADER] = String(generation);
|
|
146
|
+
for (let attempt = 0; ; attempt++) {
|
|
147
|
+
const response = await this.fetch(url, {
|
|
148
|
+
method,
|
|
149
|
+
headers,
|
|
150
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
151
|
+
signal: AbortSignal.timeout(this.timeoutMs),
|
|
152
|
+
redirect: "error",
|
|
153
|
+
});
|
|
154
|
+
const text = await response.text();
|
|
155
|
+
const decoded = text ? JSON.parse(text) : null;
|
|
156
|
+
if (response.ok) return decoded;
|
|
157
|
+
// Not processed: safe to retry after the server's hint.
|
|
158
|
+
if ((response.status === 429 || response.status === 503) && attempt < this.maxRetries) {
|
|
159
|
+
const hint = Number(response.headers.get("retry-after"));
|
|
160
|
+
await sleep(Number.isFinite(hint) && hint > 0 ? Math.min(hint, 30) * 1000 : Math.min(200 * 2 ** attempt, 5000));
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
const failure = decoded?.error;
|
|
164
|
+
if (failure && typeof failure === "object") {
|
|
165
|
+
const code = failure.code ?? "error";
|
|
166
|
+
throw new (HTTP_ERRORS[code] ?? ContextOSHTTPError)(response.status, code, failure.message ?? "", failure.detail);
|
|
167
|
+
}
|
|
168
|
+
throw new ContextOSHTTPError(response.status, "refused", text, decoded);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Admits a run (POST /v1/runs) and returns a handle that owns it. */
|
|
173
|
+
async admit(body, { principalChain } = {}) {
|
|
174
|
+
if (this.#serverChecked === null) {
|
|
175
|
+
// Concurrent first admissions share one check; a failed check is retried next time.
|
|
176
|
+
this.#serverChecked = this.checkServer().catch((error) => {
|
|
177
|
+
this.#serverChecked = null;
|
|
178
|
+
throw error;
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
await this.#serverChecked;
|
|
182
|
+
const admitted = await this.request("POST", "/v1/runs", { body });
|
|
183
|
+
const context = body.run_context ?? {};
|
|
184
|
+
const agent = context.agent?.agent_id;
|
|
185
|
+
return new Run(this, admitted.run_id, context.trace_id ?? "", admitted.executor_generation,
|
|
186
|
+
principalChain ?? (agent ? [{ kind: "agent", id: agent }] : []), admitted);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** A handle on an existing run at its current generation (no takeover). */
|
|
190
|
+
async attach(runId, traceId, principalChain) {
|
|
191
|
+
const status = await this.request("GET", `/v1/runs/${segment(runId)}`);
|
|
192
|
+
return new Run(this, runId, traceId, status.executor_generation, principalChain, status);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Scores a recorded decision as an independent evaluator (a client whose token has
|
|
197
|
+
* only the `evaluate` scope). The runtime adds the measured cost and latency.
|
|
198
|
+
*/
|
|
199
|
+
/**
|
|
200
|
+
* Corrects what a run's principal authorized. Narrowing is open to the executor;
|
|
201
|
+
* widening needs an `authorize` token that does not run tasks, the principal's
|
|
202
|
+
* `confirmation_ref` and the same `issued_by`. Resolves to the new revision.
|
|
203
|
+
*/
|
|
204
|
+
amendTaskAuthorization(runId, expectedRevision, task) {
|
|
205
|
+
return this.request("PUT", `/v1/runs/${segment(runId)}/task-authorization`, {
|
|
206
|
+
body: { expected_revision: expectedRevision, task_authorization: task },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
score(runId, recordId, { evaluatorRef, policy, utility, safety }) {
|
|
211
|
+
return this.request("POST", `/v1/runs/${segment(runId)}/decisions/${segment(recordId)}/scores`, {
|
|
212
|
+
body: { evaluator_ref: evaluatorRef, policy, utility, safety },
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Files an operator correction or override against a run as an independent reviewer
|
|
218
|
+
* (`evaluate` scope); the run's replay case becomes its replay obligation.
|
|
219
|
+
*/
|
|
220
|
+
fileFeedback(runId, { kind, targetSurface, summary, decisionRecordId, expectedOutcome }) {
|
|
221
|
+
const body = { kind, target_surface: targetSurface, summary };
|
|
222
|
+
if (decisionRecordId !== undefined) body.decision_record_id = decisionRecordId;
|
|
223
|
+
if (expectedOutcome !== undefined) body.expected_outcome = expectedOutcome;
|
|
224
|
+
return this.request("POST", `/v1/runs/${segment(runId)}/feedback`, { body });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The tenant's open policy escalations, oldest first (`audit:read`). */
|
|
228
|
+
openEscalations({ limit = 500 } = {}) {
|
|
229
|
+
return this.request("GET", "/v1/escalations", { query: { limit } });
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Records how a human resolved an escalation, `handled` or `dismissed` (`control`).
|
|
234
|
+
* Grants nothing: an action the human approves is retried through policy.
|
|
235
|
+
*/
|
|
236
|
+
resolveEscalation(escalationId, resolution, reason) {
|
|
237
|
+
return this.request("POST", `/v1/escalations/${segment(escalationId)}/resolve`, { body: { resolution, reason } });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/** The tenant's open feedback, oldest first: the replay corpus a change must pass. */
|
|
241
|
+
openFeedback({ limit = 500 } = {}) {
|
|
242
|
+
return this.request("GET", "/v1/feedback", { query: { limit } });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Closes feedback as `fixed`, `still_failing`, `invalid` or `superseded`, with a
|
|
247
|
+
* reference to the evidence (`control` scope).
|
|
248
|
+
*/
|
|
249
|
+
closeFeedback(feedbackId, status, { artifactType, artifactId, sha256 }) {
|
|
250
|
+
return this.request("POST", `/v1/feedback/${segment(feedbackId)}/close`, {
|
|
251
|
+
body: { status, evidence_ref: { artifact_type: artifactType, artifact_id: artifactId, sha256 } },
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Kill switch (token with the `control` scope): revokes a `tenant`, `pack`, `agent`,
|
|
257
|
+
* `adapter` or `capability` from the next dispatch and admission.
|
|
258
|
+
*/
|
|
259
|
+
revoke(kind, target, reason) {
|
|
260
|
+
return this.request("POST", "/v1/revocations", { body: { kind, target, reason } });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Restores a revoked target. */
|
|
264
|
+
restore(kind, target, reason) {
|
|
265
|
+
return this.request("POST", "/v1/revocations/restore", { body: { kind, target, reason } });
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** The tenant's revoked targets. */
|
|
269
|
+
revocations() {
|
|
270
|
+
return this.request("GET", "/v1/revocations");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Yields the tenant's signed audit entries in order. */
|
|
274
|
+
async *auditEntries({ from = 1, page = 500 } = {}) {
|
|
275
|
+
let cursor = from;
|
|
276
|
+
while (cursor != null) {
|
|
277
|
+
const batch = await this.request("GET", "/v1/audit/entries", { query: { from: cursor, limit: page } });
|
|
278
|
+
yield* batch.entries;
|
|
279
|
+
cursor = batch.next;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export class Run {
|
|
285
|
+
constructor(client, runId, traceId, executorGeneration, principalChain, admitted = {}) {
|
|
286
|
+
Object.assign(this, { client, runId, traceId, executorGeneration, principalChain, admitted });
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
#path(suffix = "") {
|
|
290
|
+
return `/v1/runs/${segment(this.runId)}${suffix}`;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
#post(suffix, body = {}) {
|
|
294
|
+
return this.client.request("POST", this.#path(suffix), { body, generation: this.executorGeneration });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
envelope(capabilityId, args, { approvalMode = "read_only", idempotencyKey = null, evidenceRefs = [], toolCallId } = {}) {
|
|
298
|
+
return {
|
|
299
|
+
envelope_version: "contextos.tool_call.v1",
|
|
300
|
+
tool_call_id: toolCallId ?? `tc_${globalThis.crypto.randomUUID().replaceAll("-", "")}`,
|
|
301
|
+
run_id: this.runId, trace_id: this.traceId, capability_id: capabilityId, args,
|
|
302
|
+
principal_chain: this.principalChain, approval_mode_requested: approvalMode,
|
|
303
|
+
approval_mode_effective: approvalMode, approval_mode_highest: approvalMode,
|
|
304
|
+
evidence_refs: evidenceRefs, idempotency_key: idempotencyKey,
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Governs and dispatches one tool call; resolves to its output or throws a ToolOutcome. */
|
|
309
|
+
async callTool(capabilityId, args, options = {}) {
|
|
310
|
+
const response = await this.#post("/tool-calls", this.envelope(capabilityId, args, options));
|
|
311
|
+
// Peer notices that came with this result (peer data, never instructions).
|
|
312
|
+
this.lastNotices = response.result?.metadata?.notices ?? null;
|
|
313
|
+
return outcome(response);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
async provideInput(paused, envelope, responses) {
|
|
317
|
+
return outcome(await this.#post(`/operations/${segment(paused.operationId ?? "")}/input`,
|
|
318
|
+
{ tool_call: envelope, input_responses: responses }));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Resolves an unknown effect: by provider query, or by asserting `outcome` with evidence. */
|
|
322
|
+
reconcile(operationId, { outcome: asserted, evidenceRef } = {}) {
|
|
323
|
+
const body = asserted === undefined ? { source: "provider" }
|
|
324
|
+
: { source: "operator", outcome: asserted, evidence_ref: evidenceRef };
|
|
325
|
+
return this.#post(`/operations/${segment(operationId)}/reconcile`, body);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Relays an outcome witness's signed reading (a compact JWS) for an applied effect whose
|
|
330
|
+
* capability declares an outcome contract. The token needs the `outcome:report` scope.
|
|
331
|
+
*/
|
|
332
|
+
reportOutcome(operationId, attestation) {
|
|
333
|
+
return this.client.request("POST", this.#path(`/operations/${segment(operationId)}/outcome`), { body: { attestation } });
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** The run's compensable effects and where each stands (`state`). */
|
|
337
|
+
compensations() {
|
|
338
|
+
return this.client.request("GET", this.#path("/compensations"));
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Compensates one applied effect with its declared compensating capability, governed as
|
|
343
|
+
* a new operation; resolves to its output or throws a ToolOutcome.
|
|
344
|
+
*/
|
|
345
|
+
async compensate(operationId, { toolCallId } = {}) {
|
|
346
|
+
const body = { tool_call_id: toolCallId ?? `tc_${globalThis.crypto.randomUUID().replaceAll("-", "")}` };
|
|
347
|
+
return outcome(await this.#post(`/operations/${segment(operationId)}/compensate`, body));
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** Compensates the run's applied effects newest first, stopping at any in doubt. */
|
|
351
|
+
compensateAll() {
|
|
352
|
+
return this.#post("/compensate");
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
recordDecision(decisionKey, status, { decisionVersion = "1", toolCalls = [], ...fields } = {}) {
|
|
356
|
+
return this.#post("/decisions", { decision_key: decisionKey, decision_version: decisionVersion, status,
|
|
357
|
+
tool_calls: toolCalls, ...fields });
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Admits a child run in a narrowed lane (AgentDelegationEnvelope). Its budget is
|
|
362
|
+
* reserved from this run, which must hold the current generation.
|
|
363
|
+
*/
|
|
364
|
+
async delegate(childAdmission, envelope) {
|
|
365
|
+
const admitted = await this.client.request("POST", "/v1/runs", {
|
|
366
|
+
body: { ...childAdmission, delegation: envelope }, generation: this.executorGeneration,
|
|
367
|
+
});
|
|
368
|
+
return new Run(this.client, admitted.run_id, childAdmission.run_context?.trace_id ?? this.traceId,
|
|
369
|
+
admitted.executor_generation, this.principalChain, admitted);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Closes a delegated child (`accept` or `reject`), settling its spend into this run. */
|
|
373
|
+
closeChild(child, decision = "accept") {
|
|
374
|
+
return this.client.request("POST", `/v1/runs/${segment(child.runId)}/close`, {
|
|
375
|
+
body: { decision }, generation: this.executorGeneration,
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Saves the orchestrator's state as the next checkpoint revision. */
|
|
380
|
+
checkpoint(state, expectedRevision) {
|
|
381
|
+
return this.#post("/checkpoint", { expected_revision: expectedRevision, state });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** The latest checkpoint (`state`, `revision`), e.g. after taking the run over. */
|
|
385
|
+
latestCheckpoint() {
|
|
386
|
+
return this.client.request("GET", this.#path("/checkpoint"), { generation: this.executorGeneration });
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Immutable task metadata shared with the root's descendants; grants no tool authority. */
|
|
390
|
+
publishWork(taskId, title, acceptanceCriteria, { dependencies = [] } = {}) {
|
|
391
|
+
return this.#post("/work", { task_id: taskId, title, acceptance_criteria: acceptanceCriteria, dependencies });
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** A live page; restart at the beginning to discover new earlier ids. */
|
|
395
|
+
workTasks({ after, limit = 100 } = {}) {
|
|
396
|
+
return this.client.request("GET", this.#path("/work"), {
|
|
397
|
+
generation: this.executorGeneration, query: { limit, ...(after === undefined ? {} : { after }) },
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
workTask(taskId) {
|
|
402
|
+
return this.client.request("GET", this.#path(`/work/${segment(taskId)}`), { generation: this.executorGeneration });
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Conditional mutation. Inspect after conflicts/lost responses; lease expiry never proves effects safe to repeat. */
|
|
406
|
+
updateWork(taskId, command) {
|
|
407
|
+
return this.#post(`/work/${segment(taskId)}`, command);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Shares a finding: a claim, or (with `basisOperationId`) an observation bound to a
|
|
412
|
+
* recorded tool call whose facts the runtime takes from its operation ledger.
|
|
413
|
+
*/
|
|
414
|
+
publishFinding(findingId, statement, { kind = "claim", dependsOn = [], basisOperationId, basisRunId, refutes, urgent = false } = {}) {
|
|
415
|
+
const body = { finding_id: findingId, kind, statement, depends_on: dependsOn, urgent };
|
|
416
|
+
if (refutes !== undefined) body.refutes = refutes;
|
|
417
|
+
if (basisOperationId !== undefined) {
|
|
418
|
+
body.kind = "observed";
|
|
419
|
+
body.basis = { operation_id: basisOperationId, ...(basisRunId === undefined ? {} : { run_id: basisRunId }) };
|
|
420
|
+
}
|
|
421
|
+
return this.#post("/findings", body);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
findings({ after, limit = 100 } = {}) {
|
|
425
|
+
return this.client.request("GET", this.#path("/findings"), {
|
|
426
|
+
generation: this.executorGeneration, query: { limit, ...(after === undefined ? {} : { after }) },
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** Falsifies a finding: withdraw your own, or cite an observed finding refuting a peer's. */
|
|
431
|
+
invalidateFinding(findingId, reason, { refutedBy } = {}) {
|
|
432
|
+
return this.#post(`/findings/${segment(findingId)}/invalidate`,
|
|
433
|
+
{ reason, ...(refutedBy === undefined ? {} : { refuted_by: refutedBy }) });
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** This run's unacknowledged peer notices; reading does not acknowledge them. */
|
|
437
|
+
notices({ limit = 20 } = {}) {
|
|
438
|
+
return this.client.request("GET", this.#path("/notices"), { generation: this.executorGeneration, query: { limit } });
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
ackNotices(through) {
|
|
442
|
+
return this.#post("/notices/ack", { through });
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** Reserves budget for a `model_call` or a `replan`; resolves to the reservation id. */
|
|
446
|
+
async reserveUsage(kind, { tokens = 0, costCents = 0 } = {}) {
|
|
447
|
+
return (await this.#post("/usage/reserve", { kind, tokens, cost_cents: costCents })).reservation_id;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Settles a reservation as the executor: the whole reservation is charged. Pass the
|
|
452
|
+
* id to your metering gateway instead to settle measured usage.
|
|
453
|
+
*/
|
|
454
|
+
settleUsage(reservationId) {
|
|
455
|
+
return this.#post("/usage/settle", { reservation_id: reservationId });
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
/** Headers for a model request that a metering LLM gateway settles with the usage it
|
|
459
|
+
* measures (`budgetedModelCall(fn, { metered: true })`). */
|
|
460
|
+
meteringHeaders(reservationId) {
|
|
461
|
+
return { [RUN_HEADER]: this.runId, [RESERVATION_HEADER]: reservationId };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Reserves budget for one model call around `fn(reservationId)` and settles it
|
|
465
|
+
* afterwards, even if `fn` throws. Throws BudgetExhausted before calling `fn` when the
|
|
466
|
+
* run cannot afford it. `metered: true` leaves settlement to a metering LLM gateway
|
|
467
|
+
* (send `meteringHeaders(id)`); if `fn` throws, a reservation the gateway did not
|
|
468
|
+
* settle is settled here, charging all of it. */
|
|
469
|
+
async budgetedModelCall(fn, { tokens, costCents = 0, metered = false }) {
|
|
470
|
+
const reservation = await this.reserveUsage("model_call", { tokens, costCents });
|
|
471
|
+
let result;
|
|
472
|
+
try {
|
|
473
|
+
result = await fn(reservation);
|
|
474
|
+
} catch (error) {
|
|
475
|
+
await (metered ? this.#settleOpen(reservation) : this.settleUsage(reservation));
|
|
476
|
+
throw error;
|
|
477
|
+
}
|
|
478
|
+
if (!metered) await this.settleUsage(reservation);
|
|
479
|
+
return result;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async #settleOpen(reservationId) {
|
|
483
|
+
try {
|
|
484
|
+
await this.settleUsage(reservationId);
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (!(error instanceof ContextOSHTTPError && error.status === 404)) throw error; // settled by the gateway
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
status() {
|
|
491
|
+
return this.client.request("GET", this.#path());
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** Takes the run over; the previous executor's generation becomes stale. */
|
|
495
|
+
async takeOver() {
|
|
496
|
+
const { executor_generation: current } = await this.status();
|
|
497
|
+
const taken = await this.client.request("POST", this.#path("/takeover"), { body: { expected_generation: current } });
|
|
498
|
+
this.executorGeneration = taken.executor_generation;
|
|
499
|
+
return this;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
complete() { return this.#post("/complete"); }
|
|
503
|
+
fail() { return this.#post("/fail"); }
|
|
504
|
+
cancel() { return this.client.request("POST", this.#path("/cancel"), { body: {} }); }
|
|
505
|
+
evidence() { return this.client.request("GET", this.#path("/evidence")); }
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* Wraps a capability as an async tool function taking named arguments. Register the
|
|
510
|
+
* result with any framework that accepts async functions (Vercel AI SDK, LangChain.js,
|
|
511
|
+
* OpenAI Agents SDK). `idempotencyKey` derives the operation key from the arguments,
|
|
512
|
+
* and `toolCallId` the call's id, so a DecisionRecord can cite it.
|
|
513
|
+
*/
|
|
514
|
+
export function governedTool(run, capabilityId, { approvalMode = "read_only", idempotencyKey, evidenceRefs = [], toolCallId } = {}) {
|
|
515
|
+
return (args) => run.callTool(capabilityId, args, {
|
|
516
|
+
approvalMode, evidenceRefs, idempotencyKey: idempotencyKey ? idempotencyKey(args) : null,
|
|
517
|
+
toolCallId: toolCallId ? toolCallId(args) : undefined,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* One `AuthorityGrant` scope for a task authorization: this capability, on these
|
|
523
|
+
* resources, to these destinations, up to `amount` = `[minorUnits, currency]`.
|
|
524
|
+
*/
|
|
525
|
+
export function taskScope(rootRunId, purposeId, capabilityId, {
|
|
526
|
+
resources = [], destinations = [], classification = "CONFIDENTIAL", amount, argumentConstraints = [],
|
|
527
|
+
} = {}) {
|
|
528
|
+
const scope = {
|
|
529
|
+
root_run_id: rootRunId, purpose_ids: [purposeId], capability_ids: [capabilityId],
|
|
530
|
+
resource_ids: [...resources], destination_ids: [...destinations], classification_labels: [classification],
|
|
531
|
+
argument_constraints: [...argumentConstraints],
|
|
532
|
+
};
|
|
533
|
+
if (amount) scope.amount_ceiling = { minor_units: amount[0], currency: amount[1] };
|
|
534
|
+
return scope;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/**
|
|
538
|
+
* What the principal authorized for a run, for `admit(body)` as
|
|
539
|
+
* `body.task_authorization`. Effects outside every scope are refused
|
|
540
|
+
* (`outOfScope: "deny"`) or wait for an exact approval (`"ask"`, thrown as
|
|
541
|
+
* `ToolPaused` with `kind === "approval"`).
|
|
542
|
+
*/
|
|
543
|
+
export function taskAuthorization(issuedBy, scopes, { outOfScope = "deny", readOnly = "allow", confirmationRef, maxEffects, amountTotal } = {}) {
|
|
544
|
+
const task = { issued_by: issuedBy, scopes, out_of_scope: outOfScope, read_only: readOnly };
|
|
545
|
+
if (confirmationRef) task.confirmation_ref = confirmationRef;
|
|
546
|
+
// Bounds on the task as a whole, across all its effects.
|
|
547
|
+
const limits = {};
|
|
548
|
+
if (maxEffects !== undefined) limits.max_effects = maxEffects;
|
|
549
|
+
if (amountTotal) limits.amount_total = { minor_units: amountTotal.minorUnits, currency: amountTotal.currency };
|
|
550
|
+
if (Object.keys(limits).length) task.limits = limits;
|
|
551
|
+
return task;
|
|
552
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "contextos-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0-alpha.12",
|
|
4
|
+
"description": "HTTP client for contextosd: govern an AI agent's tool calls. No dependencies.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/contextosai/ContextOS.git",
|
|
9
|
+
"directory": "bindings/node"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/contextosai/ContextOS/blob/main/bindings/node/README.md",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"main": "client.mjs",
|
|
14
|
+
"types": "client.d.ts",
|
|
15
|
+
"exports": {
|
|
16
|
+
".": {
|
|
17
|
+
"types": "./client.d.ts",
|
|
18
|
+
"default": "./client.mjs"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"client.mjs",
|
|
23
|
+
"client.d.ts",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"NOTICE"
|
|
27
|
+
],
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=18"
|
|
30
|
+
},
|
|
31
|
+
"sideEffects": false
|
|
32
|
+
}
|